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/no/nav/familie/ks/sak/statistikk/stønadsstatistikk/PubliserVedtakTask.kt | navikt | 533,308,075 | false | {"Kotlin": 2778706, "Shell": 1039, "Dockerfile": 141} | package no.nav.familie.ks.sak.statistikk.stønadsstatistikk
import no.nav.familie.ks.sak.integrasjon.datavarehus.KafkaProducer
import no.nav.familie.ks.sak.statistikk.stønadsstatistikk.PubliserVedtakTask.Companion.TASK_STEP_TYPE
import no.nav.familie.prosessering.AsyncTaskStep
import no.nav.familie.prosessering.TaskStepBeskrivelse
import no.nav.familie.prosessering.domene.Task
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import java.util.Properties
@Service
@TaskStepBeskrivelse(
taskStepType = TASK_STEP_TYPE,
beskrivelse = "Publiser vedtakDVH til kafka Aiven",
maxAntallFeil = 1
)
class PubliserVedtakTask(
val kafkaProducer: KafkaProducer,
val stønadsstatistikkService: StønadsstatistikkService
) : AsyncTaskStep {
override fun doTask(task: Task) {
val vedtakDVH = stønadsstatistikkService.hentVedtakDVH(task.payload.toLong())
logger.info("Send Vedtak til DVH, behandling id ${vedtakDVH.behandlingsId}")
task.metadata["offset"] = kafkaProducer.sendMessageForTopicVedtak(vedtakDVH).toString()
}
companion object {
val logger = LoggerFactory.getLogger(PubliserVedtakTask::class.java)
const val TASK_STEP_TYPE = "publiserVedtakTask"
fun opprettTask(personIdent: String, behandlingsId: Long): Task {
return Task(
type = TASK_STEP_TYPE,
payload = behandlingsId.toString(),
properties = Properties().apply {
this["personIdent"] = personIdent
this["behandlingsId"] = behandlingsId.toString()
}
)
}
}
}
| 8 | Kotlin | 1 | 2 | f4d9399ceff883c7a14a481407038d41d071b169 | 1,659 | familie-ks-sak | MIT License |
kotlin-native/backend.native/tests/filecheck/objc_direct.kt | JetBrains | 3,432,266 | false | {"Kotlin": 73968610, "Java": 6672141, "Swift": 4257498, "C": 2622360, "C++": 1898765, "Objective-C": 641056, "Objective-C++": 167134, "JavaScript": 135706, "Python": 48402, "Shell": 31423, "TypeScript": 22754, "Lex": 18369, "Groovy": 17265, "Batchfile": 11693, "CSS": 11368, "Ruby": 6922, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
import direct.*
import kotlinx.cinterop.*
//CHECK-LABEL: kfun:#callDirect(){}kotlin.ULong
fun callDirect(): ULong {
val cc = CallingConventions()
//CHECK: invoke i64 @_{{[a-zA-Z0-9]+}}_knbridge{{[0-9]+}}(i8* %{{[0-9]+}}, i64 42)
return cc.direct(42uL)
}
//CHECK-LABEL: kfun:#callRegular(){}kotlin.ULong
fun callRegular(): ULong {
val cc = CallingConventions()
//CHECK: invoke i64 @_{{[a-zA-Z0-9]+}}_knbridge{{[0-9]+}}(i8* %{{[0-9]+}}, i8* %{{[0-9]+}}, i64 42)
return cc.regular(42uL)
}
fun main() {
callDirect()
callRegular()
} | 162 | Kotlin | 5729 | 46,436 | c902e5f56504e8572f9bc13f424de8bfb7f86d39 | 772 | kotlin | Apache License 2.0 |
plugins/kotlin/idea/tests/testData/quickfix/suppress/availability/parameterSuppressForLambdaParameter.kt | ingokegel | 72,937,917 | false | null | // "Suppress 'UNUSED_ANONYMOUS_PARAMETER' for parameter a" "false"
// ACTION: Convert to anonymous function
// ACTION: Convert to lazy property
// ACTION: Convert to single-line lambda
// ACTION: Do not show implicit receiver and parameter hints
// ACTION: Enable a trailing comma by default in the formatter
// ACTION: Remove explicit lambda parameter types (may break code)
// ACTION: Rename to _
val x = { <caret>a: Int ->
5
}
// IGNORE_FIR
| 249 | null | 5023 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 450 | intellij-community | Apache License 2.0 |
ktask-base/src/main/kotlin/ktask/base/settings/config/parser/ConfigClassMap.kt | perracodex | 810,476,641 | false | {"Kotlin": 273567, "JavaScript": 11106, "HTML": 8779, "CSS": 4693, "Dockerfile": 3127, "Java": 1017} | /*
* Copyright (c) 2024-Present Perracodex. Use of this source code is governed by an MIT license.
*/
package ktask.base.settings.config.parser
import ktask.base.settings.annotation.ConfigurationAPI
import ktask.base.settings.config.ConfigurationCatalog
import ktask.base.settings.config.sections.DeploymentSettings
import kotlin.reflect.KClass
/**
* Maps a configuration path to a data class type.
*
* @property mappingName The corresponding name of the property in the [ConfigurationCatalog] class,
* to which the configuration values will be mapped to.
* @property path The section in the configuration file, i.e. "ktor.deployment".
* @property kClass The target data class type which will map the configuration, i.e. [DeploymentSettings].
*
* @see ConfigurationCatalog
*/
@ConfigurationAPI
internal data class ConfigClassMap<T : IConfigSection>(
val mappingName: String,
val path: String,
val kClass: KClass<T>
)
| 0 | Kotlin | 0 | 1 | 75e85999f2f4141db2c230c26529a7d9db9b7e4b | 965 | KTask | MIT License |
shared/src/commonMain/kotlin/co/touchlab/kampstarter/Koin.kt | direstrepo24 | 264,791,709 | false | null | package co.touchlab.kampstarter
import co.touchlab.kampstarter.ktor.DogApiImpl
import co.touchlab.kampstarter.ktor.KtorApi
import org.koin.core.context.startKoin
import org.koin.core.module.Module
import org.koin.dsl.KoinAppDeclaration
import org.koin.dsl.module
fun initKoin(appDeclaration: KoinAppDeclaration = {}) = startKoin {
appDeclaration()
modules(platformModule, coreModule)
}
val coreModule = module {
single { DatabaseHelper(get()) }
single<KtorApi> { DogApiImpl() }
}
expect val platformModule: Module | 0 | Kotlin | 0 | 0 | 1a849d873fc0f12fb945fdb146dc6eb6ce8606a4 | 533 | kampkit | Apache License 2.0 |
core/network/src/main/kotlin/com/flixclusive/core/network/retrofit/dto/tv/TMDBSeasonDto.kt | rhenwinch | 659,237,375 | false | {"Kotlin": 1637525, "Java": 18011} | package com.flixclusive.core.network.retrofit.dto.tv
import com.flixclusive.core.util.exception.safeCall
import com.flixclusive.core.util.film.isDateInFuture
import com.flixclusive.model.tmdb.Season
import com.google.gson.annotations.SerializedName
data class TMDBSeasonDto(
val _id: String,
@SerializedName("air_date") val airDate: String?,
val episodes: List<TMDBEpisodeDto>,
val name: String,
val overview: String,
val id: Int,
@SerializedName("poster_path") val posterPath: String?,
@SerializedName("season_number") val seasonNumber: Int
)
fun TMDBSeasonDto.toSeason(): Season {
return Season(
seasonNumber = seasonNumber,
image = posterPath,
name = name,
episodes = episodes.map { it.toEpisode() },
isReleased = if(airDate != null) safeCall { !isDateInFuture(airDate) } ?: true else false
)
} | 26 | Kotlin | 22 | 264 | 5128cac1ac119e84a6725fd655eb0da427964c5f | 880 | Flixclusive | MIT License |
tutorials/tutorial5/src/main/java/com/badoo/ribs/tutorials/tutorial5/rib/greetings_container/GreetingsContainerInteractor.kt | dariush-fathie | 370,315,818 | true | {"Kotlin": 1154178} | package com.badoo.ribs.tutorials.tutorial5.rib.greetings_container
import com.badoo.ribs.core.modality.BuildParams
import com.badoo.ribs.tutorials.tutorial5.rib.greetings_container.GreetingsContainer.Output.GreetingsSaid
import com.badoo.ribs.tutorials.tutorial5.rib.greetings_container.GreetingsContainerRouter.Configuration
import com.badoo.ribs.tutorials.tutorial5.rib.hello_world.HelloWorld
import com.badoo.ribs.tutorials.tutorial5.rib.hello_world.HelloWorld.Output.HelloThere
import com.badoo.ribs.tutorials.tutorial5.rib.option_selector.OptionSelector
import com.badoo.ribs.tutorials.tutorial5.util.BackStackInteractor
import com.jakewharton.rxrelay2.PublishRelay
import com.jakewharton.rxrelay2.Relay
import io.reactivex.functions.Consumer
class GreetingsContainerInteractor(
buildParams: BuildParams<Nothing?>,
output: Consumer<GreetingsContainer.Output>
) : BackStackInteractor<GreetingsContainer, Nothing, Configuration>(
buildParams = buildParams,
initialConfiguration = Configuration.HelloWorld
) {
internal val helloWorldInputSource: Relay<HelloWorld.Input> = PublishRelay.create()
internal val helloWorldOutputConsumer: Consumer<HelloWorld.Output> = Consumer {
when (it) {
is HelloThere -> output.accept(GreetingsSaid(it.greeting))
}
}
internal val optionsSelectorOutputConsumer: Consumer<OptionSelector.Output> = Consumer {
// TODO
}
}
| 0 | Kotlin | 0 | 0 | d1635b60ad2610c122d88e3b8d179ebd5946dc7c | 1,427 | RIBs | Apache License 2.0 |
app/src/main/java/com/avaliadorimovel/details/interfaces/InterfaceDetailsView.kt | rolphmc | 350,545,871 | false | null | package com.avaliadorimovel.details.interfaces
interface InterfaceDetailsView {
fun setControls()
fun createSamples()
fun onValidationError()
fun navigateToResult(result: String)
} | 0 | Kotlin | 0 | 0 | 4222503f4be7ec3c224b4e089d1c4bb39df982fa | 197 | projeto-quanto-custa-seu-imovel | MIT License |
app/src/main/java/com/avaliadorimovel/details/interfaces/InterfaceDetailsView.kt | rolphmc | 350,545,871 | false | null | package com.avaliadorimovel.details.interfaces
interface InterfaceDetailsView {
fun setControls()
fun createSamples()
fun onValidationError()
fun navigateToResult(result: String)
} | 0 | Kotlin | 0 | 0 | 4222503f4be7ec3c224b4e089d1c4bb39df982fa | 197 | projeto-quanto-custa-seu-imovel | MIT License |
SDF/src/me/anno/sdf/SDFGroup.kt | AntonioNoack | 456,513,348 | false | null | package me.anno.sdf
import me.anno.ecs.Entity
import me.anno.ecs.annotations.Range
import me.anno.ecs.components.mesh.TypeValue
import me.anno.ecs.prefab.PrefabSaveable
import me.anno.gpu.pipeline.Pipeline
import me.anno.gpu.shader.GLSLType
import me.anno.maths.Maths.SQRT1_2f
import me.anno.maths.Maths.clamp
import me.anno.maths.Maths.length
import me.anno.maths.Maths.max
import me.anno.maths.Maths.min
import me.anno.utils.pooling.JomlPools
import me.anno.utils.structures.arrays.IntArrayList
import me.anno.utils.structures.lists.Lists.count2
import me.anno.utils.structures.lists.Lists.first2
import me.anno.utils.structures.tuples.Quad
import org.joml.AABBf
import org.joml.Vector2f
import org.joml.Vector4f
import kotlin.math.abs
import kotlin.math.roundToInt
// todo the sdf things have become quite a lot of code, and probably won't be in that many games,
// therefore they probably should be a mod/plugin
/**
* joins multiple sdf components together, like a folder;
* can also join them using special operations like subtraction, xor, and logical and (see type)
* */
open class SDFGroup : SDFComponent() {
enum class CombinationMode(
val id: Int,
val funcName: String,
val glslCode: List<String>,
val isStyleable: Boolean
) {
UNION(0, "sdMin", listOf(smoothMinCubic, SDFGroup.Companion.sdMin), true), // A or B
INTERSECTION(1, "sdMax", listOf(
smoothMinCubic,
SDFGroup.Companion.sdMax
), true), // A and B
DIFFERENCE1(2, "sdMax", listOf(
smoothMinCubic,
SDFGroup.Companion.sdMax
), true), // A \ B
DIFFERENCE2(3, "sdMax", listOf(
smoothMinCubic,
SDFGroup.Companion.sdMax
), true), // B \ A
DIFFERENCE_SYM(4, "sdDiff3", listOf(
smoothMinCubic,
SDFGroup.Companion.sdMin,
SDFGroup.Companion.sdMax,
SDFGroup.Companion.sdDiff1,
SDFGroup.Companion.sdDiff
), false), // A xor B
INTERPOLATION(5, "sdInt", listOf(SDFGroup.Companion.sdInt), false),
PIPE(10, "sdPipe", listOf(hgFunctions), false),
ENGRAVE(11, "sdEngrave", listOf(hgFunctions), false),
GROOVE(12, "sdGroove", listOf(hgFunctions), false),
TONGUE(13, "sdTongue", listOf(hgFunctions), false),
}
enum class Style(val id: Int) {
DEFAULT(0),
ROUND(1),
COLUMNS(2),
STAIRS(3),
CHAMFER(4),
SOFT(5),
}
var style = Style.DEFAULT
set(value) {
// probably should check whether the type is applied at all,
// whether we really need to invalidate the shader
if (field != value) {
invalidateShader()
field = value
}
}
override val children = ArrayList<SDFComponent>()
override fun getOptionsByType(type: Char) =
if (type == 'c') getOptionsByClass(this, SDFComponent::class)
else super.getOptionsByType(type)
override fun listChildTypes(): String = "c" + super.listChildTypes()
override fun getChildListNiceName(type: Char) = if (type == 'c') "Children" else super.getChildListNiceName(type)
override fun getChildListByType(type: Char) = if (type == 'c') children else super.getChildListByType(type)
override fun getTypeOf(child: PrefabSaveable): Char = if (child is SDFComponent) 'c' else super.getTypeOf(child)
override fun addChildByType(index: Int, type: Char, child: PrefabSaveable) {
if (child is SDFComponent) {
children.add(index, child)
child.parent = this
invalidateShader()
} else super.addChildByType(index, type, child)
}
override fun removeChild(child: PrefabSaveable) {
if (child is SDFComponent) children.remove(child)
invalidateShader()
super.removeChild(child)
}
override fun fill(
pipeline: Pipeline,
entity: Entity,
clickId: Int
): Int {
val clickId1 = super.fill(pipeline, entity, clickId)
return assignClickIds(this, clickId1)
}
private fun assignClickIds(sdf: SDFGroup, clickId0: Int): Int {
var clickId = clickId0
val children = sdf.children
for (i in children.indices) {
val child = children[i]
if (child.isEnabled) {
child.clickId = clickId++
if (child is SDFGroup) {
clickId = assignClickIds(child, clickId)
}
}
}
return clickId
}
var dynamicSmoothness = false
set(value) {
if (field != value) {
field = value
invalidateShader()
}
}
@Range(0.0, 1e38)
var smoothness = 0f
set(value) {
if (field != value &&
!dynamicSmoothness &&
type != CombinationMode.INTERPOLATION
) invalidateShader()
field = value
}
// currently this is always dynamic -> no shader check needed
@Range(0.0, 2e9)
var progress = 0.5f
set(value) {
if (field != value) {
if (type == CombinationMode.INTERPOLATION) invalidateBounds()
field = value
}
}
var type = CombinationMode.UNION
set(value) {
if (field != value) {
invalidateShader()
field = value
}
}
@Range(0.0, 1e38)
var numStairs = 5f
@Range(0.0, 1e38)
var groove = Vector2f(0.1f)
set(value) {
field.set(value)
}
private val numActiveChildren get() = children.count { it.isEnabled }
override fun calculateBaseBounds(dst: AABBf) {
// for now, just use the worst case
calculateBaseBounds(dst, children)
}
fun calculateBaseBounds(dst: AABBf, children: List<SDFComponent>) {
when (val size = children.count { it.isEnabled }) {
0 -> {}
1 -> children.first { it.isEnabled }.calculateBounds(dst)
else -> {
val tmp = JomlPools.aabbf.create()
when (type) {
// we could try to subtract one bbx from another
// we also probably should merge all others first, so the subtraction is maximal
// -> no, a bbx is a BOUNDING box: the actually subtracted amount may be smaller
// ... we could set a flag, whether we're allowed to subtract :)
CombinationMode.DIFFERENCE1,
CombinationMode.ENGRAVE,
CombinationMode.GROOVE -> { // use first only, the rest is cut off
children.first { it.isEnabled }.calculateBounds(dst)
if (type == CombinationMode.GROOVE) dst.addMargin(smoothness)
}
CombinationMode.TONGUE -> { // use first only, then widen
children.first { it.isEnabled }.calculateBounds(dst)
dst.addMargin(smoothness)
}
CombinationMode.DIFFERENCE2 -> {// use last only, the rest is cut off
children.last { it.isEnabled }.calculateBounds(dst)
}
// for interpolation only use meshes with weight > 0f
// is it possible to interpolate bounds? maybe
CombinationMode.INTERPOLATION -> {
dst.setMin(0f, 0f, 0f)
dst.setMax(0f, 0f, 0f)
val progress = clamp(progress, 0f, children.size - 1f)
var activeIndex = -1
for (childIndex in 0 until size) {
val child = children[childIndex]
if (child.isEnabled) {
activeIndex++
val weight = 1f - abs(progress - activeIndex)
if (weight > 0f) {
tmp.clear()
child.calculateBounds(tmp)
dst.minX += tmp.minX * weight
dst.minY += tmp.minY * weight
dst.minZ += tmp.minZ * weight
dst.maxX += tmp.maxX * weight
dst.maxY += tmp.maxY * weight
dst.maxZ += tmp.maxZ * weight
}
}
}
}
// difference sym-s bounds are only smaller, if the two objects are identical,
// so they get cancelled out ... why would sb want this? idk -> ignore that case
CombinationMode.UNION,
CombinationMode.DIFFERENCE_SYM -> {
dst.clear()
for (childIndex in children.indices) {
val child = children[childIndex]
if (child.isEnabled) {
tmp.clear()
child.calculateBounds(tmp)
dst.union(tmp)
}
}
}
CombinationMode.PIPE,
CombinationMode.INTERSECTION -> {
dst.all()
for (childIndex in children.indices) {
val child = children[childIndex]
if (child.isEnabled) {
tmp.clear()
child.calculateBounds(tmp)
dst.intersect(tmp)
}
}
if (type == CombinationMode.PIPE) dst.addMargin(smoothness)
}
}
JomlPools.aabbf.sub(1)
}
}
}
override fun buildShader(
builder: StringBuilder,
posIndex0: Int,
nextVariableId: VariableCounter,
dstIndex: Int,
uniforms: HashMap<String, TypeValue>,
functions: HashSet<String>,
seeds: ArrayList<String>
) {
val children = children
buildShader1(builder, posIndex0, nextVariableId, dstIndex, uniforms, functions, seeds, children, true)
}
fun buildShader1(
builder: StringBuilder,
posIndex0: Int, nextVariableId: VariableCounter, dstIndex: Int,
uniforms: HashMap<String, TypeValue>, functions: HashSet<String>,
seeds: ArrayList<String>, children: List<SDFComponent>,
applyTransform: Boolean
) {
val enabledChildCount = children.count { it.isEnabled }
if (enabledChildCount > 0) {
val type = type
val transform = if (applyTransform) buildTransform(builder, posIndex0, nextVariableId, uniforms, functions, seeds) else null
val posIndex = transform?.posIndex ?: posIndex0
if (enabledChildCount == 1) {
// done ^^
children.first2 { it.isEnabled }
.buildShader(builder, posIndex, nextVariableId, dstIndex, uniforms, functions, seeds)
} else {
val tmpIndex = nextVariableId.next()
builder.append("vec4 res").append(tmpIndex).append(";\n")
if (type == CombinationMode.INTERPOLATION) {
appendInterpolation(
builder, posIndex, tmpIndex, nextVariableId,
dstIndex, uniforms, functions, seeds,
children
)
} else {
val (funcName, smoothness, groove, stairs) = appendGroupHeader(functions, uniforms, type, style)
var activeIndex = -1
for (index in children.indices) {
val child = children[index]
if (!child.isEnabled) continue
activeIndex++
child.buildShader(
builder, posIndex, nextVariableId,
if (activeIndex == 0) dstIndex else tmpIndex,
uniforms, functions, seeds
)
if (activeIndex > 0) {
appendMerge(builder, dstIndex, tmpIndex, funcName, smoothness, groove, stairs)
}
}
}
}
// first scale or offset? offset, because it was applied after scaling
if (transform != null) buildTransformCorrection(builder, transform, dstIndex, uniforms)
buildDistanceMapperShader(builder, posIndex, dstIndex, nextVariableId, uniforms, functions, seeds)
} else {
builder.append("res").append(dstIndex).append("=vec4(Infinity,-1.0,0.0,0.0);\n")
buildDistanceMapperShader(builder, posIndex0, dstIndex, nextVariableId, uniforms, functions, seeds)
}
}
fun buildTransformCorrection(
builder: StringBuilder,
trans: SDFTransform,
dstIndex: Int,
uniforms: HashMap<String, TypeValue>
) {
val offsetName = trans.offsetName
val scaleName = trans.scaleName
if (offsetName != null)
builder.append("res").append(dstIndex).append(".x+=").append(offsetName).append(";\n")
if (scaleName != null)
builder.append("res").append(dstIndex).append(".x*=").append(scaleName).append(";\n")
if (localReliability != 1f)
builder.append("res").append(dstIndex).append(".x*=")
.appendUniform(uniforms, GLSLType.V1F) { localReliability }.append(";\n")
}
fun appendInterpolation(
builder: StringBuilder,
posIndex: Int, tmpIndex: Int,
nextVariableId: VariableCounter,
dstIndex: Int,
uniforms: HashMap<String, TypeValue>,
functions: HashSet<String>,
seeds: ArrayList<String>,
children: List<SDFComponent>
) {
val param1 = SDFComponent.Companion.defineUniform(uniforms, GLSLType.V1F) {
clamp(
progress,
0f,
children.size - 1f
)
}
// helper functions
functions.addAll(type.glslCode)
val weightIndex = nextVariableId.next()
builder.append("res").append(dstIndex).append("=vec4(Infinity,-1.0,0.0,0.0);\n")
builder.append("float w").append(weightIndex).append(";\n")
var activeIndex = 0
for (index in children.indices) {
val child = children[index]
if (!child.isEnabled) continue
// calculate weight and only compute child if weight > 0
builder.append('w').append(weightIndex)
builder.append("=1.0-abs(").append(param1).append('-').append(activeIndex).append(".0);\n")
//builder.append("if(w").append(weightIndex).append(" > 0.0){\n")
child.buildShader(builder, posIndex, nextVariableId, tmpIndex, uniforms, functions, seeds)
// assign material if this is the most dominant
val needsCondition = activeIndex > 0
if (needsCondition) builder.append("if(w").append(weightIndex).append(" >= 0.5){\n")
builder.append("res").append(dstIndex).append(".yzw=res").append(tmpIndex).append(".yzw;\n")
if (needsCondition) builder.append("}\n")
builder.append("res").append(dstIndex)
.append(if (needsCondition) ".x+=w" else ".x=w").append(weightIndex)
.append("*res").append(tmpIndex)
.append(".x;\n")
activeIndex++
}
}
fun appendGroupHeader(
functions: HashSet<String>,
uniforms: HashMap<String, TypeValue>,
type: CombinationMode,
style: Style,
): Quad<String, String?, String?, String?> {
functions.add(smoothMinCubic)
val useSmoothness = dynamicSmoothness || smoothness > 0f
|| (style != Style.DEFAULT && type.isStyleable) ||
when (type) {// types that require smoothness
CombinationMode.PIPE,
CombinationMode.ENGRAVE,
CombinationMode.GROOVE,
CombinationMode.TONGUE -> true
else -> false
}
val smoothness = if (useSmoothness) SDFComponent.Companion.defineUniform(
uniforms,
GLSLType.V1F
) { smoothness } else null
// helper functions
functions.addAll(type.glslCode)
val funcName = when (type) {
// if is styleable type, apply style
CombinationMode.UNION -> {
if (style != Style.DEFAULT) functions.add(hgFunctions)
when (style) {
Style.COLUMNS -> "unionColumn"
Style.CHAMFER -> "unionChamfer"
Style.ROUND -> "unionRound"
Style.SOFT -> "unionSoft"
Style.STAIRS -> "unionStairs"
else -> "sdMin"
}
}
CombinationMode.INTERSECTION,
CombinationMode.DIFFERENCE1,
CombinationMode.DIFFERENCE2 -> {
if (style != Style.DEFAULT) functions.add(hgFunctions)
when (style) {
Style.COLUMNS -> "interColumn"
Style.CHAMFER -> "interChamfer"
Style.ROUND -> "interRound"
Style.STAIRS -> "interStairs"
// no other types are supported
else -> "sdMax"
}
}
else -> type.funcName
}
val groove = if (type == CombinationMode.GROOVE || type == CombinationMode.TONGUE) {
SDFComponent.Companion.defineUniform(uniforms, groove)
} else null
val stairs = if (
funcName.contains("column", true) ||
funcName.contains("stairs", true)
) {
SDFComponent.Companion.defineUniform(uniforms, GLSLType.V1F) { numStairs + 1f }
} else null
return Quad(funcName, smoothness, groove, stairs)
}
fun appendMerge(
builder: StringBuilder,
dstIndex: Int,
tmpIndex: Int,
funcName: String,
smoothness: String?,
groove: String?,
stairs: String?
) {
// we need to merge two values
builder.append("res").append(dstIndex)
builder.append('=')
builder.append(funcName)
builder.append('(')
if (type == CombinationMode.DIFFERENCE2) {
builder.appendMinus(dstIndex)
} else {
builder.append("res").append(dstIndex)
}
builder.append(',')
if (type == CombinationMode.DIFFERENCE1) builder.appendMinus(tmpIndex)
else builder.append("res").append(tmpIndex)
when {
groove != null -> builder.append(',').append(groove)
smoothness != null -> builder.append(',').append(smoothness)
}
if (stairs != null) {
builder.append(',').append(stairs)
}
builder.append(");\n")
}
override fun computeSDFBase(pos: Vector4f, seeds: IntArrayList): Float {
return when (children.count2 { it.isEnabled }) {
0 -> Float.POSITIVE_INFINITY
1 -> {
val pw = pos.w
pos.w = 0f
return (children.first { it.isEnabled }.computeSDF(pos, seeds) + pw) * scale
}
else -> {
val pw = pos.w
var d0 = Float.POSITIVE_INFINITY
val px = pos.x
val py = pos.y
val pz = pos.z
val k = smoothness
val progress = progress
val type = type
var activeIndex = -1
for (index in children.indices) {
val child = children[index]
if (!child.isEnabled) continue
activeIndex++
if (type == CombinationMode.INTERPOLATION) {
if (activeIndex == 0) d0 = 0f
val weight = 1f - abs(progress - activeIndex)
if (weight > 0f) {
pos.set(px, py, pz, 0f)
val d1 = child.computeSDF(pos, seeds)
d0 += d1 * weight
}// we could maybe exit early...
} else {
pos.set(px, py, pz, 0f)
val d1 = child.computeSDF(pos, seeds)
d0 = if (activeIndex == 0) d1
else when (type) {
CombinationMode.UNION -> sMinCubic(
d0,
d1,
k
)
CombinationMode.INTERSECTION -> sMaxCubic(
d0,
d1,
k
)
CombinationMode.DIFFERENCE1 -> sMaxCubic(
+d0,
-d1,
k
)
CombinationMode.DIFFERENCE2 -> sMaxCubic(
-d0,
+d1,
k
)
CombinationMode.DIFFERENCE_SYM -> sMaxCubic(
sMinCubic(d0, d1, k),
-sMaxCubic(d0, d1, k),
k
)
CombinationMode.INTERPOLATION -> {
if (activeIndex == 1) d0 *= max(1f - abs(progress), 0f)
d0 + d1 * max(1f - abs(progress - activeIndex), 0f)
}
CombinationMode.PIPE -> length(d0, d1) - smoothness
CombinationMode.TONGUE -> {
val g = groove
min(d0, max(d0 - g.x, abs(d1) - g.y))
}
CombinationMode.GROOVE -> {
val g = groove
max(d0, min(d0 + g.x, g.y - abs(d1)))
}
CombinationMode.ENGRAVE -> {
max(d0, (d0 + smoothness - abs(d1)) * SQRT1_2f)
}
}
}
}
return (d0 + pw) * scale
}
}
}
override fun findClosestComponent(pos: Vector4f, seeds: IntArrayList): SDFComponent {
val children = children
return when (children.count2 { it.isEnabled }) {
0 -> this
1 -> {
applyTransform(pos, seeds)
children.first { it.isEnabled }.findClosestComponent(pos, seeds)
}
else -> {
applyTransform(pos, seeds)
val px = pos.x
val py = pos.y
val pz = pos.z
val progress = progress
// to do best match the GPU implementation, so we get equal results
when (type) {
CombinationMode.UNION,
CombinationMode.PIPE,
CombinationMode.INTERSECTION,
CombinationMode.DIFFERENCE1,
CombinationMode.DIFFERENCE2,
CombinationMode.DIFFERENCE_SYM -> {
// find the closest child
val bestChild = children
.filter { it.isEnabled }
.minByOrNull {
pos.set(px, py, pz, 0f)
abs(it.computeSDF(pos, seeds))
}!!
pos.set(px, py, pz, 0f)
return bestChild.findClosestComponent(pos, seeds)
}
CombinationMode.INTERPOLATION -> {
// child with the largest weight
pos.set(px, py, pz, 0f)
val enabled = children.filter { it.isEnabled }
return enabled[clamp(progress.roundToInt(), 0, enabled.lastIndex)]
.findClosestComponent(pos, seeds)
}
CombinationMode.ENGRAVE,
CombinationMode.GROOVE,
CombinationMode.TONGUE -> {
var bestComp: SDFComponent? = null
val k = groove.y
for (index in children.indices) {
val child = children[index]
if (child.isEnabled) {
pos.set(px, py, pz, 0f)
val distance = child.computeSDF(pos, seeds)
if (bestComp == null || abs(distance) < k) {
pos.set(px, py, pz, 0f)
bestComp = child.findClosestComponent(pos, seeds)
}
}
}
return bestComp!!
}
}
}
}
}
override fun findDrawnSubject(searchedId: Int): Any? {
val children = children
for (i in children.indices) {
val child = children[i]
if (child.isEnabled) {
// LOGGER.debug("[S] ${child.clickId.toString(16)} vs ${searchedId.toString(16)}")
if (child.clickId == searchedId) return child
if (child is SDFGroup) {
val found = child.findDrawnSubject(searchedId)
if (found != null) return found
}
}
}
return null
}
override fun onUpdate(): Int {
super.onUpdate()
val children = children
for (index in children.indices) {
val child = children[index]
if (child.isEnabled) child.onUpdate()
}
return 1
}
override fun copyInto(dst: PrefabSaveable) {
super.copyInto(dst)
dst as SDFGroup
dst.smoothness = smoothness
dst.progress = progress
dst.type = type
dst.style = style
dst.groove.set(groove)
dst.numStairs = numStairs
dst.dynamicSmoothness = dynamicSmoothness
dst.children.clear()
dst.children.addAll(children.map {
val child = it.clone() as SDFComponent
child.parent = dst
child
})
}
override val className: String get() = "SDFGroup"
companion object {
fun sMinCubic(a: Float, b: Float, k: Float): Float {
if (k <= 0f) return min(a, b)
val h = max(k - abs(a - b), 0f) / k
val m = h * h * h * 0.5f
val s = m * k / 3f
return min(a, b) - s
}
fun sMaxCubic(a: Float, b: Float, k: Float): Float {
if (k <= 0f) return max(a, b)
val h = max(k - abs(a - b), 0f) / k
val m = h * h * h * 0.5f
val s = m * k / 3f
return max(a, b) + s
}
const val hgFunctions = "" +
// some of these types could use an additional material index for the intersection...
// but we'll change the material system anyway
"void pR45(inout vec2 p) {\n" +
" p = (p + vec2(p.y, -p.x))*sqrt(0.5);\n" +
"}\n" +
"float pMod1(inout float p, float size) {\n" +
" float halfSize = size * 0.5;\n" +
" float c = round(p/size);\n" +
" p = mod(p + halfSize, size) - halfSize;\n" +
" return c;\n" +
"}\n" +
"float unionChamfer(float a, float b, float r){\n" +
" return min(min(a,b),(a+b-r)*sqrt(0.5));\n" +
"}\n" +
"vec4 unionChamfer(vec4 a, vec4 b, float r){\n" +
" return vec4(unionChamfer(a.x,b.x,r),a.x+r<b.x?a.yzw:b.yzw);\n" +
"}\n" +
"float interChamfer(float a, float b, float r){\n" +
" return max(max(a,b),(a+b+r)*sqrt(0.5));\n" +
"}\n" +
"vec4 interChamfer(vec4 a, vec4 b, float r){\n" +
" return vec4(interChamfer(a.x,b.x,r),a.x>b.x?a.yzw:b.yzw);\n" +
"}\n" +
"float diffChamfer(float a, float b, float r){\n" +
" return interChamfer(a,-b,r);\n" +
"}\n" +
// quarter circle
"float unionRound(float a, float b, float r){\n" +
" vec2 u = max(r-vec2(a,b), vec2(0.0));\n" +
" return max(r,min(a,b)) - length(u);\n" +
"}\n" +
"vec4 unionRound(vec4 a, vec4 b, float r){\n" +
" return vec4(unionRound(a.x,b.x,r),a.x<b.x?a.yzw:b.yzw);\n" +
"}\n" +
"float interRound(float a, float b, float r){\n" +
" vec2 u = max(r+vec2(a,b), vec2(0.0));\n" +
" return min(-r,max(a,b)) + length(u);" +
"}\n" +
"vec4 interRound(vec4 a, vec4 b, float r){\n" +
" return vec4(interRound(a.x,b.x,r),a.x>b.x?a.yzw:b.yzw);\n" +
"}\n" +
"float diffRound(float a, float b, float r){\n" +
" return interRound(a,-b,r);\n" +
"}\n" +
// n-1 circular columns at 45° angle
"float unionColumn(float a, float b, float r, float n){\n" +
" if ((a < r) && (b < r)) {\n" +// todo is there a way to make this smooth over n?
" vec2 p = vec2(a, b);\n" +
" float columnRadius = r*sqrt(2.0)/((n-1.0)*2.0+sqrt(2.0));\n" +
" pR45(p);\n" +
" p.x -= sqrt(0.5)*r;\n" +
" p.x += columnRadius*sqrt(2.0);\n" +
" if (mod(n,2.0) >= 1.0) {\n" + // mmh..
" p.y += columnRadius;\n" +
" }\n" +
// At this point, we have turned 45 degrees and moved at a point on the
// diagonal that we want to place the columns on.
// Now, repeat the domain along this direction and place a circle.
" pMod1(p.y, columnRadius*2.0);\n" +
" return min(length(p) - columnRadius, min(p.x, a));\n" +
" } else return min(a, b);\n" + // saving computations
"}\n" +
"vec4 unionColumn(vec4 a, vec4 b, float r, float n){\n" +
// +r*(1.0-1.0/n)
" return vec4(unionColumn(a.x,b.x,r,n),a.x<b.x?a.yzw:b.yzw);\n" +
"}\n" +
// todo inter-column would need to have it's sign reversed...
"float interColumn(float a, float b, float r, float n){\n" +
" return -unionColumn(-a,-b,r,n);\n" +
"}\n" +
"vec4 interColumn(vec4 a, vec4 b, float r, float n){\n" +
" return vec4(interColumn(a.x,b.x,r,n),a.x>b.x?a.yzw:b.yzw);\n" +
"}\n" +
"float unionStairs(float a, float b, float r, float n){\n" +
" float s = r/n;\n" +
" float u = b-r;\n" +
" return min(min(a,b), 0.5*(u+a+abs((mod(u-a+s, 2.0*s))-s)));" +
"}\n" +
"vec4 unionStairs(vec4 a, vec4 b, float r, float n){\n" +
// +r*(1.0-1.0/n)
" return vec4(unionStairs(a.x,b.x,r,n),a.x<b.x?a.yzw:b.yzw);\n" +
"}\n" +
"float interStairs(float a, float b, float r, float n){\n" +
" return -unionStairs(-a,-b,r,n);\n" +
"}\n" +
"vec4 interStairs(vec4 a, vec4 b, float r, float n){\n" +
" return vec4(interStairs(a.x,b.x,r,n),a.x>b.x?a.yzw:b.yzw);\n" +
"}\n" +
"float unionSoft(float a, float b, float r){\n" +
" if(r <= 0.0) return min(a,b);\n" +
" float e = max(r-abs(a-b),0.0);\n" +
" return min(a,b)-e*e*0.25/r;\n" +
"}\n" +
"vec4 unionSoft(vec4 a, vec4 b, float r){\n" +
" return vec4(unionSoft(a.x,b.x,r),a.x<b.x?a.yzw:b.yzw);\n" +
"}\n" +
"float sdEngrave(float a, float b, float r){\n" +
" return max(a,(a+r-abs(b))*sqrt(0.5));\n" +
"}\n" +
"vec4 sdEngrave(vec4 a, vec4 b, float r){\n" +
" return vec4(sdEngrave(a.x,b.x,r),abs(b.x)<r?b.yzw:a.yzw);\n" +
"}\n" +
"float sdGroove(float a, float b, vec2 r){\n" +
" return max(a,min(a+r.x,r.y-abs(b)));\n" +
"}\n" +
"vec4 sdGroove(vec4 a, vec4 b, vec2 r){\n" +
" return vec4(sdGroove(a.x,b.x,r),abs(b.x)<r.y?b.yzw:a.yzw);\n" +
"}\n" +
"float sdTongue(float a, float b, vec2 r){\n" +
" return min(a,max(a-r.x,abs(b)-r.y));\n" +
"}\n" +
"vec4 sdTongue(vec4 a, vec4 b, vec2 r){\n" +
" return vec4(sdTongue(a.x,b.x,r),abs(b.x)<r.y?b.yzw:a.yzw);\n" +
"}\n" +
"float sdPipe(float a, float b, float r){\n" +
" return length(vec2(a,b))-r;\n" +
"}\n" +
"vec4 sdPipe(vec4 a, vec4 b, float r){\n" +
" return vec4(sdPipe(a.x,b.x,r),a.x<b.x?a.yzw:b.yzw);\n" +
"}\n"
const val smoothMinCubic = "" +
// to do when we have material colors, use the first one as mixing parameter
// inputs: sd.a, sd.b, k
// outputs: sd.mix, mix factor
"vec2 sMinCubic(float a, float b, float k){\n" +
" float h = max(k-abs(a-b), 0.0)/k;\n" +
" float m = h*h*h*0.5;\n" +
" float s = m*k*(1.0/3.0); \n" +
" return (a<b) ? vec2(a-s,m) : vec2(b-s,1.0-m);\n" +
"}\n" +
"vec2 sMaxCubic(float a, float b, float k){\n" +
" float h = max(k-abs(a-b), 0.0)/k;\n" +
" float m = h*h*h*0.5;\n" +
" float s = m*k*(1.0/3.0); \n" +
" return (a>b) ? vec2(a+s,m) : vec2(b+s,1.0-m);\n" +
"}\n" +
// inputs: sd.a, sd.b, k
// outputs: sd.mix
"float sMinCubic1(float a, float b, float k){\n" +
" if(k <= 0.0) return min(a,b);\n" +
" float h = max(k-abs(a-b), 0.0)/k;\n" +
" float m = h*h*h*0.5;\n" +
" float s = m*k*(1.0/3.0); \n" +
" return min(a,b)-s;\n" +
"}\n" +
"float sMaxCubic1(float a, float b, float k){\n" +
" if(k <= 0.0) return max(a,b);\n" +
" float h = max(k-abs(a-b), 0.0)/k;\n" +
" float m = h*h*h*0.5;\n" +
" float s = m*k*(1.0/3.0); \n" +
" return max(a,b)+s;\n" +
"}\n" +
// inputs: sd/m1, sd/m2, k
// outputs: sd/m-mix
"vec4 sMinCubic2(vec4 a, vec4 b, float k){\n" +
" if(k <= 0.0) return (a.x<b.x) ? a : b;\n" +
" float h = max(k-abs(a.x-b.x), 0.0)/k;\n" +
" float m = h*h*h*0.5;\n" +
" float s = m*k*(1.0/3.0); \n" +
" return (a.x<b.x) ? vec4(a.x-s,a.yzw) : vec4(b.x-s,b.yzw);\n" +
"}\n" +
"vec4 sMaxCubic2(vec4 a, vec4 b, float k){\n" +
" if(k <= 0.0) return (a.x>b.x) ? a : b;\n" +
" float h = max(k-abs(a.x-b.x), 0.0)/k;\n" +
" float m = h*h*h*0.5;\n" +
" float s = m*k*(1.0/3.0); \n" +
" return (a.x>b.x) ? vec4(a.x+s,a.yzw) : vec4(b.x+s,b.yzw);\n" +
"}\n"
const val sdMin = "" +
"float sdMin3(float a, float b, float c){ return min(a,min(b,c)); }\n" +
"float sdMin3(float a, float b, float c, float k){ return sMinCubic1(a,sMinCubic1(b,c,k),k); }\n" +
"float sdMin(float d1, float d2){ return min(d1,d2); }\n" +
"vec4 sdMin(vec4 d1, vec4 d2){ return d1.x < d2.x ? d1 : d2; }\n" +
"vec4 sdMin(vec4 d1, vec4 d2, float k){ return sMinCubic2(d1,d2,k); }\n"
const val sdMax = "" +
"float sdMax(float d1, float d2){ return max(d1,d2); }\n" +
"vec4 sdMax(vec4 d1, vec4 d2){ return d1.x < d2.x ? d2 : d1; }\n" +
"float sdMax(float d1, float d2, float k){ return sMaxCubic1(d1,d2,k); }\n" +
"vec4 sdMax(vec4 d1, vec4 d2, float k){ return sMaxCubic2(d1,d2,k); }\n"
const val sdDiff = "" +
"vec4 sdDiff3(vec4 d1, vec4 d2){\n" +
" vec4 e1 = sdMin(d1,d2);\n" +
" vec4 e2 = sdMax(d1,d2);\n" +
" return sdDiff1(e1,e2); }\n" +
"vec4 sdDiff3(vec4 d1, vec4 d2, float k){\n" +
" vec4 e1 = sdMin(d1,d2,k);\n" +
" vec4 e2 = sdMax(d1,d2,k);\n" +
" return sdDiff1(e1,e2,k); }\n"
const val sdDiff1 = "" + // max(+-)
"float sdDiff1(float d1, float d2){ return max(d1, -d2); }\n" +
"float sdDiff1(float d1, float d2, float k){ return sdMax(d1, -d2, k); }\n" +
"vec4 sdDiff1(vec4 d1, vec4 d2){ return sdMax(d1, vec4(-d2.x, d2.yzw)); }\n" +
"vec4 sdDiff1(vec4 d1, vec4 d2, float k){ return sdMax(d1, vec4(-d2.x, d2.yzw), k); }\n"
const val sdInt = "vec4 sdInt(vec4 sum, vec4 di, float weight){\n" +
"weight = 1.0-abs(weight);\n" +
"if(weight < 0.0) return sum;\n" +
"return vec4(sum.x + di.x * weight, weight >= 0.5 ? di.yzw : sum.yzw); }\n"
}
} | 0 | Kotlin | 3 | 9 | 94bc7c74436aa567ec3c19f386dd67af0f1ced00 | 39,190 | RemsEngine | Apache License 2.0 |
library/src/androidTest/java/io/setapp/android/settings/client/SettingsMockContentResolver.kt | setapp-io | 411,024,636 | false | {"Kotlin": 29346, "Shell": 536} | package io.setapp.android.settings.client
import android.test.mock.MockContentResolver
internal class SettingsMockContentResolver : MockContentResolver()
| 0 | Kotlin | 0 | 3 | c89362fbb6131b0b663a21fbf9fe06b4cf14f36c | 156 | setapp-android-sdk | Apache License 2.0 |
compiler/testData/diagnostics/tests/PrimaryConstructors.kt | JakeWharton | 99,388,807 | false | null | // FIR_DISABLE_LAZY_RESOLVE_CHECKS
// FIR_IDENTICAL
class X {
<!MUST_BE_INITIALIZED_OR_BE_ABSTRACT!>val x : Int<!>
}
open class Y() {
val x : Int = 2
}
class Y1 {
val x : Int get() = 1
}
class Z : Y() {
}
//KT-650 Prohibit creating class without constructor.
class MyIterable<T> : Iterable<T>
{
override fun iterator(): Iterator<T> = MyIterator()
inner class MyIterator : Iterator<T>
{
override fun hasNext(): Boolean = false
override fun next(): T {
throw UnsupportedOperationException()
}
}
} | 7 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 559 | kotlin | Apache License 2.0 |
ripple-core/src/test/java/com/ripple/crypto/keys/IVerifyingKeyTest.kt | sublimator | 16,341,429 | false | null | package com.ripple.crypto.keys
import com.ripple.crypto.Seed
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class IVerifyingKeyTest {
@Test
fun fromEd25519Test() {
val seed = Seed.fromPassPhrase("niq")
.setEd25519()
helper(seed, { key ->
assertEquals(0xED.toByte(), key.canonicalPubBytes()[0])
})
}
@Test
fun fromK256Test() {
val seed = Seed.fromPassPhrase("niq")
helper(seed, { key ->
assertEquals(0x2.toByte(), key.canonicalPubBytes()[0])
})
}
private fun helper(seed: Seed, block: ((verifier: IVerifyingKey) -> Unit)? = null) {
val pair = seed.keyPair()
val message = byteArrayOf(0xb, 0xe, 0xe, 0xf)
val signature = pair.signMessage(message)
val verifier = IVerifyingKey.from(pair.canonicalPubBytes())
assertTrue(verifier.verify(message, signature))
if (block != null) {
block(verifier)
}
}
} | 17 | null | 7 | 7 | 909f983d9cfb379591d3b1abf6622840e4ffd2d1 | 1,047 | ripple-lib-java | ISC License |
src/main/kotlin/frc/chargers/hardware/sensors/imu/IMUSimulation.kt | frc-5160-the-chargers | 497,722,545 | false | {"Kotlin": 438322, "Java": 56704} | package frc.chargers.hardware.sensors.imu
import com.batterystaple.kmeasure.quantities.Angle
import edu.wpi.first.math.kinematics.ChassisSpeeds
/**
* Configures simulation for all IMUs.
*/
public fun configureIMUSimulation(
headingSupplier: () -> Angle = { Angle(0.0) },
chassisSpeedsSupplier: () -> ChassisSpeeds = { ChassisSpeeds() },
){
getSimChassisSpeeds = chassisSpeedsSupplier
getSimHeading = headingSupplier
}
internal var getSimChassisSpeeds: () -> ChassisSpeeds = { ChassisSpeeds() }
internal var getSimHeading: () -> Angle = { Angle(0.0) } | 3 | Kotlin | 0 | 2 | ef0bca03f00901ffcc5508981089edced59f91aa | 571 | ChargerLib | MIT License |
shared/src/commonMain/kotlin/engine/components/Card.kt | Startappz | 678,331,232 | false | null | package engine.components
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Card
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import io.kamel.image.KamelImage
import io.kamel.image.asyncPainterResource
import model.ItemView
import model.UiConfigurationContainerData
import model.UiConfigurationContainerDataItem
object Card {
@Composable
fun CardItem(
itemType: ItemView,
data: UiConfigurationContainerData,
content: @Composable (itemType: ItemView, page: Int) -> Unit,
) {
Card(
modifier = Modifier,
) {
}
}
// @OptIn(ExperimentalLayoutApi::class)
// @Composable
// fun ProductItem(
// modifier: Modifier = Modifier,
// product: ProductItemUiState,
// navigateToProductDetails: (String) -> Unit,
// ) {
// Card(
// modifier = modifier
// .fillMaxWidth()
// .padding(vertical = 12.dp, horizontal = 16.dp)
// .clickable { },
// ) {
// Row {
// Column(
// modifier = Modifier
// .width(128.dp)
// .padding(end = 16.dp),
//
// ) {
// KamelImage(
// modifier = Modifier.size(width = 98.dp, height = 123.dp),
// resource = asyncPainterResource(product.thumbnailUrl),
// contentDescription = product.name,
// onLoading = { CircularProgressIndicator(it) },
// onFailure = { Icon(
// modifier = Modifier.size(width = 98.dp, height = 123.dp),
// imageVector = Icons.Default.Close,
// contentDescription = null
// ) }
// )
//
// Spacer(modifier = Modifier.height(18.dp))
//
// FlowRow(
// modifier = Modifier.fillMaxWidth(),
// horizontalArrangement = Arrangement.Center,
// ) {
// product.colors.forEach {
// Box(
// modifier = Modifier
// .padding(2.dp)
// .size(8.dp)
// .clip(CircleShape)
// .background(it.asColor()),
// )
// }
// }
// }
//
// Column {
// Text(
// text = product.brand,
// color = MaterialTheme.colors.secondary,
// maxLines = 1,
// style = MaterialTheme.typography.body1
// )
//
// EcTextH3(text = product.name.take(20), maxLines = 1)
//
// Spacer(Modifier.height(6.dp))
//
// EcTextH6(
// text = stringResource(productR.string.ec_1_1_1_lbl_full_price),
// color = MaterialTheme.colorScheme.textPrimary,
// )
//
// EcTextH5(
// text = product.price,
// color = MaterialTheme.colorScheme.primary,
// )
//
// Box(
// Modifier
// .padding(top = 6.dp, bottom = 6.dp, end = 24.dp)
// .height(1.dp)
// .fillMaxWidth()
// .background(
// MaterialTheme.colorScheme.textSecondary,
// shape = DottedShape(step = 5.dp),
// ),
// )
//
// EcTextH6(
// text = stringResource(productR.string.ec_1_1_1_lbl_installment),
// color = MaterialTheme.colorScheme.textPrimary,
// )
//
// Row {
// EcTextH5(
// text = product.installmentPerMonth,
// color = MaterialTheme.colorScheme.primary,
// modifier = Modifier.alignByBaseline(),
// maxLines = 1,
// )
// EcTextH7(
// text = stringResource(productR.string.ec_1_1_1_lbl_monthly),
// modifier = Modifier.alignByBaseline(),
// maxLines = 1,
// )
// }
//
// Spacer(modifier = Modifier.size(14.dp))
//
// Row(
// modifier = Modifier.defaultMinSize(80.dp, 32.dp)
// .clip(CircleShape)
// .background(
// color = MaterialTheme.colors.primary,
// ),
// verticalAlignment = Alignment.CenterVertically,
// horizontalArrangement = Arrangement.Center,
// ) {
// EcTextH6(
// modifier = Modifier,
// text = stringResource(productR.string.ec_1_1_1_action_select),
// color = MaterialTheme.colorScheme.onPrimary,
// textAlign = TextAlign.Center,
// )
// }
// }
// }
// }
// }
}
| 0 | Kotlin | 0 | 0 | 02495bd9159fc03cb7fb9ef90d8111cd19e2bcfe | 7,154 | UIConfigurationParser | Apache License 2.0 |
pager/src/main/java/com/angcyo/pager/ViewTransitionCallback.kt | angcyo | 229,037,615 | false | null | package com.angcyo.pager
import android.graphics.Color
import android.graphics.Rect
import android.view.View
import android.view.ViewGroup
import androidx.transition.*
import com.angcyo.library.L
import com.angcyo.picker.R
import com.angcyo.transition.ColorTransition
import com.angcyo.widget.DslViewHolder
import com.angcyo.library.ex.setWidthHeight
/**
*
* Email:<EMAIL>
* @author angcyo
* @date 2020/01/22
*/
open class ViewTransitionCallback {
/**过渡延迟[postDelayed], 当结束状态加载需要一段加载时间时, 这个延迟就有很重要的作用
* [com.angcyo.pager.ViewTransitionFragment.initTransitionLayout] 预先加载[EndValues]需要的资源, 再启动转场.*/
var transitionShowDelay: Long = 0L
//var transitionHideDelay: Long = 0L
/**界面状态栏的颜色*/
var startBarColor: Int = Color.TRANSPARENT
/**根布局, 通常也是背景动画视图*/
var sceneRoot: ViewGroup? = null
var backgroundStartColor: Int = Color.TRANSPARENT
var backgroundEndColor: Int = Color.BLACK
var transitionShowFromRect: Rect? = null
var transitionShowToRect: Rect? = null
var transitionHideFromRect: Rect? = null
var transitionHideToRect: Rect? = null
/**过渡动画需要隐藏的视图id列表*/
var transitionOverlayViewIds = mutableListOf(
R.id.lib_transition_overlay_view,
R.id.lib_transition_overlay_view1,
R.id.lib_transition_overlay_view2,
R.id.lib_transition_overlay_view3,
R.id.lib_transition_overlay_view4,
R.id.lib_transition_overlay_view5,
R.id.lib_transition_overlay_view6,
R.id.lib_transition_overlay_view7,
R.id.lib_transition_overlay_view8,
R.id.lib_transition_overlay_view9
)
/**背景过渡视图*/
open fun backgroundTransitionView(viewHolder: DslViewHolder): View {
return sceneRoot ?: viewHolder.itemView
}
/**转场动画视图*/
open fun transitionTargetView(viewHolder: DslViewHolder): View? {
return null
}
//<editor-fold desc="show过渡">
/**界面显示时, 动画开始的值设置*/
open fun onCaptureShowStartValues(viewHolder: DslViewHolder) {
//背景颜色动画
backgroundTransitionView(viewHolder).setBackgroundColor(backgroundStartColor)
//转场动画 矩阵坐标设置
transitionTargetView(viewHolder)?.apply {
transitionShowFromRect?.let {
translationX = it.left.toFloat()
translationY = it.top.toFloat()
setWidthHeight(it.width(), it.height())
L.i("过渡从:$it")
}
}
//隐藏干扰元素
transitionOverlayViewIds.forEach {
viewHolder.gone(it)
}
}
/**界面显示时, 动画结束后的值设置*/
open fun onCaptureShowEndValues(viewHolder: DslViewHolder) {
backgroundTransitionView(viewHolder).setBackgroundColor(backgroundEndColor)
transitionTargetView(viewHolder)?.apply {
val x = (transitionShowToRect?.left ?: 0).toFloat()
val y = (transitionShowToRect?.top ?: 0).toFloat()
translationX = x
translationY = y
val w = transitionShowToRect?.width() ?: -1
val h = transitionShowToRect?.height() ?: -1
setWidthHeight(w, h)
L.i("过渡到:x:$x y:$y w:$w, h:$h")
}
transitionOverlayViewIds.forEach {
viewHolder.visible(it)
}
}
/**开始show的转场动画, 返回true, 拦截过渡*/
open fun onStartShowTransition(
fragment: ViewTransitionFragment,
viewHolder: DslViewHolder
): Boolean {
return false
}
open fun onSetShowTransitionSet(
viewHolder: DslViewHolder,
transitionSet: TransitionSet
): TransitionSet {
transitionSet.apply {
//.addTarget(backgroundTransitionView(viewHolder))
addTransition(ColorTransition())
//addTransition(Fade(Fade.OUT))
addTransition(ChangeBounds())
addTransition(ChangeTransform())
addTransition(ChangeImageTransform())
addTransition(ChangeClipBounds())
addTransition(Fade(Fade.IN))
}
return transitionSet
}
//</editor-fold desc="show过渡">
//<editor-fold desc="hide过渡">
/**界面关闭, 动画开始时的值(通过可以不设置此处)*/
open fun onCaptureHideStartValues(viewHolder: DslViewHolder) {
//backgroundTransitionView(viewHolder).setBackgroundColor(backgroundEndColor)
//就是用当前设置的背景颜色
transitionTargetView(viewHolder)?.apply {
//关闭Outline, 这个很重要. 否则只能看到[View]的一部分
this.clipToOutline = false
visibility = View.VISIBLE
transitionHideFromRect?.let {
translationX = it.left.toFloat()
translationY = it.top.toFloat()
setWidthHeight(it.width(), it.height())
L.i("隐藏从:$it")
}
}
//隐藏干扰元素
transitionOverlayViewIds.forEach {
viewHolder.gone(it)
}
}
/**界面关闭, 动画需要结束的值*/
open fun onCaptureHideEndValues(viewHolder: DslViewHolder) {
backgroundTransitionView(viewHolder).setBackgroundColor(backgroundStartColor)
transitionTargetView(viewHolder)?.apply {
transitionHideToRect?.let {
translationX = it.left.toFloat()
translationY = it.top.toFloat()
setWidthHeight(it.width(), it.height())
L.i("隐藏到:$it")
}
}
}
/**开始hide的转场动画, 返回true, 拦截过渡*/
open fun onStartHideTransition(
fragment: ViewTransitionFragment,
viewHolder: DslViewHolder
): Boolean {
return false
}
open fun onSetHideTransitionSet(
viewHolder: DslViewHolder,
transitionSet: TransitionSet
): TransitionSet {
transitionSet.apply {
//.addTarget(backgroundTransitionView(viewHolder))
addTransition(ColorTransition())
addTransition(ChangeBounds())
addTransition(ChangeTransform())
addTransition(ChangeImageTransform())
addTransition(ChangeClipBounds())
addTransition(Fade(Fade.OUT))
//addTransition(Fade(Fade.IN))
}
return transitionSet
}
//</editor-fold desc="hide过渡">
//<editor-fold desc="事件回调">
var initFragment: (fragment: ViewTransitionFragment) -> Unit = {}
//</editor-fold desc="事件回调">
}
| 0 | null | 6 | 5 | 73c1ad1bef2dbaeb3cafe412f34c741da288e934 | 6,281 | UICore | MIT License |
node-kotlin/src/jsMain/kotlin/node/fs/rmdirSync.kt | karakum-team | 393,199,102 | false | {"Kotlin": 7083457} | // Automatically generated - do not modify!
@file:JsModule("node:fs")
package node.fs
/**
* Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`.
*
* Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error
* on Windows and an `ENOTDIR` error on POSIX.
*
* To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`.
* @since v0.1.21
*/
external fun rmdirSync(
path: PathLike,
options: RmDirOptions = definedExternally,
)
| 0 | Kotlin | 6 | 26 | 3ca49a8f44fc8b46e393ffe66fbd81f8b4943c18 | 572 | types-kotlin | Apache License 2.0 |
app/src/main/java/com/shuyu/github/kotlin/model/bean/IssueEvent.kt | CarGuo | 156,679,291 | false | null | package com.kk.hub.model.bean
import com.google.gson.annotations.SerializedName
import java.util.Date
class IssueEvent {
var id: String? = null
var user: User? = null
@SerializedName("created_at")
var createdAt: Date? = null
@SerializedName("updated_at")
var updatedAt: Date? = null
var body: String? = null
@SerializedName("body_html")
var bodyHtml: String? = null
@SerializedName("event")
var type: String? = null
@SerializedName("html_url")
var htmlUrl: String? = null
}
| 4 | Kotlin | 232 | 1,312 | a8c0697f92dea388a3cf86aed26db12ddde640f5 | 531 | GSYGithubAppKotlin | Apache License 2.0 |
app/src/main/java/com/shuyu/github/kotlin/model/bean/IssueEvent.kt | CarGuo | 156,679,291 | false | null | package com.kk.hub.model.bean
import com.google.gson.annotations.SerializedName
import java.util.Date
class IssueEvent {
var id: String? = null
var user: User? = null
@SerializedName("created_at")
var createdAt: Date? = null
@SerializedName("updated_at")
var updatedAt: Date? = null
var body: String? = null
@SerializedName("body_html")
var bodyHtml: String? = null
@SerializedName("event")
var type: String? = null
@SerializedName("html_url")
var htmlUrl: String? = null
}
| 4 | Kotlin | 232 | 1,312 | a8c0697f92dea388a3cf86aed26db12ddde640f5 | 531 | GSYGithubAppKotlin | Apache License 2.0 |
app/src/main/java/com/company/app/scenes/login/LoginFragment.kt | mt1729 | 192,827,563 | false | {"Kotlin": 19807} | package com.company.app.scenes.login
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.company.app.databinding.FragmentLoginBinding
import com.google.android.material.snackbar.Snackbar
import org.koin.androidx.viewmodel.ext.android.viewModel
class LoginFragment : Fragment() {
private val vm by viewModel<LoginViewModel>()
private var binding: FragmentLoginBinding? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val binding = FragmentLoginBinding.inflate(inflater, container, false)
.also { binding = it }
binding.vm = vm
binding.lifecycleOwner = viewLifecycleOwner
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
vm.loginSuccess.observe(viewLifecycleOwner) {
val directions = LoginFragmentDirections.fromLoginToHome(it)
findNavController().navigate(directions)
}
vm.loginFailure.observe(viewLifecycleOwner) {
val root = binding?.root ?: return@observe
Snackbar.make(root, it, Snackbar.LENGTH_SHORT).show()
}
}
// Prevent memory retention of previously inflated binding
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
}
| 0 | Kotlin | 0 | 0 | f7a2e3da08cb29d7a2163832a10699c97d69bf16 | 1,539 | android-template-data-binding | MIT License |
app/src/main/java/com/example/returnpals/services/backend/ModelRepository.kt | BC-CS481-Capstone | 719,299,432 | false | {"Kotlin": 378665, "Java": 57406} | package com.example.returnpals.services.backend
import android.util.Log
import com.amplifyframework.api.graphql.model.ModelMutation
import com.amplifyframework.api.graphql.model.ModelQuery
import com.amplifyframework.core.Amplify
import com.amplifyframework.core.model.Model
/**
* Encapsulates create, read, update, and delete (CRUD) operations for a specified data model
* using [GraphQL API](https://docs.amplify.aws/gen1/android/build-a-backend/graphqlapi/).
* @param type ModelType cannot be reified so type information needs to be passed at runtime.
*/
open class ModelRepository<ModelType>(
private val type: Class<ModelType>
) where ModelType : Model {
fun create(model: ModelType): ModelType? {
var result: ModelType? = null
Amplify.API.mutate(
ModelMutation.create(model),
{ response ->
// NOTE: A successful GraphQL response doesn't always mean that the user was successfully created.
if (response.hasErrors()) {
var errors = ""
response.errors.forEachIndexed { index, error -> errors += "[$index] ${error.message}\n" }
Log.w("ModelRepository<${type.simpleName}>", "Failed to create ${model.modelName} due to GraphQL errors:\n$errors")
} else if (!response.hasData()) {
Log.w("ModelRepository<${type.simpleName}>", "Failed to create ${model.modelName}. GraphQL response is empty.")
} else {
result = response.data
Log.i("ModelRepository<${type.simpleName}>", "Created ${result?.modelName} with primary key: ${result?.primaryKeyString}")
}
},
{ exception ->
Log.e("ModelRepository<${type.simpleName}>", "Failed to create ${model.modelName}. Amplify API threw exception:\n" +
exception.message + '\n' + exception.cause + '\n' + exception.recoverySuggestion + '\n')
}
)
return result
}
fun delete(model: ModelType): ModelType? {
var result: ModelType? = null
Amplify.API.mutate(
ModelMutation.delete(model),
{ response ->
if (response.hasErrors()) {
var errors = ""
response.errors.forEachIndexed { index, error -> errors += "[$index] ${error.message}\n" }
Log.e("ModelRepository<${type.simpleName}>", "Failed to delete ${model.modelName} due to GraphQL errors:\n$errors")
} else if (!response.hasData()) {
Log.e("ModelRepository<${type.simpleName}>", "Failed to delete ${model.modelName}. GraphQL response is empty.")
} else {
result = response.data
Log.i("ModelRepository<${type.simpleName}>", "Deleted ${result?.modelName} with primary key: ${result?.primaryKeyString}")
}
},
{ exception ->
Log.e("ModelRepository<${type.simpleName}>", "Failed to delete ${model.modelName}. Amplify API threw exception:\n" +
exception.message + '\n' + exception.cause + '\n' + exception.recoverySuggestion + '\n')
}
)
return result
}
fun update(model: ModelType): Boolean {
var result = false
Amplify.API.mutate(
ModelMutation.update(model),
{ response ->
if (response.hasErrors()) {
var errors = ""
response.errors.forEachIndexed { index, error -> errors += "[$index] ${error.message}\n" }
Log.e("ModelRepository<${type.simpleName}>", "Failed to update ${model.modelName} due to GraphQL errors:\n$errors")
} else if (!response.hasData()) {
Log.e("ModelRepository<${type.simpleName}>", "Failed to update ${model.modelName}. GraphQL response is empty.")
} else {
result = true
Log.i("ModelRepository<${type.simpleName}>", "Updated ${response.data.modelName} with primary key: ${response.data.primaryKeyString}")
}
},
{ exception ->
Log.e("ModelRepository<${type.simpleName}>", "Failed to update ${model.modelName}. Amplify API threw exception:\n" +
exception.message + '\n' + exception.cause + '\n' + exception.recoverySuggestion + '\n')
}
)
return result
}
operator fun get(id: String): ModelType? {
var result: ModelType? = null
Amplify.API.query(
ModelQuery[type, id],
{ response ->
if (response.hasErrors()) {
var errors = ""
response.errors.forEachIndexed { index, error -> errors += "[$index] ${error.message}\n" }
Log.e("ModelRepository<${type.simpleName}>", "Failed to retrieve $type due to GraphQL errors:\n$errors")
} else if (response.hasData()) {
result = response.data
Log.i("ModelRepository<${type.simpleName}>", "Retrieved ${result?.modelName} with primary key: ${result?.primaryKeyString}")
}
},
{ exception ->
Log.e("ModelRepository<${type.simpleName}>", "Failed to update $type. Amplify API threw exception:\n" +
exception.message + '\n' + exception.cause + '\n' + exception.recoverySuggestion + '\n')
}
)
return result
}
} | 26 | Kotlin | 0 | 0 | b9be2454004844edc5815e7e67db7a3ebe7c1c5f | 5,624 | ReturnPalsApp | MIT License |
kotlinsupplement/src/main/java/in/sarangal/kotlinsupplement/ActivityExtension.kt | thesarangal | 374,148,747 | false | null | package `in`.sarangal.kotlinsupplement
import android.app.Activity
import android.app.ActivityManager
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.view.View
import android.view.WindowInsetsController
import android.view.inputmethod.InputMethodManager
import androidx.annotation.DrawableRes
import androidx.annotation.RequiresApi
import kotlin.system.exitProcess
/**
* Activity Extension Function
* */
// Static Data Members
const val GOOGLE_MAP_PACKAGE = "com.google.android.apps.maps"
// Exception Message
const val ACTIVITY_NOT_FOUND_EXCEPTION = "You may not have a proper app for viewing this content"
/**
* Set Background of Activity Theme
*
* @param resId Resource ID
* */
fun Activity.setWindowBackground(@DrawableRes resId: Int? = null) = run {
this.window?.let {
if (resId == null)
it.setBackgroundDrawable(null)
else
it.setBackgroundDrawableResource(resId)
}
}
/**
* Hide Keyboard
* */
fun Activity.hideKeyboard() {
val imm: InputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE)
as InputMethodManager
/* Find the currently focused view,
* so we can grab the correct window token from it. */
var view = currentFocus
/* If no view currently has focus, create a new one,
* just so we can grab a window token from it */
if (view == null) {
view = View(this)
}
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
/**
* Finish Activity by Killing All Running Process
* */
fun Activity.killTheApp() {
moveTaskToBack(true)
exitProcess(-1)
}
/**
* Restart Activity Without Animation
* */
fun Activity.restart() {
finish()
overridePendingTransition(0, 0)
startActivity(intent)
overridePendingTransition(0, 0)
}
/**
* Restart Application
* */
fun Activity.restartApplication() {
val packageManager: PackageManager = packageManager
val intent = packageManager.getLaunchIntentForPackage(packageName)
if (intent == null) {
restart()
return
}
val componentName = intent.component
val mainIntent = Intent.makeRestartActivityTask(componentName)
startActivity(mainIntent)
overridePendingTransition(0, 0)
Runtime.getRuntime().exit(0)
}
/**
* Open Dialer for Call
*
* @param number Phone Number
* @param exceptionMsg Custom Message for Exception
* */
fun Activity.openDialerForCall(
number: String,
exceptionMsg: String = ACTIVITY_NOT_FOUND_EXCEPTION
) {
val intent = Intent(Intent.ACTION_DIAL)
/* Send phone number to intent as data */
intent.data = Uri.parse("tel:$number")
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
toast(exceptionMsg)
}
}
/**
* Open Email
*
* @param email Email Address
* @param exceptionMsg Custom Message for Exception
* */
fun Activity.openEmail(
email: String,
exceptionMsg: String = ACTIVITY_NOT_FOUND_EXCEPTION
) {
val emailIntent = Intent(Intent.ACTION_SENDTO)
emailIntent.data = Uri.parse("mailto:$email")
startActivity(emailIntent)
try {
startActivity(emailIntent)
} catch (e: ActivityNotFoundException) {
toast(exceptionMsg)
}
}
/**
* Open URL in Browser
*
* @param urlString Web URL
* @param exceptionMsg Custom Message for Exception
* */
fun Activity.openURLInBrowser(
urlString: String,
exceptionMsg: String = ACTIVITY_NOT_FOUND_EXCEPTION
) {
var url = urlString
if (!url.startsWith("www.") && !url.startsWith("http")) {
url = "http://$url"
}
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(url)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
toast(exceptionMsg)
}
}
/**
* Share Plain Text via ShareIntent
*
* @param shareText Text To Share
* @param exceptionMsg Custom Message for Exception
* */
fun Activity.shareTextMessage(
shareText: String?,
exceptionMsg: String = ACTIVITY_NOT_FOUND_EXCEPTION
) {
val intent2 = Intent()
intent2.action = Intent.ACTION_SEND
intent2.type = "text/plain"
intent2.putExtra(Intent.EXTRA_TEXT, shareText)
val chooser: Intent = Intent.createChooser(
intent2,
"Share Via"
)
if (intent2.resolveActivity(packageManager) != null) {
startActivity(chooser)
} else {
toast(exceptionMsg)
}
}
/**
* Open Location in Google Map
*
* @param latitude Latitude Value
* @param longitude Longitude Value
* */
fun Activity.openDirectionInGoogleMap(latitude: Double, longitude: Double) {
val gmmIntentUri = Uri.parse("http://maps.google.com/maps?daddr=$latitude,$longitude")
val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
mapIntent.setPackage(GOOGLE_MAP_PACKAGE)
if (mapIntent.resolveActivity(packageManager) != null) {
startActivity(mapIntent)
} else {
openURLInBrowser("https://www.google.com/maps/?daddr=$latitude,$longitude")
}
}
/**
* Open Location in Google Map
*
* @param latitude Latitude Value
* @param longitude Longitude Value
* */
fun Activity.openLocationInGoogleMap(latitude: Double, longitude: Double) {
val gmmIntentUri =
Uri.parse("geo:$latitude,$longitude?q=$latitude,$longitude($latitude,$longitude)")
val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
mapIntent.setPackage(GOOGLE_MAP_PACKAGE)
if (mapIntent.resolveActivity(packageManager) != null) {
startActivity(mapIntent)
} else {
openURLInBrowser("https://www.google.com/maps/?q=$latitude,$longitude")
}
}
/**
* Open Address in Google Map
*
* @param address Address in String format
* */
fun Activity.openAddressInGoogleMap(address: String) {
val gmmIntentUri = Uri.parse("http://maps.google.co.in/maps?q=$address")
val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
mapIntent.setPackage(GOOGLE_MAP_PACKAGE)
if (mapIntent.resolveActivity(packageManager) != null) {
startActivity(mapIntent)
} else {
openURLInBrowser("https://www.google.com/maps/place/$address/")
}
}
/**
* Set System Bar Color (StatusBar)
*
* @param statusBarColor For StatusBar Color
* @param view Parent View of Activity
*
* Makes status bars become opaque with solid dark background and light foreground.
*/
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
fun Activity.setStatusBarColor(statusBarColor: Int, view: View? = null) {
window.statusBarColor = statusBarColor
val isColorDark = statusBarColor.isColorDark()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.insetsController?.setSystemBarsAppearance(
if (isColorDark) 0
else WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS,
WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS
)
return
}
@Suppress("DEPRECATION")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
(view ?: window.decorView).systemUiVisibility =
if (isColorDark) 0 else View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
}
}
/**
* Set System Bar Color (NavigationBar)
*
* @param navigationBarColor For System NavigationBar Color
* @param view Parent View of Activity
*
* Makes status bars become opaque with solid dark background and light foreground.
*/
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
fun Activity.setNavigationBarColor(navigationBarColor: Int, view: View? = null) {
window.navigationBarColor = navigationBarColor
val isColorDark = navigationBarColor.isColorDark()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.insetsController?.setSystemBarsAppearance(
if (isColorDark) 0
else WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS,
WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
)
return
}
@Suppress("DEPRECATION")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
(view ?: window.decorView).apply {
systemUiVisibility = if (isColorDark) 0
else View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
}
}
}
/**
* Set System Bar Color (StatusBar & NavigationBar)
*
* @param statusBarColor For StatusBar Color
* @param navigationBarColor For System NavigationBar Color
* @param view Parent View of Activity
*
* Makes status bars become opaque with solid dark background and light foreground.
*/
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
fun Activity.setSystemBarColor(
statusBarColor: Int,
navigationBarColor: Int,
view: View? = null
) {
window.statusBarColor = statusBarColor
window.navigationBarColor = navigationBarColor
val isColorDarkStatusBar = statusBarColor.isColorDark()
val isColorDarkNavigationBar = navigationBarColor.isColorDark()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.insetsController?.setSystemBarsAppearance(
when {
isColorDarkStatusBar && isColorDarkNavigationBar -> {
0
}
isColorDarkStatusBar -> {
WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
}
isColorDarkNavigationBar -> {
WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS
}
else -> {
WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS or WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
}
},
WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS or WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
)
return
}
@Suppress("DEPRECATION")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
(view ?: window.decorView).systemUiVisibility = when {
isColorDarkStatusBar && isColorDarkNavigationBar -> {
0
}
isColorDarkStatusBar -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
} else {
0
}
}
isColorDarkNavigationBar -> {
View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
}
else -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
} else {
View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
}
}
}
}
}
/**
* @return TRUE if Server is running else FALSE
* */
fun Activity.isServiceRunning(serviceClass: Class<*>): Boolean {
val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager?
if (manager != null) for (service in manager.getRunningServices(Int.MAX_VALUE)) {
if (serviceClass.name == service.service.className) {
return true
}
}
return false
}
/**
* Open Application Setting Screen with Package Name
*
* @param applicationId Pass Package Name (BuildConfig.APPLICATION_ID)
* @param exceptionMsg Custom Message for Exception
* */
fun Activity.openAppSettings(
applicationId: String,
exceptionMsg: String = ACTIVITY_NOT_FOUND_EXCEPTION
) {
val intent = Intent()
intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
val uri = Uri.fromParts("package", applicationId.trim(), null)
intent.data = uri
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
toast(exceptionMsg)
}
} | 0 | Kotlin | 0 | 0 | f6b037efb1960a7c70248fc1d6c5bdc7592e1655 | 11,913 | kotlinsupplement | MIT License |
app/src/main/java/dev/hitools/noah/modules/sample/detail/androidx/coordinatorLayout/SampleCoordinatorLayoutFragment.kt | EHG613 | 389,940,695 | true | {"Kotlin": 1096191, "Java": 274915, "Python": 4980, "Shell": 505} | package dev.hitools.noah.modules.sample.detail.androidx.coordinatorLayout
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import dev.hitools.noah.R
import dev.hitools.noah.databinding.FSampleCoordinatorLayoutBinding
import dev.hitools.noah.modules.base.mvvm.view.AppBindFragment
/**
* Created by yuhaiyang on 2020-06-29.
*/
class SampleCoordinatorLayoutFragment : AppBindFragment<FSampleCoordinatorLayoutBinding, SampleCoordinatorLayoutViewModel>() {
override fun getLayout(): Int = R.layout.f_sample_coordinator_layout
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding.appBar.addOnOffsetChangedListener(TopEffectListener(R.id.toolbar))
val activity = activity as AppCompatActivity
activity.setSupportActionBar(binding.toolbar)
activity.supportActionBar?.setHomeButtonEnabled(true)
activity.supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
} | 0 | null | 0 | 0 | be12dc9266810f3e64d55025e926a01b946c7228 | 980 | android-Common | Apache License 2.0 |
kamp-core/src/main/kotlin/ch/leadrian/samp/kamp/core/api/entity/HasPlayer.kt | Double-O-Seven | 142,487,686 | false | {"Kotlin": 3854710, "C": 23964, "C++": 23699, "Java": 4753, "Dockerfile": 769, "Objective-C": 328, "Batchfile": 189} | package ch.leadrian.samp.kamp.core.api.entity
interface HasPlayer {
val player: Player
} | 1 | Kotlin | 1 | 7 | af07b6048210ed6990e8b430b3a091dc6f64c6d9 | 95 | kamp | Apache License 2.0 |
vyne-query-service/src/test/java/com/orbitalhq/queryService/SavedQueryWithAuthPolicyIntegrationTest.kt | orbitalapi | 541,496,668 | false | {"TypeScript": 9344934, "Kotlin": 5669840, "HTML": 201985, "SCSS": 170620, "HCL": 55741, "Java": 29373, "JavaScript": 24697, "Shell": 8800, "Dockerfile": 7001, "Smarty": 4741, "CSS": 2966, "Mustache": 1392, "Batchfile": 983, "MDX": 884, "PLpgSQL": 337} | package com.orbitalhq.queryService
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.whenever
import com.orbitalhq.AuthClaimType
import com.orbitalhq.PackageMetadata
import com.orbitalhq.UserType
import com.orbitalhq.VersionedSource
import com.orbitalhq.VyneProvider
import com.orbitalhq.cockpit.core.WebSocketConfig
import com.orbitalhq.cockpit.core.pipelines.StreamResultsWebsocketPublisher
import com.orbitalhq.cockpit.core.security.authorisation.VyneAuthorisationConfig
import com.orbitalhq.errors.ErrorType
import com.orbitalhq.metrics.NoOpMetricsReporter
import com.orbitalhq.metrics.QueryMetricsReporter
import com.orbitalhq.models.json.parseJson
import com.orbitalhq.pipelines.jet.streams.ResultStreamAuthorizationDecorator
import com.orbitalhq.pipelines.jet.streams.StreamResultsService
import com.orbitalhq.query.runtime.core.gateway.QueryRouteService
import com.orbitalhq.queryService.security.TestRoles.adminUserName
import com.orbitalhq.queryService.security.TestRoles.platformManagerUser
import com.orbitalhq.queryService.security.TestRoles.viewerUserName
import com.orbitalhq.schema.api.SchemaProvider
import com.orbitalhq.schema.consumer.SchemaStore
import com.orbitalhq.schemaStore.LocalValidatingSchemaStoreClient
import com.orbitalhq.schemas.taxi.TaxiSchema
import com.orbitalhq.spring.SimpleVyneProvider
import com.orbitalhq.spring.config.TestDiscoveryClientConfig
import com.orbitalhq.testVyne
import io.kotest.matchers.collections.shouldContainAll
import io.kotest.matchers.shouldBe
import org.junit.runner.RunWith
import org.junit.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.boot.test.web.server.LocalServerPort
import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Import
import org.springframework.context.annotation.Primary
import org.springframework.http.HttpStatusCode
import org.springframework.http.MediaType
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.junit4.SpringRunner
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.reactive.function.client.bodyToFlux
import org.springframework.web.reactive.function.client.bodyToMono
import reactor.core.publisher.Sinks
import reactor.kotlin.test.test
import java.time.Duration
@RunWith(SpringRunner::class)
@AutoConfigureWireMock(port = 0)
@ActiveProfiles("test")
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = [
"server.error.include-message=always",
"server.error.include-exception=true",
"server.error.include-stacktrace=always",
"server.error.include-binding-errors=always",
"vyne.schema.publisher.method=Local",
"vyne.schema.consumer.method=Local",
"spring.main.allow-bean-definition-overriding=true",
"vyne.search.directory=./search/\${random.int}",
"vyne.security.open-idp.jwks-uri=\${wiremock.server.baseUrl}/.well-known/jwks.json",
"vyne.security.openIdp.enabled=true",
"vyne.security.open-idp.issuer-url=http://localhost:\${wiremock.server.port}",
"vyne.security.open-idp.client-id=vyne-spa",
"wiremock.server.baseUrl=http://localhost:\${wiremock.server.port}",
"logging.level.org.springframework.security=DEBUG",
"vyne.analytics.persistResults=true",
"vyne.telemetry.enabled=false",
]
)
class SavedQueryWithAuthPolicyIntegrationTest : BaseIntegrationTest() {
object TestSchema {
val source = """
${AuthClaimType.AuthClaimsTypeDefinition}
${UserType.UsernameTypeDefinition}
${ErrorType.ErrorTypeDefinition}
namespace com.petflix {
model Film {
filmId : FilmId inherits Int
title : Title inherits String
}
model NewReleaseAnnouncement {
filmId : FilmId
}
service FilmsService {
operation getFilms() : Film[]
operation getSingleFilm(): Film
stream getNewReleases : Stream<NewReleaseAnnouncement>
}
@HttpOperation(url = "/api/q/films", method = "GET")
query GetFilms {
find { Film[] }
}
@HttpOperation(url = "/api/q/films/123", method = "GET")
query GetSingleFilm {
find { Film }
}
@HttpOperation(url = "/api/q/newReleases", method = "GET")
@WebsocketOperation(path = "/api/s/newReleases")
query GetNewReleases {
stream { Film }
}
@HttpOperation(url = "/api/wrongPath/newReleases", method = "GET")
@WebsocketOperation(path = "/api/wrongPath/newReleases")
query BadQuery {
stream { NewReleaseAnnouncement }
}
type Role inherits String
model UserInfo inherits ${AuthClaimType.AuthClaimsTypeName.parameterizedName}{
realm_access : {
roles : Role[]
}
}
policy HideTitle against Film (userInfo:UserInfo) -> {
read {
when {
userInfo.realm_access.roles.contains("Admin") -> Film
userInfo.realm_access.roles.contains("Viewer") -> throw( (NotAuthorizedError) { message: 'Not Authorized' })
else -> Film as { ... except { title } }
}
}
}
}
""".trimIndent()
val schema = TaxiSchema.from(source, "UserSchema", "0.1.0")
}
@TestConfiguration
@Import(TestDiscoveryClientConfig::class, WebSocketConfig::class, StreamResultsWebsocketPublisher::class, StreamResultsService::class, ResultStreamAuthorizationDecorator::class)
class SpringConfig {
@Bean
@Primary
fun schemaProvider(): SchemaProvider = TestSchemaProvider.withBuiltInsAnd(TestSchema.schema)
@Bean
@Primary
fun queryMetricsReporter(): QueryMetricsReporter = NoOpMetricsReporter
@Bean
fun schemaStore(): LocalValidatingSchemaStoreClient {
val schemaStore = LocalValidatingSchemaStoreClient()
schemaStore.submitSchemas(
PackageMetadata.from("com.foo", "test", "1.0.0"),
listOf(VersionedSource.sourceOnly(TestSchema.source))
)
return schemaStore
}
@Bean
@Primary
fun vyneProvider(schemaStore: SchemaStore): VyneProvider {
val (vyne, stub) = testVyne(TestSchema.source)
stub.addResponse(
"getFilms", vyne.parseJson(
"com.petflix.Film[]", """
[
{ "filmId": "1010", "title": "Star Wars" },
{ "filmId": "1020", "title": "Empire Strikes Back" },
{ "filmId": "1030", "title": "Return of the Jedi" }
]
""".trimIndent()
)
)
stub.addResponse("getSingleFilm", vyne.parseJson(
"com.petflix.Film", """
{ "filmId": "1010", "title": "Star Wars" }
""".trimIndent()
))
return SimpleVyneProvider(vyne)
}
@Primary
@Bean
fun vyneAuthorisationConfig(): VyneAuthorisationConfig {
return VyneAuthorisationConfig()
}
}
@LocalServerPort
val randomServerPort = 0
@Autowired
private lateinit var restTemplate: TestRestTemplate
@Value("\${wiremock.server.baseUrl}")
private lateinit var wireMockServerBaseUrl: String
@Autowired
lateinit var queryRouteService: QueryRouteService
@Test
fun `requesting a saved request-response query applies policy hiding value`() {
val result = loadUrlResponseForUser(platformManagerUser, "/api/q/films")
result.shouldContainAll(
mapOf("filmId" to 1010, "title" to null),
mapOf("filmId" to 1020, "title" to null),
mapOf("filmId" to 1030, "title" to null),
)
}
@Test
fun `requesting a saved request-response query applies policy permitting value`() {
val result = loadUrlResponseForUser(adminUserName, "/api/q/films")
result.shouldContainAll(
mapOf("filmId" to 1010, "title" to "Star Wars"),
mapOf("filmId" to 1020, "title" to "Empire Strikes Back"),
mapOf("filmId" to 1030, "title" to "Return of the Jedi"),
)
}
@Test
fun `requesting a saved request-response single-value query applies policy hiding value`() {
val result = loadSingleValueUrlResponseForUser(platformManagerUser, "/api/q/films/123")
result.shouldBe(
mapOf("filmId" to 1010, "title" to null),
)
}
@Test
fun `requesting a saved request-response single-value query applies policy permitting value`() {
val result = loadSingleValueUrlResponseForUser(adminUserName, "/api/q/films/123")
result.shouldBe(
mapOf("filmId" to 1010, "title" to "Star Wars"),
)
}
@Test
fun `requesting a saved request-response stream applies policy permitting value`() {
val result = loadUrlStreamForUser(adminUserName, "/api/q/films", count = 3)
result.shouldContainAll(
mapOf("filmId" to 1010, "title" to "Star Wars"),
mapOf("filmId" to 1020, "title" to "Empire Strikes Back"),
mapOf("filmId" to 1030, "title" to "Return of the Jedi"),
)
}
@Test
fun `requesting a saved request-response stream applies policy hiding value`() {
val result = loadUrlStreamForUser(platformManagerUser, "/api/q/films", count = 3)
result.shouldContainAll(
mapOf("filmId" to 1010, "title" to null),
mapOf("filmId" to 1020, "title" to null),
mapOf("filmId" to 1030, "title" to null),
)
}
@Test
fun `requesting a saved request-response query applies policy returning 401 Not Authorized`() {
val (status,body) = getUrlResponseSpecForUser(viewerUserName, "/api/q/films")
.statusCodeAndBody()
status.value().shouldBe(401)
body.shouldBe("Not Authorized")
}
@Test
fun `requesting a saved request-response with single return value query applies policy returning 401 Not Authorized`() {
val (status,body) = getUrlResponseSpecForUser(viewerUserName, "/api/q/films/123")
.statusCodeAndBody()
status.value().shouldBe(401)
body.shouldBe("Not Authorized")
}
@Test
fun `requesting a saved request-response SSE stream applies policy returning 401 Not Authorized`() {
val (status, body) = getUrlStreamResponseSpecForUser(viewerUserName, "/api/q/films")
.statusCodeAndBody()
status.value().shouldBe(401)
body.shouldBe("Not Authorized")
}
@Test
fun `observe a persistent stream over SSE with a policy applied permitting value`() {
val sink = Sinks.many().unicast().onBackpressureBuffer<Any>()
whenever(hazelcastStreamObserver.getResultStream(any())).thenReturn(sink.asFlux())
val result = getUrlStreamResponseSpecForUser(adminUserName, "/api/q/newReleases")
.retrieve()
.bodyToFlux<Map<String,Any?>>()
result.test()
.expectSubscription()
.then { sink.emitNext(film(123, "Star Wars"), Sinks.EmitFailureHandler.FAIL_FAST) }
.expectNextMatches { next -> next.hasTitle("Star Wars") }
.then { sink.emitNext(film(123, "Empire Strikes Back"), Sinks.EmitFailureHandler.FAIL_FAST) }
.expectNextMatches { next -> next.hasTitle("Empire Strikes Back") }
.then { sink.tryEmitComplete() }
.expectComplete()
.verify()
}
@Test
fun `observe a persistent stream over SSE with a policy applied hiding a value`() {
val sink = Sinks.many().unicast().onBackpressureBuffer<Any>()
whenever(hazelcastStreamObserver.getResultStream(any(),)).thenReturn(sink.asFlux())
val result = getUrlStreamResponseSpecForUser(platformManagerUser, "/api/q/newReleases")
.retrieve()
.bodyToFlux<Map<String,Any?>>()
result.test()
.expectSubscription()
.then { sink.emitNext(film(123, "Star Wars"), Sinks.EmitFailureHandler.FAIL_FAST) }
.expectNextMatches { next -> next.hasTitle(null) }
.then { sink.emitNext(film(123, "Empire Strikes Back"), Sinks.EmitFailureHandler.FAIL_FAST) }
.expectNextMatches { next -> next.hasTitle(null) }
.then { sink.tryEmitComplete() }
.expectComplete()
.verify()
}
private fun film(id: Int, title: String) = mapOf("filmId" to id, "title" to title)
private fun Map<*, *>.hasTitle(title: String?): Boolean = this["title"] == title
private fun getUrlResponseSpecForUser(username: String, url: String): WebClient.RequestHeadersSpec<*> {
val token = getTestAuthToken(username)
val client = WebClient.builder()
.baseUrl("http://localhost:$randomServerPort")
.build()
return client.get().uri(url)
.header("Authorization", "Bearer $token")
}
private fun getUrlStreamResponseSpecForUser(username: String, url: String): WebClient.RequestHeadersSpec<*> {
val token = getTestAuthToken(username)
val client = WebClient.builder()
.baseUrl("http://localhost:$randomServerPort")
.build()
return client.get().uri(url)
.header("Authorization", "Bearer $token")
.accept(MediaType.TEXT_EVENT_STREAM)
}
private fun loadUrlResponseForUser(username: String, url: String): List<Map<String, Any>> {
return getUrlResponseSpecForUser(username, url)
.retrieve()
.bodyToMono<List<Map<String, Any>>>()
.block()!!
}
private fun loadSingleValueUrlResponseForUser(username: String, url: String): Map<String, Any> {
return getUrlResponseSpecForUser(username, url)
.retrieve()
.bodyToMono<Map<String, Any>>()
.block()!!
}
private fun loadUrlStreamForUser(username: String, url: String, count: Int): List<Map<String, Any>> {
val token = getTestAuthToken(username)
val client = WebClient.builder()
.baseUrl("http://localhost:$randomServerPort")
.build()
return client.get().uri(url)
.header("Authorization", "Bearer $token")
.accept(MediaType.TEXT_EVENT_STREAM)
.retrieve()
.bodyToFlux<Map<String, Any>>()
.take(count.toLong())
.collectList()
.block(Duration.ofSeconds(2))!!
}
private fun getTestAuthToken(username: String) =
com.orbitalhq.queryService.security.getTestAuthToken(username, wireMockServerBaseUrl)
private fun getTestAuthToken(roles: List<String>) {
com.orbitalhq.queryService.security.getTestAuthToken(
"adminUser", wireMockServerBaseUrl, mapOf(
"roles" to roles
)
)
}
}
private fun WebClient.RequestHeadersSpec<*>.statusCodeAndBody(): Pair<HttpStatusCode, String> {
return this.exchangeToMono { response ->
response.bodyToMono<String>().defaultIfEmpty("")
.map { response.statusCode() to it }
}
.block()!!
}
| 9 | TypeScript | 10 | 292 | 2be59abde0bd93578f12fc1e2ecf1f458a0212ec | 15,325 | orbital | Apache License 2.0 |
src/main/kotlin/com/imoonday/util/LearnableSkillData.kt | iMoonDay | 759,188,611 | false | {"Kotlin": 472390, "Java": 57363} | package com.imoonday.util
import com.imoonday.skill.Skill
import net.minecraft.nbt.NbtCompound
class LearnableSkillData(
private var choice: SkillChoice = SkillChoice.EMPTY,
var refreshed: Boolean = false,
var count: Int = 0,
) {
val first
get() = choice.first
val second
get() = choice.second
val third
get() = choice.third
fun next(except: Collection<Skill> = emptyList(), filter: (Skill) -> Boolean = { true }) {
if (hasNext()) {
count--
choice = SkillChoice.generate(except, filter)
} else {
choice = SkillChoice.EMPTY
}
refreshed = false
}
fun hasNext() = count > 0
fun clear() {
choice = SkillChoice.EMPTY
refreshed = false
}
fun reset() {
count = 0
clear()
}
fun get() = choice
fun isEmpty() = choice.isEmpty()
fun refresh(
force: Boolean = false,
except: Collection<Skill> = emptyList(),
filter: (Skill) -> Boolean = { true },
) {
if (refreshed && !force || choice.isEmpty() || !SkillChoice.canGenerate(except, filter)) return
refreshed = true
choice = SkillChoice.generate(except, filter)
}
fun correct(except: Collection<Skill> = emptyList(), filter: (Skill) -> Boolean = { true }): Boolean {
var modified = false
if (count < 0) {
count = 0
modified = true
}
if (choice.isEmpty() && hasNext()) {
next(except, filter)
modified = true
}
// if (choice.skills.any { it.invalid || it in except || !filter(it) }
// && SkillChoice.canGenerate(except, filter)) {
// choice = choice.replaceWith({ it.invalid || it in except || !filter(it) }) {
// Skill.random(except.intersect(it), filter)
// }
// modified = true
// }
return modified
}
fun toNbt(): NbtCompound = NbtCompound().apply {
put("choice", choice.toNbt())
putBoolean("refreshed", refreshed)
putInt("count", count)
}
companion object {
fun fromNbt(nbt: NbtCompound): LearnableSkillData {
val choice = SkillChoice.fromNbt(nbt.getCompound("choice"))
val refreshed = nbt.getBoolean("refreshed")
val remainingCount = nbt.getInt("count")
return LearnableSkillData(choice, refreshed, remainingCount)
}
}
}
| 0 | Kotlin | 0 | 0 | ae6a676e6caa7a1ad09231e263460c7144236699 | 2,497 | AdvancedSkills | Creative Commons Zero v1.0 Universal |
app/src/main/java/io/github/wulkanowy/ui/modules/timetable/TimetableDialog.kt | bujakpvp | 167,613,504 | true | {"Kotlin": 413721, "IDL": 131} | package io.github.wulkanowy.ui.modules.timetable
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import io.github.wulkanowy.R
import io.github.wulkanowy.data.db.entities.Timetable
import io.github.wulkanowy.utils.toFormattedString
import kotlinx.android.synthetic.main.dialog_timetable.*
class TimetableDialog : DialogFragment() {
private lateinit var lesson: Timetable
companion object {
private const val ARGUMENT_KEY = "Item"
fun newInstance(exam: Timetable): TimetableDialog {
return TimetableDialog().apply {
arguments = Bundle().apply { putSerializable(ARGUMENT_KEY, exam) }
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(STYLE_NO_TITLE, 0)
arguments?.run {
lesson = getSerializable(ARGUMENT_KEY) as Timetable
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.dialog_timetable, container, false)
}
@SuppressLint("SetTextI18n")
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
timetableDialogSubject.text = lesson.subject
timetableDialogTime.text = "${lesson.start.toFormattedString("HH:mm")} - ${lesson.end.toFormattedString("HH:mm")}"
lesson.group.let {
if (it.isBlank()) {
timetableDialogGroupTitle.visibility = GONE
timetableDialogGroup.visibility = GONE
} else timetableDialogGroup.text = it
}
lesson.room.let {
if (it.isBlank()) {
timetableDialogRoomTitle.visibility = GONE
timetableDialogRoom.visibility = GONE
} else timetableDialogRoom.text = it
}
lesson.teacher.let {
if (it.isBlank()) {
timetableDialogTeacherTitle.visibility = GONE
timetableDialogTeacher.visibility = GONE
} else timetableDialogTeacher.text = it
}
lesson.info.let {
if (it.isBlank()) {
timetableDialogChangesTitle.visibility = GONE
timetableDialogChanges.visibility = GONE
} else timetableDialogChanges.text = it
}
timetableDialogClose.setOnClickListener { dismiss() }
}
}
| 0 | Kotlin | 0 | 0 | 4da812af392ffbdf55960f8bb8d0d0f46721531b | 2,640 | wulkanowy | Apache License 2.0 |
example/src/test/java/com/mitteloupe/randomgenktexample/domain/GeneratePlanetarySystemUseCaseTest.kt | EranBoudjnah | 154,015,466 | false | null | package com.mitteloupe.randomgenktexample.domain
import com.mitteloupe.randomgenkt.RandomGen
import com.mitteloupe.randomgenktexample.data.generator.PlanetarySystemGeneratorFactory
import com.mitteloupe.randomgenktexample.data.model.planet.PlanetarySystem
import com.nhaarman.mockitokotlin2.given
import com.nhaarman.mockitokotlin2.mock
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
/**
* Created by Eran Boudjnah on 01/11/2018.
*/
@RunWith(MockitoJUnitRunner::class)
class GeneratePlanetarySystemUseCaseTest {
private lateinit var cut: GeneratePlanetarySystemUseCase
private lateinit var coroutineContextProvider: CoroutineContextProvider
@Mock
lateinit var planetarySystemGeneratorFactory: PlanetarySystemGeneratorFactory
@Mock
lateinit var planetarySystemGenerator: RandomGen<PlanetarySystem>
@Before
fun setUp() {
coroutineContextProvider = testCoroutineContextProvider()
given(planetarySystemGeneratorFactory.newPlanetarySystemGenerator).willReturn(planetarySystemGenerator)
cut = GeneratePlanetarySystemUseCase(coroutineContextProvider, planetarySystemGeneratorFactory)
}
@Test
fun `Given generator with planetary system when execute then returns same planetary system`() {
// Given
val expectedResult = mock<PlanetarySystem>()
var actualResult: PlanetarySystem? = null
given(planetarySystemGenerator.generate()).willReturn(expectedResult)
// When
runBlocking {
cut.execute { planetarySystem -> actualResult = planetarySystem }
}
// Then
assertEquals(expectedResult, actualResult)
}
} | 0 | Kotlin | 0 | 28 | c5db0d07a3dda1b9215f767acde7f51d7c958070 | 1,831 | RandomGenKt | MIT License |
topic/topic-api/src/main/java/ru/softeg/slartus/forum.api/TopicAttachment.kt | slartus | 21,554,455 | false | {"HTML": 6951966, "CSS": 1246476, "Java": 1138597, "Kotlin": 744082, "JavaScript": 47541, "PHP": 3566, "Less": 1459} | package ru.softeg.slartus.forum.api
data class TopicAttachment(
val id: String,
val iconUrl: String,
val url: String,
val name: String,
val date: String,
val size: String,
val postUrl: String
) | 16 | HTML | 17 | 86 | 03dfdb68c1ade272cf84ff1c89dc182f7fe69c39 | 222 | 4pdaClient-plus | Apache License 2.0 |
bgw-net/bgw-net-server/src/main/kotlin/tools/aqua/bgw/net/server/service/FrontendService.kt | tudo-aqua | 377,420,862 | false | null | /*
* Copyright 2022-2024 The BoardGameWork Authors
* SPDX-License-Identifier: Apache-2.0
*
* 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("UseDataClass")
package tools.aqua.bgw.net.server.service
import org.springframework.stereotype.Service
import tools.aqua.bgw.net.server.entity.GameInstance
import tools.aqua.bgw.net.server.entity.Player
import tools.aqua.bgw.net.server.entity.repositories.GameRepository
import tools.aqua.bgw.net.server.entity.repositories.PlayerRepository
import tools.aqua.bgw.net.server.entity.tables.SchemasByGame
import tools.aqua.bgw.net.server.entity.tables.SchemasByGameRepository
/** This service exposes all active games and players to the frontend. */
@Service
class FrontendService(
private val playerRepository: PlayerRepository,
private val gameRepository: GameRepository,
private val schemasByGameRepository: SchemasByGameRepository
) {
/** List of active [Player]s. */
val activePlayers: List<Player>
get() = playerRepository.getAll()
/** List of active [GameInstance]s. */
val activeGames: List<GameInstance>
get() = gameRepository.getAll()
/** List of all schemas grouped by their gameID. */
val allSchemas: List<SchemasByGame>
get() = schemasByGameRepository.findAll().toList()
/** List of all gameIDs of games that have been registered. */
val allGameIds: List<String>
get() = allSchemas.map { it.gameID }.distinct()
}
| 8 | null | 16 | 24 | 266db439e4443d10bc1ec7eb7d9032f29daf6981 | 1,943 | bgw | Apache License 2.0 |
app/src/test/java/com/gmail/bogumilmecel2/fitnessappv2/feature_summary/domain/use_case/HandleWeightDialogsQuestionUseCaseTest.kt | BogumilMecel | 499,018,800 | false | {"Kotlin": 808610} | package com.gmail.bogumilmecel2.fitnessappv2.feature_summary.domain.use_case
import com.gmail.bogumilmecel2.fitnessappv2.common.BaseTest
import com.gmail.bogumilmecel2.fitnessappv2.common.MockConstants
import com.gmail.bogumilmecel2.fitnessappv2.common.util.Resource
import com.gmail.bogumilmecel2.fitnessappv2.feature_summary.domain.model.WeightDialogsQuestion
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockkClass
import kotlinx.coroutines.test.runTest
import org.junit.Test
class HandleWeightDialogsQuestionUseCaseTest : BaseTest() {
private val saveAskForWeightDailyUseCase = mockkClass(SaveAskForWeightDailyUseCase::class)
private val handleWeightDialogsQuestionUseCase = HandleWeightDialogsQuestionUseCase(
cachedValuesProvider = cachedValuesProvider,
saveAskForWeightDaily = saveAskForWeightDailyUseCase
)
@Test
fun `Check if save return resource error, resource error is returned`() = runTest {
mockData(responseResource = Resource.Error())
handleWeightDialogsQuestionUseCase(accepted = true).assertIsError()
}
@Test
fun `Check if accepted is null last time asked is updated and resource error is returned`() =
runTest {
val weightDialogsQuestion = WeightDialogsQuestion(
lastTimeAsked = MockConstants.getDate2021(),
askedCount = 1
)
mockData(savedWeightDialogsQuestion = weightDialogsQuestion)
handleWeightDialogsQuestionUseCase(accepted = null).assertIsError()
coVerify(exactly = 1) { cachedValuesProvider.getLocalWeightDialogsQuestion() }
coVerify(exactly = 1) {
cachedValuesProvider.updateLocalWeightDialogsQuestion(
weightDialogsQuestion = weightDialogsQuestion.copy(
lastTimeAsked = MockConstants.getDate2021(),
askedCount = weightDialogsQuestion.askedCount.plus(1)
)
)
}
}
@Test
fun `Check if repository return resource success, resource success is returned and weight dialogs are cached`() =
runTest {
mockData()
handleWeightDialogsQuestionUseCase(accepted = true).assertIsSuccess()
}
private fun mockData(
responseResource: Resource<Unit> = Resource.Success(Unit),
savedWeightDialogsQuestion: WeightDialogsQuestion? = null
) {
mockDate()
coEvery {
cachedValuesProvider.getLocalWeightDialogsQuestion()
} returns savedWeightDialogsQuestion
coEvery {
cachedValuesProvider.updateLocalWeightDialogsQuestion(
weightDialogsQuestion = any()
)
} returns Unit
coEvery {
saveAskForWeightDailyUseCase(
accepted = any(),
cachedValuesProvider = cachedValuesProvider
)
} returns responseResource
}
} | 0 | Kotlin | 0 | 0 | f1036ca805dec913c5ca444d8efab87686442f39 | 2,986 | FitnessAppV2 | Apache License 2.0 |
app/src/main/java/com/sarlomps/evemento/event/transport/TransportFragment.kt | sarlomps | 176,547,309 | false | null | package com.hellfish.evemento.event.transport
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.BitmapDescriptor
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.hellfish.evemento.EventViewModel
import com.hellfish.evemento.NavigatorFragment
import com.hellfish.evemento.R
import kotlinx.android.synthetic.main.fragment_transport.*
import android.support.v4.content.ContextCompat
import android.support.annotation.DrawableRes
import com.hellfish.evemento.SessionManager
import com.hellfish.evemento.api.User
class TransportFragment : NavigatorFragment(), OnMapReadyCallback {
private lateinit var mMap: GoogleMap
override val titleId = R.string.title_activity_maps
private lateinit var eventViewModel: EventViewModel
private lateinit var transportViewModel: TransportViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
eventViewModel = ViewModelProviders.of(activity!!).get(EventViewModel::class.java)
eventViewModel.loadRides { _ -> showToast(R.string.errorLoadingRides) }
eventViewModel.rides.observe(this, Observer { if (::mMap.isInitialized) it?.let { loadTransportsOnMap(it) } })
transportViewModel = ViewModelProviders.of(activity!!).get(TransportViewModel::class.java)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.fragment_transport, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
cardView.setOnClickListener { navigatorListener.replaceFragment(TransportListFragment()) }
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
}
private fun loadTransportsOnMap(transports: MutableList<TransportItem>) {
mMap.clear()
transports.forEach {
val marker = MarkerOptions()
.position(it.latLong())
.title(it.startpoint.name)
.icon(bitmapDescriptorFromVector(context!!, R.drawable.ic_map_car_white_30dp))
mMap.addMarker(marker)
}
eventViewModel.selected()!!.location.let {
val marker = MarkerOptions()
.position(it.latLng())
.title(it.name)
mMap.addMarker(marker)
val currentLocation = it.latLng()
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 15f))
}
mMap.setOnMarkerClickListener { marker ->
//TODO si hay varios markers en la misma localizacion va a ir al que encuentre el find que puede no ser el correcto
val transportClicked = transports.find { it.latLong().equals(marker.position) }
if (transportClicked != null) {
transportViewModel.selectDriver(transportClicked.driver)
navigatorListener.replaceFragment(TransportDetailFragment())
}
return@setOnMarkerClickListener false
}
}
private fun getLastLocation() = LatLng(2.0, 2.0)
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
eventViewModel.rides.observe(this, Observer { it?.let { loadTransportsOnMap(it) } })
}
private fun bitmapDescriptorFromVector(context: Context, @DrawableRes vectorDrawableResourceId: Int): BitmapDescriptor {
val background = ContextCompat.getDrawable(context, R.drawable.ic_place_primary_blue_48dp)
background!!.setBounds(0, 0, background.intrinsicWidth, background.intrinsicHeight)
val vectorDrawable = ContextCompat.getDrawable(context, vectorDrawableResourceId)
vectorDrawable!!.setBounds(25, 3, vectorDrawable.intrinsicWidth + 20, vectorDrawable.intrinsicHeight)
val bitmap = Bitmap.createBitmap(background.intrinsicWidth, background.intrinsicHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
background.draw(canvas)
vectorDrawable.draw(canvas)
return BitmapDescriptorFactory.fromBitmap(bitmap)
}
}
| 0 | Kotlin | 0 | 0 | ab68fd31df52e225f61073cad3f5e736a25caeb6 | 5,487 | evemento | MIT License |
one.lfa.updater.xml.spi/src/main/java/one/lfa/updater/xml/spi/SPIFormatXMLSerializerType.kt | AULFA | 189,855,520 | false | null | package one.lfa.updater.xml.spi
import java.io.Closeable
interface SPIFormatXMLSerializerType<T> : Closeable {
val contentClass: Class<T>
fun serialize(value: T)
} | 2 | null | 1 | 1 | 5cde488e4e9f9e60f5737d9e1a8fc8817f6b22a8 | 172 | updater | Apache License 2.0 |
app/src/main/java/com/guness/lottie/utils/compose/LazyListScopeExtensions.kt | guness | 449,084,007 | false | {"Kotlin": 117766} | package com.guness.lottie.utils.compose
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyItemScope
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.guness.lottie.ui.theme.Padding
/**
* Created by guness on 14.11.2021 21:00
*/
inline fun <T> LazyListScope.items(list: List<T>, column: Int, crossinline itemContent: @Composable LazyItemScope.(item: T) -> Unit) {
val rows = (list.size + column - 1) / column
items(rows) { rowIndex ->
Row(modifier = Modifier.padding(horizontal = Padding.xs)) {
for (columnIndex in 0 until column) {
val itemIndex = rowIndex * column + columnIndex
if (itemIndex < list.size) {
Box(
modifier = Modifier.weight(1f, fill = true),
propagateMinConstraints = true
) {
itemContent(list[itemIndex])
}
} else {
Spacer(Modifier.weight(1f, fill = true))
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 493c8288579fec02c1c8bdadf03e7196dbd3daee | 1,337 | lottiefiles | MIT License |
modules/api-types/src/commonTest-generated/kotlin/com/gw2tb/gw2api/types/v2/GW2v2PvPAmulet.kt | GW2ToolBelt | 117,367,550 | false | null | /*
* Copyright (c) 2018-2024 <NAME>
* MACHINE GENERATED FILE, DO NOT EDIT
*
* 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.gw2tb.gw2api.types.v2
import kotlin.test.*
import kotlinx.serialization.*
import kotlinx.serialization.json.*
class GW2v2PvpAmuletTest {
private val json = Json {
useAlternativeNames = false // https://github.com/Kotlin/kotlinx.serialization/issues/1512
}
@Test
fun testType_00() {
json.decodeFromString<GW2v2PvpAmulet>(
"""
{
"id": 4,
"name": "Meucheler-Amulett",
"icon": "https://render.guildwars2.com/file/02E9EFDEF9587130A25F17AC396913FBBE3C716D/455602.png",
"attributes": {
"Precision": 1200,
"Power": 900,
"CritDamage": 900
}
}
""".trimIndent()
)
}
@Test
fun testType_01() {
json.decodeFromString<GW2v2PvpAmulet>(
"""
{
"id": 8,
"name": "Berserker-Amulett",
"icon": "https://render.guildwars2.com/file/5044509F3DB0F391576CCAD891BC654DC5FE79B3/63600.png",
"attributes": {
"Power": 1200,
"Precision": 900,
"CritDamage": 900
}
}
""".trimIndent()
)
}
@Test
fun testType_02() {
json.decodeFromString<GW2v2PvpAmulet>(
"""
{
"id": 9,
"name": "<NAME>",
"icon": "https://render.guildwars2.com/file/AA26E9092621670E6C55A65307B7F43C0CC5F138/63595.png",
"attributes": {
"ConditionDamage": 1200,
"Power": 900,
"Vitality": 900
}
}
""".trimIndent()
)
}
@Test
fun testType_03() {
json.decodeFromString<GW2v2PvpAmulet>(
"""
{
"id": 13,
"name": "<NAME>",
"icon": "https://render.guildwars2.com/file/090C47B6BFC5F70B5BA83D3B0F4630A51F07ED34/220642.png",
"attributes": {
"ConditionDamage": 1200,
"Precision": 900,
"Toughness": 900
}
}
""".trimIndent()
)
}
@Test
fun testType_04() {
json.decodeFromString<GW2v2PvpAmulet>(
"""
{
"id": 14,
"name": "Wüter-Amulett",
"icon": "https://render.guildwars2.com/file/E156072918919C4CDCA9C075D04CE365B13F724F/220655.png",
"attributes": {
"Precision": 1200,
"Power": 900,
"ConditionDamage": 900
}
}
""".trimIndent()
)
}
@Test
fun testType_05() {
json.decodeFromString<GW2v2PvpAmulet>(
"""
{
"id": 18,
"name": "Walküren-Amulett",
"icon": "https://render.guildwars2.com/file/B9595BAFC57D70621D0A0C745C6E475FC540707C/66230.png",
"attributes": {
"Power": 1200,
"Vitality": 900,
"CritDamage": 900
}
}
""".trimIndent()
)
}
@Test
fun testType_06() {
json.decodeFromString<GW2v2PvpAmulet>(
"""
{
"id": 20,
"name": "Marodeur-Amulett",
"icon": "https://render.guildwars2.com/file/1A0ED77906F73270CE9CC2E67C68429DD3FAB43E/1010501.png",
"attributes": {
"Power": 1000,
"Precision": 1000,
"CritDamage": 500,
"Vitality": 500
}
}
""".trimIndent()
)
}
@Test
fun testType_07() {
json.decodeFromString<GW2v2PvpAmulet>(
"""
{
"id": 22,
"name": "<NAME>",
"icon": "https://render.guildwars2.com/file/6504267032DB14B7507F34685409563C283F08C6/222394.png",
"attributes": {
"ConditionDamage": 1200,
"Power": 900,
"Precision": 900
}
}
""".trimIndent()
)
}
@Test
fun testType_08() {
json.decodeFromString<GW2v2PvpAmulet>(
"""
{
"id": 29,
"name": "Heilkundigen-Amulett",
"icon": "https://render.guildwars2.com/file/F5BBC542A696001AAC085192C64EC5E6A2769D56/1341197.png",
"attributes": {
"Power": 1000,
"Healing": 1000,
"Precision": 500,
"Vitality": 500
}
}
""".trimIndent()
)
}
@Test
fun testType_09() {
json.decodeFromString<GW2v2PvpAmulet>(
"""
{
"id": 30,
"name": "Paladin-Amulett",
"icon": "https://render.guildwars2.com/file/690CCB0FF13943ABD065CECC056B9F439F12963F/1341199.png",
"attributes": {
"Power": 1000,
"Precision": 1000,
"Toughness": 400,
"Vitality": 400
}
}
""".trimIndent()
)
}
@Test
fun testType_10() {
json.decodeFromString<GW2v2PvpAmulet>(
"""
{
"id": 31,
"name": "Weisen-Amulett",
"icon": "https://render.guildwars2.com/file/58143BE0060D92D1CD32BBD99DD12102F811960A/1341200.png",
"attributes": {
"Power": 1000,
"ConditionDamage": 1000,
"Vitality": 500,
"Healing": 500
}
}
""".trimIndent()
)
}
@Test
fun testType_11() {
json.decodeFromString<GW2v2PvpAmulet>(
"""
{
"id": 34,
"name": "Demolierer-Amulett",
"icon": "https://render.guildwars2.com/file/C275399647F3744A0E0FEC071938B23EAE370704/1423719.png",
"attributes": {
"Power": 1000,
"Precision": 1000,
"Toughness": 500,
"CritDamage": 500
}
}
""".trimIndent()
)
}
@Test
fun testType_12() {
json.decodeFromString<GW2v2PvpAmulet>(
"""
{
"id": 35,
"name": "Zerstörer-Amulett",
"icon": "https://render.guildwars2.com/file/7FC9D25204099E6B4CB57D0C05BD24993F1E0627/1423720.png",
"attributes": {
"Power": 1000,
"Precision": 1000,
"ConditionDamage": 500,
"CritDamage": 500
}
}
""".trimIndent()
)
}
@Test
fun testType_13() {
json.decodeFromString<GW2v2PvpAmulet>(
"""
{
"id": 40,
"name": "Zauberer-Amulett",
"icon": "https://render.guildwars2.com/file/96079F0EB0C6CE0476D230AF7A05F4AAD4807207/1876172.png",
"attributes": {
"Power": 1000,
"ConditionDamage": 1000,
"Vitality": 500,
"Precision": 500
}
}
""".trimIndent()
)
}
@Test
fun testType_14() {
json.decodeFromString<GW2v2PvpAmulet>(
"""
{
"id": 41,
"name": "Avatar-Amulett",
"icon": "https://render.guildwars2.com/file/AD9E18AA3B1C69200946FA5342B9B5C6A7B05097/1876167.png",
"attributes": {
"Power": 1000,
"Precision": 1000,
"Healing": 500,
"Vitality": 500
}
}
""".trimIndent()
)
}
@Test
fun testType_15() {
json.decodeFromString<GW2v2PvpAmulet>(
"""
{
"id": 43,
"name": "<NAME>",
"icon": "https://render.guildwars2.com/file/4C5B130518E4C07641C1CDD2AA0D62A176C852C5/1876168.png",
"attributes": {
"Power": 1000,
"ConditionDamage": 1000,
"Precision": 500,
"CritDamage": 500
}
}
""".trimIndent()
)
}
@Test
fun testType_16() {
json.decodeFromString<GW2v2PvpAmulet>(
"""
{
"id": 44,
"name": "Marschal-Amulett",
"icon": "https://render.guildwars2.com/file/E33ABC39C515C4F776B7F4F8B29C422A0752F478/1876170.png",
"attributes": {
"Power": 1000,
"Healing": 1000,
"Precision": 500,
"ConditionDamage": 500
}
}
""".trimIndent()
)
}
@Test
fun testType_17() {
json.decodeFromString<GW2v2PvpAmulet>(
"""
{
"id": 45,
"name": "Säbelrassler-Amulett",
"icon": "https://render.guildwars2.com/file/11A06FFE4CF0F92EF1BF65E87A99B5E8C4595028/1876171.png",
"attributes": {
"Power": 1000,
"Precision": 1000,
"ConditionDamage": 500,
"Vitality": 500
}
}
""".trimIndent()
)
}
} | 2 | null | 0 | 4 | 0343cbbb98c2a4c2ccba5976416e52977c4dc8ea | 11,235 | GW2APIClient | MIT License |
kotlin-eclipse-ui-test/testData/completion/handlers/insertFunctionWithBothParentheses.kt | bvfalcon | 263,980,575 | false | null | // KT-1968 Double closing parentheses entered when completing unit function
package some
fun test() = 12
fun test1()
val a = <caret>
// ELEMENT: test1 | 19 | null | 7 | 43 | e6360b023e1e377325f1d10bda5755e3fc3af591 | 153 | kotlin-eclipse | Apache License 2.0 |
app/src/main/java/com/neal786y/mvparchitecture/main/activity/RestaurantActivity.kt | neal786y | 249,264,913 | false | null | package com.neal786y.mvparchitecture.main.activity
import android.content.Intent
import android.location.Location
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.WindowManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.neal786y.mvparchitecture.R
import com.neal786y.mvparchitecture.base.*
import com.neal786y.mvparchitecture.base.Constants.Companion.ENTITY_ID
import com.neal786y.mvparchitecture.base.Constants.Companion.ENTITY_TYPE
import com.neal786y.mvparchitecture.base.Constants.Companion.LOCATION_REQUEST_CODE
import com.neal786y.mvparchitecture.base.Constants.Companion.PERMISSION_REQUEST_CODE
import com.neal786y.mvparchitecture.main.adaper.RestaurantAdapter
import com.neal786y.mvparchitecture.main.listeners.OnLocationAvailableListener
import com.neal786y.mvparchitecture.main.listeners.OnRestaurantItemClickListener
import com.neal786y.mvparchitecture.main.pojo.zomato.search_restaurants.response.RestaurantDto
import com.neal786y.mvparchitecture.main.pojo.zomato.search_restaurants.response.RestaurantResponseDto
import com.neal786y.mvparchitecture.main.pojo.zomato.search_restaurants.response.RestaurantsDto
import com.neal786y.mvparchitecture.main.presenter.RestaurantPresenter
import com.neal786y.mvparchitecture.main.util.LocationTracker
import com.neal786y.mvparchitecture.main.view.RestaurantView
import kotlinx.android.synthetic.main.activity_restaurant.*
import retrofit2.Retrofit
import javax.inject.Inject
class RestaurantActivity : BaseActivity<RestaurantView, RestaurantPresenter>(), RestaurantView {
val TAG = this::class.java.simpleName
@Inject
lateinit var retrofit: Retrofit
@Inject
lateinit var restaurantPresenter: RestaurantPresenter
@Inject
lateinit var restaurantAdapter: RestaurantAdapter
lateinit var locationTracker: LocationTracker
override fun getLayout(): Int = R.layout.activity_restaurant
override fun initPresenter(): RestaurantPresenter = restaurantPresenter
override fun onCreate(savedInstanceState: Bundle?) {
component.inject(this)
super.onCreate(savedInstanceState)
linearLayoutSearch.setOnClickListener {
val intent = Intent(this@RestaurantActivity, LocationActivity::class.java)
startActivityForResult(intent, LOCATION_REQUEST_CODE)
}
recyclerViewRestaurants.layoutManager = LinearLayoutManager(this)
recyclerViewRestaurants.adapter = restaurantAdapter
recyclerViewRestaurants.setEmptyView(textViewEmptyMessage)
restaurantAdapter.mOnRestaurantItemClickListener = object : OnRestaurantItemClickListener {
override fun onRestaurantItemClick(restaurantsDto: RestaurantDto) {
val intent = Intent(this@RestaurantActivity, DetailWebActivity::class.java)
intent.putExtra(getString(R.string.detailUrlKey), restaurantsDto.url)
startActivity(intent)
}
}
locationTracker = LocationTracker(this)
locationTracker.onLocationAvailableListener = object : OnLocationAvailableListener {
override fun onLocationAvailable(location: Location) {
val longitude: Double = location.getLongitude()
val latitude: Double = location.getLatitude()
presenter?.getRestaurantsByLatLon(retrofit, latitude, longitude);
}
override fun onPermisionRequired() {
requestPermission(this@RestaurantActivity, Constants.PERMISSION_REQUEST_CODE)
}
override fun checkPermission(): Boolean {
return isPermissionGranted(this@RestaurantActivity)
}
}
if (!isPermissionGranted(this)) requestPermission(this, PERMISSION_REQUEST_CODE)
else locationTracker.getLastLocation()
}
private fun fetchRestaurantsByEntityId(entityId: Int, entityType: String) {
presenter?.getRestaurantsByEntityId(retrofit, entityId, entityType);
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
333 -> {
//fetch restraunts from entity id and entity type
data?.let {
val entityId: Int = it.getIntExtra(ENTITY_ID, 0)
val entityType: String? = it.getStringExtra(ENTITY_TYPE)
if (entityId > 0) fetchRestaurantsByEntityId(entityId, entityType ?: "")
}
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
PERMISSION_REQUEST_CODE -> {
if (isPermissionGranted(this)) {
locationTracker.getLastLocation();
}
}
}
}
override fun onResume() {
super.onResume();
if (isPermissionGranted(this)) locationTracker.getLastLocation()
}
override fun hideLoading() {
runOnUiThread {
progressBar.visibility = View.GONE
window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE)
}
}
override fun showLoading() {
runOnUiThread {
progressBar.visibility = View.VISIBLE
window.setFlags(
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
)
}
}
override fun onLoad(data: Any) {
runOnUiThread {
when (data) {
is RestaurantResponseDto -> {
//load restaurants
restaurantAdapter.addAll(data.restaurants as List<RestaurantsDto>?)
}
}
}
}
override fun onError(error: Any) {
when (error) {
is Throwable -> {
showShortToast(getString(R.string.somethingWentWrong))
Log.d(TAG, error.printStackTrace().toString())
}
}
}
override fun onNetworkAvailable() {
}
override fun onNetworkLost() {
showShortToast(getString(R.string.no_internet_text))
}
}
| 0 | Kotlin | 0 | 0 | 69c201b439a2c7b12c1020fa213fa6a22988b886 | 6,415 | Lunching | Apache License 2.0 |
app/src/main/java/com/droidhats/campuscompass/roomdb/FavoritesDatabase.kt | RobertBeaudenon | 232,313,026 | false | null | package com.droidhats.campuscompass.roomdb
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.droidhats.campuscompass.models.FavoritePlace
@Database(entities = [FavoritePlace::class], version = 3, exportSchema = false)
abstract class FavoritesDatabase : RoomDatabase() {
abstract fun favoritePlacesDao(): FavoritePlacesDao
companion object {
// For Singleton instantiation
@Volatile
private var instance: FavoritesDatabase? = null
fun getInstance(context: Context): FavoritesDatabase {
return instance ?: synchronized(this) {
instance ?: buildDatabase(context).also { instance = it }
}
}
// Create and pre-populate the database
private fun buildDatabase(context: Context): FavoritesDatabase {
return Room.databaseBuilder(context, FavoritesDatabase::class.java, "favorites-db.rdb")
.allowMainThreadQueries().fallbackToDestructiveMigration()
.build()
}
}
} | 4 | Kotlin | 4 | 7 | ea136a60a71f5d393f4a5688e86b9c56c6bea7b6 | 1,100 | SOEN390-CampusGuideMap | MIT License |
app/src/main/java/com/altaureum/covid/tracking/services/data/ChunkHeader.kt | jllarraz | 249,151,516 | false | null | package com.altaureum.covid.tracking.services.data
class ChunkHeader {
var packets:Int=0
} | 0 | Kotlin | 1 | 2 | 08f20f2de577e2fdf76dd8c45bcff9109a5c9b54 | 95 | CovidContactTracking | Apache License 2.0 |
rulebook-ktlint/src/test/kotlin/com/hanggrian/rulebook/ktlint/SwitchCaseBranchingRuleTest.kt | hanggrian | 556,969,715 | false | {"Kotlin": 270414, "Python": 71768, "Java": 18644, "CSS": 1653, "Groovy": 323} | package com.hanggrian.rulebook.ktlint
import com.hanggrian.rulebook.ktlint.SwitchCaseBranchingRule.Companion.MSG
import com.hanggrian.rulebook.ktlint.internals.Messages
import com.pinterest.ktlint.test.KtLintAssertThat.Companion.assertThatRule
import kotlin.test.Test
class SwitchCaseBranchingRuleTest {
private val assertThatCode = assertThatRule { SwitchCaseBranchingRule() }
@Test
fun `Rule properties`() = SwitchCaseBranchingRule().assertProperties()
@Test
fun `Multiple switch branches`() =
assertThatCode(
"""
fun foo() {
when (bar) {
0 -> baz()
1 -> baz()
}
}
""".trimIndent(),
).hasNoLintViolations()
@Test
fun `Single switch branch`() =
assertThatCode(
"""
fun foo() {
when (bar) {
0 -> baz()
}
}
""".trimIndent(),
).hasLintViolationWithoutAutoCorrect(2, 5, Messages[MSG])
}
| 0 | Kotlin | 0 | 1 | a1283fc14004ac7c973c5312dede43035f10daa2 | 1,069 | rulebook | Apache License 2.0 |
src/test/kotlin/me/kuku/KotlinTest.kt | kukume | 505,702,930 | false | null | package me.kuku
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import kotlinx.coroutines.runBlocking
import me.kuku.utils.client
import org.junit.jupiter.api.Test
class KotlinTest {
@Test
fun test1() {
runBlocking {
val httpResponse = client.get("https://www.baidu.com") {
headers {
accept(ContentType.Application.OctetStream)
}
}
println(httpResponse.request.headers)
}
}
}
| 0 | Kotlin | 0 | 0 | aa4a25ac7d24acb9156ed1ede20385e53ae09d53 | 536 | utils | MIT License |
app/src/main/java/com/devspace/myapplication/detail/di/RecipeDetailModule.kt | victorashino | 822,841,572 | false | {"Kotlin": 64449} | package com.devspace.myapplication.detail.di
import com.devspace.myapplication.detail.data.DetailService
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ViewModelComponent
import retrofit2.Retrofit
@Module
@InstallIn(ViewModelComponent::class)
class RecipeDetailModule {
@Provides
fun provideMovieDetailService(retrofit: Retrofit): DetailService {
return retrofit.create(DetailService::class.java)
}
} | 0 | Kotlin | 0 | 2 | 6251125b99c6aeecebc01205bb8199d0fd81d7ba | 487 | EasyRecipes | The Unlicense |
libraries/recyclerview-renders/src/main/java/com/simplecrud/recyclerviewrenders/interfaces/Builder.kt | keppra | 510,439,516 | false | {"Kotlin": 122424, "Java": 33124} | package com.simplecrud.recyclerviewrenders.interfaces
import com.simplecrud.recyclerviewrenders.renderer.Renderer
/**
* @author <NAME> <https:></https:>//github.com/Alexrs95>
*/
interface Builder<R : Renderable> {
/**
* @param id the ID of the layout
* @return an instance of the builder
*/
fun instantiate(id: Int): Builder<R>
/**
* @return the Renderer assigned to the layout
*/
fun create(): Renderer<R>
}
| 0 | Kotlin | 0 | 0 | 67a6468860c57593e219f3942e1341198023b6e1 | 455 | simple-crud | MIT License |
modules/ktorium-datetime/src/commonTest/kotlinX/TimeZoneTest.kt | ktorium | 316,943,260 | false | {"Kotlin": 67933} | @file:Suppress("PackageDirectoryMismatch")
package org.ktorium.datetime
import kotlinx.datetime.TimeZone
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
class TimeZoneTest {
@Test
fun ofOrNull_validTimeZone_success() {
val expected = TimeZone.of("Europe/Berlin")
val value = TimeZone.ofOrNull("Europe/Berlin")
assertEquals(expected, value)
}
@Test
fun ofOrNull_invalidTimeZone_success() {
assertNull(TimeZone.ofOrNull("America/Moscow"))
}
}
| 0 | Kotlin | 0 | 0 | 132a5ee0ffeba74a5587b6d51dfaf13bb80a6eeb | 542 | ktorium-kotlin | Apache License 2.0 |
data/seasons/api/src/commonMain/kotlin/com/thomaskioko/tvmaniac/seasons/api/SeasonsRepository.kt | thomaskioko | 361,393,353 | false | {"Kotlin": 598853, "Swift": 126057} | package com.thomaskioko.tvmaniac.seasons.api
import com.thomaskioko.tvmaniac.core.db.ShowSeasons
import com.thomaskioko.tvmaniac.util.model.Either
import com.thomaskioko.tvmaniac.util.model.Failure
import kotlinx.coroutines.flow.Flow
interface SeasonsRepository {
suspend fun fetchSeasonsByShowId(id: Long): List<ShowSeasons>
fun observeSeasonsByShowId(id: Long): Flow<Either<Failure, List<ShowSeasons>>>
}
| 7 | Kotlin | 21 | 160 | 3688733b00226f7ceb7dcb8b462bf074017462f7 | 414 | tv-maniac | Apache License 2.0 |
intellij-plugin-structure/structure-base/src/main/kotlin/com/jetbrains/plugin/structure/jar/PluginJar.kt | JetBrains | 3,686,654 | false | null | package com.jetbrains.plugin.structure.jar
import com.jetbrains.plugin.structure.base.plugin.IconTheme
import com.jetbrains.plugin.structure.base.plugin.PluginIcon
import com.jetbrains.plugin.structure.base.plugin.ThirdPartyDependency
import com.jetbrains.plugin.structure.base.plugin.parseThirdPartyDependenciesByPath
import com.jetbrains.plugin.structure.base.utils.exists
import com.jetbrains.plugin.structure.base.utils.inputStream
import com.jetbrains.plugin.structure.base.utils.readBytes
import com.jetbrains.plugin.structure.base.utils.toSystemIndependentName
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.File
import java.nio.file.FileSystem
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
const val META_INF = "META-INF"
const val PLUGIN_XML = "plugin.xml"
val PLUGIN_XML_RESOURCE_PATH = META_INF + File.separator + PLUGIN_XML
private val THIRD_PARTY_LIBRARIES_FILE_NAME = "dependencies.json"
private val LOG: Logger = LoggerFactory.getLogger(PluginJar::class.java)
class PluginJar(private val jarPath: Path, private val jarFileSystemProvider: JarFileSystemProvider = DefaultJarFileSystemProvider()): AutoCloseable {
private val jarFileSystem: FileSystem = jarFileSystemProvider.getFileSystem(jarPath).also {
LOG.debug("Provider '{}' created file system for [{}]", jarFileSystemProvider.javaClass.name, jarPath)
}
fun resolveDescriptorPath(descriptorPath: String = PLUGIN_XML_RESOURCE_PATH): Path? {
val descriptor = jarFileSystem.getPath(toCanonicalPath(descriptorPath))
return if (Files.exists(descriptor)) {
descriptor
} else {
null
}
}
fun getPluginDescriptor(descriptorPathValue: String = PLUGIN_XML_RESOURCE_PATH): PluginDescriptorResult {
val descriptorPath = resolveDescriptorPath(descriptorPathValue) ?: return PluginDescriptorResult.NotFound
return PluginDescriptorResult.Found(descriptorPath, descriptorPath.inputStream().buffered())
}
fun getPluginDescriptor(vararg possibleDescriptorPaths: String): PluginDescriptorResult {
return possibleDescriptorPaths
.asSequence()
.map { getPluginDescriptor(it) }
.firstOrNull { it is PluginDescriptorResult.Found }
?: PluginDescriptorResult.NotFound
}
fun getIcons(): List<PluginIcon> {
val defaultIcon = findPluginIcon(IconTheme.DEFAULT)
if (defaultIcon == null) {
LOG.debug("Default plugin icon not found (plugin archive {})", jarPath)
return emptyList()
}
return IconTheme.values().mapNotNull {
when (it) {
IconTheme.DEFAULT -> defaultIcon
IconTheme.DARCULA -> findPluginIcon(it)
}
}
}
private fun findPluginIcon(theme: IconTheme): PluginIcon? {
val iconEntryName = "$META_INF/${getIconFileName(theme)}"
val iconPath = jarFileSystem.getPath(META_INF, getIconFileName(theme))
return if (iconPath.exists()) {
PluginIcon(theme, iconPath.readBytes(), iconEntryName)
} else {
null
}
}
fun getThirdPartyDependencies(): List<ThirdPartyDependency> {
val path = jarFileSystem.getPath(META_INF, THIRD_PARTY_LIBRARIES_FILE_NAME)
return parseThirdPartyDependenciesByPath(path)
}
private fun toCanonicalPath(descriptorPath: String): String {
return Paths.get(descriptorPath.toSystemIndependentName()).normalize().toString()
}
private fun getIconFileName(iconTheme: IconTheme) = "pluginIcon${iconTheme.suffix}.svg"
override fun close() {
jarFileSystemProvider.close(jarPath)
}
} | 4 | null | 47 | 178 | 8be19a2c67854545d719fe56f3677122481b372f | 3,515 | intellij-plugin-verifier | Apache License 2.0 |
src/commonMain/kotlin/com/ashampoo/kim/format/webp/chunk/WebPChunkVP8.kt | Ashampoo | 647,186,626 | false | null | /*
* Copyright 2024 Ashampoo GmbH & Co. KG
* Copyright 2007-2023 The Apache Software Foundation
*
* 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.ashampoo.kim.format.webp.chunk
import com.ashampoo.kim.common.ImageReadException
import com.ashampoo.kim.format.webp.WebPChunkType
import com.ashampoo.kim.format.webp.WebPConstants
import com.ashampoo.kim.model.ImageSize
/*
* https://developers.google.com/speed/webp/docs/riff_container#simple_file_format_lossy
*/
@Suppress("MagicNumber")
class WebPChunkVP8(
bytes: ByteArray
) : WebPChunk(WebPChunkType.VP8, bytes), ImageSizeAware {
val versionNumber: Int
override val imageSize: ImageSize
val horizontalScale: Int
val verticalScale: Int
init {
if (bytes.size < REQUIRED_BYTE_SIZE)
throw ImageReadException("Invalid VP8 chunk")
/*
* https://datatracker.ietf.org/doc/html/rfc6386#section-9
*
* Frame Header:
*
* 1. A 1-bit frame type (0 for key frames, 1 for interframes).
*
* 2. A 3-bit version number (0 - 3 are defined as four different profiles with different
* decoding complexity; other values may be defined for future variants of the VP8 data format).
*
* 3. A 1-bit show_frame flag (0 when current frame is not for display, 1 when current frame is for display).
*
* 4. A 19-bit field containing the size of the first data partition in bytes.
*/
val b0: Int = bytes[0].toInt() and 0xFF
if (b0 and 1 != 0)
throw ImageReadException("Invalid VP8 chunk: should be key frame")
versionNumber = b0 and 14 shr 1
if (b0 and 16 == 0)
throw ImageReadException("Invalid VP8 chunk: frame should to be display")
/*
* Key Frame:
*
* Start code byte 0 0x9d Start code byte 1 0x01 Start code byte 2 0x2a
*
* 16 bits : (2 bits Horizontal Scale << 14) | Width (14 bits)
* 16 bits : (2 bits Vertical Scale << 14) | Height (14 bits)
*/
val b3: Int = bytes[3].toInt() and 0xFF
val b4: Int = bytes[4].toInt() and 0xFF
val b5: Int = bytes[5].toInt() and 0xFF
val b6: Int = bytes[6].toInt() and 0xFF
val b7: Int = bytes[7].toInt() and 0xFF
val b8: Int = bytes[8].toInt() and 0xFF
val b9: Int = bytes[9].toInt() and 0xFF
if (b3 != 0x9D || b4 != 0x01 || b5 != 0x2A)
throw ImageReadException("Invalid VP8 chunk: invalid signature")
imageSize = ImageSize(
width = b6 + (b7 and 63 shl 8),
height = b8 + (b9 and 63 shl 8)
)
if (imageSize.longestSide > WebPConstants.MAX_SIDE_LENGTH)
throw ImageReadException("Illegal dimensions: $imageSize")
horizontalScale = b7 shr 6
verticalScale = b9 shr 6
}
override fun toString(): String =
super.toString() +
" versionNumber=$versionNumber imageSize=$imageSize" +
" horizontalScale=$horizontalScale verticalScale=$verticalScale"
companion object {
private const val REQUIRED_BYTE_SIZE: Int = 10
}
}
| 8 | null | 8 | 172 | 5e6cd23c52abf8c840b235eb68744a9ab135c235 | 3,714 | kim | Apache License 2.0 |
app/src/main/java/ch/abwesend/privatecontacts/domain/model/contactdata/Company.kt | fgubler | 462,182,037 | false | {"Kotlin": 1159351, "Java": 369326} | /*
* Private Contacts
* Copyright (c) 2022.
* <NAME>
*/
package ch.abwesend.privatecontacts.domain.model.contactdata
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Apartment
import ch.abwesend.privatecontacts.R
import ch.abwesend.privatecontacts.domain.model.ModelStatus
import ch.abwesend.privatecontacts.domain.model.ModelStatus.CHANGED
data class Company(
override val id: ContactDataId,
override val sortOrder: Int,
override val type: ContactDataType,
override val value: String,
override val isMain: Boolean = false,
override val modelStatus: ModelStatus,
) : StringBasedContactDataGeneric<Company> {
override val category: ContactDataCategory = ContactDataCategory.COMPANY
override val allowedTypes: List<ContactDataType>
get() = defaultAllowedTypes
override fun changeValue(value: String): Company {
val status = modelStatus.tryChangeTo(CHANGED)
return copy(value = value, modelStatus = status)
}
override fun changeType(type: ContactDataType): Company {
val status = modelStatus.tryChangeTo(CHANGED)
return copy(type = type, modelStatus = status)
}
override fun overrideStatus(newStatus: ModelStatus) = copy(modelStatus = newStatus)
override fun changeToInternalId(): ContactData = copy(id = createContactDataId())
override fun changeToExternalId(): ContactData = copy(id = createExternalDummyContactDataId())
override fun changeSortOrder(newSortOrder: Int): Company {
val status = modelStatus.tryChangeTo(CHANGED)
return copy(sortOrder = newSortOrder, modelStatus = status)
}
override fun delete(): Company {
val status = modelStatus.tryChangeTo(ModelStatus.DELETED)
return copy(modelStatus = status)
}
companion object {
val icon = Icons.Default.Apartment
val labelPlural get() = R.string.companies
val labelSingular get() = R.string.company
private val defaultAllowedTypes = listOf(
ContactDataType.Main,
ContactDataType.Other,
ContactDataType.Custom,
)
fun createEmpty(sortOrder: Int): Company {
val isMain = (sortOrder == 0)
return Company(
id = createContactDataId(),
sortOrder = sortOrder,
type = if (isMain) ContactDataType.Main else ContactDataType.Other,
value = "",
isMain = isMain,
modelStatus = ModelStatus.NEW,
)
}
}
}
| 1 | Kotlin | 1 | 9 | 52f679a7803883e6c2530e0fb642049631201656 | 2,579 | PrivateContacts | Apache License 2.0 |
app/src/main/java/ch/abwesend/privatecontacts/domain/model/contactdata/Company.kt | fgubler | 462,182,037 | false | {"Kotlin": 1159351, "Java": 369326} | /*
* Private Contacts
* Copyright (c) 2022.
* <NAME>
*/
package ch.abwesend.privatecontacts.domain.model.contactdata
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Apartment
import ch.abwesend.privatecontacts.R
import ch.abwesend.privatecontacts.domain.model.ModelStatus
import ch.abwesend.privatecontacts.domain.model.ModelStatus.CHANGED
data class Company(
override val id: ContactDataId,
override val sortOrder: Int,
override val type: ContactDataType,
override val value: String,
override val isMain: Boolean = false,
override val modelStatus: ModelStatus,
) : StringBasedContactDataGeneric<Company> {
override val category: ContactDataCategory = ContactDataCategory.COMPANY
override val allowedTypes: List<ContactDataType>
get() = defaultAllowedTypes
override fun changeValue(value: String): Company {
val status = modelStatus.tryChangeTo(CHANGED)
return copy(value = value, modelStatus = status)
}
override fun changeType(type: ContactDataType): Company {
val status = modelStatus.tryChangeTo(CHANGED)
return copy(type = type, modelStatus = status)
}
override fun overrideStatus(newStatus: ModelStatus) = copy(modelStatus = newStatus)
override fun changeToInternalId(): ContactData = copy(id = createContactDataId())
override fun changeToExternalId(): ContactData = copy(id = createExternalDummyContactDataId())
override fun changeSortOrder(newSortOrder: Int): Company {
val status = modelStatus.tryChangeTo(CHANGED)
return copy(sortOrder = newSortOrder, modelStatus = status)
}
override fun delete(): Company {
val status = modelStatus.tryChangeTo(ModelStatus.DELETED)
return copy(modelStatus = status)
}
companion object {
val icon = Icons.Default.Apartment
val labelPlural get() = R.string.companies
val labelSingular get() = R.string.company
private val defaultAllowedTypes = listOf(
ContactDataType.Main,
ContactDataType.Other,
ContactDataType.Custom,
)
fun createEmpty(sortOrder: Int): Company {
val isMain = (sortOrder == 0)
return Company(
id = createContactDataId(),
sortOrder = sortOrder,
type = if (isMain) ContactDataType.Main else ContactDataType.Other,
value = "",
isMain = isMain,
modelStatus = ModelStatus.NEW,
)
}
}
}
| 1 | Kotlin | 1 | 9 | 52f679a7803883e6c2530e0fb642049631201656 | 2,579 | PrivateContacts | Apache License 2.0 |
src/main/kotlin/application/service/PatientServices.kt | SmartOperatingBlock | 606,908,179 | false | null | /*
* Copyright (c) 2023. Smart Operating Block
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
package application.service
import entity.Patient
import entity.PatientData.TaxCode
import usecase.repository.PatientRepository
/** The module with all the [Patient] [ApplicationService]. */
object PatientServices {
/** Application service to create a [patient] using a [patientRepository]. */
class CreatePatient(
private val patient: Patient,
private val patientRepository: PatientRepository,
) : ApplicationService<Boolean> {
override fun execute(): Boolean =
if (patientRepository.getPatient(patient.taxCode) == null) {
patientRepository.createPatient(patient)
} else {
false
}
}
/** Application service to delete a [Patient] given the [taxCode] using a [patientRepository]. */
class DeletePatient(
private val taxCode: TaxCode,
private val patientRepository: PatientRepository,
) : ApplicationService<Boolean> {
override fun execute(): Boolean =
patientRepository.deletePatient(taxCode)
}
/** Application service to det a [Patient] given the [taxCode] using a [patientRepository]. */
class GetPatient(
private val taxCode: TaxCode,
private val patientRepository: PatientRepository,
) : ApplicationService<Patient?> {
override fun execute(): Patient? =
patientRepository.getPatient(taxCode)
}
}
| 2 | Kotlin | 0 | 0 | 3c8ad933b959e6b2ced8dc892094d393cdac566e | 1,625 | patient-management-integration-microservice | MIT License |
sdk/src/test/kotlin/com/processout/sdk/config/TestConstants.kt | processout | 117,821,122 | false | {"Kotlin": 804764, "Java": 85526, "Shell": 696} | package com.processout.sdk.config
internal const val PROCESSOUT_GATEWAY_CONFIGURATION_ID = "gway_conf_VJEp8Y6ZCqiiwkSa3JioJrwdVM3bVgJd"
| 0 | Kotlin | 5 | 2 | 9faf6fc6db47aa2119febc59423acd359c408fb8 | 137 | processout-android | MIT License |
code/app/src/main/java/com/tanfra/shopmob/smob/ui/planning/lists/PlanningListsTableFragment.kt | fwornle | 440,434,944 | false | null | package com.tanfra.shopmob.smob.ui.planning.lists
import android.os.Bundle
import android.view.*
import androidx.databinding.DataBindingUtil
import com.tanfra.shopmob.R
import com.tanfra.shopmob.smob.ui.base.BaseFragment
import com.tanfra.shopmob.smob.ui.base.NavigationCommand
import com.tanfra.shopmob.utils.setDisplayHomeAsUpEnabled
import com.tanfra.shopmob.utils.setTitle
import android.content.Intent
import android.widget.Toast
import androidx.core.os.bundleOf
import androidx.core.view.MenuHost
import androidx.core.view.MenuProvider
import androidx.lifecycle.Lifecycle
import androidx.recyclerview.widget.ItemTouchHelper
import com.firebase.ui.auth.AuthUI
import com.tanfra.shopmob.databinding.FragmentPlanningListsTableBinding
import com.tanfra.shopmob.smob.data.repo.utils.Status
import com.tanfra.shopmob.smob.ui.auth.SmobAuthActivity
import com.tanfra.shopmob.smob.ui.planning.PlanningViewModel
import com.tanfra.shopmob.smob.ui.shopping.SmobShoppingActivity
import com.tanfra.shopmob.utils.setup
import com.tanfra.shopmob.utils.wrapEspressoIdlingResource
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
import org.koin.core.component.KoinComponent
class PlanningListsTableFragment : BaseFragment(), KoinComponent {
// use Koin service locator to retrieve the ViewModel instance(s)
override val _viewModel: PlanningViewModel by sharedViewModel()
// data binding for fragment_planning_lists.xml
private lateinit var binding: FragmentPlanningListsTableBinding
@OptIn(ExperimentalCoroutinesApi::class)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// bind layout class
binding =
DataBindingUtil.inflate(
inflater,
R.layout.fragment_planning_lists_table, container, false
)
// set injected viewModel (from KOIN service locator)
binding.viewModel = _viewModel
setDisplayHomeAsUpEnabled(true)
setTitle(getString(R.string.app_name))
// install listener for SwipeRefreshLayout view
binding.refreshLayout.setOnRefreshListener {
// deactivate SwipeRefreshLayout spinner
binding.refreshLayout.setRefreshing(false)
// refresh local DB data from backend (for this list) - also updates 'showNoData'
_viewModel.swipeRefreshDataInLocalDB()
// empty? --> inform user that there is no point swiping for further updates...
if (_viewModel.showNoData.value == true) {
Toast.makeText(activity, getString(R.string.error_add_smob_lists), Toast.LENGTH_SHORT).show()
}
}
// refresh local DB data from backend (for this list) - also updates 'showNoData'
_viewModel.swipeRefreshDataInLocalDB()
return binding.root
}
@OptIn(ExperimentalCoroutinesApi::class)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.lifecycleOwner = viewLifecycleOwner
// RV - incl. onClick listener for items
setupRecyclerView()
// handlers for "+" FAB, "SHOP" FAB and "STORE" FAB
binding.addSmobItemFab.setOnClickListener { navigateToAddSmobList() }
binding.goShop.setOnClickListener { navigateToShopping() }
binding.defineShop.setOnClickListener { navigateToShopEditFragment() }
// The usage of an interface lets you inject your own implementation
val menuHost: MenuHost = requireActivity()
// Add menu items without using the Fragment Menu APIs
// Note how we can tie the MenuProvider to the viewLifecycleOwner
// and an optional Lifecycle.State (here, STARTED) to indicate when
// the menu should be visible
menuHost.addMenuProvider(
object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.main_menu, menu)
}
override fun onMenuItemSelected(item: MenuItem) = when (item.itemId) {
// logout menu
R.id.logout -> {
// logout authenticated user
AuthUI.getInstance()
.signOut(requireContext())
.addOnCompleteListener {
// user is now signed out -> redirect to login screen
startActivity(Intent(requireContext(), SmobAuthActivity::class.java))
// and we're done here
requireActivity().finish()
}
true
}
// back arrow (home button)
android.R.id.home -> {
_viewModel.navigationCommand.postValue(NavigationCommand.Back)
true
}
// unhandled...
else -> false
} // when(item...)
},
viewLifecycleOwner,
Lifecycle.State.RESUMED,
)
}
// "+" FAB handler --> navigate to selected fragment of the admin activity
private fun navigateToAddSmobList() {
// determine hightest index in all smobLists
val highPos = _viewModel.smobLists.value.let {
if (it.status == Status.SUCCESS) {
// return highest index
it.data?.fold(0L) { max, list -> if (list?.itemPosition!! > max) list.itemPosition else max } ?: 0L
} else {
0L
}
}
// communicate the currently highest list position
val bundle = bundleOf(
"listPosMax" to highPos,
)
// use the navigationCommand live data to navigate between the fragments
_viewModel.navigationCommand.postValue(
NavigationCommand.ToWithBundle(
R.id.smobPlanningListsAddNewItemFragment,
bundle
)
)
}
// "SHOP" FAB handler --> navigate to shopping activity (SmobShoppingActivity)
private fun navigateToShopping() {
val intent = SmobShoppingActivity.newIntent(requireContext())
wrapEspressoIdlingResource {
startActivity(intent)
}
}
// "STORE" FAB handler --> navigate to shop/store management fragment
private fun navigateToShopEditFragment() {
// use the navigationCommand live data to navigate between the fragments
_viewModel.navigationCommand.postValue(
NavigationCommand.To(
PlanningListsTableFragmentDirections.actionSmobPlanningListsTableFragmentToSmobPlanningShopsAddNewItemFragment()
)
)
}
private fun setupRecyclerView() {
val adapter = PlanningListsTableAdapter(binding.root) {
// this lambda is the 'callback' function which gets called when clicking an item in the
// RecyclerView - it gets the data behind the clicked item as parameter
// communicate the ID and name of the selected item (= shopping list)
val bundle = bundleOf(
"listId" to it.id,
"listName" to it.name,
)
// use the navigationCommand live data to navigate between the fragments
_viewModel.navigationCommand.postValue(
NavigationCommand.ToWithBundle(
R.id.smobPlanningProductsTableFragment,
bundle
)
)
} // "on-item-click" lambda
// setup the recycler view using the extension function
binding.smobItemsRecyclerView.setup(adapter)
// enable swiping left/right
val itemTouchHelper = ItemTouchHelper(PlanningListsTableSwipeActionHandler(adapter))
itemTouchHelper.attachToRecyclerView(binding.smobItemsRecyclerView)
}
} | 0 | Kotlin | 0 | 0 | e202df0b49a3a499cedf2b36df5c887dda828c0f | 8,171 | ShopMob | MIT License |
platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/changesHandler/CommonInjectedFileChangesHandler.kt | hieuprogrammer | 284,920,751 | false | null | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl.source.tree.injected.changesHandler
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.diagnostic.RuntimeExceptionWithAttachments
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.util.ProperTextRange
import com.intellij.openapi.util.Segment
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import org.jetbrains.annotations.ApiStatus
import java.util.*
import kotlin.math.max
import kotlin.math.min
open class CommonInjectedFileChangesHandler(
shreds: List<PsiLanguageInjectionHost.Shred>,
hostEditor: Editor,
fragmentDocument: Document,
injectedFile: PsiFile
) : BaseInjectedFileChangesHandler(hostEditor, fragmentDocument, injectedFile) {
protected val markers: MutableList<MarkersMapping> =
LinkedList<MarkersMapping>().apply {
addAll(getMarkersFromShreds(shreds))
}
protected fun getMarkersFromShreds(shreds: List<PsiLanguageInjectionHost.Shred>): List<MarkersMapping> {
val result = ArrayList<MarkersMapping>(shreds.size)
val smartPointerManager = SmartPointerManager.getInstance(myProject)
var curOffset = -1
for (shred in shreds) {
val rangeMarker = fragmentMarkerFromShred(shred)
val rangeInsideHost = shred.rangeInsideHost
val host = shred.host ?: failAndReport("host should not be null", null, null)
val origMarker = myHostDocument.createRangeMarker(rangeInsideHost.shiftRight(host.textRange.startOffset))
val elementPointer = smartPointerManager.createSmartPsiElementPointer(host)
result.add(MarkersMapping(origMarker, rangeMarker, elementPointer))
origMarker.isGreedyToRight = true
rangeMarker.isGreedyToRight = true
if (origMarker.startOffset > curOffset) {
origMarker.isGreedyToLeft = true
rangeMarker.isGreedyToLeft = true
}
curOffset = origMarker.endOffset
}
return result
}
override fun isValid(): Boolean = myInjectedFile.isValid && markers.all { it.isValid() }
override fun commitToOriginal(e: DocumentEvent) {
val text = myFragmentDocument.text
val map = markers.groupByTo(LinkedHashMap()) { it.host }
val documentManager = PsiDocumentManager.getInstance(myProject)
documentManager.commitDocument(myHostDocument) // commit here and after each manipulator update
var localInsideFileCursor = 0
for (host in map.keys) {
if (host == null) continue
val hostText = host.text
var insideHost: ProperTextRange? = null
val sb = StringBuilder()
for ((hostMarker, fragmentMarker, _) in map[host].orEmpty()) {
val hostOffset = host.textRange.startOffset
val localInsideHost = ProperTextRange(hostMarker.startOffset - hostOffset, hostMarker.endOffset - hostOffset)
val localInsideFile = ProperTextRange(max(localInsideFileCursor, fragmentMarker.startOffset), fragmentMarker.endOffset)
if (insideHost != null) {
//append unchanged inter-markers fragment
sb.append(hostText, insideHost.endOffset, localInsideHost.startOffset)
}
if (localInsideFile.endOffset <= text.length && !localInsideFile.isEmpty) {
sb.append(localInsideFile.substring(text))
}
localInsideFileCursor = localInsideFile.endOffset
insideHost = insideHost?.union(localInsideHost) ?: localInsideHost
}
if (insideHost == null) failAndReport("insideHost is null", e)
updateInjectionHostElement(host, insideHost, sb.toString())
documentManager.commitDocument(myHostDocument)
}
}
protected fun updateInjectionHostElement(host: PsiLanguageInjectionHost, insideHost: ProperTextRange, content: String) {
ElementManipulators.getManipulator(host).handleContentChange(host, insideHost, content)
}
override fun dispose() {
markers.forEach(MarkersMapping::dispose)
markers.clear()
super.dispose()
}
override fun handlesRange(range: TextRange): Boolean {
if (markers.isEmpty()) return false
val hostRange = TextRange.create(markers[0].hostMarker.startOffset,
markers[markers.size - 1].hostMarker.endOffset)
return range.intersects(hostRange)
}
protected fun fragmentMarkerFromShred(shred: PsiLanguageInjectionHost.Shred): RangeMarker =
myFragmentDocument.createRangeMarker(shred.innerRange)
protected fun failAndReport(message: String, e: DocumentEvent? = null, exception: Exception? = null): Nothing =
throw getReportException(message, e, exception)
protected fun getReportException(message: String,
e: DocumentEvent?,
exception: Exception?): RuntimeExceptionWithAttachments =
RuntimeExceptionWithAttachments("${this.javaClass.simpleName}: $message (event = $e)," +
" myInjectedFile.isValid = ${myInjectedFile.isValid}, isValid = $isValid",
*listOfNotNull(
Attachment("hosts", markers.joinToString("\n\n") { it.host?.text ?: "<null>" }),
Attachment("markers", markers.logMarkersRanges()),
Attachment("injected document", this.myFragmentDocument.text),
exception?.let { Attachment("exception", it) }
).toTypedArray()
)
protected fun MutableList<MarkersMapping>.logMarkersRanges(): String = joinToString("\n") { mm ->
"fragment:${myFragmentDocument.logMarker(mm.fragmentRange)} host:${logHostMarker(mm.hostMarker.range)}"
}
protected fun logHostMarker(rangeInHost: TextRange?) = myHostDocument.logMarker(rangeInHost)
protected fun Document.logMarker(rangeInHost: TextRange?): String = "$rangeInHost -> '${rangeInHost?.let {
try {
getText(it)
}
catch (e: IndexOutOfBoundsException) {
e.toString()
}
}}'"
protected fun String.substringVerbose(start: Int, cursor: Int): String = try {
substring(start, cursor)
}
catch (e: StringIndexOutOfBoundsException) {
failAndReport("can't get substring ($start, $cursor) of '${this}'[$length]", exception = e)
}
fun distributeTextToMarkers(affectedMarkers: List<MarkersMapping>,
affectedRange: TextRange,
limit: Int): List<Pair<MarkersMapping, String>> {
var cursor = 0
return affectedMarkers.indices.map { i ->
val marker = affectedMarkers[i]
val fragmentMarker = marker.fragmentMarker
marker to if (fragmentMarker.isValid) {
val start = max(cursor, fragmentMarker.startOffset)
val text = fragmentMarker.document.text
cursor = if (affectedLength(marker, affectedRange) == 0 && affectedLength(affectedMarkers.getOrNull(i + 1), affectedRange) > 1)
affectedMarkers.getOrNull(i + 1)!!.fragmentMarker.startOffset
else
min(text.length, max(fragmentMarker.endOffset, limit))
text.substringVerbose(start, cursor)
}
else ""
}
}
}
data class MarkersMapping(val hostMarker: RangeMarker,
val fragmentMarker: RangeMarker,
val hostPointer: SmartPsiElementPointer<PsiLanguageInjectionHost>) {
val host: PsiLanguageInjectionHost? get() = hostPointer.element
val hostElementRange: TextRange? get() = hostPointer.range?.range
val fragmentRange: TextRange get() = fragmentMarker.range
fun isValid(): Boolean = hostMarker.isValid && fragmentMarker.isValid && hostPointer.element?.isValid == true
fun dispose() {
fragmentMarker.dispose()
hostMarker.dispose()
}
}
inline val Segment.range: TextRange get() = TextRange.create(this)
inline val PsiLanguageInjectionHost.Shred.innerRange: TextRange
get() = TextRange.create(this.range.startOffset + this.prefix.length,
this.range.endOffset - this.suffix.length)
val PsiLanguageInjectionHost.contentRange
get() = ElementManipulators.getManipulator(this).getRangeInElement(this).shiftRight(textRange.startOffset)
private val PsiElement.withNextSiblings: Sequence<PsiElement>
get() = generateSequence(this) { it.nextSibling }
@ApiStatus.Internal
fun getInjectionHostAtRange(hostPsiFile: PsiFile, contextRange: Segment): PsiLanguageInjectionHost? =
hostPsiFile.findElementAt(contextRange.startOffset)?.withNextSiblings.orEmpty()
.takeWhile { it.textRange.startOffset < contextRange.endOffset }
.flatMap { sequenceOf(it, it.parent) }
.filterIsInstance<PsiLanguageInjectionHost>().firstOrNull()
private fun affectedLength(markersMapping: MarkersMapping?, affectedRange: TextRange): Int =
markersMapping?.fragmentRange?.let { affectedRange.intersection(it)?.length } ?: -1 | 1 | null | 1 | 2 | dc846ecb926c9d9589c1ed8a40fdb20e47874db9 | 9,099 | intellij-community | Apache License 2.0 |
stellaris-modding-support/src/main/kotlin/com/windea/plugin/idea/stellaris/script/editor/StellarisScriptDescriptionProvider.kt | DragonKnightOfBreeze | 271,196,420 | false | null | package com.windea.plugin.idea.stellaris.script.editor
import com.intellij.psi.*
import com.intellij.usageView.*
import com.windea.plugin.idea.stellaris.*
import com.windea.plugin.idea.stellaris.script.psi.*
class StellarisScriptDescriptionProvider: ElementDescriptionProvider {
override fun getElementDescription(element: PsiElement, location: ElementDescriptionLocation): String? {
return when(element) {
is StellarisScriptVariable ->{
if(location == UsageViewTypeLocation.INSTANCE) message("stellaris.script.description.variable")
else element.name
}
is StellarisScriptProperty ->{
if(location == UsageViewTypeLocation.INSTANCE) message("stellaris.script.description.property")
else element.name
}
else -> null
}
}
}
| 1 | Kotlin | 2 | 4 | abadd50d6fba765e64995f27d525270d4907efed | 759 | Idea-Plugins | MIT License |
stellaris-modding-support/src/main/kotlin/com/windea/plugin/idea/stellaris/script/editor/StellarisScriptDescriptionProvider.kt | DragonKnightOfBreeze | 271,196,420 | false | null | package com.windea.plugin.idea.stellaris.script.editor
import com.intellij.psi.*
import com.intellij.usageView.*
import com.windea.plugin.idea.stellaris.*
import com.windea.plugin.idea.stellaris.script.psi.*
class StellarisScriptDescriptionProvider: ElementDescriptionProvider {
override fun getElementDescription(element: PsiElement, location: ElementDescriptionLocation): String? {
return when(element) {
is StellarisScriptVariable ->{
if(location == UsageViewTypeLocation.INSTANCE) message("stellaris.script.description.variable")
else element.name
}
is StellarisScriptProperty ->{
if(location == UsageViewTypeLocation.INSTANCE) message("stellaris.script.description.property")
else element.name
}
else -> null
}
}
}
| 1 | Kotlin | 2 | 4 | abadd50d6fba765e64995f27d525270d4907efed | 759 | Idea-Plugins | MIT License |
app/src/main/java/com/example/myapplication/MainActivity.kt | ArthurMitsuo | 676,304,718 | false | null | package com.example.myapplication
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Button
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*var textoPrincipal = this.findViewById<TextView>(R.id.textView)
textoPrincipal.setText("VAI");
var botaoPrincipal = this.findViewById<Button>(R.id.button)
botaoPrincipal.setOnClickListener{
if(textoPrincipal.getText().equals("VAi")){
textoPrincipal.setText("TOMAR NO")
}else if (textoPrincipal.getText().equals("TOMAR NO")){
textoPrincipal.setText("CELULAR")
}else {
textoPrincipal.setText("VAI")
}
}*/
/*
val languageName:String = "Kotlin"; //constante
var laguageName: String = null; //não funciona/compila
var laguageName: String? = null; //funciona
*/
var button1:Button = findViewById(R.id.button);
var doido:Int = 1;
button1.setOnClickListener{
Toast.makeText(this, "Clicou", Toast.LENGTH_LONG).show();
var imagem:ImageView = findViewById(R.id.imageView2);
var checkBox:CheckBox = findViewById(R.id.checkBox2)
val marcado = checkBox.isChecked
if(marcado){
imagem.setImageResource(R.mipmap.pablo_escobar)
}else{
imagem.setImageResource(R.mipmap.albert_hoffman)
}
}
}
fun clicouTrocou(view: View){
var checkBox:CheckBox = findViewById(R.id.checkBox2)
val marcado:Boolean = checkBox.isChecked;
var imagem:ImageView = findViewById(R.id.imageView2);
if(marcado){
imagem.setImageResource(R.mipmap.pablo_escobar)
}else{
imagem.setImageResource(R.mipmap.albert_hoffman)
}
}
} | 0 | Kotlin | 0 | 0 | 460da7b937e526c1ce401e01a5fe0d72e424faa4 | 2,168 | meuProjetoAndroid | Apache License 2.0 |
app/src/main/java/com/example/myapplication/MainActivity.kt | ArthurMitsuo | 676,304,718 | false | null | package com.example.myapplication
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Button
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*var textoPrincipal = this.findViewById<TextView>(R.id.textView)
textoPrincipal.setText("VAI");
var botaoPrincipal = this.findViewById<Button>(R.id.button)
botaoPrincipal.setOnClickListener{
if(textoPrincipal.getText().equals("VAi")){
textoPrincipal.setText("TOMAR NO")
}else if (textoPrincipal.getText().equals("TOMAR NO")){
textoPrincipal.setText("CELULAR")
}else {
textoPrincipal.setText("VAI")
}
}*/
/*
val languageName:String = "Kotlin"; //constante
var laguageName: String = null; //não funciona/compila
var laguageName: String? = null; //funciona
*/
var button1:Button = findViewById(R.id.button);
var doido:Int = 1;
button1.setOnClickListener{
Toast.makeText(this, "Clicou", Toast.LENGTH_LONG).show();
var imagem:ImageView = findViewById(R.id.imageView2);
var checkBox:CheckBox = findViewById(R.id.checkBox2)
val marcado = checkBox.isChecked
if(marcado){
imagem.setImageResource(R.mipmap.pablo_escobar)
}else{
imagem.setImageResource(R.mipmap.albert_hoffman)
}
}
}
fun clicouTrocou(view: View){
var checkBox:CheckBox = findViewById(R.id.checkBox2)
val marcado:Boolean = checkBox.isChecked;
var imagem:ImageView = findViewById(R.id.imageView2);
if(marcado){
imagem.setImageResource(R.mipmap.pablo_escobar)
}else{
imagem.setImageResource(R.mipmap.albert_hoffman)
}
}
} | 0 | Kotlin | 0 | 0 | 460da7b937e526c1ce401e01a5fe0d72e424faa4 | 2,168 | meuProjetoAndroid | Apache License 2.0 |
app/src/main/java/com/sahu/playground/Playground.kt | sahruday | 824,622,867 | false | {"Kotlin": 61507} | package com.sahu.playground
import android.app.Application
import android.util.Log
import android.widget.Toast
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.FirebaseApp
import com.google.firebase.messaging.FirebaseMessaging
import com.sahu.playground.appUtil.NotificationChannelManager
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class Playground: Application() {
companion object{
const val TAG = "Playground"
}
override fun onCreate() {
super.onCreate()
FirebaseApp.initializeApp(this)
notificationChannel()
// getMessageKey()
}
private fun notificationChannel(){
NotificationChannelManager.createNotificationChannels(this)
}
private fun getMessageKey() {
FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
if (!task.isSuccessful) {
Log.w(TAG, "Fetching FCM registration token failed", task.exception)
return@OnCompleteListener
}
// Get new FCM registration token
val token = task.result
// Log and toast
val msg = "Firebase Message token: $token"
Log.d(TAG, msg)
Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
})
}
} | 0 | Kotlin | 0 | 0 | f0a737920b926eca6e452086327df7a23e34b0e4 | 1,355 | playground | MIT License |
castled-notifications/src/main/java/io/castled/android/notifications/workmanager/models/CastledNetworkRequest.kt | castledio | 525,047,434 | false | {"Kotlin": 305550, "HTML": 28150, "Java": 18371, "JavaScript": 1717} | package io.castled.android.notifications.workmanager.models
import kotlinx.serialization.Polymorphic
import kotlinx.serialization.Serializable
@Serializable
@Polymorphic
internal sealed class CastledNetworkRequest {
abstract val requestType: CastledNetworkRequestType
}
| 0 | Kotlin | 2 | 3 | 0109de7ce414d97742993786a0a4d9ba99b9425e | 276 | castled-notifications-android | MIT License |
src/main/kotlin/io/github/light0x00/lightjson/internal/Toolkit.kt | light0x00 | 618,861,123 | false | null | package io.github.light0x00.lightjson.internal
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.collections.HashSet
//import java.util.*
fun readUnexpectedErrorMsg(reader: IReader, actual: String, expected: String): String {
return """
|${expected} expected ,but got ${actual} at line ${reader.line()} column ${reader.column()}
""".trimMargin("|")
}
fun readUnexpectedErrorMsg(reader: IReader, expected: String): String {
return readUnexpectedErrorMsg(reader, ":\n" + reader.nearbyChars(), expected)
}
fun readErrorMsg(reader: IReader, msg: String): String {
return """
|$msg
|${reader.nearbyChars()}
| at line ${reader.line()} column ${reader.column()}
""".trimMargin()
}
class Graph<T> {
private val G = HashMap<T, MutableList<T>>()
fun addEdge(from: T, to: T) {
if (G[from] == null) {
G[from] = ArrayList()
}
G[from]!!.add(to);
}
fun path(from: T, to: T): List<T>? {
val stack = Stack<T>().apply { add(from) }
val visited = HashSet<T>().apply { add(from) }
val track = HashMap<T, T>()
while (stack.isNotEmpty()) {
val node = stack.pop()
val adjacencyList = G[node] ?: continue
for (adj in adjacencyList) {
track[adj] = node
if (adj == to)
return backtrack(from, to, track)
if (visited.contains(adj))
continue
stack.add(adj)
visited.add(adj)
}
}
return null
}
private fun backtrack(from: T, to: T, track: HashMap<T, T>): List<T> {
val queue = LinkedList<T>().apply {
}
var node = track.get(to)
while (node != from) {
queue.addFirst(node)
node = track.get(node)
}
queue.addFirst(from)
queue.addLast(to)
return queue
}
} | 0 | Kotlin | 0 | 0 | 527695909ebff1f37e9d8965550442f55149a878 | 2,057 | light-json | MIT License |
src/main/kotlin/com/example/cms/domains/sitepages/models/dtos/SitePageDto.kt | teambankrupt | 378,458,792 | false | {"Kotlin": 100695, "HTML": 43301, "Java": 554} | package com.example.cms.domains.sitepages.models.dtos
import com.example.coreweb.domains.base.models.dtos.BaseDto
import com.fasterxml.jackson.annotation.JsonProperty
import io.swagger.annotations.ApiModelProperty
import javax.validation.constraints.Min
import javax.validation.constraints.NotBlank
import javax.validation.constraints.NotNull
class SitePageDto : BaseDto() {
@ApiModelProperty(required = true)
@NotBlank
@JsonProperty("title")
lateinit var title: String
@JsonProperty("slug")
var slug: String? = null
@JsonProperty("description")
var description: String? = null
@ApiModelProperty(required = true)
@NotBlank
@JsonProperty("content")
lateinit var content: String
@ApiModelProperty(required = true)
@JsonProperty("site_id")
@NotNull
@Min(1)
var siteId: Long = 0
/*
READONLY
*/
@ApiModelProperty(readOnly = true)
@JsonProperty("summary")
var summary: String? = null
}
| 0 | Kotlin | 1 | 1 | 5bcc19e8a675781ea26ac27c6d12fe74d801322a | 982 | cms | Apache License 2.0 |
buildSrc/src/main/kotlin/Libs.kt | juanchosandox90 | 243,320,800 | false | null | object Libs {
object Kotlin {
const val stdlib = "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${Versions.kotlin}"
object Coroutines {
const val coroutines = "org.jetbrains.kotlinx:kotlinx-coroutines-core:${Versions.coroutines}"
const val android = "org.jetbrains.kotlinx:kotlinx-coroutines-android:${Versions.coroutines}"
}
}
object UI {
const val appcompat = "androidx.appcompat:appcompat:${Versions.appcompat}"
const val coreKtx = "androidx.core:core-ktx:${Versions.core}"
const val constraintLayout = "androidx.constraintlayout:constraintlayout:${Versions.constraintLayout}"
const val material = "com.google.android.material:material:${Versions.material}"
const val recyclerView = "androidx.recyclerview:recyclerview:${Versions.recyclerView}"
const val paging = "androidx.paging:paging-runtime-ktx:${Versions.paging}"
const val browser = "androidx.browser:browser:${Versions.browser}"
const val swipeRefresh = "androidx.swiperefreshlayout:swiperefreshlayout:${Versions.swipeRefresh}"
const val lottieVersion = "com.airbnb.android:lottie:${Versions.lottieVersion}"
object Navigation {
const val fragment = "androidx.navigation:navigation-fragment-ktx:${Versions.navigation}"
const val ui = "androidx.navigation:navigation-ui-ktx:${Versions.navigation}"
}
}
object Arch {
const val koin = "org.koin:koin-android-viewmodel:${Versions.koin}"
const val lifecycle = "androidx.lifecycle:lifecycle-extensions:${Versions.lifecycle}"
object Room {
const val runtime = "androidx.room:room-runtime:${Versions.room}"
const val ktx = "androidx.room:room-ktx:${Versions.room}"
const val compiler = "androidx.room:room-compiler:${Versions.room}"
}
}
object Network {
object Retrofit {
const val retrofit = "com.squareup.retrofit2:retrofit:${Versions.retrofit}"
const val converterMoshi = "com.squareup.retrofit2:converter-moshi:${Versions.retrofit}"
}
object OkHttp {
const val okHttp = "com.squareup.okhttp3:okhttp:${Versions.okHttp}"
const val loggingInterceptor = "com.squareup.okhttp3:logging-interceptor:${Versions.okHttp}"
}
object Glide {
const val glide = "com.github.bumptech.glide:glide:${Versions.glide}"
const val okHttp = "com.github.bumptech.glide:okhttp3-integration:${Versions.glide}"
const val compiler = "com.github.bumptech.glide:compiler:${Versions.glide}"
}
}
object Debug {
const val timber = "com.jakewharton.timber:timber:${Versions.timber}"
}
object Test {
const val runner = "androidx.test:runner:${Versions.test}"
const val rules = "androidx.test:rules:${Versions.test}"
const val kakao = "com.agoda.kakao:kakao:${Versions.kakao}"
object Espresso {
const val core = "androidx.test.espresso:espresso-core:${Versions.espresso}"
const val contrib = "androidx.test.espresso:espresso-contrib:${Versions.espresso}"
const val idling = "androidx.test.espresso.idling:idling-concurrent:${Versions.espresso}"
}
object Mockito {
const val core = "org.mockito:mockito-core:${Versions.mockito}"
const val android = "org.mockito:mockito-android:${Versions.mockito}"
const val kotlin = "com.nhaarman.mockitokotlin2:mockito-kotlin:${Versions.mockitoKotlin}"
}
}
} | 0 | Kotlin | 0 | 0 | 0528c7fd53936303519a8c01c5839fe394468f8e | 3,612 | ChipperRedditTest | Apache License 2.0 |
src/main/kotlin/dev/zlagi/application/model/request/RefreshTokenRequest.kt | Zlagi | 470,380,982 | false | {"Kotlin": 77094, "Procfile": 45} | package dev.zlagi.application.model.request
import kotlinx.serialization.Serializable
@Serializable
data class RefreshTokenRequest(
val token: String
) | 1 | Kotlin | 2 | 41 | 16e6462cafc347dff822b7dac42449f62e269e66 | 157 | Blogfy-api | Apache License 2.0 |
src/test/kotlin/ch/derlin/dcvizmermaid/renderers/MermaidRendererTest.kt | derlin | 408,822,160 | false | {"Kotlin": 80536, "Dockerfile": 889, "Makefile": 773, "Shell": 408} | package ch.derlin.dcvizmermaid.renderers
import assertk.assertThat
import assertk.assertions.contains
import assertk.assertions.isGreaterThan
import assertk.assertions.isNotNull
import assertk.assertions.isTrue
import ch.derlin.dcvizmermaid.graph.GraphTheme
import dummyGraph
import isJpeg
import isSvg
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertDoesNotThrow
import org.junit.jupiter.api.assertThrows
import size
import tmpFileWithExtension
import java.net.URL
class MermaidRendererTest {
@Test
fun `preview and editor link`() {
val url = assertDoesNotThrow { MermaidRenderer.getPreviewLink(dummyGraph(), GraphTheme.DARK) }
assertIsValidEditorLink(url)
}
@Test
fun `editor link`() {
val url = assertDoesNotThrow { MermaidRenderer.getEditorLink(dummyGraph(), GraphTheme.DARK) }
assertIsValidEditorLink(url)
}
@Test
fun `generate invalid graph`() {
val outFile = tmpFileWithExtension(".png")
val message = assertThrows<Exception> {
MermaidRenderer.savePng(outFile, graph = "invalid graph", theme = GraphTheme.DEFAULT, bgColor = null)
}.message
assertThat(message).isNotNull().contains("response code", "400")
}
@Test
fun `generate png (actually jpeg)`() {
val outFile = tmpFileWithExtension(".jpeg")
assertDoesNotThrow {
MermaidRenderer.savePng(outFile, graph = dummyGraph(), theme = GraphTheme.DEFAULT, bgColor = null)
}
assertThat(outFile.size()).isGreaterThan(0L)
assertThat(outFile.isJpeg()).isTrue()
}
@Test
fun `generate svg`() {
val outFile = tmpFileWithExtension(".svg")
assertDoesNotThrow {
MermaidRenderer.saveSvg(outFile, graph = dummyGraph(), theme = GraphTheme.DEFAULT, bgColor = null)
}
assertThat(outFile.size()).isGreaterThan(0L)
assertThat(outFile.isSvg()).isTrue()
}
private fun assertIsValidEditorLink(url: String) {
val content = assertDoesNotThrow { URL(url).readText() }
assertThat(content).contains("<!DOCTYPE", "Mermaid Live Editor")
}
}
| 5 | Kotlin | 3 | 32 | 0cc5e7c3065d527e8c9e2bdfe4a7a07cf7140d38 | 2,158 | docker-compose-viz-mermaid | MIT License |
MultiActivity/app/src/main/java/com/example/multiactivity/SecondActivityActivity.kt | tiszczesz | 555,715,986 | false | null | package com.example.multiactivity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class SecondActivityActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.second_activity)
}
} | 1 | Kotlin | 0 | 3 | 3f9eecde821c471cd9856b52056f6a1785d13b3a | 319 | Mobilne_kurs_2022_23 | MIT License |
src/main/kotlin/de/huddeldaddel/euler/Problem052.kt | huddeldaddel | 171,357,298 | false | null | package de.huddeldaddel.euler
import de.huddeldaddel.euler.extensions.isPermutationOf
import kotlin.system.exitProcess
/**
* Solution for https://projecteuler.net/problem=52
*/
fun main() {
var base = 1L
var num = base
while(true) {
while(num.toString().startsWith("1")) {
if(isMatch(num)) {
println(num)
exitProcess(0)
}
num ++
}
base *= 10
num = base
}
}
fun isMatch(num: Long): Boolean {
return num.isPermutationOf(num * 2) &&
num.isPermutationOf(num * 3) &&
num.isPermutationOf(num * 4) &&
num.isPermutationOf(num * 5) &&
num.isPermutationOf(num * 6)
} | 0 | Kotlin | 1 | 0 | df514adde8c62481d59e78a44060dc80703b8f9f | 725 | euler | MIT License |
Sauti/app/src/main/java/com/labs/sauti/view_state/dashboard/FavoritesViewState.kt | labs14-sauti-android | 196,241,962 | false | null | package com.labs.sauti.view_state.dashboard
class FavoritesViewState(
var isLoading: Boolean = false,
var favorites: MutableList<Any>? = null
) | 0 | Kotlin | 1 | 3 | c129424dc65db7a437e20e9dd35564b7b7fd3c2d | 152 | sauti-android | MIT License |
src/main/kotlin/org/gamekins/statistics/Statistics.kt | jenkinsci | 452,610,454 | false | {"Kotlin": 688455, "JavaScript": 24388, "CSS": 1712, "HTML": 777} | /*
* Copyright 2021 Gamekins contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gamekins.statistics
import hudson.model.*
import org.gamekins.GameUserProperty
import org.gamekins.util.JUnitUtil
import org.jenkinsci.plugins.workflow.job.WorkflowJob
import org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject
import java.text.Collator
import java.util.*
import kotlin.Comparator
import kotlin.collections.ArrayList
/**
* Class for evaluation purposes. Displays the information about the users and the runs in an XML format.
*
* @author <NAME>
* @since 0.1
*/
class Statistics(job: AbstractItem) {
private var fullyInitialized: Boolean = false
private val projectName: String = job.name
private val runEntries: MutableList<RunEntry>?
init {
runEntries = generateRunEntries(job)
fullyInitialized = true
}
companion object {
private const val RUN_TOTAL_COUNT = 200
}
/**
* Adds the number of [additionalGenerated] Challenges after rejection to the current run of [branch].
*/
fun addGeneratedAfterRejection(branch: String, additionalGenerated: Int) {
val entry = runEntries!!.lastOrNull { it.branch == branch }
entry?.generatedChallenges = entry?.generatedChallenges?.plus(additionalGenerated)!!
}
/**
* If Gamekins is not enabled when the [job] is created, this method adds the previous entries to the [Statistics]
* according to the [branch] (only if [job] is of type [WorkflowMultiBranchProject]) recursively with the [number]
* to the [runEntries]. It can happen that a job is aborted or fails and Gamekins is not executed. For this
* problem, this method also adds old runs until the point where it last stopped. The [listener] reports the events
* to the console output of Jenkins.
*/
private fun addPreviousEntries(job: AbstractItem, branch: String, number: Int, listener: TaskListener) {
if (number <= 0) return
for (entry in runEntries!!) {
if (entry.branch == branch && entry.runNumber == number) return
}
addPreviousEntries(job, branch, number - 1, listener)
if (runEntries.size > 0) {
listener.logger.println(runEntries[runEntries.size - 1].printToXML(""))
}
when (job) {
is WorkflowMultiBranchProject -> {
addPreviousEntriesWorkflowMultiBranchProject(job, branch, number)
}
is WorkflowJob -> {
addPreviousEntriesWorkflowJob(job, number)
}
is AbstractProject<*, *> -> {
addPreviousEntriesAbstractProject(job, number)
}
}
}
/**
* Adds the build with [number] of the [job] to the [runEntries].
*/
private fun addPreviousEntriesAbstractProject(job: AbstractProject<*, *>, number: Int) {
for (abstractBuild in job.builds) {
if (abstractBuild.getNumber() == number) {
runEntries?.add(RunEntry(
abstractBuild.getNumber(),
"",
abstractBuild.result,
abstractBuild.startTimeInMillis,
0,
0,
0,
JUnitUtil.getTestCount(null, abstractBuild),
0.0))
return
}
}
}
/**
* Adds the build with [number] of the [job] to the [runEntries].
*/
private fun addPreviousEntriesWorkflowJob(job: WorkflowJob, number: Int) {
for (workflowRun in job.builds) {
if (workflowRun.getNumber() == number) {
runEntries?.add(RunEntry(
workflowRun.getNumber(),
"",
workflowRun.result,
workflowRun.startTimeInMillis,
0,
0,
0,
JUnitUtil.getTestCount(null, workflowRun),
0.0))
return
}
}
}
/**
* Adds the build with [number] of the [job] and [branch] to the [runEntries].
*/
private fun addPreviousEntriesWorkflowMultiBranchProject(job: WorkflowMultiBranchProject, branch: String,
number: Int) {
for (workflowJob in job.items) {
if (workflowJob.name == branch) {
for (workflowRun in workflowJob.builds) {
if (workflowRun.getNumber() == number) {
runEntries?.add(RunEntry(
workflowRun.getNumber(),
workflowJob.name,
workflowRun.result,
workflowRun.startTimeInMillis,
0,
0,
0,
JUnitUtil.getTestCount(null, workflowRun),
0.0))
return
}
}
}
}
}
/**
* Adds a new [entry] for a [job] and [branch] to the [Statistics]. Checks and optionally adds previous entries.
* The [listener] reports the events to the console output of Jenkins.
*/
fun addRunEntry(job: AbstractItem, branch: String, entry: RunEntry, listener: TaskListener) {
addPreviousEntries(job, branch, entry.runNumber - 1, listener)
runEntries!!.add(entry)
listener.logger.println("[Gamekins] ${entry.printToXML("")}")
runEntries.sortWith(Comparator { obj: RunEntry, o: RunEntry -> obj.compareTo(o) })
}
/**
* Generates the [runEntries] during the creation of the the property of the [job]. Only adds the entries for the
* branch master of a [WorkflowMultiBranchProject] to the [runEntries].
*/
private fun generateRunEntries(job: AbstractItem): ArrayList<RunEntry> {
val entries = ArrayList<RunEntry>()
val list = mutableListOf<Run<*, *>>()
var branch = ""
when (job) {
is WorkflowMultiBranchProject -> {
val master = job.items.firstOrNull { it.name == "master" }
if (master != null) {
master.builds.forEach { list.add(it) }
branch = "master"
}
}
is WorkflowJob -> {
job.builds.forEach { list.add(it) }
}
is AbstractProject<*, *> -> {
job.builds.forEach { list.add(it) }
}
}
if (list.isEmpty() && job is WorkflowMultiBranchProject) {
entries.addAll(generateRunEntriesWorkflowMultiBranchProject(job))
} else {
list.reverse()
for (run in list) {
entries.add(RunEntry(
run.getNumber(),
branch,
run.result,
run.startTimeInMillis,
0,
0,
0,
JUnitUtil.getTestCount(null, run),
0.0))
}
}
entries.sortedWith(compareBy({it.branch}, {it.runNumber}))
return entries
}
/**
* Generates [RUN_TOTAL_COUNT] entries from the [job] if no master branch was found.
*/
private fun generateRunEntriesWorkflowMultiBranchProject(job: WorkflowMultiBranchProject): ArrayList<RunEntry> {
val entries = ArrayList<RunEntry>()
var count = 0
for (workflowJob in job.items) {
if (count >= RUN_TOTAL_COUNT) break
val runList = mutableListOf<Run<*, *>>()
workflowJob.builds.forEach { runList.add(it) }
runList.reverse()
for (workflowRun in runList) {
if (count >= RUN_TOTAL_COUNT) break
entries.add(RunEntry(
workflowRun.getNumber(),
workflowJob.name,
workflowRun.result,
workflowRun.startTimeInMillis,
0,
0,
0,
JUnitUtil.getTestCount(null, workflowRun),
0.0))
count++
}
}
return entries
}
/**
* Returns the last run of a [branch].
*/
fun getLastRun(branch: String): RunEntry? {
return runEntries?.filter { it.branch == branch }?.maxByOrNull {it.runNumber }
}
/**
* If the [Statistics] is interrupted during initialization, it is triggered again.
*/
fun isNotFullyInitialized(): Boolean {
return !fullyInitialized || runEntries == null
}
/**
* Returns an XML representation of the [Statistics].
*/
fun printToXML(): String {
val print = StringBuilder()
print.append("<Statistics project=\"").append(projectName).append("\">\n")
val users: ArrayList<User> = ArrayList(User.getAll())
users.removeIf { user: User -> !user.getProperty(GameUserProperty::class.java).isParticipating(projectName) }
print.append(" <Users count=\"").append(users.size).append("\">\n")
for (user in users) {
val property = user.getProperty(GameUserProperty::class.java)
if (property != null && property.isParticipating(projectName)) {
print.append(property.printToXML(projectName, " ")).append("\n")
}
}
print.append(" </Users>\n")
runEntries!!.removeIf { obj: RunEntry? -> Objects.isNull(obj) }
print.append(" <Runs count=\"").append(runEntries.size).append("\">\n")
for (entry in runEntries) {
print.append(entry.printToXML(" ")).append("\n")
}
print.append(" </Runs>\n")
print.append("</Statistics>")
return replaceClassesInString(print.toString())
}
fun replaceClassesInString(file: String): String {
var regex = "class=\"[^\"]+\"".toRegex()
var matchResults = regex.findAll(file)
var map = hashMapOf<String, String>()
var resultString = file
for (result in matchResults) {
map.putIfAbsent(result.value, UUID.randomUUID().toString())
resultString = resultString.replace(result.value, "class=\"${map[result.value]}\"")
}
regex = "project=\"[^\"]+\"".toRegex()
matchResults = regex.findAll(file)
map = hashMapOf()
for (result in matchResults) {
map.putIfAbsent(result.value, UUID.randomUUID().toString())
resultString = resultString.replace(result.value, "project=\"${map[result.value]}\"")
}
regex = "branch=\"[^\"]+\"".toRegex()
matchResults = regex.findAll(file)
map = hashMapOf()
map["branch=\"master\""] = "master"
map["branch=\"main\""] = "main"
for (result in matchResults) {
map.putIfAbsent(result.value, UUID.randomUUID().toString())
resultString = resultString.replace(result.value, "branch=\"${map[result.value]}\"")
}
return resultString
}
/**
* Represents a run of Jenkins job.
*
* @author <NAME>
* @since 1.0
*/
class RunEntry(val runNumber: Int, val branch: String, val result: Result?, val startTime: Long,
var generatedChallenges: Int, val solvedChallenges: Int, var solvedAchievements: Int,
val testCount: Int, val coverage: Double)
: Comparable<RunEntry> {
/**
* Returns an XML representation of the [RunEntry].
*/
fun printToXML(indentation: String): String {
return (indentation + "<Run number=\"" + runNumber + "\" branch=\"" + branch +
"\" result=\"" + (result?.toString() ?: "NULL") + "\" startTime=\"" +
startTime + "\" generatedChallenges=\"" + generatedChallenges +
"\" solvedChallenges=\"" + solvedChallenges + "\" solvedAchievements=\"" + solvedAchievements +
"\" tests=\"" + testCount + "\" coverage=\"" + coverage + "\"/>")
}
/**
* Compares two [RunEntry] with first [branch] and second [runNumber].
*
* @see [Comparable.compareTo]
*/
override fun compareTo(other: RunEntry): Int {
val result = Collator.getInstance().compare(branch, other.branch)
return if (result == 0) runNumber.compareTo(other.runNumber) else result
}
/**
* Called by Jenkins after the object has been created from his XML representation. Used for data migration.
*/
@Suppress("unused", "SENSELESS_COMPARISON")
private fun readResolve(): Any {
if (solvedAchievements == null) solvedAchievements = 0
return this
}
}
}
| 0 | Kotlin | 3 | 4 | 7b8ecc3e94cd2c18a377587d276f532284b47e9b | 13,515 | gamekins-plugin | Apache License 2.0 |
app/src/main/java/com/example/omdb/data/firebase/fcm/FirebaseMessagingServiceClass.kt | Pro-55 | 195,038,410 | false | null | package com.example.omdb.data.firebase.fcm
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Color
import android.os.Bundle
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.res.ResourcesCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.navigation.NavDeepLinkBuilder
import com.example.omdb.R
import com.example.omdb.ui.MainActivity
import com.example.omdb.util.Constants
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class FirebaseMessagingServiceClass : FirebaseMessagingService() {
// Global
private val TAG = FirebaseMessagingServiceClass::class.java.simpleName
/**
* Called when message is received.
* @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
override fun onMessageReceived(remoteMessage: RemoteMessage) {
val requestId =
Integer.parseInt(SimpleDateFormat("ddHHmssS", Locale.ENGLISH).format(Date()))
val data = remoteMessage.data
// showDeepLinkNotification(requestId, data)
// showSystemNotification(requestId, data)
// broadcastNotificationData(requestId, data)
}
private fun showDeepLinkNotification(requestId: Int, data: MutableMap<String, String>) {
// Check if message contains a data payload.
data.isNotEmpty().let {
val args = Bundle()
data.keys.forEach { key -> args.putString(key, data[key]) }
val pendingIntent = NavDeepLinkBuilder(this)
.setComponentName(MainActivity::class.java)
.setArguments(args)
.createPendingIntent()
buildNotification(requestId, data, pendingIntent)
}
}
private fun showSystemNotification(requestId: Int, data: MutableMap<String, String>) {
// Check if message contains a data payload.
data.isNotEmpty().let {
val notificationIntent = Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
data.keys.forEach { key -> notificationIntent.putExtra(key, data[key]) }
val pendingIntentFlags =
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
val pendingIntent =
PendingIntent.getActivity(this, requestId, notificationIntent, pendingIntentFlags)
buildNotification(requestId, data, pendingIntent)
}
}
private fun broadcastNotificationData(requestId: Int, data: MutableMap<String, String>) {
// Check if message contains a data payload.
if (data.isNotEmpty()) {
val notificationIntent = Intent(Constants.NOTIFICATION_INTENT_FILTER)
notificationIntent.putExtra(Constants.KEY_NOTIFICATION_ID, requestId)
data.keys.forEach { key -> notificationIntent.putExtra(key, data[key]) }
val localBroadcastManager = LocalBroadcastManager.getInstance(this)
localBroadcastManager.sendBroadcast(notificationIntent)
}
}
private fun buildNotification(
requestId: Int,
data: MutableMap<String, String>,
pendingIntent: PendingIntent
) {
val builder = NotificationCompat.Builder(
this,
data[Constants.KEY_NOTIFICATION_CHANNEL_ID]
?: resources.getString(R.string.default_notification_channel_id)
)
builder.setSmallIcon(R.drawable.ic_notification_badge)
val color = data[Constants.KEY_NOTIFICATION_COLOR]
builder.color = if (color != null) Color.parseColor(color)
else ResourcesCompat.getColor(resources, android.R.color.black, null)
builder.apply {
setContentTitle(data[Constants.KEY_NOTIFICATION_TITLE])
setContentText(data[Constants.KEY_NOTIFICATION_BODY])
setContentIntent(pendingIntent)
setAutoCancel(true)
}
with(NotificationManagerCompat.from(this)) { notify(requestId, builder.build()) }
}
/**
* Called if InstanceID token is updated.
*/
override fun onNewToken(token: String) {
val sp = getSharedPreferences()
//Save new token
sp.edit().putString(Constants.KEY_FCM_TOKEN, token).apply()
}
private fun getSharedPreferences(): SharedPreferences =
application.getSharedPreferences(Constants.OMDB_SHARED_PREFS, Context.MODE_PRIVATE)
} | 0 | null | 0 | 1 | dc72f1773730f2777a542818e06a0fac5fa99101 | 4,801 | OMDb | Apache License 2.0 |
src/test/kotlin/unibz/cs/semint/kprime/domain/dql/QueryTest.kt | kprime-dev | 722,929,885 | false | {"Kotlin": 383495, "XSLT": 1078, "HTML": 372, "Makefile": 218} | package unibz.cs.semint.kprime.domain.dql
import junit.framework.Assert.assertEquals
import org.junit.Test
import unibz.cs.semint.kprime.adapter.service.XMLSerializerJacksonAdapter
import unibz.cs.semint.kprime.domain.db.Database
import unibz.cs.semint.kprime.domain.db.SchemaCmdParser
import unibz.cs.semint.kprime.usecase.common.SQLizeSelectUseCase
import unibz.cs.semint.kprime.usecase.common.UnSQLizeSelectUseCase
import kotlin.test.assertEquals as assertEquals1
class QueryTest {
fun simpleQueryFixture(tableName:String): Query {
val query = Query()
var select = query.select
var attr = Attribute()
attr.name = "Name"
select.attributes.add(attr)
attr = Attribute()
attr.name = "Surname"
select.attributes.add(attr)
val fromT1 = From()
fromT1.tableName = tableName
select.from = fromT1
select.where.condition = "Name='Gigi'"
return query
}
private fun unionFixtureQuery(): Query {
var query = Query()
query.select = simpleQueryFixture("Table1").select
var simple2 = simpleQueryFixture("Table2")
val union = Union()
union.selects().add(simple2.select)
query.union=union
return query
}
@Test
fun test_from_simple_query_to_xml() {
// given
val query = simpleQueryFixture("Table1")
// when
var queryXml = XMLSerializerJacksonAdapter().prettyQuery(query) as String
// then
assertEquals("""
<query id="" name="">
<select>
<distinct>false</distinct>
<attributes>
<attribute name="Name"/>
<attribute name="Surname"/>
</attributes>
<from tableName="Table1" alias=""/>
<where condition="Name='Gigi'"/>
<groupBy/>
</select>
<union/>
<minus/>
<options/>
</query>
""".trimIndent(),queryXml)
}
@Test
fun test_from_simple_query_to_sql() {
// given
val query = simpleQueryFixture("Table1")
// when
var querySql = SQLizeSelectUseCase().sqlize(query)
// then
assertEquals1("""
SELECT Name,Surname
FROM Table1
WHERE Name='Gigi'
""".trimIndent(),querySql)
}
@Test
fun test_from_simple_select_to_sql(){
// given
val select = Select()
val att = Attribute()
att.name="ww"
select.attributes.add(att)
val from = From()
from.tableName="tab"
select.from = from
select.where.condition="a = b"
// when
val selectSql = SQLizeSelectUseCase().sqlizeSelect(select)
// then
assertEquals1("""
SELECT ww
FROM tab
WHERE a = b
""".trimIndent(),selectSql)
}
@Test
fun test_simple_join_to_sql(){
// given
val select = Select()
val att = Attribute()
att.name="ww"
select.attributes.add(att)
val from = From()
from.tableName="Orders"
val join = Join()
join.joinLeftTableAlias = "Orders"
join.joinOnLeft = "Orders.customerId"
join.joinRightTable = "Customer"
join.joinOnRight = "Customer.customerId"
join.joinType = "INNER"
from.addJoin(join)
select.from = from
select.where.condition="a = b"
// when
val selectSql = SQLizeSelectUseCase().sqlizeSelect(select)
// then
assertEquals1("""
SELECT ww
FROM Orders
INNER JOIN Customer
ON Orders.customerId = Customer.customerId
WHERE a = b
""".trimIndent(),selectSql)
}
@Test
fun test_multiple_join_to_sql(){
// given
val select = Select()
val att = Attribute()
att.name="ww"
select.attributes.add(att)
val from = From()
from.tableName="Orders"
val join = Join()
join.joinLeftTableAlias = "Orders"
join.joinOnLeft = "Orders.customerId"
join.joinRightTable = "Customer"
join.joinOnRight = "Customer.customerId"
join.joinType = "INNER"
from.addJoin(join)
val join2 = Join()
join2.joinLeftTableAlias = "Customer"
join2.joinOnLeft = "Customer.orderId"
join2.joinRightTable = "Sales"
join2.joinOnRight = "Sales.orderId"
join2.joinType = "LEFT"
from.addJoin(join2)
select.from= from
select.where.condition="a = b"
// when
val selectSql = SQLizeSelectUseCase().sqlizeSelect(select)
// then
assertEquals1("""
SELECT ww
FROM Orders
INNER JOIN Customer
ON Orders.customerId = Customer.customerId
LEFT JOIN Sales
ON Customer.orderId = Sales.orderId
WHERE a = b
""".trimIndent(),selectSql)
}
@Test
fun test_from_union_query_to_xml() {
// given
val query = unionFixtureQuery()
// when
var queryXml = XMLSerializerJacksonAdapter().prettyQuery(query) as String
// then
assertEquals("""
<query id="" name="">
<select>
<distinct>false</distinct>
<attributes>
<attribute name="Name"/>
<attribute name="Surname"/>
</attributes>
<from tableName="Table1" alias=""/>
<where condition="Name='Gigi'"/>
<groupBy/>
</select>
<union>
<selects>
<selects>
<distinct>false</distinct>
<attributes>
<attribute name="Name"/>
<attribute name="Surname"/>
</attributes>
<from tableName="Table2" alias=""/>
<where condition="Name='Gigi'"/>
<groupBy/>
</selects>
</selects>
</union>
<minus/>
<options/>
</query>
""".trimIndent(),queryXml)
}
@Test
fun test_from_union_query_to_sql() {
// given
val query = unionFixtureQuery()
// when
var querySql = SQLizeSelectUseCase().sqlize(query)
// then
assertEquals1("""
SELECT Name,Surname
FROM Table1
WHERE Name='Gigi'
UNION
SELECT Name,Surname
FROM Table2
WHERE Name='Gigi'
""".trimIndent(),querySql)
}
@Test
fun test_from_xml_to_query() {
}
@Test
fun test_from_minimal_sql_to_query() {
// given
val sqlQuery="""
SELECT *
FROM tab1
""".trimIndent()
val query = UnSQLizeSelectUseCase().fromsql("query1",sqlQuery)
assertEquals("*",query.select.attributes[0].name)
assertEquals("tab1",query.select.from.tableName)
}
@Test
fun test_from_conditional_sql_to_query() {
// given
val sqlQuery="""
SELECT alfa,beta
FROM tab1
WHERE a = b
""".trimIndent()
val query = UnSQLizeSelectUseCase().fromsql("query1",sqlQuery)
assertEquals("alfa",query.select.attributes[0].name)
assertEquals("beta",query.select.attributes[1].name)
assertEquals("tab1",query.select.from.tableName)
assertEquals("a = b",query.select.where.condition)
}
@Test
fun test_from_3_union_sql_to_query() {
// given
val sqlQuery="""
SELECT alfa,beta
FROM tab1
WHERE a = b
UNION
SELECT gamma,theta
FROM tab2
WHERE c = d
""".trimIndent()
val query = UnSQLizeSelectUseCase().fromsql("query1",sqlQuery)
assertEquals(1,query.union?.selects()?.size)
assertEquals("alfa", query.select.attributes[0].name)
assertEquals("beta", query.select.attributes[1].name)
assertEquals("tab1", query.select.from.tableName)
assertEquals("a = b", query.select.where.condition)
val select = query.union!!.selects()[0]
assertEquals("gamma", select.attributes[0].name)
assertEquals("theta", select.attributes[1].name)
assertEquals("tab2", select.from.tableName)
assertEquals("c = d", select.where.condition)
}
@Test
fun test_from_union_sql_to_query() {
// given
val sqlQuery="""
SELECT alfa,beta
FROM tab1
WHERE a = b
UNION
SELECT gamma,theta
FROM tab2
WHERE c = d
UNION
SELECT delta,zeta
FROM tab3
WHERE e = f
""".trimIndent()
val query = UnSQLizeSelectUseCase().fromsql("query1",sqlQuery)
assertEquals(2,query.union!!.selects().size)
assertEquals("alfa", query.select.attributes[0].name)
assertEquals("beta", query.select.attributes[1].name)
assertEquals("tab1", query.select.from.tableName)
assertEquals("a = b", query.select.where.condition)
val select = query.union!!.selects()[0]
assertEquals("gamma", select.attributes[0].name)
assertEquals("theta", select.attributes[1].name)
assertEquals("tab2", select.from.tableName)
assertEquals("c = d", select.where.condition)
val select1 = query.union!!.selects()[1]
assertEquals("delta", select1.attributes[0].name)
assertEquals("zeta", select1.attributes[1].name)
assertEquals("tab3", select1.from.tableName)
assertEquals("e = f", select1.where.condition)
val sqlize = SQLizeSelectUseCase().sqlize(query)
assertEquals("""
SELECT alfa,beta
FROM tab1
WHERE a = b
UNION
SELECT gamma,theta
FROM tab2
WHERE c = d
UNION
SELECT delta,zeta
FROM tab3
WHERE e = f
""".trimIndent(),sqlize)
}
@Test
fun test_query_from_table() {
// given
val table = SchemaCmdParser.parseTable("person:name,surname")
// when
val query = Query.buildFromTable(table)
// then
val sql = SQLizeSelectUseCase().sqlize(query)
assertEquals("""
SELECT name,surname
FROM person
""".trimIndent(),sql)
}
} | 0 | Kotlin | 0 | 0 | 34ceb56e3da8b2e64329c7655d50f40400487f25 | 10,812 | kprime-arm | MIT License |
framework/src/main/java/com/example/framework/extension/ActivityExtension.kt | samyoney | 783,208,332 | false | {"Kotlin": 136569} | package com.example.framework.extension
import android.app.Activity
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import com.example.framework.BuildConfig
import timber.log.Timber
fun Activity.allowDebugRotation() {
requestedOrientation = if (BuildConfig.DEBUG) {
ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
} else {
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
}
fun Activity.registerFragmentLifecycleCallbacks() {
if (this is FragmentActivity) {
supportFragmentManager
.registerFragmentLifecycleCallbacks(
object : FragmentManager.FragmentLifecycleCallbacks() {
override fun onFragmentViewCreated(
fm: FragmentManager,
f: Fragment,
v: View,
savedInstanceState: Bundle?
) {
super.onFragmentViewCreated(fm, f, v, savedInstanceState)
Timber.tag(f.classTag).d("onCreateView()")
}
override fun onFragmentResumed(fm: FragmentManager, f: Fragment) {
super.onFragmentResumed(fm, f)
Timber.tag(f.classTag).d("onResume()")
}
override fun onFragmentPaused(fm: FragmentManager, f: Fragment) {
super.onFragmentPaused(fm, f)
Timber.tag(f.classTag).d("onPause()")
}
override fun onFragmentViewDestroyed(fm: FragmentManager, f: Fragment) {
super.onFragmentViewDestroyed(fm, f)
Timber.tag(f.classTag).d("onDestroyView()")
}
},
true
)
}
} | 0 | Kotlin | 0 | 7 | 38ebae18cd04f7533f151885746f8b90cef0099a | 1,982 | compose_clean_base | MIT License |
app/src/main/java/com/xwq/companyvxwhelper/bean/ResponseBean/PublicRsaResponse.kt | aidenpierce2 | 421,354,234 | false | null | package com.xwq.companyvxwhelper.bean.ResponseBean
import com.xwq.companyvxwhelper.base.BaseEntity
data class PublicRsaResponse(var publicRsa : String, var keyUUID: String) : BaseEntity() {
}
| 0 | Kotlin | 0 | 0 | f3dea6373b9a48e9fbbd69dba8a27da10d6569b3 | 195 | companyvxwhelper | MIT License |
iris-mock-compiler/src/main/kotlin/dev/arildo/iris/plugin/codegen/IrisMockModuleDescriptorImpl.kt | arildojr7 | 634,544,161 | false | null | package dev.arildo.iris.plugin.codegen
import dev.arildo.iris.plugin.codegen.ClassReference.Descriptor
import dev.arildo.iris.plugin.codegen.ClassReference.Psi
import dev.arildo.iris.plugin.codegen.IrisMockModuleDescriptorImpl.ClassReferenceCacheKey.Companion.toClassReferenceCacheKey
import dev.arildo.iris.plugin.util.requireFqName
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.resolveClassByFqName
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.descriptorUtil.classId
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
/**
* Adapted from https://github.com/square/anvil
*/
class IrisMockModuleDescriptorImpl private constructor(delegate: ModuleDescriptor) :
IrisMockModuleDescriptor, ModuleDescriptor by delegate {
private val ktFileToClassReferenceMap = mutableMapOf<String, List<Psi>>()
private val allPsiClassReferences: Sequence<Psi>
get() = ktFileToClassReferenceMap.values.asSequence().flatten()
private val resolveDescriptorCache = mutableMapOf<FqName, ClassDescriptor?>()
private val resolveClassIdCache = mutableMapOf<ClassId, FqName?>()
private val classReferenceCache = mutableMapOf<ClassReferenceCacheKey, ClassReference>()
fun addFiles(files: Collection<KtFile>) {
files.forEach { ktFile ->
val classReferences = ktFile.classesAndInnerClasses().map { ktClass ->
Psi(ktClass, ktClass.toClassId(), this)
}
ktFileToClassReferenceMap[ktFile.identifier] = classReferences
}
}
override fun getClassAndInnerClassReferences(ktFile: KtFile): List<Psi> {
return ktFileToClassReferenceMap.getOrPut(ktFile.identifier) {
ktFile.classesAndInnerClasses().map { getClassReference(it) }
}
}
override fun resolveClassIdOrNull(classId: ClassId): FqName? =
resolveClassIdCache.getOrPut(classId) {
val fqName = classId.asSingleFqName()
resolveFqNameOrNull(fqName)?.fqNameSafe
?: allPsiClassReferences.firstOrNull { it.fqName == fqName }?.fqName
}
override fun resolveFqNameOrNull(
fqName: FqName,
lookupLocation: LookupLocation
): ClassDescriptor? {
return resolveDescriptorCache.getOrPut(fqName) {
resolveClassByFqName(fqName, lookupLocation)
}
}
override fun getClassReference(clazz: KtClassOrObject): Psi {
return classReferenceCache.getOrPut(clazz.toClassReferenceCacheKey()) {
Psi(clazz, clazz.toClassId(), this)
} as Psi
}
override fun getClassReference(descriptor: ClassDescriptor): Descriptor {
return classReferenceCache.getOrPut(descriptor.toClassReferenceCacheKey()) {
val classId = descriptor.classId ?: throw Exception(
"Couldn't find the classId for $fqNameSafe."
)
Descriptor(descriptor, classId, this)
} as Descriptor
}
override fun getClassReferenceOrNull(fqName: FqName): ClassReference? {
fun psiClassReference(): Psi? = allPsiClassReferences.firstOrNull { it.fqName == fqName }
fun descriptorClassReference(): Descriptor? =
resolveFqNameOrNull(fqName)?.let { getClassReference(it) }
return psiClassReference() ?: descriptorClassReference()
}
private val KtFile.identifier: String
get() = packageFqName.asString() + name
internal class Factory {
private val cache = mutableMapOf<ModuleDescriptor, IrisMockModuleDescriptorImpl>()
fun create(delegate: ModuleDescriptor): IrisMockModuleDescriptorImpl {
return cache.getOrPut(delegate) { IrisMockModuleDescriptorImpl(delegate) }
}
}
private data class ClassReferenceCacheKey(
private val fqName: FqName,
private val type: Type
) {
enum class Type {
PSI,
DESCRIPTOR
}
companion object {
fun KtClassOrObject.toClassReferenceCacheKey(): ClassReferenceCacheKey =
ClassReferenceCacheKey(requireFqName(), Type.PSI)
fun ClassDescriptor.toClassReferenceCacheKey(): ClassReferenceCacheKey =
ClassReferenceCacheKey(fqNameSafe, Type.DESCRIPTOR)
}
}
}
private fun KtFile.classesAndInnerClasses(): List<KtClassOrObject> {
val children = findChildrenByClass(KtClassOrObject::class.java)
return generateSequence(children.toList()) { list ->
list.flatMap { it.declarations.filterIsInstance<KtClassOrObject>() }
.ifEmpty { null }
}.flatten().toList()
}
private fun KtClassOrObject.toClassId(): ClassId {
val className = parentsWithSelf.filterIsInstance<KtClassOrObject>()
.toList()
.reversed()
.joinToString(separator = ".") { it.nameAsSafeName.asString() }
return ClassId(containingKtFile.packageFqName, FqName(className), false)
}
| 4 | null | 3 | 56 | 884745b47387c64241447582c1b893960739e122 | 5,274 | iris-mock | Apache License 2.0 |
app/src/main/java/space/taran/arkretouch/data/ImageDefaults.kt | ARK-Builders | 553,609,385 | false | null | package dev.arkbuilders.arkretouch.data
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.IntSize
import kotlinx.serialization.Serializable
@Serializable
data class ImageDefaults(
val colorValue: ULong = Color.White.value,
val resolution: Resolution? = null
)
@Serializable
data class Resolution(
val width: Int,
val height: Int
) {
fun toIntSize() = IntSize(this.width, this.height)
companion object {
fun fromIntSize(intSize: IntSize) = Resolution(intSize.width, intSize.height)
}
}
| 21 | null | 1 | 1 | 6f1f6158a37ffa20314c387339eca715f285056e | 549 | ARK-Retouch | MIT License |
src/main/kotlin/com/droid/explorer/command/shell/impl/Remove.kt | jonatino | 56,899,891 | false | {"Kotlin": 40686, "CSS": 9445, "Batchfile": 318} | /*
* Copyright 2016 <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.droid.explorer.command.shell.impl
import com.droid.explorer.command.shell.ShellCommand
/**
* Created by Jonathan on 4/23/2016.
*/
class Copy(file: String, target: String) : ShellCommand() {
override val shellArgs = arrayOf("cp", "-r", "\"$file\"", "\"$target\"")
} | 1 | Kotlin | 8 | 34 | 6a39d7f72b7d3c8d3709dd3489f6ef47afa1f80d | 907 | Droid-Explorer | Apache License 2.0 |
androiddata/src/main/java/com/wiseassblog/androiddata/data/DataExtensions.kt | BracketCove | 84,023,304 | false | null | package com.wiseassblog.androiddata.data
import com.wiseassblog.androiddata.data.realmmodel.RealmReminder
import com.wiseassblog.domain.domainmodel.Reminder
import java.util.*
internal val RealmReminder.toReminder: Reminder
get() = Reminder(
this.reminderId,
this.reminderTitle,
this.isActive,
this.isVibrateOnly,
this.isRenewAutomatically,
this.hourOfDay,
this.minute
)
internal val Reminder.toRealmReminder: RealmReminder
get() = RealmReminder(
this.reminderId,
this.reminderTitle,
this.isActive,
this.isVibrateOnly,
this.isRenewAutomatically,
this.hourOfDay,
this.minute
)
/**
* Read out of the Hour and
*/
internal fun Calendar.setReminderTime(reminder: Reminder): Calendar {
timeInMillis = System.currentTimeMillis()
set(Calendar.HOUR_OF_DAY, reminder.hourOfDay)
set(Calendar.MINUTE, reminder.minute)
return this
}
| 1 | Kotlin | 36 | 85 | 66136bf7b3e173d964dc15729f982293189b2ee2 | 971 | PosTrainer | Apache License 2.0 |
app/src/main/java/me/mitul/aij/home/UniversityListActivity.kt | mitulvaghamshi | 555,605,505 | false | {"Kotlin": 99663} | package me.mitul.aij.home
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.AdapterView.OnItemClickListener
import android.widget.EditText
import android.widget.ListView
import android.widget.TextView
import me.mitul.aij.R
import me.mitul.aij.adapter.AdapterUniversity
import me.mitul.aij.helper.HelperUniversity
import me.mitul.aij.model.University
import me.mitul.aij.utils.ArrayListOps
import me.mitul.aij.utils.MyTextWatcher
class UniversityListActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_common_listview)
findViewById<View>(R.id.expandableListView).visibility = View.GONE
val dbHelper = HelperUniversity(this)
val universities = dbHelper.selectAllUniversity()
val listview = findViewById<ListView>(R.id.common_listview)
listview.visibility = View.VISIBLE
listview.setAdapter(AdapterUniversity(this, universities))
listview.isTextFilterEnabled = true
listview.onItemClickListener = OnItemClickListener { _, view, _, _ ->
startActivity(
Intent(this, DetailUniversityActivity::class.java)
.putExtra(
"id_to_find_university",
(view.findViewById<TextView>(R.id.list_simple_public_id)).getText()
.toString()
)
)
}
findViewById<EditText>(R.id.edSearchCommon).addTextChangedListener(
MyTextWatcher(universities, object : ArrayListOps<University> {
override fun onListSet(list: ArrayList<University>) =
listview.setAdapter(AdapterUniversity(this@UniversityListActivity, list))
override fun getName(item: University) = item.universityName!!
})
)
}
}
| 0 | Kotlin | 0 | 0 | 322df9b37045da04dfe9fb6f488a2d100540ba30 | 1,975 | AIJ | MIT License |
jetbrains-core/src/software/aws/toolkits/jetbrains/services/lambda/execution/sam/LocalLambdaRunSettings.kt | JetBrains | 223,485,227 | false | null | // Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.aws.toolkits.jetbrains.services.lambda.execution.sam
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PathMappingSettings.PathMapping
import software.amazon.awssdk.services.lambda.model.Runtime
import software.aws.toolkits.core.ConnectionSettings
import software.aws.toolkits.jetbrains.services.lambda.RuntimeGroup
import software.aws.toolkits.jetbrains.services.lambda.runtimeGroup
import software.aws.toolkits.jetbrains.services.lambda.sam.SamOptions
interface TemplateSettings {
val templateFile: VirtualFile
val logicalId: String
}
interface ZipSettings {
val runtime: Runtime
val handler: String
}
interface ImageSettings {
val imageDebugger: ImageDebugSupport
}
sealed class LocalLambdaRunSettings(
val connection: ConnectionSettings,
val samOptions: SamOptions,
val environmentVariables: Map<String, String>,
val debugHost: String,
val input: String
) {
abstract val runtimeGroup: RuntimeGroup
}
class TemplateRunSettings(
override val templateFile: VirtualFile,
override val runtime: Runtime,
override val handler: String,
override val logicalId: String,
environmentVariables: Map<String, String>,
connection: ConnectionSettings,
samOptions: SamOptions,
debugHost: String,
input: String
) : TemplateSettings, ZipSettings, LocalLambdaRunSettings(connection, samOptions, environmentVariables, debugHost, input) {
override val runtimeGroup = runtime.runtimeGroup ?: throw IllegalStateException("Attempting to run SAM for unsupported runtime $runtime")
}
class HandlerRunSettings(
override val runtime: Runtime,
override val handler: String,
val timeout: Int,
val memorySize: Int,
environmentVariables: Map<String, String>,
connection: ConnectionSettings,
samOptions: SamOptions,
debugHost: String,
input: String
) : ZipSettings, LocalLambdaRunSettings(connection, samOptions, environmentVariables, debugHost, input) {
override val runtimeGroup = runtime.runtimeGroup ?: throw IllegalStateException("Attempting to run SAM for unsupported runtime $runtime")
}
class ImageTemplateRunSettings(
override val templateFile: VirtualFile,
override val imageDebugger: ImageDebugSupport,
override val logicalId: String,
val dockerFile: VirtualFile,
val pathMappings: List<PathMapping>,
environmentVariables: Map<String, String>,
connection: ConnectionSettings,
samOptions: SamOptions,
debugHost: String,
input: String
) : ImageSettings, TemplateSettings, LocalLambdaRunSettings(connection, samOptions, environmentVariables, debugHost, input) {
override val runtimeGroup = RuntimeGroup.find { imageDebugger.languageId in it.languageIds }
?: throw IllegalStateException("Attempting to run SAM for unsupported language ${imageDebugger.languageId}")
}
fun LocalLambdaRunSettings.resolveDebuggerSupport() = when (this) {
is ImageTemplateRunSettings -> imageDebugger
is ZipSettings -> RuntimeDebugSupport.getInstance(runtimeGroup)
else -> throw IllegalStateException("Can't find debugger support for $this")
}
| 7 | null | 4 | 9 | ccee3307fe58ad48f93cd780d4378c336ee20548 | 3,247 | aws-toolkit-jetbrains | Apache License 2.0 |
filesystem/src/jvmMain/kotlin/ext/FileSystemByteBufferExt.kt | illarionov | 848,247,126 | false | {"Kotlin": 1343464, "ANTLR": 6038, "TypeScript": 3148, "CSS": 1042, "FreeMarker": 450, "JavaScript": 89} | /*
* Copyright 2024, the wasi-emscripten-host project authors and contributors. Please see the AUTHORS file
* for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
* SPDX-License-Identifier: Apache-2.0
*/
package at.released.weh.filesystem.ext
import at.released.weh.filesystem.op.readwrite.FileSystemByteBuffer
import java.nio.ByteBuffer
internal fun FileSystemByteBuffer.asByteBuffer(): ByteBuffer = ByteBuffer.wrap(this.array, offset, length)
| 0 | Kotlin | 0 | 4 | 774f9d4fc1c05080636888c4fe03049fdb038a8d | 513 | wasi-emscripten-host | Apache License 2.0 |
examples/kotlin/src/main/kotlin/com/xebia/functional/xef/auto/Population.kt | xebia-functional | 629,411,216 | false | null | package com.xebia.functional.xef.auto
import com.xebia.functional.xef.auto.llm.openai.getOrElse
import com.xebia.functional.xef.auto.llm.openai.image
import kotlinx.serialization.Serializable
@Serializable
data class Population(val size: Int, val description: String)
@Serializable
data class Image(
val description: String,
val url: String,
)
suspend fun main() =
ai {
val img: Image = image("")
println(img)
}.getOrElse { println(it) }
| 7 | null | 7 | 85 | 19243b04b107990c9cf549703d7e9d738aab0444 | 474 | xef | Apache License 2.0 |
simplified-tests/src/test/java/org/nypl/simplified/tests/mocking/MockAnalytics.kt | ThePalaceProject | 367,082,997 | false | null | package org.nypl.simplified.tests
import org.nypl.simplified.analytics.api.AnalyticsEvent
import org.nypl.simplified.analytics.api.AnalyticsType
class MockAnalytics : AnalyticsType {
override fun publishEvent(event: AnalyticsEvent) {
}
}
| 1 | null | 4 | 8 | 95ea5f21c6408207eddccb7210721743d57a500f | 244 | android-core | Apache License 2.0 |
app/src/main/java/org/haidy/servify/presentation/screens/settings/SettingsRoute.kt | HaidyAbuGom3a | 805,534,454 | false | {"Kotlin": 702248} | package org.haidy.servify.presentation.screens.settings
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import org.haidy.servify.app.navigation.ServifyDestination
private const val ROUTE = ServifyDestination.SETTINGS
fun NavController.navigateToSettings(clearBackStack: Boolean = false) {
navigate(ROUTE) {
if (clearBackStack) {
popUpTo(graph.id) {
inclusive = true
}
}
}
}
fun NavGraphBuilder.settingsRoute() {
composable(ROUTE) { SettingsScreen() }
} | 0 | Kotlin | 0 | 2 | 8c2ba73cea5d29cc2ef7048d832f8ecea13f34ee | 606 | Servify | Apache License 2.0 |
compiler/testData/codegen/box/classes/inner/kt6708.kt | JakeWharton | 99,388,807 | false | null | // IGNORE_BACKEND_FIR: JVM_IR
open class A() {
open inner class InnerA
}
class B : A() {
inner class InnerB : A.InnerA()
}
fun box(): String {
B().InnerB()
return "OK"
}
| 181 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 188 | kotlin | Apache License 2.0 |
Week9/app/src/main/java/com/em4n0101/mytvshows/view/showdetail/CastAdapter.kt | em4n0101 | 268,436,903 | false | null | package com.em4n0101.mytvshows.ui.showdetail
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.em4n0101.mytvshows.R
import com.em4n0101.mytvshows.model.response.CastForShowResponse
class CastAdapter(private val onCastClicked: (CastForShowResponse) -> Unit): RecyclerView.Adapter<CastViewHolder>() {
private val castList: MutableList<CastForShowResponse> = mutableListOf()
fun setData(cast: List<CastForShowResponse>) {
castList.clear()
castList.addAll(cast)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CastViewHolder {
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.generic_item_view_holder, parent, false)
return CastViewHolder(itemView)
}
override fun getItemCount() = castList.size
override fun onBindViewHolder(holder: CastViewHolder, position: Int) {
holder.bind(castList[position], onCastClicked)
}
} | 0 | Kotlin | 0 | 1 | 4f1ebb9d68091ef741ac69f2f46e16f512401de2 | 1,050 | AndroidBootcampSummer2020 | Apache License 2.0 |
app/src/main/java/com/razeware/emitron/ui/download/workers/UpdateDownloadWorker.kt | razeware | 192,712,585 | false | null | package com.razeware.emitron.ui.download.workers
import android.content.Context
import androidx.hilt.work.HiltWorker
import androidx.work.*
import com.razeware.emitron.data.download.DownloadRepository
import com.razeware.emitron.model.DownloadProgress
import com.razeware.emitron.model.DownloadState
import com.razeware.emitron.ui.download.DownloadService
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
/**
* Worker for updating a download,
*
* It will fetch content to be downloaded and add it to db.
* It will be followed by [DownloadWorker] which will read from database and forward downloads
* to [DownloadService]
*/
@HiltWorker
class UpdateDownloadWorker @AssistedInject constructor(
@Assisted appContext: Context,
@Assisted workerParameters: WorkerParameters,
/**
* Download repository.
* */
val downloadRepository: DownloadRepository
) : CoroutineWorker(appContext, workerParameters) {
/**
* See [Worker.doWork]
*/
override suspend fun doWork(): Result {
val downloadId =
inputData.getString(DOWNLOAD_ID) ?: return Result.failure()
val downloadProgress = inputData.getInt(DOWNLOAD_PROGRESS, 0)
val downloadState = inputData.getInt(DOWNLOAD_STATE, DownloadState.FAILED.ordinal)
val progress = DownloadProgress(
downloadId,
downloadProgress,
DownloadState.values()[downloadState]
)
downloadRepository.updateDownloadProgress(progress)
return Result.success()
}
companion object {
/**
* Download id
*/
const val DOWNLOAD_ID: String = "download_id"
/**
* Download progress
*/
const val DOWNLOAD_PROGRESS: String = "download_progress"
/**
* Download state
*/
const val DOWNLOAD_STATE: String = "download_state"
/**
* Start content download
*
* @param workManager WorkManager
* @param downloadId
* @param progress
* @param state
*/
fun updateAndStartNext(
workManager: WorkManager,
downloadId: String,
progress: Int,
state: DownloadState,
downloadOnlyOnWifi: Boolean
) {
val downloadData =
workDataOf(
DOWNLOAD_ID to downloadId,
DOWNLOAD_PROGRESS to progress,
DOWNLOAD_STATE to state.ordinal
)
val startDownloadWorkRequest = OneTimeWorkRequestBuilder<UpdateDownloadWorker>()
.setInputData(downloadData)
.build()
val downloadWorkRequest =
DownloadWorker.buildWorkRequest(downloadOnlyOnWifi)
workManager
.beginUniqueWork(
downloadId,
ExistingWorkPolicy.REPLACE,
startDownloadWorkRequest
)
.then(downloadWorkRequest)
.enqueue()
}
}
}
| 30 | null | 31 | 53 | 4dcb00f09eee2ae1ff0a6c9c2e2dd141227b51c4 | 2,750 | emitron-Android | Apache License 2.0 |
main/src/kotlinx/team/infra/NativeMultiplatform.kt | Kotlin | 172,077,797 | false | {"Kotlin": 38592} | package kotlinx.team.infra
import groovy.lang.*
import org.gradle.api.*
import org.gradle.api.plugins.*
import org.gradle.util.*
import org.jetbrains.kotlin.gradle.dsl.*
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet
import org.jetbrains.kotlin.gradle.plugin.mpp.*
import org.jetbrains.kotlin.konan.target.*
fun Project.configureNativeMultiplatform() {
val multiplatformExtensionClass =
tryGetClass<KotlinMultiplatformExtension>("org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension")
if (multiplatformExtensionClass == null) {
logger.infra("Skipping native configuration because multiplatform plugin has not been applied")
return
}
val ideaActive = System.getProperty("idea.active")?.toBoolean() ?: false
subprojects {
val subproject = this
// Checking for MPP beforeEvaluate is too early, and in afterEvaluate too late because node plugin breaks
subproject.pluginManager.withPlugin("kotlin-multiplatform") {
val kotlin = subproject.extensions.findByType(multiplatformExtensionClass)
if (kotlin == null) {
logger.infra("Skipping native configuration for $subproject because multiplatform plugin has not been configured properly")
return@withPlugin
}
val useNativeBuildInfraInIdea = subproject.findProperty("useNativeBuildInfraInIdea")?.toString()?.toBoolean() ?: false
val commonMain = kotlin.sourceSets.getByName("commonMain")
val commonTest = kotlin.sourceSets.getByName("commonTest")
val extension: Any = if (ideaActive && !useNativeBuildInfraInIdea)
NativeIdeaInfraExtension(subproject, kotlin, "native", commonMain, commonTest)
else
NativeBuildInfraExtension(subproject, kotlin, "native", commonMain, commonTest)
(kotlin as ExtensionAware).extensions.add("infra", extension)
}
}
}
abstract class NativeInfraExtension(
protected val project: Project,
protected val kotlin: KotlinMultiplatformExtension,
protected val sourceSetName: String,
commonMainSourceSet: KotlinSourceSet,
commonTestSourceSet: KotlinSourceSet,
) {
protected val mainSourceSet = kotlin.sourceSets.maybeCreate("${sourceSetName}Main").apply { dependsOn(commonMainSourceSet) }
protected val testSourceSet = kotlin.sourceSets.maybeCreate("${sourceSetName}Test").apply { dependsOn(commonTestSourceSet) }
protected val sharedConfigs = mutableListOf<KotlinNativeTarget.() -> Unit>()
fun shared(configure: Closure<*>) = shared { ConfigureUtil.configure(configure, this) }
fun shared(configure: KotlinNativeTarget.() -> Unit) {
sharedConfigs.add(configure)
}
fun target(name: String) = target(name) { }
fun target(name: String, configure: Closure<*>) = target(name) { ConfigureUtil.configure(configure, this) }
abstract fun target(name: String, configure: KotlinNativeTarget.() -> Unit)
fun common(name: String, configure: Closure<*>) = common(name) { ConfigureUtil.configure(configure, this) }
abstract fun common(name: String, configure: NativeInfraExtension.() -> Unit)
}
class NativeIdeaInfraExtension(
project: Project,
kotlin: KotlinMultiplatformExtension,
sourceSetName: String,
commonMainSourceSet: KotlinSourceSet,
commonTestSourceSet: KotlinSourceSet,
) : NativeInfraExtension(project, kotlin, sourceSetName, commonMainSourceSet, commonTestSourceSet) {
private val hostManager = createHostManager()
private val hostTarget = HostManager.host
private val hostPreset =
kotlin.presets.filterIsInstance<AbstractKotlinNativeTargetPreset<*>>().let { nativePresets ->
nativePresets.singleOrNull { preset ->
hostManager.isEnabled(preset.konanTarget) && hostTarget == preset.konanTarget
} ?: error("No native preset of ${nativePresets.map { it.konanTarget }} matches current host target $hostTarget")
}
init {
project.logger.infra("Configuring native targets for $project for IDEA")
project.logger.infra("Host preset: ${hostPreset.name}")
}
override fun target(name: String, configure: KotlinNativeTarget.() -> Unit) {
if (name != hostPreset.name)
return
kotlin.targetFromPreset(hostPreset, sourceSetName) {
configure()
sharedConfigs.forEach { it() }
}
project.afterEvaluate {
kotlin.sourceSets.getByName("${sourceSetName}Main") {
kotlin.srcDir("${hostPreset.name}Main/src")
}
}
}
override fun common(name: String, configure: NativeInfraExtension.() -> Unit) {
val extension = NativeIdeaInfraExtension(project, kotlin, name, mainSourceSet, testSourceSet)
extension.configure()
}
}
class NativeBuildInfraExtension(
project: Project,
kotlin: KotlinMultiplatformExtension,
sourceSetName: String,
commonMainSourceSet: KotlinSourceSet,
commonTestSourceSet: KotlinSourceSet,
) : NativeInfraExtension(project, kotlin, sourceSetName, commonMainSourceSet, commonTestSourceSet) {
private val nativePresets = kotlin.presets.filterIsInstance<AbstractKotlinNativeTargetPreset<*>>()
init {
project.logger.infra("Configuring native targets for $project for build")
project.logger.infra("Enabled native targets: ${nativePresets.joinToString { it.name }}")
}
override fun target(name: String, configure: KotlinNativeTarget.() -> Unit) {
val preset = nativePresets.singleOrNull { it.name == name } ?: return
project.logger.infra("Creating target '${preset.name}' with dependency on '$sourceSetName'")
val target = kotlin.targetFromPreset(preset) {
configure()
sharedConfigs.forEach { config -> config() }
}
kotlin.sourceSets.getByName("${preset.name}Main") {
dependsOn(mainSourceSet)
}
kotlin.sourceSets.getByName("${preset.name}Test") {
dependsOn(testSourceSet)
}
}
override fun common(name: String, configure: NativeInfraExtension.() -> Unit) {
val extension = NativeBuildInfraExtension(project, kotlin, name, mainSourceSet, testSourceSet)
extension.configure()
}
}
private fun createHostManager(): HostManager {
val managerClass = HostManager::class.java
val constructors = managerClass.constructors
val constructor = constructors.first { it.parameterCount == 0 }
return constructor.newInstance() as HostManager
}
| 1 | Kotlin | 8 | 10 | 50c83f793b1a24932023b2ca9ac568b0c52e4863 | 6,603 | kotlinx.team.infra | Apache License 2.0 |
presentation/src/main/java/dev/olog/basil/presentation/base/ImageModel.kt | ologe | 167,401,725 | false | null | package dev.olog.basil.presentation.base
data class ImageModel(
override val id: Int,
override val type: Int,
val image: String
) : BaseModel | 2 | Kotlin | 3 | 11 | c8c3f7991e4fec934d7e1a3018ee6a1be7862dd8 | 154 | basil | MIT License |
app-core/src/main/kotlin/ru/micron/security/CustomUserDetails.kt | m1cron | 326,198,639 | false | null | package ru.micron.security
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.userdetails.UserDetails
import java.util.*
data class CustomUserDetails(
var uuid: UUID,
private val username: String,
private val password: String,
private val isEnabled: Boolean,
private val authorities: MutableCollection<out GrantedAuthority>
) : UserDetails {
override fun getUsername(): String = username
override fun getPassword(): String = password
override fun isEnabled(): Boolean = isEnabled
override fun getAuthorities(): MutableCollection<out GrantedAuthority> = authorities
override fun isAccountNonExpired(): Boolean = true
override fun isAccountNonLocked(): Boolean = true
override fun isCredentialsNonExpired(): Boolean = true
} | 0 | Kotlin | 1 | 4 | dde2817edbe5e20f539804d1e9ccbec7c27330d3 | 820 | films_catalog | MIT License |
app/src/test/java/io/benic/shoppinglist/viewmodel/ItemViewModelTest.kt | BBenicio | 325,425,619 | false | null | package io.benic.shoppinglist.viewmodel
import androidx.lifecycle.MutableLiveData
import io.benic.shoppinglist.model.Item
import io.benic.shoppinglist.model.ShoppingCart
import io.benic.shoppinglist.repository.ItemRepository
import io.benic.shoppinglist.repository.ShoppingCartRepository
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.MockitoAnnotations
class ItemViewModelTest {
@Mock
private lateinit var itemRepository: ItemRepository
@Mock
private lateinit var cartRepository: ShoppingCartRepository
private lateinit var itemViewModel: ItemViewModel
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
itemViewModel = ItemViewModel(itemRepository, cartRepository)
`when`(itemRepository.getItems(anyLong())).thenReturn(MutableLiveData())
`when`(cartRepository.getCart(anyInt())).thenReturn(MutableLiveData())
}
@Test
fun fetchItems() {
itemViewModel.fetchItems(0)
verify(itemRepository).getItems(0)
verifyNoMoreInteractions(itemRepository)
}
@Test
fun fetchCart() {
itemViewModel.fetchCart(0)
verify(cartRepository).getCart(0)
verifyNoMoreInteractions(cartRepository)
}
@Test
fun createCart() {
val cart = ShoppingCart(name = "cart")
itemViewModel.createCart(cart)
verify(cartRepository).addCart(cart)
verifyNoMoreInteractions(cartRepository)
}
@Test
fun addItem() {
val item = Item(name = "item")
itemViewModel.addItem(item)
verify(itemRepository).addItem(item)
verifyNoMoreInteractions(itemRepository)
}
@Test
fun updateCart() {
val cart = ShoppingCart(name = "cart")
itemViewModel.updateCart(cart)
verify(cartRepository).updateCart(cart)
verifyNoMoreInteractions(cartRepository)
}
@Test
fun updateItem() {
val item = Item(name = "item")
itemViewModel.updateItem(item)
verify(itemRepository).updateItem(item)
verifyNoMoreInteractions(itemRepository)
}
@Test
fun deleteItem() {
val item = Item(name = "item")
itemViewModel.deleteItem(item)
verify(itemRepository).deleteItem(item)
verifyNoMoreInteractions(itemRepository)
}
} | 0 | Kotlin | 0 | 0 | f1ee39e0ef2e61c0a78066483918c51a15d9223f | 2,382 | shoppinglist | MIT License |
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/VideoChatSharp.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/VideoChatSharp")
@file:JsNonModule
package mui.icons.material
@JsName("default")
external val VideoChatSharp: SvgIconComponent
| 1 | Kotlin | 5 | 35 | eb68a042133a7d025aef8450151ee0150cbc9b1b | 210 | mui-kotlin | Apache License 2.0 |
core/src/commonMain/kotlin/it/unibo/tuprolog/argumentation/core/model/Support.kt | tuProlog | 333,103,830 | false | {"Kotlin": 300090, "Prolog": 61781, "JavaScript": 917, "Java": 258} | package it.unibo.tuprolog.argumentation.core.model
import it.unibo.tuprolog.core.Struct
import it.unibo.tuprolog.core.Term
import it.unibo.tuprolog.core.parsing.parse
data class Support(val supporter: Argument, val supported: Argument) {
override fun toString(): String {
return "support(${supporter.termRepresentation()}, ${supported.termRepresentation()})"
}
fun toTerm(): Term {
return Struct.parse(this.toString())
}
}
| 15 | Kotlin | 0 | 6 | 2cf65e2f1c94bc625447a10f12e765a20245bdcc | 458 | arg2p-kt | MIT License |
app/src/main/java/com/ecjtu/sharebox/MainApplication.kt | xulele | 98,136,422 | true | {"JavaScript": 493766, "HTML": 409276, "CSS": 352097, "Java": 252722, "Kotlin": 91753} | package com.ecjtu.sharebox
import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.os.Environment
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.cache.DiskLruCacheFactory
import com.bumptech.glide.load.DecodeFormat
import android.os.Environment.getExternalStorageDirectory
import android.support.v4.content.LocalBroadcastManager
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory
import com.bumptech.glide.load.engine.cache.LruResourceCache
import com.bumptech.glide.load.engine.cache.MemoryCache
import com.bumptech.glide.module.AppGlideModule
import com.bumptech.glide.module.GlideModule
import com.bumptech.glide.module.LibraryGlideModule
import com.ecjtu.sharebox.service.DaemonService
import com.ecjtu.sharebox.service.MainService
import org.ecjtu.channellibrary.wifidirect.WifiDirectManager
//http://blog.csdn.net/jiangwei0910410003/article/details/41384667 class loader
//https://mp.weixin.qq.com/s?__biz=MzI2OTQxMTM4OQ==&mid=2247485000&idx=1&sn=2d74c597c62c9c4229f79cce9587b6bf&chksm=eae1f31add967a0cddf98dd3bbf529b50420bbf7a9cb6b238e6e6fe993c8bd8ba5cca728e0da#rd
/**
* Created by KerriGan on 2017/6/9 0009.
*/
class MainApplication:Application(){
private val mSavedStateInstance=HashMap<String,Any>()
override fun onCreate() {
super.onCreate()
var module=SimpleGlideModule()
var builder=GlideBuilder()
module.applyOptions(this,builder)
var glide=builder.build(this)
Glide.init(glide)
WifiDirectManager.getInstance(this)
LocalBroadcastManager.getInstance(this)
initSavedState()
startService(Intent(this,MainService::class.java))
}
fun getSavedStateInstance():MutableMap<String,Any>{
return mSavedStateInstance
}
private fun initSavedState(){
}
inner class SimpleGlideModule : AppGlideModule() {
override fun applyOptions(context: Context, builder: GlideBuilder) {
//定义缓存大小为100M
val diskCacheSize = 100 * 1024 * 1024
//自定义缓存 路径 和 缓存大小
// val diskCachePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/glideCache"
//提高图片质量
builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888)
//自定义磁盘缓存:这种缓存只有自己的app才能访问到
builder.setDiskCache(InternalCacheDiskCacheFactory( context , diskCacheSize )) ;
// builder.setDiskCache( new InternalCacheDiskCacheFactory( context , diskCachePath , diskCacheSize )) ;
//自定义磁盘缓存:这种缓存存在SD卡上,所有的应用都可以访问到
// builder.setDiskCache(DiskLruCacheFactory(diskCachePath, diskCacheSize))
//Memory Cache
builder.setMemoryCache(LruResourceCache(24*1024*1024))
}
}
}
| 0 | JavaScript | 0 | 0 | 2f8dfbb783c3df8f0e4d20773ce22ba97fa8dfd9 | 2,922 | ShareBox | Apache License 2.0 |
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/UseRequireSpec.kt | dector | 212,993,385 | false | null | package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.test.assertThat
import io.gitlab.arturbosch.detekt.test.lint
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class UseRequireSpec : Spek({
val subject by memoized { UseRequire(Config.empty) }
describe("UseRequire rule") {
it("reports if a precondition throws an IllegalArgumentException") {
val code = """
fun x(a: Int) {
if (a < 0) throw IllegalArgumentException()
doSomething()
}"""
assertThat(subject.lint(code)).hasSourceLocation(2, 16)
}
it("reports if a precondition throws an IllegalArgumentException with more details") {
val code = """
fun x(a: Int) {
if (a < 0) throw IllegalArgumentException("More details")
doSomething()
}"""
assertThat(subject.lint(code)).hasSourceLocation(2, 16)
}
it("reports if a precondition throws a fully qualified IllegalArgumentException") {
val code = """
fun x(a: Int) {
if (a < 0) throw java.lang.IllegalArgumentException()
doSomething()
}"""
assertThat(subject.lint(code)).hasSourceLocation(2, 16)
}
it("reports if a precondition throws a fully qualified IllegalArgumentException using the kotlin type alias") {
val code = """
fun x(a: Int) {
if (a < 0) throw kotlin.IllegalArgumentException()
doSomething()
}"""
assertThat(subject.lint(code)).hasSourceLocation(2, 16)
}
it("does not report if a precondition throws a different kind of exception") {
val code = """
fun x(a: Int) {
if (a < 0) throw SomeBusinessException()
doSomething()
}"""
assertThat(subject.lint(code)).isEmpty()
}
it("does not report an issue if the exception thrown has a message and a cause") {
val code = """
private fun x(a: Int): Nothing {
doSomething()
throw IllegalArgumentException("message", cause)
}"""
assertThat(subject.lint(code)).isEmpty()
}
it("does not report an issue if the exception thrown as the only action in a block") {
val code = """
fun unsafeRunSync(): A =
foo.fold({ throw IllegalArgumentException("message") }, ::identity)"""
assertThat(subject.lint(code)).isEmpty()
}
it("does not report an issue if the exception thrown unconditionally") {
val code = """fun doThrow() = throw IllegalArgumentException("message")"""
assertThat(subject.lint(code)).isEmpty()
}
it("does not report an issue if the exception thrown unconditionally in a function block") {
val code = """fun doThrow() { throw IllegalArgumentException("message") }"""
assertThat(subject.lint(code)).isEmpty()
}
context("throw is not after a precondition") {
it("does not report an issue if the exception is inside a when") {
val code = """
fun whenOrThrow(item : List<*>) = when(item) {
is ArrayList<*> -> 1
is LinkedList<*> -> 2
else -> throw IllegalArgumentException("Not supported List type")
}
"""
assertThat(subject.lint(code)).isEmpty()
}
it("does not report an issue if the exception is after a block") {
val code = """
fun doSomethingOrThrow(test: Int): Int {
var index = 0
repeat(test){
if (Math.random() == 1.0) {
return it
}
}
throw IllegalArgumentException("Test was too big")
}"""
assertThat(subject.lint(code)).isEmpty()
}
it("does not report an issue if the exception is after a elvis operator") {
val code = """
fun tryToCastOrThrow(list: List<*>) : LinkedList<*> {
val subclass = list as? LinkedList
?: throw IllegalArgumentException("List is not a LinkedList")
return subclass
}"""
assertThat(subject.lint(code)).isEmpty()
}
}
}
})
| 0 | null | 0 | 1 | 0706bb359dcb39bf113cbb87d08e6639a8acc7de | 4,942 | detekt | Apache License 2.0 |
feature/accounts/src/main/java/org/expenny/feature/accounts/AccountsListScreen.kt | expenny-application | 712,607,222 | false | {"Kotlin": 933192} | package org.expenny.feature.accounts
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.hilt.navigation.compose.hiltViewModel
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.result.ResultBackNavigator
import org.expenny.core.ui.utils.ExpennySnackbarManager
import org.expenny.core.ui.data.navargs.NavArgResult
import org.expenny.core.ui.utils.ExpennyDrawerState
import org.expenny.feature.accounts.model.Event
import org.expenny.feature.accounts.navigation.AccountsListNavArgs
import org.expenny.feature.accounts.navigation.AccountsListNavigator
import org.expenny.feature.accounts.view.AccountsListContent
import org.orbitmvi.orbit.compose.collectAsState
import org.orbitmvi.orbit.compose.collectSideEffect
@Destination(navArgsDelegate = AccountsListNavArgs::class)
@Composable
fun AccountsListScreen(
snackbarManager: ExpennySnackbarManager,
navigator: AccountsListNavigator,
resultNavigator: ResultBackNavigator<NavArgResult>,
drawerState: ExpennyDrawerState
) {
val vm: AccountsListViewModel = hiltViewModel()
val state by vm.collectAsState()
val lazyListState = rememberLazyListState()
vm.collectSideEffect {
when (it) {
is Event.NavigateToCreateAccount -> navigator.navigateToCreateAccountScreen()
is Event.NavigateToEditAccount -> navigator.navigateToEditAccountScreen(it.id)
is Event.NavigateBackWithResult -> resultNavigator.navigateBack(it.result)
is Event.NavigateBack -> navigator.navigateBack()
}
}
AccountsListContent(
state = state,
lazyListState = lazyListState,
drawerState = drawerState,
onAction = vm::onAction
)
}
| 0 | Kotlin | 4 | 40 | d6502acbd44adeb9597ae2a9c0d628168af2ec7a | 1,844 | expenny-android | Apache License 2.0 |
src/test/kotlin/no/nav/bidrag/vedtak/BidragVedtakTestConfig.kt | navikt | 331,260,160 | false | null | package no.nav.bidrag.vedtak
import no.nav.bidrag.commons.web.test.HttpHeaderTestRestTemplate
import no.nav.bidrag.vedtak.BidragVedtakLocal.Companion.TEST_PROFILE
import no.nav.bidrag.vedtak.hendelser.VedtakKafkaEventProducer
import no.nav.bidrag.vedtak.model.VedtakHendelse
import no.nav.security.token.support.test.jersey.TestTokenGeneratorResource
import org.slf4j.LoggerFactory
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Profile
import org.springframework.http.HttpHeaders
private val LOGGER = LoggerFactory.getLogger(BidragVedtakTestConfig::class.java)
@Configuration
@Profile(TEST_PROFILE)
class BidragVedtakTestConfig {
@Bean
fun securedTestRestTemplate(testRestTemplate: TestRestTemplate?): HttpHeaderTestRestTemplate? {
val httpHeaderTestRestTemplate = HttpHeaderTestRestTemplate(testRestTemplate)
httpHeaderTestRestTemplate.add(HttpHeaders.AUTHORIZATION) { generateTestToken() }
return httpHeaderTestRestTemplate
}
private fun generateTestToken(): String {
val testTokenGeneratorResource = TestTokenGeneratorResource()
return "Bearer " + testTokenGeneratorResource.issueToken("localhost-idtoken")
}
@Bean
fun vedtakKafkaEventProducer() = TestVedtakKafkaEventProducer()
}
class TestVedtakKafkaEventProducer: VedtakKafkaEventProducer{
override fun publish(vedtakHendelse: VedtakHendelse) {
LOGGER.info("Test Kafka: $vedtakHendelse")
}
} | 0 | Kotlin | 0 | 1 | 6aeb9b13aa048166eecfec2350ded177d2d10597 | 1,572 | bidrag-vedtak | MIT License |
sdk-scrapper/src/main/kotlin/io/github/wulkanowy/sdk/scrapper/student/StudentGuardian.kt | wulkanowy | 138,756,468 | false | {"Kotlin": 705036, "HTML": 70768} | package io.github.wulkanowy.sdk.scrapper.student
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonNames
@Serializable
@OptIn(ExperimentalSerializationApi::class)
data class StudentGuardian(
@SerialName("Id")
val id: Int = -1,
@SerialName("Imie")
@JsonNames("imie")
val name: String,
@SerialName("Nazwisko")
@JsonNames("nazwisko")
val lastName: String,
@SerialName("StPokrewienstwa")
@JsonNames("stPokrewienstwa")
val kinship: String?,
@SerialName("Adres")
@JsonNames("adres")
val address: String,
@SerialName("TelDomowy")
@JsonNames("telDomowy")
val homePhone: String?,
@SerialName("TelKomorkowy")
@JsonNames("telKomorkowy")
val cellPhone: String?,
@SerialName("TelSluzbowy")
@JsonNames("telSluzbowy")
val workPhone: String?,
@SerialName("Email")
@JsonNames("email")
val email: String?,
@SerialName("FullName")
val fullName: String = "",
@SerialName("Telefon")
val phone: String = "",
)
| 11 | Kotlin | 5 | 8 | 340245d8ccc2790dcb75219c2839e8bdd8b448a4 | 1,149 | sdk | Apache License 2.0 |
src/main/kotlin/it/czerwinski/intellij/wavefront/lang/parser/MtlParserDefinition.kt | sczerwinski | 283,832,623 | false | null | /*
* Copyright 2020-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 it.czerwinski.intellij.wavefront.lang.parser
import com.intellij.lang.ASTNode
import com.intellij.lang.ParserDefinition
import com.intellij.lang.PsiParser
import com.intellij.lexer.Lexer
import com.intellij.openapi.project.Project
import com.intellij.psi.FileViewProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.tree.IFileElementType
import com.intellij.psi.tree.TokenSet
import it.czerwinski.intellij.wavefront.lang.MtlLanguage
import it.czerwinski.intellij.wavefront.lang.MtlLexerAdapter
import it.czerwinski.intellij.wavefront.lang.psi.MtlFile
import it.czerwinski.intellij.wavefront.lang.psi.MtlTypes
class MtlParserDefinition : ParserDefinition {
override fun createLexer(project: Project?): Lexer = MtlLexerAdapter()
override fun getCommentTokens(): TokenSet = TokenSet.create(MtlTypes.COMMENT_BLOCK)
override fun getStringLiteralElements(): TokenSet = TokenSet.EMPTY
override fun createParser(project: Project?): PsiParser = MtlParser()
override fun getFileNodeType(): IFileElementType = IFileElementType(MtlLanguage)
override fun createFile(viewProvider: FileViewProvider): PsiFile = MtlFile(viewProvider)
override fun spaceExistenceTypeBetweenTokens(left: ASTNode, right: ASTNode): ParserDefinition.SpaceRequirements =
ParserDefinition.SpaceRequirements.MUST
override fun createElement(node: ASTNode): PsiElement = MtlTypes.Factory.createElement(node)
}
| 27 | null | 1 | 9 | ca6ee47083cdca9b52cd2a59994d12a4a10033eb | 2,068 | wavefront-obj-intellij-plugin | Apache License 2.0 |
app/src/main/java/com/omen273/crossLingo/Timer.kt | omen273 | 300,259,349 | false | null | package com.omen273.crossLingo
import android.os.Handler
import android.os.Looper
class Timer(private val duration : Long, private val action1 : () -> Unit, private val action2 : () -> Unit,
val changeCondition : () -> Boolean) {
private val handler = Handler(Looper.getMainLooper())
private fun start(act: () -> Unit) = handler.postDelayed({
act()
}, duration)
fun stop() = handler.removeCallbacksAndMessages(null)
fun restart() {
stop()
start(if(changeCondition()) action2 else action1)
}
}
class Dimmer(private val duration : Long, private val action1 : () -> Unit, private val action2 : () -> Unit) {
enum class Action{ACTION1, ACTION2}
var action = Action.ACTION1
private val handler = Handler(Looper.getMainLooper())
fun start() {
handler.postDelayed({
when (action) {
Action.ACTION1 -> {
action1()
action = Action.ACTION2
start()
}
Action.ACTION2 -> {
action2()
action = Action.ACTION1
start()
}
}
}, duration)
}
fun stop() {
handler.removeCallbacksAndMessages(null)
action = Action.ACTION1
}
}
| 41 | Kotlin | 3 | 3 | 77ea80effb56ac90cacc2932dbd86fc5ac7baf28 | 1,338 | crosswordApp | MIT License |
app/src/main/java/at/guger/moneybook/ui/home/accounts/addeditaccount/AddEditAccountDialogFragmentViewModel.kt | guger | 198,668,519 | false | null | /*
* Copyright 2022 <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 at.guger.moneybook.ui.home.accounts.addeditaccount
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import at.guger.moneybook.R
import at.guger.moneybook.core.ui.viewmodel.Event
import at.guger.moneybook.core.ui.widget.CurrencyTextInputEditText
import at.guger.moneybook.core.util.ext.ifNull
import at.guger.moneybook.data.model.Account
import at.guger.moneybook.data.repository.AccountsRepository
import at.guger.moneybook.util.DataUtils
import kotlinx.coroutines.launch
/**
* [ViewModel] for the [AddEditAccountBottomSheetDialogFragment].
*/
class AddEditAccountDialogFragmentViewModel(private val accountsRepository: AccountsRepository) : ViewModel() {
//region Variables
private var account: Account? = null
private val _titleRes = MutableLiveData(R.string.NewAccount)
val titleRes: LiveData<Int> = _titleRes
val accountName = MutableLiveData<String>()
val accountStartBalance = MutableLiveData<String>()
private val _accountStartBalanceError = MutableLiveData<Event<Unit>>()
val accountStartBalanceError: LiveData<Event<Unit>> = _accountStartBalanceError
private val _accountSaved = MutableLiveData<Event<Unit>>()
val accountSaved: LiveData<Event<Unit>> = _accountSaved
//endregion
//region Methods
fun setupAccount(account: Account) {
this.account = account
_titleRes.value = R.string.EditAccount
accountName.value = account.name
accountStartBalance.value = CurrencyTextInputEditText.CURRENCY_FORMAT.format(account.startBalance)
}
fun save() {
viewModelScope.launch {
val startBalance = parseNumber(accountStartBalance.value)
if (startBalance != null) {
account.ifNull {
val colors = DataUtils.ACCOUNT_COLORS
val accountColor: Int = accountsRepository.countAccounts() % colors.size
accountsRepository.insert(
Account(
name = accountName.value!!.trim(),
color = colors[accountColor],
startBalance = startBalance
)
)
} ?: accountsRepository.update(
Account(
id = account!!.id,
name = accountName.value!!.trim(),
color = account!!.color,
startBalance = startBalance
)
)
_accountSaved.value = Event(Unit)
} else {
_accountStartBalanceError.value = Event(Unit)
}
}
}
private fun parseNumber(text: String?) = if (text.isNullOrBlank()) 0.0 else text.replace(",", ".").toDoubleOrNull()
//endregion
} | 18 | null | 1 | 13 | cc374cf434aad9db5a3fc8f336aaf3e4eb91100d | 3,543 | MoneyBook | Apache License 2.0 |
src/main/kotlin/dec23/Input.kt | dladukedev | 318,188,745 | false | null | package dec23
val input = listOf(9,7,4,6,1,8,3,5,2) | 0 | Kotlin | 0 | 0 | d4591312ddd1586dec6acecd285ac311db176f45 | 52 | advent-of-code-2020 | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.