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/net/ormr/userskripter/plugin/UserskripterPlugin.kt
Olivki
567,437,327
false
{"Kotlin": 42726}
/* * Copyright 2022 Oliver Berg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.ormr.userskripter.plugin import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.plugins.ExtensionAware import org.gradle.kotlin.dsl.properties import org.gradle.kotlin.dsl.withType import org.jetbrains.kotlin.gradle.dsl.KotlinJsProjectExtension import org.jetbrains.kotlin.gradle.dsl.kotlinExtension import org.jetbrains.kotlin.gradle.targets.js.webpack.KotlinWebpack import org.jetbrains.kotlin.gradle.tasks.Kotlin2JsCompile private const val PACKAGE = "net.ormr.userskripter" private const val ENGINES_PACKAGE = "${PACKAGE}.engine" private const val GREASE_MONKEY_PATH = "${ENGINES_PACKAGE}.greasemonkey" private const val TAMPER_MONKEY_PATH = "${ENGINES_PACKAGE}.tampermonkey" private const val UNSAFE_WINDOW_COMPATIBLE = "${ENGINES_PACKAGE}.UnsafeWindowCompatibleScriptEngine" class UserskripterPlugin : Plugin<Project> { companion object { private val gmGrants = mapOf( "GM.setValue" to "GrantGMSetValue", "GM.getValue" to "GrantGMGetValue", "GM.deleteValue" to "GrantGMDeleteValue", "GM.listValues" to "GrantGMListValues", "GM.getResourceUrl" to "GrantGMGetResourceUrl", "GM.notification" to "GrantGMNotification", "GM.openInTab" to "GrantGMOpenInTab", "GM.registerMenuCommand" to "GrantGMRegisterMenuCommand", "GM.setClipboard" to "GrantGMSetClipboard", "GM.xmlHttpRequest" to "GrantGMXmlHttpRequest", "unsafeWindow" to "GrantUnsafeWindow", // blocking "GM_setValue" to "GrantGMSetValueBlocking", "GM_getValue" to "GrantGMGetValueBlocking", "GM_deleteValue" to "GrantGMDeleteValueBlocking", "GM_listValues" to "GrantGMListValuesBlocking", "GM_getResourceUrl" to "GrantGMGetResourceUrlBlocking", "GM_notification" to "GrantGMNotificationBlocking", "GM_openInTab" to "GrantGMOpenInTabBlocking", "GM_registerMenuCommand" to "GrantGMRegisterMenuCommandBlocking", "GM_setClipboard" to "GrantGMSetClipboardBlocking", "GM_xmlHttpRequest" to "GrantGMXmlHttpRequestBlocking", ) private val tmGrants = mapOf( "GM.addStyle" to "GrantTMAddStyle", "GM.addElement" to "GrantTMAddElement", "GM.addValueChangeListener" to "GrantTMAddValueChangeListener", "GM.removeValueChangeListener" to "GrantTMRemoveValueChangeListener", "GM.log" to "GrantTMLog", "GM.getResourceText" to "GrantTMGetResourceText", "GM.unregisterMenuCommand" to "GrantTMUnregisterMenuCommand", "GM.download" to "GrantTMDownload", "GM.getTab" to "GrantTMGetTab", "GM.saveTab" to "GrantTMSaveTab", "GM.getTabs" to "GrantTMGetTabs", // blocking "GM_addStyle" to "GrantTMAddStyleBlocking", "GM_addElement" to "GrantTMAddElementBlocking", "GM_addValueChangeListener" to "GrantTMAddValueChangeListenerBlocking", "GM_removeValueChangeListener" to "GrantTMRemoveValueChangeListenerBlocking", "GM_log" to "GrantTMLogBlocking", "GM_getResourceText" to "GrantTMGetResourceTextBlocking", "GM_unregisterMenuCommand" to "GrantTMUnregisterMenuCommandBlocking", "GM_download" to "GrantTMDownloadBlocking", "GM_getTab" to "GrantTMGetTabBlocking", "GM_saveTab" to "GrantTMSaveTabBlocking", "GM_getTabs" to "GrantTMGetTabsBlocking", ) } @OptIn(ExperimentalStdlibApi::class) override fun apply(project: Project) { // TODO: this does screw over multiplatform projects, but multiplatform project is way out of scope for this // plugin atm val kotlinJs = project.kotlinExtension as? KotlinJsProjectExtension ?: error("Project is not Kotlin/JS") val userskripterDirectory = project.buildDir.resolve("userskripter") val generatedDirectory = project.buildDir.resolve("generated/userskripter/kotlin/") val extension = project.extensions.create("userskript", UserskripterExtension::class.java, project) val metadata = (extension as ExtensionAware).extensions.create( "metadata", UserskripterMetadataBlockExtension::class.java, project, extension, ) val metadataTranspiler = (extension as ExtensionAware).extensions.create( "metadataTranspiler", UserskripterMetadataTranspilerExtension::class.java, project, generatedDirectory, ) kotlinJs.sourceSets.named("main") { kotlin.srcDir(generatedDirectory) } project.task("printUserscriptMetadata") { group = "userskripter" doLast { print(serializeMetadataBlock(metadata)) } } project.afterEvaluate { // greasemonkey api stuff should be supported in virtually every script-engine, so we just use that as a base // we still annotate greasemonkey stuff with opt-in, just in case we encounter an engine that is not // compatible addGrants(project, metadata, gmGrants, GREASE_MONKEY_PATH) when (extension.scriptEngine) { ScriptEngine.GREASE_MONKEY -> { addOptIns(project, listOf("${ENGINES_PACKAGE}.ScriptEngineGreaseMonkey", UNSAFE_WINDOW_COMPATIBLE)) } ScriptEngine.TAMPER_MONKEY -> { addOptIns(project, listOf("${ENGINES_PACKAGE}.ScriptEngineTamperMonkey", UNSAFE_WINDOW_COMPATIBLE)) addGrants(project, metadata, tmGrants, TAMPER_MONKEY_PATH) } } val webpackTask = project.tasks.getByPath(extension.mode.taskName) as KotlinWebpack val metaFile = userskripterDirectory.resolve("${extension.id}.meta.js") val userFile = userskripterDirectory.resolve("${extension.id}.user.js") val userSourceMapFile = userskripterDirectory.resolve("${extension.id}.user.js.map") val transpiledFile = metadataTranspiler.outputDirectory.resolve("${metadataTranspiler.outputName}.kt") val generateMetaFile = project.task("generateMetaFile") { outputs.file(metaFile) inputs.properties(metadata.buildGradleProperties()) group = "userskripter" doLast { metaFile.writeText(serializeMetadataBlock(metadata)) } } val generateUserFile = project.task("generateUserFile") { dependsOn(webpackTask) inputs.properties(metadata.buildGradleProperties()) inputs.properties("mode" to extension.mode, "id" to extension.id) inputs.file(webpackTask.outputFile) outputs.file(userFile) group = "userskripter" doLast { // TODO: can we do this writing more efficiently? userFile.writeText(serializeMetadataBlock(metadata)) userFile.appendBytes(webpackTask.outputFile.readBytes()) } } // TODO: is this proper? val copyUserSourceMap = project.task("copyUserSourceMap") { val sourceMapFile = webpackTask.destinationDirectory.resolve("${webpackTask.outputFileName}.map") dependsOn(generateUserFile) inputs.file(sourceMapFile) outputs.file(userSourceMapFile) group = "userskripter" doLast { if (sourceMapFile.exists()) { sourceMapFile.copyTo(userSourceMapFile) } else { logger.warn("Could not find a source-map at: $sourceMapFile") } } } // TODO: if used this should run first of all the tasks in 'generateUserscript', but it doesn't rn val generateUserscriptKotlinFile = project.task("generateUserscriptKotlinFile") { inputs.properties(metadata.buildGradleProperties()) inputs.properties(metadataTranspiler.properties.toGradlePropertyMap()) outputs.file(transpiledFile) group = "userskripter" doLast { transpiledFile.writeText(compileToKotlin(extension, metadata, metadataTranspiler)) } } project.task("generateUserscript") { setDependsOn(buildList { add(generateMetaFile) add(generateUserFile) if (extension.includeSourceMap) add(copyUserSourceMap) if (metadataTranspiler.runOnGenerate) add(generateUserscriptKotlinFile) }) outputs.files(metaFile, userFile) group = "userskripter" } } } private fun addGrants( project: Project, metadata: UserskripterMetadataBlockExtension, grants: Map<String, String>, path: String, ) { addOptIns(project, metadata.grant.mapNotNull { grants[it] }.map { "${path}.$it" }) } private fun addOptIn(project: Project, annotation: String) { project.tasks.withType<Kotlin2JsCompile>().configureEach { kotlinOptions { freeCompilerArgs = freeCompilerArgs + "-opt-in=${annotation}" } } } private fun addOptIns(project: Project, annotations: Iterable<String>) { project.tasks.withType<Kotlin2JsCompile>().configureEach { kotlinOptions { freeCompilerArgs = freeCompilerArgs + annotations.map { "-opt-in=$it" } } } } }
0
Kotlin
0
2
0f13f366355d4233c38546d7b393ac886fb56cb2
10,558
userskripter-gradle
Apache License 2.0
project/src/main/kotlin/cga/exercise/components/geometry/Mesh.kt
itsAltamas
396,089,178
true
{"Kotlin": 103779, "GLSL": 24426}
package cga.exercise.components.geometry import cga.exercise.components.shader.ShaderProgram import cga.framework.OBJLoader import org.lwjgl.opengl.GL11 import org.lwjgl.opengl.GL15 import org.lwjgl.opengl.GL15.* import org.lwjgl.opengl.GL20 import org.lwjgl.opengl.GL30 import org.lwjgl.opengl.GL30.* /** * Creates a Mesh object from vertexdata, intexdata and a given set of vertex attributes * * @param vertexdata plain float array of vertex data * @param indexdata index data * @param attributes vertex attributes contained in vertex data * @throws Exception If the creation of the required OpenGL objects fails, an exception is thrown * * Created by Fabian on 16.09.2017. */ class Mesh(vertexdata: FloatArray, indexdata: IntArray, attributes: Array<VertexAttribute>) { //private data private var vao = 0 private var vbo = 0 private var ibo = 0 private var indexcount = indexdata.size private var material: Material? = null private var cubeMaterial: CubeMaterial? = null constructor(vertexdata: FloatArray, indexdata: IntArray, attributes: Array<VertexAttribute>, material: Material) : this(vertexdata, indexdata, attributes) { this.material = material } constructor(vertexdata: FloatArray, indexdata: IntArray, attributes: Array<VertexAttribute>, cubeMaterial: CubeMaterial) : this(vertexdata, indexdata, attributes) { this.cubeMaterial = cubeMaterial } init { vao = GL30.glGenVertexArrays() GL30.glBindVertexArray(vao) vbo = glGenBuffers() glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, vertexdata, GL_STATIC_DRAW) attributes.forEach { GL30.glEnableVertexAttribArray(it.index) GL30.glVertexAttribPointer(it.index, it.size, it.type,it.normalized, it.stride, it.offset) } ibo = glGenBuffers() glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexdata, GL_STATIC_DRAW) GL30.glBindVertexArray(0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) } /** * renders the mesh */ fun render() { // call the rendering method every frame GL30.glBindVertexArray(vao) glDrawElements(GL_TRIANGLES, indexcount, GL_UNSIGNED_INT, 0) GL30.glBindVertexArray(0) } //Aufgabe 3.4 fun render(staticShader: ShaderProgram) { // call the rendering method every frame if (material != null) material?.bind(staticShader) if (cubeMaterial != null) cubeMaterial?.bind(staticShader) GL30.glBindVertexArray(vao) glDrawElements(GL_TRIANGLES, indexcount, GL_UNSIGNED_INT, 0) GL30.glBindVertexArray(0) } /** * Deletes the previously allocated OpenGL objects for this mesh */ fun cleanup() { if (ibo != 0) GL15.glDeleteBuffers(ibo) if (vbo != 0) GL15.glDeleteBuffers(vbo) if (vao != 0) GL30.glDeleteVertexArrays(vao) } }
0
Kotlin
0
0
4babb82a385fb502750e63a7cd4f0f6ae9b65619
3,008
CGA_Project
MIT License
src/main/kotlin/frc/chargers/controls/FeedbackController.kt
frc-5160-the-chargers
497,722,545
false
{"Kotlin": 438322, "Java": 56704}
package frc.chargers.controls /** * A [Controller] that uses feedback control to calculate its output. */ public interface FeedbackController<I, out T>: Controller<T>{ public var target: I public val error: I public fun calculateOutput(target: I): T{ this.target = target return calculateOutput() } }
3
Kotlin
0
2
ef0bca03f00901ffcc5508981089edced59f91aa
337
ChargerLib
MIT License
androidApp/src/main/java/com/bupware/wedraw/android/ui/widget/WeDrawPreferences.kt
ricardogdz6
673,342,069
false
{"Kotlin": 291056, "Swift": 342}
package com.bupware.wedraw.android.ui.widget import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.MutablePreferences import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import com.bupware.wedraw.android.roomData.tables.image.Image import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map const val IMAGE_KEY = "image_key" class WeDrawPreferences(private val context: Context) { companion object { const val WIMAGE_KEY = "wimage_key" val Context.dataStore : DataStore<Preferences> by preferencesDataStore(name = "wedraw_preferences") } //to get the uri val getUri: Flow<String> = context.dataStore.data.map { preferences -> preferences[stringPreferencesKey(IMAGE_KEY)] ?: "" } //to set the uri suspend fun setUri(uri: String) { context.dataStore.edit { preferences -> preferences[stringPreferencesKey(WIMAGE_KEY)] = uri } } } fun MutablePreferences.setImageData(image: Image) { this[stringPreferencesKey(IMAGE_KEY)] = image.uri }
0
Kotlin
0
0
438a26ff0502888858f797478786157e4213b1c6
1,277
WeDraw
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/menuxx/miaosha/queue/lisenter/RequestObtainListener.kt
menuxx
113,003,250
false
null
package com.menuxx.miaosha.queue.lisenter import com.menuxx.miaosha.disruptor.ChannelUserEventDisruptor import com.menuxx.miaosha.queue.msg.ObtainUserMsg import org.springframework.amqp.core.ExchangeTypes import org.springframework.amqp.rabbit.annotation.Exchange import org.springframework.amqp.rabbit.annotation.Queue import org.springframework.amqp.rabbit.annotation.QueueBinding import org.springframework.amqp.rabbit.annotation.RabbitListener import org.springframework.stereotype.Component import java.io.IOException /** * 作者: <EMAIL> * 创建于: 2017/12/10 * 微信: yin80871901 * 将用户请求 持有商品 的请求投递到 disruptor 高速队列 */ @Component @RabbitListener( containerFactory = "rabbitListenerContainerFactory" ) class RequestObtainListener ( private val producerDisruptor: ChannelUserEventDisruptor ) { @RabbitListener( bindings = [ (QueueBinding( value = Queue("request_obtain.queue", durable = "true"), exchange = Exchange("request_obtain.queue", type = ExchangeTypes.FANOUT, durable = "true"), key = "disruptor.request_obtain" )) ] ) @Throws(InterruptedException::class, IOException::class) fun onRequestObtainEvent(obtainUser: ObtainUserMsg) { producerDisruptor.product(userId = obtainUser.userId, channelId = obtainUser.channelId, orderId = 0, loopRefId = obtainUser.loopRefId) } }
0
Kotlin
0
0
f7b368e5cc8f6a005ae3174541e430e9fb106397
1,445
shuxiang-api
Apache License 2.0
app/src/main/java/com/muhammednazeer/bestquotes/QuotesAdapter.kt
muhammednazeer
267,317,412
false
null
package com.muhammednazeer.bestquotes import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView class QuotesAdapter (val context : Context, val quotes : List<String>, val onItemLongClick: (String) -> Unit) : RecyclerView.Adapter<QuotesAdapter.QuoteHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QuoteHolder { val view = LayoutInflater.from(context).inflate(R.layout.quote_item, parent, false) return QuoteHolder(view, onItemLongClick) } override fun getItemCount(): Int { return quotes.count() } override fun onBindViewHolder(holder: QuoteHolder, position: Int) { holder.bindQuotes(quotes[position]) } inner class QuoteHolder(itemView: View?, onItemLongClick: (String) -> Unit) : RecyclerView.ViewHolder(itemView!!){ val quotesText = itemView?.findViewById<TextView>(R.id.textViewQuote) fun bindQuotes(quote: String){ quotesText?.text = quote itemView.setOnLongClickListener { onItemLongClick(quote) true } } } }
0
Kotlin
0
1
a980e1c12a360c536cf5b83a2cd17609ab643b86
1,252
BestQuotes
MIT License
app/src/main/java/kh/farrukh/progee/db/framework/models/FrameworkRemoteKey.kt
KhusainovFarrukh
504,784,895
false
{"Kotlin": 122426}
package kh.farrukh.progee.db.framework.models import androidx.room.Entity import androidx.room.PrimaryKey /** *Created by farrukh_kh on 6/24/22 2:22 AM *kh.farrukh.progee.db.framework.models **/ @Entity(tableName = "framework_remote_keys") data class FrameworkRemoteKey( @PrimaryKey val id: Int = 0, val frameworkId: Long, val nextPage: Int?, val prevPage: Int? )
0
Kotlin
0
0
e52008d3442644e42be5187b6782ffd5350f23cd
389
Progee-Android
Apache License 2.0
build-logic/convention/src/main/kotlin/com/lukmadev/buildlogic/Detekt.kt
lukma
702,989,427
false
{"Kotlin": 133997}
package com.lukmadev.buildlogic import io.gitlab.arturbosch.detekt.Detekt import io.gitlab.arturbosch.detekt.extensions.DetektExtension import org.gradle.api.Project import org.gradle.kotlin.dsl.dependencies internal fun Project.configureDetekt(block: DetektExtension.() -> Unit) { tasks.withType(Detekt::class.java) { reports { xml.required.set(false) html.required.set(true) txt.required.set(false) sarif.required.set(true) md.required.set(false) } } extensions.configure<DetektExtension>("detekt") { apply(block) } dependencies { detektPlugins(libs.findLibrary("detekt.formatting")) detektPlugins(libs.findLibrary("detekt.rules.ruleauthors")) } } internal inline val Project.detektConfigDir: String get() = "${projectDir}/config/detekt/"
0
Kotlin
0
0
39f98c410e0fdf18de76e90403814dfe29403ee0
874
kmm-weather
Apache License 2.0
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/cloudwatch/VerticalShading.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 142794926}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.cloudwatch public enum class VerticalShading( private val cdkObject: software.amazon.awscdk.services.cloudwatch.VerticalShading, ) { NONE(software.amazon.awscdk.services.cloudwatch.VerticalShading.NONE), BEFORE(software.amazon.awscdk.services.cloudwatch.VerticalShading.BEFORE), AFTER(software.amazon.awscdk.services.cloudwatch.VerticalShading.AFTER), ; public companion object { internal fun wrap(cdkObject: software.amazon.awscdk.services.cloudwatch.VerticalShading): VerticalShading = when (cdkObject) { software.amazon.awscdk.services.cloudwatch.VerticalShading.NONE -> VerticalShading.NONE software.amazon.awscdk.services.cloudwatch.VerticalShading.BEFORE -> VerticalShading.BEFORE software.amazon.awscdk.services.cloudwatch.VerticalShading.AFTER -> VerticalShading.AFTER } internal fun unwrap(wrapped: VerticalShading): software.amazon.awscdk.services.cloudwatch.VerticalShading = wrapped.cdkObject } }
0
Kotlin
0
4
77ca8a42760b4bc23bbd76535c06a8aa626fe944
1,190
kotlin-cdk-wrapper
Apache License 2.0
TennisLabExposed/src/main/kotlin/models/Usuario.kt
idanirf
578,303,195
false
{"Kotlin": 247706}
package models import models.enums.TipoUsuario import java.util.* /** * Usuario * * @property id * @property uuid * @property nombre * @property apellido * @property correo * @property password * @property tipoUsuario * @constructor Create empty Usuario */ data class Usuario( val id:Int, val uuid: UUID, val nombre: String, val apellido: String, val correo: String, val password: String, val tipoUsuario: TipoUsuario )
0
Kotlin
2
2
618af3cdf691a44ba5ad4c0993b3aae0d0728f08
460
AD-P2-jsanchez-drodriguez-amaldonado
MIT License
core/src/main/java/com/rcosteira/core/di/modules/ViewModelFactoryModule.kt
rcosteira79
105,062,893
false
null
package com.rcosteira.core.di.modules import androidx.lifecycle.ViewModelProvider import com.rcosteira.core.ui.ViewModelFactory import dagger.Binds import dagger.Module import dagger.Reusable @Module abstract class ViewModelFactoryModule { @Binds @Reusable abstract fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory }
0
Kotlin
5
34
fbc34905496044a950862aee4dea16abfdad98a0
361
AndroidMultiModuleCleanArchTemplate
Apache License 2.0
src/main/kotlin/com/cognifide/gradle/aem/instance/Instance.kt
McAvity
139,147,788
true
{"Kotlin": 236312, "Shell": 5207, "Java": 1813, "Batchfile": 233}
package com.cognifide.gradle.aem.instance import com.cognifide.gradle.aem.api.AemConfig import com.cognifide.gradle.aem.api.AemException import com.cognifide.gradle.aem.internal.Formats import com.cognifide.gradle.aem.internal.Patterns import com.cognifide.gradle.aem.pkg.deploy.ListResponse import com.fasterxml.jackson.annotation.JsonIgnore import org.gradle.api.Project import java.io.Serializable import kotlin.reflect.KClass interface Instance : Serializable { companion object { val FILTER_ANY = "*" val ENVIRONMENT_CMD = "cmd" val URL_AUTHOR_DEFAULT = "http://localhost:4502" val URL_PUBLISH_DEFAULT = "http://localhost:4503" val USER_DEFAULT = "admin" val PASSWORD_DEFAULT = "<PASSWORD>" val AUTHORS_PROP = "aem.instance.authors" val PUBLISHERS_PROP = "aem.instance.publishers" fun parse(str: String): List<RemoteInstance> { return str.split(";").map { urlRaw -> val parts = urlRaw.split(",") when (parts.size) { 4 -> { val (httpUrl, type, user, password) = parts RemoteInstance.create(httpUrl, { this.user = user this.password = <PASSWORD> this.typeName = type }) } 3 -> { val (httpUrl, user, password) = parts RemoteInstance.create(httpUrl, { this.user = user this.password = <PASSWORD> }) } else -> { RemoteInstance.create(urlRaw) } } } } fun properties(project: Project): List<Instance> { val localInstances = collectProperties(project, "local").map { val (name, props) = it val nameParts = name.split("-") if (nameParts.size != 2) { throw InstanceException("Local instance name has invalid format: '$name'.") } val (environment, typeName) = nameParts val httpUrl = props["httpUrl"] ?: throw InstanceException("Local instance named '$name' must have property 'httpUrl' defined.") LocalInstance.create(httpUrl, { this.environment = environment this.typeName = typeName props["password"]?.let { this.password = it } props["jvmOpts"]?.let { this.jvmOpts = it.split(" ") } props["startOpts"]?.let { this.startOpts = it.split(" ") } props["runModes"]?.let { this.runModes = it.split(",") } props["debugPort"]?.let { this.debugPort = it.toInt() } }) }.sortedBy { it.name } val remoteInstances = collectProperties(project, "remote").map { val (name, props) = it val nameParts = name.split("-") if (nameParts.size != 2) { throw InstanceException("Remote instance name has invalid format: '$name'.") } val (environment, typeName) = nameParts val httpUrl = props["httpUrl"] ?: throw InstanceException("Remote instance named '$name' must have property 'httpUrl' defined.") RemoteInstance.create(httpUrl, { this.environment = environment this.typeName = typeName props["user"]?.let { this.user = it } props["password"]?.let { this.password = it } }) }.sortedBy { it.name } return localInstances + remoteInstances } private fun collectProperties(project: Project, type: String): MutableMap<String, MutableMap<String, String>> { return project.properties.filterKeys { Patterns.wildcard(it, "aem.instance.$type.*.*") }.entries.fold(mutableMapOf(), { result, e -> val (key, value) = e val parts = key.substringAfter(".$type.").split(".") if (parts.size != 2) { throw InstanceException("Instance list property '$key' has invalid format.") } val (name, prop) = parts result.getOrPut(name, { mutableMapOf() })[prop] = value as String result }) } fun defaults(project: Project): List<RemoteInstance> { val config = AemConfig.of(project) return listOf( RemoteInstance.create(URL_AUTHOR_DEFAULT, { environment = config.environment }), RemoteInstance.create(URL_PUBLISH_DEFAULT, { environment = config.environment }) ) } fun filter(project: Project): List<Instance> { return filter(project, AemConfig.of(project).instanceName) } fun filter(project: Project, instanceFilter: String): List<Instance> { val config = AemConfig.of(project) val all = config.instances.values // Specified by command line should not be filtered val cmd = all.filter { it.environment == Instance.ENVIRONMENT_CMD } if (cmd.isNotEmpty()) { return cmd } // Defined by build script, via properties or defaults are filterable by name return all.filter { instance -> when { config.props.flag(AUTHORS_PROP) -> { Patterns.wildcard(instance.name, "${config.environment}-${InstanceType.AUTHOR}*") } config.props.flag(PUBLISHERS_PROP) -> { Patterns.wildcard(instance.name, "${config.environment}-${InstanceType.PUBLISH}*") } else -> Patterns.wildcards(instance.name, instanceFilter) } } } fun <T : Instance> filter(project: Project, type: KClass<T>): List<T> { return filter(project).filterIsInstance(type.java) } fun locals(project: Project): List<LocalInstance> { return filter(project, LocalInstance::class) } fun handles(project: Project): List<LocalHandle> { return Instance.locals(project).map { LocalHandle(project, it) } } fun remotes(project: Project): List<RemoteInstance> { return filter(project, RemoteInstance::class) } } val httpUrl: String val httpPort: Int get() = InstanceUrl.parse(httpUrl).httpPort @get:JsonIgnore val httpBasicAuthUrl: String get() = InstanceUrl.parse(httpUrl).httpBasicAuthUrl(user, password) val user: String val password: String @get:JsonIgnore val hiddenPassword: String get() = "*".repeat(password.length) val environment: String @get:JsonIgnore val cmd: Boolean get() = environment == ENVIRONMENT_CMD val typeName: String val type: InstanceType get() = InstanceType.byName(typeName) @get:JsonIgnore val credentials: String get() = "$user:$password" val name: String get() = "$environment-$typeName" fun validate() { if (!Formats.URL_VALIDATOR.isValid(httpUrl)) { throw AemException("Malformed URL address detected in $this") } if (user.isBlank()) { throw AemException("User cannot be blank in $this") } if (password.isBlank()) { throw AemException("Password cannot be blank in $this") } if (environment.isBlank()) { throw AemException("Environment cannot be blank in $this") } if (typeName.isBlank()) { throw AemException("Type cannot be blank in $this") } } @get:JsonIgnore var packages: ListResponse? } val Collection<Instance>.names: String get() = joinToString(", ") { it.name } fun Instance.isInitialized(project: Project): Boolean { return this !is LocalInstance || LocalHandle(project, this).initialized } fun Instance.isBeingInitialized(project: Project): Boolean { return this is LocalInstance && !LocalHandle(project, this).initialized }
0
Kotlin
0
0
815df8117edd345b1e477eb3366d59b4379c64d9
8,541
gradle-aem-plugin
Apache License 2.0
releases/glory-v0.1/view/src/main/kotlin/notes/view/NoteList.kt
Oliver-Fenton
721,902,234
false
{"Kotlin": 134039, "Java": 980, "Dockerfile": 164}
package notes.view import javafx.collections.ListChangeListener import javafx.collections.ObservableList import javafx.event.EventHandler import javafx.geometry.Insets import javafx.scene.control.Label import javafx.scene.layout.Background import javafx.scene.layout.HBox import javafx.scene.layout.Priority import javafx.scene.layout.VBox import javafx.scene.paint.Color import notes.model.Model import notes.model.NoteData class NoteList(val noteModel: Model): VBox() { private inner class NotePreview(noteData: NoteData): VBox() { val title = Label( noteData.getTitle() ) val date = Label( noteData.getDateEdited() ).apply { // TODO set the min width here to be the size of the text contained by the label so it is not truncated minWidth = this.layoutBounds.width } val preview = Label( noteData.getPreview() ).apply { HBox.setHgrow(this, Priority.NEVER) } fun refresh(noteData: NoteData) { title.text = noteData.getTitle() date.text = noteData.getDateEdited() preview.text = noteData.getPreview() background = if (noteData.isActive) Background.fill(Color.AQUA) else Background.fill(Color.TRANSPARENT) } init { val dateAndPreview = HBox(date, preview).apply { HBox.setMargin(date, Insets(0.0, 5.0, 0.0, 0.0)) } children.addAll( title, dateAndPreview ) prefHeight = 50.0 onMouseClicked = EventHandler { noteModel.setActiveNote(noteData) println("Note named ${noteData.getTitle()} set as active note with body ${noteData.getBody()}") } noteData.addListener { _, _, newValue -> println("detected a change in note ${newValue?.getTitle()}") if (newValue != null) refresh(newValue) } } } private fun refreshList(noteList: ObservableList<NoteData>) { children.clear() for ( noteData in noteList.reversed()) { children.add( NotePreview(noteData) ) } } init { minWidth = 200.0 maxWidth = 500.0 refreshList( noteModel.notes ) noteModel.notes.addListener(ListChangeListener { println("detected a change in note list") refreshList( noteModel.notes ) }) } }
0
Kotlin
0
0
5d4a2c0cc5526c1c698854076b94aa79ff9bde14
2,422
notes
MIT License
common/src/main/java/io/github/jbarr21/runterval/ui/Screen.kt
jbarr21
110,423,257
false
null
package io.github.jbarr21.runterval.ui sealed class Screen(val route: String) { object Launcher : Screen("launcher") object Workouts : Screen("workouts") object Timer : Screen("timer") companion object { val items = listOf( Launcher, Workouts, Timer ) } }
0
Kotlin
0
5
1e6f39bb154f70ba821e7bcdcab052c5697c1a99
294
runterval
Apache License 2.0
app/src/main/java/com/buglione/ui/components/appBar/TopAppBarExample.kt
StevenBuglione
715,901,501
false
{"Kotlin": 15479}
package com.buglione.ui.components.appBar import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Call import androidx.compose.material.icons.filled.Check import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.icons.filled.Menu import androidx.compose.material3.BottomAppBar import androidx.compose.material3.BottomAppBarDefaults import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MediumTopAppBar import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.TopAppBarScrollBehavior import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.FloatingActionButtonDefaults import androidx.compose.material3.LargeTopAppBar import androidx.compose.material3.rememberTopAppBarState import androidx.compose.runtime.Composable import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview @ExperimentalMaterial3Api @Preview @Composable fun SmallTopAppBarExample() { TopAppBar( title = { { /*TODO*/ } Text("Small Top App Bar") }, colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.primary, ) ) } @ExperimentalMaterial3Api @Composable fun CenterAlignedTopAppBarExample(scrollBehavior: TopAppBarScrollBehavior){ CenterAlignedTopAppBar( title = { Text( "Center Aligned Top App Bar", maxLines = 1, overflow = TextOverflow.Ellipsis ) }, navigationIcon = { IconButton(onClick = { /*TODO*/ }) { Icon( imageVector = Icons.Filled.ArrowBack, contentDescription = "Localized description") } }, actions = { IconButton(onClick = { /*TODO*/ }) { Icon( imageVector = Icons.Filled.Menu, contentDescription = "Localized description") } }, scrollBehavior = scrollBehavior, ) } @Preview @Composable @ExperimentalMaterial3Api fun CenterAlignedTopAppBarExamplePreview(){ val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior(rememberTopAppBarState()) CenterAlignedTopAppBarExample(scrollBehavior) } @ExperimentalMaterial3Api @Composable fun MediumTopBarExample(scrollBehavior: TopAppBarScrollBehavior){ MediumTopAppBar( title = { Text( "Medium Top App Bar", maxLines = 1, overflow = TextOverflow.Ellipsis ) }, navigationIcon = { IconButton(onClick = { /*TODO*/ }) { Icon( imageVector = Icons.Filled.ArrowBack, contentDescription = "Localized description") } }, actions = { IconButton(onClick = { /*TODO*/ }) { Icon( imageVector = Icons.Filled.Menu, contentDescription = "Localized description") } }, scrollBehavior = scrollBehavior ) } @Preview @Composable @ExperimentalMaterial3Api fun MediumTopBarExamplePreview(){ val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior(rememberTopAppBarState()) MediumTopBarExample(scrollBehavior) } @ExperimentalMaterial3Api @Composable fun LargeTopBarExample(scrollBehavior: TopAppBarScrollBehavior){ LargeTopAppBar( title = { Text( "Large Top App Bar", maxLines = 1, overflow = TextOverflow.Ellipsis ) }, navigationIcon = { IconButton(onClick = { /*TODO*/ }) { Icon( imageVector = Icons.Filled.ArrowBack, contentDescription = "Localized description") } }, actions = { IconButton(onClick = { /*TODO*/ }) { Icon( imageVector = Icons.Filled.Menu, contentDescription = "Localized description" ) } }, scrollBehavior = scrollBehavior ) } @Preview @Composable @ExperimentalMaterial3Api fun LargeTopBarExamplePreview(){ val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior(rememberTopAppBarState()) LargeTopBarExample(scrollBehavior) } @ExperimentalMaterial3Api @Preview @Composable fun BottomAppBarExample(){ BottomAppBar( actions = { IconButton(onClick = { /*TODO*/ }) { Icon(Icons.Filled.Check, contentDescription = "Localized description") } IconButton(onClick = { /*TODO*/ }) { Icon(Icons.Filled.Edit, contentDescription = "Localized description") } IconButton(onClick = { /*TODO*/ }) { Icon(Icons.Filled.Call, contentDescription = "Localized description") } IconButton(onClick = { /*TODO*/ }) { Icon(Icons.Filled.Favorite, contentDescription = "Localized description") } }, floatingActionButton = { FloatingActionButton( onClick = {}, containerColor = BottomAppBarDefaults.bottomAppBarFabColor, elevation = FloatingActionButtonDefaults.bottomAppBarFabElevation() ){ Icon(Icons.Filled.Add, contentDescription = "Localized description") } } ) }
0
Kotlin
0
0
5fa22b52de7b4452c7a8ff5952cb39b2258c69ee
6,156
Jetpack-Compose-Components
MIT License
conductor-extra/src/main/java/com/esafirm/conductorextra/components/configs/ControllerConfigManager.kt
esafirm
93,383,816
false
{"Gradle": 9, "Shell": 2, "Java Properties": 2, "YAML": 1, "Text": 1, "Ignore List": 8, "Batchfile": 1, "Markdown": 1, "Proguard": 7, "XML": 24, "Kotlin": 48, "Java": 7}
package com.esafirm.conductorextra.components.configs import com.bluelinelabs.conductor.Controller typealias ConfigResolver<T> = (Class<T>) -> ControllerConfig object ControllerConfigManager { private val DEFAULT_CONFIG = ControllerConfig(true) var configResolver: ConfigResolver<Controller> = { _ -> DEFAULT_CONFIG } }
1
null
1
1
304262c284ab117808afd7c68e45360d7c606b4f
333
conductor-extra
MIT License
multi-functions/src/test/kotlin/io/multifunctions/models/QuadSpec.kt
sandeep1401
145,104,288
true
{"Kotlin": 53565}
package io.multifunctions.models import io.kotlintest.matchers.shouldBe import io.kotlintest.specs.WordSpec class QuadSpec : WordSpec() { init { "Quad" should { "be initialized with Strings" { Quad("one", "two", "three", "four").let { quad -> quad.first shouldBe "one" quad.second shouldBe "two" quad.third shouldBe "three" quad.fourth shouldBe "four" Quad(quad.first, quad.second, quad.third, quad.fourth) } shouldBe Quad("one", "two", "three", "four") } "handle null values" { Quad<String?, String?, String?, String?>(null, null, null, null).let { quad -> quad.first shouldBe null quad.second shouldBe null quad.third shouldBe null quad.fourth shouldBe null Quad(quad.first, quad.second, quad.third, quad.fourth) } shouldBe Quad(null, null, null, null) } "handle toString" { Quad("one", "two", "three", "four").toString() shouldBe "Quad(first=one, second=two, third=three, fourth=four)" } "handle copy()" { val quad = Quad("one", "two", "three", "four") quad.copy() shouldBe Quad("one", "two", "three", "four") } "handle toList" { Quad("one", "two", "three", "four").toList() shouldBe listOf("one", "two", "three", "four") } } } }
0
Kotlin
0
0
bdb4af98aea657452159436e1bf5db79cbedd269
1,629
MultiFunctions
Apache License 2.0
src/main/kotlin/bik/thermostat/exceptions/ThermostatException.kt
inigodm
456,147,379
false
{"Kotlin": 21790, "Java": 510}
package bik.thermostat.exceptions import java.lang.Exception class ThermostatException : Exception { constructor(message: String?, e: Exception?) : super(message, e) {} constructor(message: String?) : super(message) {} } class ThermostatError : RuntimeException { constructor(message: String?, e: Exception?) : super(message, e) {} constructor(message: String?) : super(message) {} }
0
Kotlin
0
1
9ce84e6cba8292791d9823a929b0158bec74bf2c
403
amaia-thermostat
Apache License 2.0
app/src/main/java/de/schalter/losungen/components/verseCard/VerseCardView.kt
schalterDev
162,886,394
false
{"Kotlin": 369098, "Java": 1100, "Shell": 645}
package de.schalter.losungen.components.verseCard import android.content.Context import android.text.Editable import android.text.TextWatcher import android.util.AttributeSet import android.view.View import android.widget.FrameLayout import android.widget.ImageView import android.widget.TextView import android.widget.Toast import de.schalter.losungen.R import de.schalter.losungen.components.dialogs.openVerseExternal.OpenExternalDialog import de.schalter.losungen.dataAccess.VersesDatabase import de.schalter.losungen.firebase.FirebaseUtil import de.schalter.losungen.utils.openExternal.BibleVerse import de.schalter.losungen.utils.openExternal.BibleVerseParseException import kotlinx.android.synthetic.main.verse_card.view.* class VerseCardView : FrameLayout { private var titleView: TextView private var verseTextView: TextView private var verseInBibleView: TextView private var titleView2: TextView private var verseTextView2: TextView private var verseInBibleView2: TextView private var imageFavourite: ImageView private var notesView: TextView private var verseCardViewModel = VerseCardViewModel(VersesDatabase.provideVerseDatabase(context)) constructor(context: Context) : super(context) constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) constructor(context: Context, attributeSet: AttributeSet, defStyle: Int) : super(context, attributeSet, defStyle) init { val view = View.inflate(context, R.layout.verse_card, null) addView(view) titleView = view.findViewById(R.id.verseTitle) verseTextView = view.findViewById(R.id.verseText) verseInBibleView = view.findViewById(R.id.verseInBible) titleView2 = view.findViewById(R.id.verseTitle2) verseTextView2 = view.findViewById(R.id.verseText2) verseInBibleView2 = view.findViewById(R.id.verseInBible2) imageFavourite = view.findViewById(R.id.verseCardFavoriteImage) notesView = view.findViewById<TextView>(R.id.verseNotes).also { it.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable) { verseCardViewModel.updateNotes(s.toString()) } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} }) } hideSecondVerse() this.setOnClickListener { try { // only one verse is shown if (verseInBibleView2.visibility == View.GONE) { val bibleVerse = BibleVerse(verseInBible.text as String) OpenExternalDialog(context).open(bibleVerse) } else { val items = listOf( context.getString(R.string.old_testament_card_title), context.getString(R.string.new_testament_card_title)) val builder = androidx.appcompat.app.AlertDialog.Builder(context) builder.setTitle(R.string.open_verse_external) builder.setCancelable(true) builder.setItems(items.toTypedArray()) { _, which -> val bibleVerse: BibleVerse = if (which == 0) { BibleVerse(verseInBible.text as String) } else { BibleVerse(verseInBible2.text as String) } OpenExternalDialog(context).open(bibleVerse) } builder.show() } } catch (e: BibleVerseParseException) { Toast.makeText(context, R.string.could_not_parse_verse, Toast.LENGTH_LONG).show() } } } private fun setTitle(title: String) { titleView.text = title } private fun setVerse(verse: String) { verseTextView.text = verse } private fun setVerseInBible(verseInBible: String) { verseInBibleView.text = verseInBible } private fun setTitle2(title: String) { titleView2.text = title titleView2.visibility = View.VISIBLE } private fun setVerse2(verse: String) { verseTextView2.text = verse verseTextView2.visibility = View.VISIBLE } private fun setVerseInBible2(verseInBible: String) { verseInBibleView2.text = verseInBible verseInBibleView2.visibility = View.VISIBLE } private fun setIsFavourite(isFavourite: Boolean) { val imageResource = if (isFavourite) { R.drawable.ic_action_favorite } else { R.drawable.ic_action_favorite_border } imageFavourite.setImageResource(imageResource) } fun setData(verseCardData: VerseCardData) { verseCardViewModel.setData(verseCardData) setVisibilityFavouriteIcon(verseCardData.showFavouriteIcon) imageFavourite.setOnClickListener { verseCardViewModel.getData()?.let { data -> FirebaseUtil.trackFavouriteVerse( context, weekly = data.type == VerseCardData.Type.WEEKLY, monthly = data.type == VerseCardData.Type.MONTHLY, value = !data.isFavourite) } verseCardViewModel.toggleIsFavourite() } setTitle(verseCardData.title) setVerse(verseCardData.text) setVerseInBible(verseCardData.verse) setIsFavourite(verseCardData.isFavourite) verseCardData.title2?.let { setTitle2(it) } ?: run { titleView2.visibility = View.GONE } verseCardData.text2?.let { setVerse2(it) } ?: run { verseTextView2.visibility = View.GONE } verseCardData.verse2?.let { setVerseInBible2(it) } ?: run { verseInBibleView2.visibility = View.GONE } verseCardData.notes?.let { notesView.text = it } } private fun setVisibilityFavouriteIcon(visible: Boolean) { if (visible) { imageFavourite.visibility = View.VISIBLE } else { imageFavourite.visibility = View.GONE } } fun getData(): VerseCardData { return verseCardViewModel.getData()!! } private fun hideSecondVerse() { titleView2.visibility = View.GONE verseTextView2.visibility = View.GONE verseInBibleView2.visibility = View.GONE } fun showNotes(showNotes: Boolean) { if (showNotes) { notesView.visibility = View.VISIBLE } else { notesView.visibility = View.GONE } } fun saveNotes() { verseCardViewModel.saveNotes() } }
7
Kotlin
1
2
1bc635ef9e5f4612cde4b38126ba1f74b8315259
6,906
Losungen-Android-2
MIT License
app/src/main/java/io/zoemeow/dutschedule/ui/view/account/TrainingResult.kt
ZoeMeow1027
504,228,485
false
{"Kotlin": 505302}
package io.zoemeow.dutschedule.ui.view.account import android.content.Context import android.content.Intent import androidx.activity.ComponentActivity import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.filled.Refresh import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.LargeTopAppBar import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.unit.dp import io.zoemeow.dutschedule.activity.AccountActivity import io.zoemeow.dutschedule.model.ProcessState import io.zoemeow.dutschedule.ui.component.base.ButtonBase import io.zoemeow.dutschedule.ui.component.base.OutlinedTextBox import io.zoemeow.dutschedule.ui.component.base.SimpleCardItem import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) @Composable fun AccountActivity.TrainingResult( context: Context, snackBarHostState: SnackbarHostState, containerColor: Color, contentColor: Color ) { val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior() Scaffold( modifier = Modifier .fillMaxSize() .nestedScroll(scrollBehavior.nestedScrollConnection), snackbarHost = { SnackbarHost(hostState = snackBarHostState) }, containerColor = containerColor, contentColor = contentColor, topBar = { LargeTopAppBar( title = { Text("Account Training Result") }, colors = TopAppBarDefaults.largeTopAppBarColors(containerColor = Color.Transparent, scrolledContainerColor = Color.Transparent), navigationIcon = { IconButton( onClick = { setResult(ComponentActivity.RESULT_OK) finish() }, content = { Icon( Icons.AutoMirrored.Filled.ArrowBack, "", modifier = Modifier.size(25.dp) ) } ) }, scrollBehavior = scrollBehavior ) }, floatingActionButton = { if (getMainViewModel().accountTrainingStatus.processState.value != ProcessState.Running) { FloatingActionButton( onClick = { CoroutineScope(Dispatchers.IO).launch { getMainViewModel().accountLogin( after = { if (it) { getMainViewModel().accountTrainingStatus.refreshData(force = true) } } ) } }, content = { Icon(Icons.Default.Refresh, "Refresh") } ) } }, content = { padding -> Column( modifier = Modifier .fillMaxSize() .padding(padding), content = { if (getMainViewModel().accountTrainingStatus.processState.value == ProcessState.Running) { LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) } Column( modifier = Modifier .fillMaxSize() .verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.Start, content = { getMainViewModel().accountTrainingStatus.data.value?.let { fun graduateStatus(): String { val owned = ArrayList<String>() val missing = ArrayList<String>() if (it.graduateStatus?.hasSigGDTC == true) { owned.add("GDTC certificate") } else { missing.add("GDTC certificate") } if (it.graduateStatus?.hasSigGDQP == true) { owned.add("GDQP certificate") } else { missing.add("GDQP certificate") } if (it.graduateStatus?.hasSigEnglish == true) { owned.add("English certificate") } else { missing.add("English certificate") } if (it.graduateStatus?.hasSigIT == true) { owned.add("IT certificate") } else { missing.add("IT certificate") } val hasQualifiedGraduate = it.graduateStatus?.hasQualifiedGraduate == true val result = "- Owned certificate(s): ${owned.joinToString(", ")}\n- Missing certificate(s): ${missing.joinToString(", ")}\n- Has qualified graduate: ${if (hasQualifiedGraduate) "Yes" else "No (check information below)"}" owned.clear() missing.clear() return result } SimpleCardItem( title = "Your training result", isTitleCentered = true, padding = PaddingValues(start = 10.dp, end = 10.dp, bottom = 7.dp), opacity = getControlBackgroundAlpha(), content = { Column( modifier = Modifier .fillMaxWidth() .padding(horizontal = 10.dp) .padding(bottom = 10.dp), content = { OutlinedTextBox( title = "Score (point / 4)", value = "${it.trainingSummary?.avgTrainingScore4 ?: "(unknown)"}", modifier = Modifier .fillMaxWidth() .padding(bottom = 5.dp) ) OutlinedTextBox( title = "School year updated", value = it.trainingSummary?.schoolYearCurrent ?: "(unknown)", modifier = Modifier .fillMaxWidth() .padding(bottom = 5.dp) ) ButtonBase( modifier = Modifier .fillMaxWidth() .padding(vertical = 5.dp), horizontalArrangement = Arrangement.Center, content = { Text("View your training details") }, clicked = { val intent = Intent(context, AccountActivity::class.java) intent.action = "acc_training_result_subjectresult" context.startActivity(intent) } ) } ) }, clicked = {} ) Spacer(modifier = Modifier.size(5.dp)) SimpleCardItem( title = "Graduate status", isTitleCentered = true, padding = PaddingValues(horizontal = 10.dp), opacity = getControlBackgroundAlpha(), content = { Column( modifier = Modifier .fillMaxWidth() .padding(horizontal = 10.dp) .padding(bottom = 10.dp), content = { OutlinedTextBox( title = "Certificate & graduate result", value = graduateStatus(), modifier = Modifier .fillMaxWidth() .padding(bottom = 5.dp) ) OutlinedTextBox( title = "Khen thuong", value = it.graduateStatus?.info1 ?: "(unknown)", modifier = Modifier .fillMaxWidth() .padding(bottom = 5.dp) ) OutlinedTextBox( title = "Ky luat", value = it.graduateStatus?.info2 ?: "(unknown)", modifier = Modifier .fillMaxWidth() .padding(bottom = 5.dp) ) OutlinedTextBox( title = "Information about graduation thesis approval", value = it.graduateStatus?.info3 ?: "(unknown)", modifier = Modifier .fillMaxWidth() .padding(bottom = 5.dp) ) OutlinedTextBox( title = "Information about graduate process approval", value = it.graduateStatus?.approveGraduateProcessInfo ?: "(unknown)", modifier = Modifier .fillMaxWidth() .padding(bottom = 5.dp) ) } ) }, clicked = {} ) Spacer(modifier = Modifier.size(5.dp)) } } ) } ) } ) val hasRun = remember { mutableStateOf(false) } run { if (!hasRun.value) { CoroutineScope(Dispatchers.IO).launch { getMainViewModel().accountLogin( after = { if (it) { getMainViewModel().accountTrainingStatus.refreshData() } } ) } hasRun.value = true } } }
1
Kotlin
0
1
4ef00cd06ecf3396a2eebba9b320516dbcf81587
14,668
DutSchedule
MIT License
domain/src/main/java/com/bankwithmit/domain/repositories/CardRepository.kt
IkemNwodo
336,539,958
false
null
package com.bankwithmit.domain.repositories import com.bankwithmit.domain.models.CardInfo import com.bankwithmit.domain.utils.Result interface CardRepository { suspend fun getCardInfo(cardNumber: Int): Result<CardInfo> suspend fun getSavedCards(): Result<List<CardInfo>> }
0
Kotlin
0
0
f9c8af46ba295253f5c800f0a54b0f8e5ddcdee8
282
CardInfoFinder
The Unlicense
urbanairship-preference-center/src/test/java/com/urbanairship/preferencecenter/ConditionStateMonitorTest.kt
jameshnsears
592,661,904
true
{"INI": 13, "Markdown": 20, "Gradle": 20, "Shell": 4, "Batchfile": 1, "Text": 1, "Ignore List": 7, "Proguard": 16, "XML": 389, "Java": 960, "Kotlin": 188, "JSON": 15, "CODEOWNERS": 1, "YAML": 33, "Gradle Kotlin DSL": 2, "Python": 2, "SVG": 2, "CSS": 2, "C#": 2, "Java Properties": 2}
package com.urbanairship.preferencecenter import androidx.test.ext.junit.runners.AndroidJUnit4 import app.cash.turbine.test import com.google.common.truth.Truth.assertThat import com.urbanairship.channel.AirshipChannel import com.urbanairship.channel.AirshipChannelListener import com.urbanairship.preferencecenter.data.Condition import com.urbanairship.push.PushManager import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestCoroutineDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.runBlockingTest import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @OptIn(ExperimentalCoroutinesApi::class) @RunWith(AndroidJUnit4::class) class ConditionStateMonitorTest { private val testDispatcher = TestCoroutineDispatcher() private val mockChannel = mock<AirshipChannel> {} private val mockPushManager = mock<PushManager> {} private lateinit var conditionStateMonitor: ConditionStateMonitor @Before fun setUp() { Dispatchers.setMain(testDispatcher) conditionStateMonitor = ConditionStateMonitor(mockChannel, mockPushManager) } @After fun tearDown() { testDispatcher.cleanupTestCoroutines() Dispatchers.resetMain() } @Test fun testInitialState() = testDispatcher.runBlockingTest { whenever(mockPushManager.isOptIn).thenReturn(true) conditionStateMonitor.states.test { assertThat(awaitItem()).isEqualTo(Condition.State(isOptedIn = true)) } } @Test fun testChannelCreatedStateChange() = testDispatcher.runBlockingTest { whenever(mockPushManager.isOptIn).thenReturn(false) conditionStateMonitor.states.test { assertThat(awaitItem()).isEqualTo(Condition.State(isOptedIn = false)) whenever(mockPushManager.isOptIn).thenReturn(true) withChannelListener { onChannelCreated("created-channel-id") } assertThat(awaitItem()).isEqualTo(Condition.State(isOptedIn = true)) } } @Test fun testChannelUpdatedStateChange() = testDispatcher.runBlockingTest { whenever(mockPushManager.isOptIn).thenReturn(false) conditionStateMonitor.states.test { assertThat(awaitItem()).isEqualTo(Condition.State(isOptedIn = false)) whenever(mockPushManager.isOptIn).thenReturn(true) withChannelListener { onChannelUpdated("updated-channel-id") } assertThat(awaitItem()).isEqualTo(Condition.State(isOptedIn = true)) } } @Test fun testCurrentState() { whenever(mockPushManager.isOptIn).thenReturn(false) assertThat(conditionStateMonitor.currentState) .isEqualTo(Condition.State(isOptedIn = false)) whenever(mockPushManager.isOptIn).thenReturn(true) assertThat(conditionStateMonitor.currentState) .isEqualTo(Condition.State(isOptedIn = true)) } private fun withChannelListener(block: AirshipChannelListener.() -> Unit) { argumentCaptor<AirshipChannelListener>().apply { verify(mockChannel).addChannelListener(capture()) block.invoke(firstValue) } } }
0
null
0
0
70ec0a5cba923c7d16d3186a8b794267bfb1b14a
3,515
android-library
Apache License 2.0
urbanairship-preference-center/src/test/java/com/urbanairship/preferencecenter/ConditionStateMonitorTest.kt
jameshnsears
592,661,904
true
{"INI": 13, "Markdown": 20, "Gradle": 20, "Shell": 4, "Batchfile": 1, "Text": 1, "Ignore List": 7, "Proguard": 16, "XML": 389, "Java": 960, "Kotlin": 188, "JSON": 15, "CODEOWNERS": 1, "YAML": 33, "Gradle Kotlin DSL": 2, "Python": 2, "SVG": 2, "CSS": 2, "C#": 2, "Java Properties": 2}
package com.urbanairship.preferencecenter import androidx.test.ext.junit.runners.AndroidJUnit4 import app.cash.turbine.test import com.google.common.truth.Truth.assertThat import com.urbanairship.channel.AirshipChannel import com.urbanairship.channel.AirshipChannelListener import com.urbanairship.preferencecenter.data.Condition import com.urbanairship.push.PushManager import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestCoroutineDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.runBlockingTest import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @OptIn(ExperimentalCoroutinesApi::class) @RunWith(AndroidJUnit4::class) class ConditionStateMonitorTest { private val testDispatcher = TestCoroutineDispatcher() private val mockChannel = mock<AirshipChannel> {} private val mockPushManager = mock<PushManager> {} private lateinit var conditionStateMonitor: ConditionStateMonitor @Before fun setUp() { Dispatchers.setMain(testDispatcher) conditionStateMonitor = ConditionStateMonitor(mockChannel, mockPushManager) } @After fun tearDown() { testDispatcher.cleanupTestCoroutines() Dispatchers.resetMain() } @Test fun testInitialState() = testDispatcher.runBlockingTest { whenever(mockPushManager.isOptIn).thenReturn(true) conditionStateMonitor.states.test { assertThat(awaitItem()).isEqualTo(Condition.State(isOptedIn = true)) } } @Test fun testChannelCreatedStateChange() = testDispatcher.runBlockingTest { whenever(mockPushManager.isOptIn).thenReturn(false) conditionStateMonitor.states.test { assertThat(awaitItem()).isEqualTo(Condition.State(isOptedIn = false)) whenever(mockPushManager.isOptIn).thenReturn(true) withChannelListener { onChannelCreated("created-channel-id") } assertThat(awaitItem()).isEqualTo(Condition.State(isOptedIn = true)) } } @Test fun testChannelUpdatedStateChange() = testDispatcher.runBlockingTest { whenever(mockPushManager.isOptIn).thenReturn(false) conditionStateMonitor.states.test { assertThat(awaitItem()).isEqualTo(Condition.State(isOptedIn = false)) whenever(mockPushManager.isOptIn).thenReturn(true) withChannelListener { onChannelUpdated("updated-channel-id") } assertThat(awaitItem()).isEqualTo(Condition.State(isOptedIn = true)) } } @Test fun testCurrentState() { whenever(mockPushManager.isOptIn).thenReturn(false) assertThat(conditionStateMonitor.currentState) .isEqualTo(Condition.State(isOptedIn = false)) whenever(mockPushManager.isOptIn).thenReturn(true) assertThat(conditionStateMonitor.currentState) .isEqualTo(Condition.State(isOptedIn = true)) } private fun withChannelListener(block: AirshipChannelListener.() -> Unit) { argumentCaptor<AirshipChannelListener>().apply { verify(mockChannel).addChannelListener(capture()) block.invoke(firstValue) } } }
0
null
0
0
70ec0a5cba923c7d16d3186a8b794267bfb1b14a
3,515
android-library
Apache License 2.0
core/src/main/java/com/example/core/mapper/route/RouteMapper.kt
rakhmukova
716,540,491
false
{"Kotlin": 364537}
package com.example.core.mapper.route import com.example.core.logic.route.Route import com.example.core.models.route.RouteDto import dagger.Reusable import javax.inject.Inject @Reusable class RouteMapper @Inject constructor( private val routeSearchMapper: RouteSearchMapper, private val segmentMapper: RouteSegmentMapper ) { fun fromDto(routeDto: RouteDto): Route { return Route( search = routeDto.search?.let { routeSearchMapper.fromDto(it) }, segments = routeDto.segments?.map { segmentMapper.fromDto(it) } ) } fun toDto(route: Route): RouteDto { return RouteDto( search = route.search?.let { routeSearchMapper.toDto(it) }, segments = route.segments?.map { segmentMapper.toDto(it) } ) } }
0
Kotlin
0
0
7707ae1fac0dcbf98b79596cda5f5308f5e908ab
798
travel-app
Apache License 2.0
app/src/main/java/com/test/pocketaces/di/FeatureScope.kt
stAyushJain
342,903,412
false
null
package com.test.pocketaces.di import javax.inject.Scope @Scope @Retention(AnnotationRetention.RUNTIME) annotation class FeatureScope
0
Kotlin
0
0
010a95a97cd75d665d41144abb6780d32075a7a4
135
MovieApp
Apache License 2.0
client/slack-spring-api-client/src/main/kotlin/io/hndrs/slack/api/spring/group/users/SpringUsersGetPresenceMethod.kt
hndrs
168,710,332
false
null
package io.hndrs.slack.api.spring.group.users import io.hndrs.slack.api.contract.jackson.group.users.ErrorGetPresenceResponse import io.hndrs.slack.api.contract.jackson.group.users.GetPresenceResponse import io.hndrs.slack.api.contract.jackson.group.users.SuccessfulGetPresenceResponse import io.hndrs.slack.api.group.ApiCallResult import io.hndrs.slack.api.group.users.UsersGetPresenceMethod import io.hndrs.slack.api.group.users.UsersMethodGroup import io.hndrs.slack.api.spring.group.RestTemplateFactory import io.hndrs.slack.api.spring.group.SlackRequestBuilder import org.springframework.web.client.RestTemplate /** * Spring based implementation of [UsersMethodGroup.getPresence] */ @Suppress("UNCHECKED_CAST") class SpringUsersGetPresenceMethod( private val authToken: String, private val restTemplate: RestTemplate = io.hndrs.slack.api.spring.group.RestTemplateFactory.slackTemplate() ) : io.hndrs.slack.api.group.users.UsersGetPresenceMethod() { override fun request(): io.hndrs.slack.api.group.ApiCallResult<SuccessfulGetPresenceResponse, ErrorGetPresenceResponse> { val response = SlackRequestBuilder<GetPresenceResponse>(authToken, restTemplate) .toMethod("users.getPresence") .returnAsType(GetPresenceResponse::class.java) .with(this.params) .postUrlEncoded(mapOf()) return when (response.body!!) { is SuccessfulGetPresenceResponse -> { val responseEntity = response.body as SuccessfulGetPresenceResponse this.onSuccess?.invoke(responseEntity) io.hndrs.slack.api.group.ApiCallResult(success = responseEntity) } is ErrorGetPresenceResponse -> { val responseEntity = response.body as ErrorGetPresenceResponse this.onFailure?.invoke(responseEntity) io.hndrs.slack.api.group.ApiCallResult(failure = responseEntity) } } } }
57
Kotlin
13
16
89c5a6ddd0cbac522dd9cd4324901bf2907369a8
1,974
slack-spring-boot-starter
MIT License
src/com/eventhorizonwebdesign/kgrabber/util/Data.kt
trenton-telge
97,350,278
false
{"Kotlin": 18138}
package com.eventhorizonwebdesign.kgrabber.util import com.eventhorizonwebdesign.kgrabber.util.web.PageParserThread import java.io.* import java.util.* import javax.swing.DefaultListModel import javax.swing.JFrame import javax.swing.JList var accessedPages = Vector<String>() var mainFrame: JFrame? = null var rootsPanel = JList<String>(DefaultListModel<String>()) val dataHome = System.getProperty("user.home") + System.getProperty("file.separator") + ".KGrabber" var saveHome = System.getProperty("user.home") + System.getProperty("file.separator") + "Downloads" var users = Vector<String>() var subreddits = Vector<String>() fun writeDBFile(){ /* * Type 0 = USER * Type 1 = SUBREDDIT * */ val usersFinalized = Vector<String>() users .map { it } .forEach { when { it.substring(0, 3) == "/u/" -> usersFinalized.addElement(it.substring(3, it.length)) it.substring(0, 2) == "u/" -> usersFinalized.addElement(it.substring(2, it.length)) it.substring(it.length - 1, it.length) == "/" -> usersFinalized.addElement(it.substring(0, it.length - 1)) else -> usersFinalized.addElement(it) } } writeFinalizedUsers(usersFinalized) val subsFinalized = Vector<String>() subreddits .map { it } .forEach { when { it.substring(0, 3) == "/r/" -> subsFinalized.addElement(it.substring(3, it.length)) it.substring(0, 2) == "r/" -> subsFinalized.addElement(it.substring(2, it.length)) it.substring(it.length - 1, it.length) == "/" -> subsFinalized.addElement(it.substring(0, it.length - 1)) else -> subsFinalized.addElement(it) } } writeFinalizedSubreddits(subsFinalized) } fun parseDB(){ users = Vector() subreddits = Vector() try { val folder = File(dataHome) if(folder.exists()){ if(folder.isDirectory){ val usersFile = File(dataHome + System.getProperty("file.separator") + "users.bin") if (usersFile.exists()){ if (usersFile.isFile){ val usersReader = BufferedReader(FileReader(usersFile)) var line: String? line = usersReader.readLine() while (line != null) { users.addElement(line) line = usersReader.readLine() } usersReader.close() } } val subsFile = File(dataHome + System.getProperty("file.separator") + "subs.bin") if (subsFile.exists()){ if (subsFile.isFile){ val subsReader = BufferedReader(FileReader(subsFile)) var line: String? line = subsReader.readLine() while (line != null) { subreddits.addElement(line) line = subsReader.readLine() } subsReader.close() } } } } } catch (e: Exception){ println(e.stackTrace) } } fun writeFinalizedUsers(v: Vector<String>){ try { val folder = File(dataHome) if(folder.exists()){ if(folder.isDirectory){ val file = File(dataHome + System.getProperty("file.separator") + "users.bin") if (file.exists()){ if (file.isFile){ val b = BufferedWriter(FileWriter(file)) for (s:String in v){ b.write(s) b.newLine() } b.close() } else { file.delete() file.createNewFile() writeFinalizedUsers(v) } } else { file.createNewFile() writeFinalizedUsers(v) } } else { folder.delete() folder.mkdirs() writeFinalizedUsers(v) } } else { folder.mkdirs() writeFinalizedUsers(v) } } catch (e: Exception){ println(e.stackTrace) } } fun writeFinalizedSubreddits(v: Vector<String>){ try { val folder = File(dataHome) if(folder.exists()){ if(folder.isDirectory){ val file = File(dataHome + System.getProperty("file.separator") + "subs.bin") if (file.exists()){ if (file.isFile){ val b = BufferedWriter(FileWriter(file)) for (s:String in v){ b.write(s) b.newLine() } b.close() } else { file.delete() file.createNewFile() writeFinalizedSubreddits(v) } } else { file.createNewFile() writeFinalizedSubreddits(v) } } else { folder.delete() folder.mkdirs() writeFinalizedSubreddits(v) } } else { folder.mkdirs() writeFinalizedSubreddits(v) } } catch (e: Exception){ println(e.stackTrace) } } fun fetchAll(){ for (u: String in users){ fetchUser("/u/" + u) } for (r: String in subreddits){ fetchSubreddit("/r/" + r) } } fun fetchUser(u: String){ val url = "http://reddit.com$u/submitted/" print("\nFetching $url...") url.replace("/u/", "/user/", true) val userFolder = saveHome + System.getProperty("file.separator") + u val userFolderFile = File(userFolder) userFolderFile.mkdirs() PageParserThread(url, userFolder).start() } fun fetchSubreddit(r: String){ //TODO fetch to sub folder val url = "http://reddit.com$r/new/" print("\nFetching$url...") val subredditFolder = saveHome + System.getProperty("file.separator") + r val subredditFolderFile = File(subredditFolder) subredditFolderFile.mkdirs() PageParserThread(url, subredditFolder).start() }
0
Kotlin
0
0
4ee8222b9a1baf19359e0144075ad8d9e9e227e3
6,626
KGrabber
The Unlicense
Android/app/src/main/java/com/plantry/presentation/home/viewholder/notification/HomeNotificationViewHolder.kt
GDSC-SWU
736,526,220
false
{"Kotlin": 312709, "Java": 284329, "Python": 1946, "Dockerfile": 370}
package com.plantry.presentation.home.viewholder.notification import android.os.Build import androidx.annotation.RequiresApi import androidx.recyclerview.widget.RecyclerView import com.plantry.R import com.plantry.data.dto.response.notification.ResponseNortificationAllListDto import com.plantry.data.dto.response.profile.ResponseProfileMissionListDto import com.plantry.databinding.ItemNotificationBinding import com.plantry.databinding.ItemProfileMissionBinding import java.time.Duration import java.time.LocalDate import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.time.temporal.ChronoUnit class HomeNotificationViewHolder(private val binding: ItemNotificationBinding) : RecyclerView.ViewHolder(binding.root) { private val _itemBinding: ItemNotificationBinding = binding val itemBinding: ItemNotificationBinding = _itemBinding @RequiresApi(Build.VERSION_CODES.O) fun bind(noti: ResponseNortificationAllListDto.Result) { binding.tvNotificationBody.text = noti.body binding.tvNotificationTime.text = noti.notifiedAt?.let { calculateTimeDifference(it) } binding.tvNotificationTitle.text = noti.title binding.clNotificationItemLayout.isSelected = noti.isChecked ?: true } @RequiresApi(Build.VERSION_CODES.O) fun calculateTimeDifference(dateTimeString: String): String { val formatterIso = DateTimeFormatter.ISO_LOCAL_DATE_TIME val targetDateTime = LocalDateTime.parse(dateTimeString, formatterIso) val currentDate = LocalDate.now() val targetDate = formatDateString(targetDateTime.toString().substringBefore("T")) val formatterDate = DateTimeFormatter.ofPattern("yyyy.MM.dd") val daysDifference = currentDate.toEpochDay() - LocalDate.parse(targetDate, formatterDate).toEpochDay() return when { daysDifference == 0L -> "Just now" daysDifference in 1..7L -> "$daysDifference days ago" else -> targetDate } } fun formatDateString(inputDateString: String): String { val inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd") val outputFormatter = DateTimeFormatter.ofPattern("yyyy.MM.dd") val date = LocalDate.parse(inputDateString, inputFormatter) return outputFormatter.format(date) } }
0
Kotlin
0
3
7a8074ba1a76027fe09077dd490c8c7eb8a87c9f
2,341
2024-Plantry-SolutionChallenge
MIT License
app/src/main/java/org/p2p/wallet/common/ui/bottomsheet/BaseRecyclerDoneBottomSheet.kt
p2p-org
306,035,988
false
{"Kotlin": 4545395, "HTML": 3064848, "Java": 296567, "Groovy": 1601, "Shell": 1252}
package org.p2p.wallet.common.ui.bottomsheet import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import org.p2p.wallet.databinding.DialogBaseRecyclerPartBinding /** * Base BottomSheet extended from [BaseDoneBottomSheet] used to implement [RecyclerView] as an innerView **/ abstract class BaseRecyclerDoneBottomSheet : BaseDoneBottomSheet() { lateinit var recyclerBinding: DialogBaseRecyclerPartBinding override fun onCreateInnerView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { recyclerBinding = DialogBaseRecyclerPartBinding.inflate(inflater, container, false) return recyclerBinding.root } }
8
Kotlin
18
34
d091e18b7d88c936b7c6c627f4fec96bcf4a0356
732
key-app-android
MIT License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/Template.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Bold.Template: ImageVector get() { if (_template != null) { return _template!! } _template = Builder(name = "Template", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(17.0f, 12.5f) verticalLineToRelative(5.0f) curveToRelative(0.0f, 0.83f, -0.67f, 1.5f, -1.5f, 1.5f) horizontalLineToRelative(-7.0f) curveToRelative(-0.83f, 0.0f, -1.5f, -0.67f, -1.5f, -1.5f) verticalLineToRelative(-5.0f) curveToRelative(0.0f, -0.83f, 0.67f, -1.5f, 1.5f, -1.5f) horizontalLineToRelative(7.0f) curveToRelative(0.83f, 0.0f, 1.5f, 0.67f, 1.5f, 1.5f) close() moveTo(8.5f, 9.0f) horizontalLineToRelative(1.0f) curveToRelative(0.83f, 0.0f, 1.5f, -0.67f, 1.5f, -1.5f) reflectiveCurveToRelative(-0.67f, -1.5f, -1.5f, -1.5f) horizontalLineToRelative(-1.0f) curveToRelative(-0.83f, 0.0f, -1.5f, 0.67f, -1.5f, 1.5f) reflectiveCurveToRelative(0.67f, 1.5f, 1.5f, 1.5f) close() moveTo(22.0f, 8.16f) verticalLineToRelative(10.34f) curveToRelative(0.0f, 3.03f, -2.47f, 5.5f, -5.5f, 5.5f) lineTo(7.5f, 24.0f) curveToRelative(-3.03f, 0.0f, -5.5f, -2.47f, -5.5f, -5.5f) lineTo(2.0f, 5.5f) curveTo(2.0f, 2.47f, 4.47f, 0.0f, 7.5f, 0.0f) horizontalLineToRelative(6.34f) curveToRelative(1.47f, 0.0f, 2.85f, 0.57f, 3.89f, 1.61f) lineToRelative(2.66f, 2.66f) curveToRelative(1.04f, 1.04f, 1.61f, 2.42f, 1.61f, 3.89f) close() moveTo(19.0f, 18.5f) lineTo(19.0f, 9.0f) horizontalLineToRelative(-4.0f) curveToRelative(-1.1f, 0.0f, -2.0f, -0.9f, -2.0f, -2.0f) lineTo(13.0f, 3.0f) lineTo(7.5f, 3.0f) curveToRelative(-1.38f, 0.0f, -2.5f, 1.12f, -2.5f, 2.5f) verticalLineToRelative(13.0f) curveToRelative(0.0f, 1.38f, 1.12f, 2.5f, 2.5f, 2.5f) horizontalLineToRelative(9.0f) curveToRelative(1.38f, 0.0f, 2.5f, -1.12f, 2.5f, -2.5f) close() } } .build() return _template!! } private var _template: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,403
icons
MIT License
core/src/main/kotlin/dev/komu/kraken/model/creature/Monster.kt
komu
83,556,775
false
{"Kotlin": 225797}
package dev.komu.kraken.model.creature import dev.komu.kraken.model.Game import dev.komu.kraken.model.actions.Action import dev.komu.kraken.model.region.Cell class Monster(name: String, val race: Race): Creature(name) { init { letter = race.letter } var lastKnownPlayerPosition: Cell? = null var state: MonsterState = DefaultMonsterState.INSTANCE override val isFriendly: Boolean get() = state.isFriendly override fun getAction(game: Game): Action? { val seesPlayer = seesCreature(game.player) if (seesPlayer) lastKnownPlayerPosition = game.player.cell else if (cell == lastKnownPlayerPosition) lastKnownPlayerPosition = null val (action, nextState) = state.act(this, game) state = nextState return action } override fun talk(target: Creature) { state.talk(this, target) } override fun onAttackedBy(attacker: Creature) { if (attacker.isPlayer && state.isFriendly) state = DefaultMonsterState.INSTANCE } override fun didTakeDamage(points: Int, attacker: Creature) { state.didTakeDamage(this, points, attacker) } }
0
Kotlin
0
0
680362d8e27c475b4ef1e2d13b67cb87f67249f6
1,201
kraken
Apache License 2.0
app/src/main/java/com/mycompany/advioo/repo/InstallerRepository.kt
demirelarda
609,874,629
false
{"Kotlin": 330942}
package com.mycompany.advioo.repo import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.QuerySnapshot import com.google.firebase.firestore.ktx.toObject import com.mycompany.advioo.models.installer.Installer import javax.inject.Inject class InstallerRepository @Inject constructor( private val db: FirebaseFirestore ) : InstallerRepositoryInterface { private val installersCollection = db.collection("installers") override fun getInstallersByState(stateId: String, onSuccess: (List<Installer>) -> Unit, onFailure: (Exception) -> Unit) { installersCollection.whereEqualTo("stateId", stateId) .get() .addOnSuccessListener { snapshot -> val installerList = mutableListOf<Installer>() snapshot.forEach { document -> val installer = document.toObject<Installer>() installerList.add(installer) } onSuccess(installerList) } .addOnFailureListener { exception -> onFailure(exception) } } }
0
Kotlin
0
0
b27390784a5903d4ba81249f7b3535ff49c08ab1
1,133
AdTracker
FSF All Permissive License
fontawesome/src/de/msrd0/fontawesome/icons/FA_CIRCLE_NOTCHED.kt
msrd0
363,665,023
false
null
/* @generated * * This file is part of the FontAwesome Kotlin library. * https://github.com/msrd0/fontawesome-kt * * This library is not affiliated with FontAwesome. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.msrd0.fontawesome.icons import de.msrd0.fontawesome.Icon import de.msrd0.fontawesome.Style import de.msrd0.fontawesome.Style.SOLID object FA_CIRCLE_NOTCHED: Icon { override val name get() = "Circle Notched" override val unicode get() = "f1ce" override val styles get() = setOf(SOLID) override fun svg(style: Style) = when(style) { SOLID -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M288 39.056v16.659c0 10.804 7.281 20.159 17.686 23.066C383.204 100.434 440 171.518 440 256c0 101.689-82.295 184-184 184-101.689 0-184-82.295-184-184 0-84.47 56.786-155.564 134.312-177.219C216.719 75.874 224 66.517 224 55.712V39.064c0-15.709-14.834-27.153-30.046-23.234C86.603 43.482 7.394 141.206 8.003 257.332c.72 137.052 111.477 246.956 248.531 246.667C393.255 503.711 504 392.788 504 256c0-115.633-79.14-212.779-186.211-240.236C302.678 11.889 288 23.456 288 39.056z"/></svg>""" else -> null } }
0
Kotlin
0
0
2fc4755051325e730e9d012c9dfe94f5ea800fdd
1,679
fontawesome-kt
Apache License 2.0
app/src/main/java/com/pokemon/jv/internal/dagger/module/NetworkModule.kt
jdvalladaresc
355,704,988
false
null
package com.pokemon.jv.internal.dagger.module import android.content.Context import com.pokemon.data.network.Endpoints import com.pokemon.data.network.RestApi import com.pokemon.data.network.RestApiImpl import com.pokemon.data.network.RestService import dagger.Module import dagger.Provides import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Singleton @Module class NetworkModule { @Provides @Singleton fun provideOkHttpBuilder(context: Context): OkHttpClient.Builder { val okHttpClient = OkHttpClient.Builder() .readTimeout(60, TimeUnit.SECONDS) .connectTimeout(60, TimeUnit.SECONDS) .build() return okHttpClient.newBuilder() } @Provides @Singleton fun provideRestService(httpClientBuilder: OkHttpClient.Builder): RestService { val retrofit = Retrofit.Builder() .baseUrl(Endpoints.URL_BASE) .addConverterFactory(GsonConverterFactory.create()) .client(httpClientBuilder.build()) .build() return retrofit.create(RestService::class.java) } @Provides @Singleton fun provideRestApi( context: Context, restService: RestService ): RestApi { return RestApiImpl(context, restService) } }
0
Kotlin
0
0
8ce0961f387ff53f92581ca842e56a2b3aa7cfd7
1,388
pokemon
Apache License 2.0
jdroid-android-core/src/main/java/com/jdroid/android/google/GooglePlayUtils.kt
petsnarua
258,267,623
true
{"Kotlin": 742915, "Java": 383189, "HTML": 3936, "Shell": 2559, "JavaScript": 564}
package com.jdroid.android.google import android.content.Intent import android.net.Uri import androidx.fragment.app.FragmentActivity import com.jdroid.android.activity.ActivityLauncher import com.jdroid.android.dialog.AlertDialogFragment import com.jdroid.android.intent.IntentUtils import com.jdroid.android.kotlin.getRequiredStringArgument import com.jdroid.android.utils.AppUtils object GooglePlayUtils { private const val GOOGLE_PLAY_DETAILS_LINK = "http://play.google.com/store/apps/details?id=" class UpdateAppDialogFragment : AlertDialogFragment() { override fun onPositiveClick() { launchAppDetails(AppUtils.getReleaseApplicationId()) requireActivity().finish() } } class DownloadAppDialogFragment : AlertDialogFragment() { override fun onPositiveClick() { launchAppDetails(getRequiredStringArgument(APPLICATION_ID)) } fun setApplicationId(applicationId: String) { addParameter(APPLICATION_ID, applicationId) } companion object { private const val APPLICATION_ID = "APPLICATION_ID" } } fun showUpdateDialog(fragmentActivity: FragmentActivity?) { if (fragmentActivity != null) { val title = fragmentActivity.getString(com.jdroid.android.R.string.jdroid_updateAppTitle) val message = fragmentActivity.getString(com.jdroid.android.R.string.jdroid_updateAppMessage) AlertDialogFragment.show( fragmentActivity, UpdateAppDialogFragment(), title, message, null, null, fragmentActivity.getString(com.jdroid.android.R.string.jdroid_ok), false ) } } fun showDownloadDialog(fragmentActivity: FragmentActivity?, appNameResId: Int, applicationId: String) { if (fragmentActivity != null) { val appName = fragmentActivity.getString(appNameResId) val title = fragmentActivity.getString(com.jdroid.android.R.string.jdroid_installAppTitle, appName) val message = fragmentActivity.getString(com.jdroid.android.R.string.jdroid_installAppMessage, appName) val fragment = DownloadAppDialogFragment() fragment.setApplicationId(applicationId) AlertDialogFragment.show(fragmentActivity, fragment, title, message, fragmentActivity.getString(com.jdroid.android.R.string.jdroid_no), null, fragmentActivity.getString(com.jdroid.android.R.string.jdroid_yes), true) } } @JvmOverloads fun launchAppDetails(applicationId: String = AppUtils.getReleaseApplicationId()) { val uri = Uri.parse("market://details?id=$applicationId") var intent = Intent(Intent.ACTION_VIEW, uri) if (IntentUtils.isIntentAvailable(intent)) { ActivityLauncher.startActivityNewTask(intent) } else { intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse(getGooglePlayLink(applicationId)) ActivityLauncher.startActivityNewTask(intent) } } @JvmOverloads fun getGooglePlayLink(applicationId: String = AppUtils.getReleaseApplicationId(), referrer: String? = null): String { val builder = StringBuilder() builder.append(GOOGLE_PLAY_DETAILS_LINK) builder.append(applicationId) if (referrer != null) { builder.append("&referrer=") builder.append(referrer) } return builder.toString() } }
0
null
0
0
8b4d1654fdabe6d2e13487f8045a83b2e6e0e5fe
3,475
jdroid-android
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppshdcapi/controllers/LicenceControllerTest.kt
ministryofjustice
747,339,025
false
{"Kotlin": 176607, "Shell": 4732, "Dockerfile": 1355}
package uk.gov.justice.digital.hmpps.hmppshdcapi.controllers import com.fasterxml.jackson.databind.ObjectMapper import org.assertj.core.api.AssertionsForClassTypes.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.kotlin.reset import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.http.MediaType import org.springframework.test.context.ActiveProfiles import org.springframework.test.context.ContextConfiguration import org.springframework.test.context.junit.jupiter.SpringExtension import org.springframework.test.context.web.WebAppConfiguration import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders import org.springframework.test.web.servlet.result.MockMvcResultMatchers import org.springframework.test.web.servlet.setup.MockMvcBuilders import uk.gov.justice.digital.hmpps.hmppshdcapi.licences.CurfewAddress import uk.gov.justice.digital.hmpps.hmppshdcapi.licences.CurfewTimes import uk.gov.justice.digital.hmpps.hmppshdcapi.licences.FirstNight import uk.gov.justice.digital.hmpps.hmppshdcapi.licences.LicenceController import uk.gov.justice.digital.hmpps.hmppshdcapi.licences.LicenceService import uk.gov.justice.digital.hmpps.hmppshdcapi.model.HdcLicence import java.time.DayOfWeek import java.time.LocalTime @ExtendWith(SpringExtension::class) @ActiveProfiles("test") @WebMvcTest(controllers = [LicenceController::class]) @AutoConfigureMockMvc(addFilters = false) @ContextConfiguration(classes = [LicenceController::class]) @WebAppConfiguration class LicenceControllerTest { @MockBean private lateinit var licenceService: LicenceService @Autowired private lateinit var mvc: MockMvc @Autowired private lateinit var mapper: ObjectMapper @BeforeEach fun reset() { reset(licenceService) mvc = MockMvcBuilders .standaloneSetup( LicenceController( licenceService, ), ) .build() } @Test fun `get a licence by booking id`() { whenever(licenceService.getByBookingId(1)).thenReturn(aLicence) val result = mvc.perform(MockMvcRequestBuilders.get("/licence/hdc/1").accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk) .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)) .andReturn() assertThat(result.response.contentAsString) .isEqualTo(mapper.writeValueAsString(aLicence)) verify(licenceService, times(1)).getByBookingId(1) } private companion object { val aLicence = HdcLicence( licenceId = 1L, CurfewAddress( addressLine1 = "123 Approved Premises Street 2", addressLine2 = "Off St Michaels Place", addressTown = "Leeds", postCode = "LS1 2AA", ), FirstNight( firstNightFrom = "15:00", firstNightUntil = "07:00", ), listOf( CurfewTimes( DayOfWeek.MONDAY, LocalTime.of(19, 0), DayOfWeek.TUESDAY, LocalTime.of(7, 0), ), CurfewTimes( DayOfWeek.TUESDAY, LocalTime.of(19, 0), DayOfWeek.WEDNESDAY, LocalTime.of(7, 0), ), CurfewTimes( DayOfWeek.WEDNESDAY, LocalTime.of(19, 0), DayOfWeek.THURSDAY, LocalTime.of(7, 0), ), CurfewTimes( DayOfWeek.THURSDAY, LocalTime.of(19, 0), DayOfWeek.FRIDAY, LocalTime.of(7, 0), ), CurfewTimes( DayOfWeek.FRIDAY, LocalTime.of(19, 0), DayOfWeek.SATURDAY, LocalTime.of(7, 0), ), CurfewTimes( DayOfWeek.SATURDAY, LocalTime.of(19, 0), DayOfWeek.SUNDAY, LocalTime.of(7, 0), ), CurfewTimes( DayOfWeek.SUNDAY, LocalTime.of(19, 0), DayOfWeek.MONDAY, LocalTime.of(7, 0), ), ), ) } }
1
Kotlin
0
0
c8daae81d760cf789004e4c45c72139657015c0a
4,408
hmpps-hdc-api
MIT License
shared/src/commonMain/kotlin/nl/tiebe/otarium/logic/root/onboarding/OnboardingComponent.kt
Tiebe
528,857,681
false
{"Kotlin": 708697, "Ruby": 6904, "Swift": 2918, "Shell": 437}
package nl.tiebe.otarium.logic.root.onboarding import nl.tiebe.otarium.logic.root.RootComponent import nl.tiebe.otarium.setupNotifications interface OnboardingComponent { val navigateRootComponent: (RootComponent.ChildScreen) -> Unit fun exitOnboarding() fun notifications() { setupNotifications() } }
14
Kotlin
0
3
0b0716d2255ca0c7ea238c97439c5fbffa27de7b
330
Otarium
MIT License
app/src/main/java/com/mityushovn/miningquiz/main/presentation/searchlistfragment/recyclerview/QuestionsSearchFrAdapter.kt
NikitaMityushov
431,692,189
false
{"Kotlin": 281441}
package com.mityushovn.miningquiz.main.presentation.searchlistfragment.recyclerview import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.text.PrecomputedTextCompat import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.mityushovn.miningquiz.R import com.mityushovn.miningquiz.core_domain.domain.models.Question import com.mityushovn.miningquiz.databinding.QuestionItemBinding // TODO: 10.05.2022 Animations, ItemDecorations /** * RecyclerView.Adapter class for List<Question>. * Extends ListAdapter because a diff between lists will be computed on a background thread. * @property clickListener is a handler for list item click navigation. */ class QuestionsSearchFrAdapter(private val clickListener: (Int) -> Unit) : ListAdapter<Question, QuestionViewHolder>(QuestionDiffCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QuestionViewHolder { val itemView = LayoutInflater.from(parent.context).inflate(R.layout.question_item, parent, false) return QuestionViewHolder(QuestionItemBinding.bind(itemView)) } override fun onBindViewHolder(holder: QuestionViewHolder, position: Int) { holder.bind(getItem(position), clickListener) } /** * private class implements DiffUtil.ItemCallback for List<Question> */ private class QuestionDiffCallback : DiffUtil.ItemCallback<Question>() { override fun areItemsTheSame(oldItem: Question, newItem: Question): Boolean { return oldItem.questionId == newItem.questionId } override fun areContentsTheSame(oldItem: Question, newItem: Question): Boolean { return oldItem == newItem } } } /** * View Holder class for question_item.xml that binds data with inflated View. * Contains static DiffUtil.ItemCallback class for RecyclerView.Adapter. */ class QuestionViewHolder( val binding: QuestionItemBinding ) : RecyclerView.ViewHolder(binding.root) { fun bind(question: Question, clickListener: (Int) -> Unit) { with(binding) { questionCountTv.text = (this@QuestionViewHolder.adapterPosition.inc()).toString() // prefetch strings with PrecomputedText questionItemTv.setTextFuture( PrecomputedTextCompat.getTextFuture( question.content, questionItemTv.textMetricsParamsCompat, null ) ) executePendingBindings() // !! essential for bindings, forcing the framework to update view right at the moment } onClickListener(question.questionId, clickListener) } private fun onClickListener(questionId: Int, onClick: (Int) -> Unit) { itemView.setOnClickListener { onClick(questionId) } } }
10
Kotlin
0
0
9013e560b6d9434da4c263ccaa9f033bd0831855
2,947
MiningQuiz
MIT License
kotlin-electron/src/jsMain/generated/electron/core/ClientRequestConstructorOptionsRedirect.kt
JetBrains
93,250,841
false
{"Kotlin": 12635434, "JavaScript": 423801}
// Generated by Karakum - do not modify it manually! package electron.core sealed external interface ClientRequestConstructorOptionsRedirect { companion object { @seskar.js.JsValue("follow") val follow: ClientRequestConstructorOptionsRedirect @seskar.js.JsValue("error") val error: ClientRequestConstructorOptionsRedirect @seskar.js.JsValue("manual") val manual: ClientRequestConstructorOptionsRedirect } }
38
Kotlin
162
1,347
997ed3902482883db4a9657585426f6ca167d556
467
kotlin-wrappers
Apache License 2.0
app/src/main/java/com/nikitosii/studyrealtorapp/core/source/net/model/location/address/CoordinateApi.kt
meanswar
702,052,508
false
{"Kotlin": 730795, "HTML": 262565}
package com.nikitosii.studyrealtorapp.core.source.net.model.location.address import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class CoordinateApi( val lat: Double? = null, val lon: Double? = null )
2
Kotlin
0
0
20c281e8954fe900812e1923600ff0fd9b82d2b4
235
StudyRealtorApp
MIT License
kurrent-spring/src/main/kotlin/org/lodenstone/kurrent/spring/eventstore/EventType.kt
papaledoupe
162,044,250
false
null
package org.lodenstone.kurrent.spring.eventstore annotation class EventType(val name: String)
0
Kotlin
0
0
ff3310d44946aa00bd7091b2ce790c93492d6d52
95
kurrent
MIT License
watchlist/src/main/java/com/pyamsoft/tickertape/watchlist/WatchlistModule.kt
pyamsoft
371,196,339
false
null
package com.pyamsoft.tickertape.watchlist import androidx.annotation.CheckResult import com.pyamsoft.tickertape.watchlist.dig.WatchlistDigInteractor import com.pyamsoft.tickertape.watchlist.dig.WatchlistDigInteractorImpl import dagger.Binds import dagger.Module @Module abstract class WatchlistModule { @Binds @CheckResult internal abstract fun bindWatchlistInteractor( impl: WatchlistInteractorImpl, ): WatchlistInteractor @Binds @CheckResult internal abstract fun bindWatchlistDigInteractor( impl: WatchlistDigInteractorImpl, ): WatchlistDigInteractor }
5
Kotlin
0
2
79edd1bb2fbc7d462da55709c1c5879ca37510fd
588
tickertape
Apache License 2.0
app/src/main/java/com/hypertrack/android/interactors/app/InitActionEffect.kt
hypertrack
241,723,736
false
null
package com.hypertrack.android.interactors.app import kotlinx.coroutines.flow.Flow /** * effect for cases when you need to perform certain effects before firing an action * but it doesn't require state, so no need to send it through reducer */ sealed class InitActionEffect : AppEffect()
1
Kotlin
17
31
7a613e4b618043d95e101b819d903c3b1eda6773
294
visits-android
MIT License
deprecated/template-xml/data/src/main/java/co/nimblehq/template/xml/data/response/ErrorResponse.kt
nimblehq
101,353,301
false
{"Kotlin": 387666, "Ruby": 5344, "XSLT": 1824}
package co.nimblehq.template.xml.data.response import co.nimblehq.template.xml.domain.model.Error import com.squareup.moshi.Json data class ErrorResponse( @Json(name = "message") val message: String ) internal fun ErrorResponse.toModel() = Error(message = message)
31
Kotlin
23
94
f07941499a70b6144f4280c233edba542ab3e516
276
android-templates
MIT License
meistercharts-commons/src/jvmMain/kotlin/it/neckar/open/time/TimeExt.jvm.kt
Neckar-IT
599,079,962
false
{"Kotlin": 5819931, "HTML": 87784, "JavaScript": 1378, "CSS": 1114}
package it.neckar.open.time import java.time.Instant import java.time.ZoneOffset import java.time.format.DateTimeFormatter import java.time.format.DateTimeFormatterBuilder import java.util.Date /** * Formats a double value (in milliseconds) as UTC string. * This method must only be used for debugging purposes. */ actual fun Double.formatUtcForDebug(): String { if (this.isNaN()) { return "NaN" } if (this.isInfinite()) { return "∞" } return try { Instant.ofEpochMilli(this.toLong()).atOffset(ZoneOffset.UTC).format(utcDateTimeFormat) } catch (e: Throwable) { "---${this}---[$e]" } } /** * Special date format that does *not* append the time zone - to be compatible with JS - adds a 'Z' at the end */ val utcDateTimeFormat: DateTimeFormatter = DateTimeFormatterBuilder() .append(DateTimeFormatter.ISO_LOCAL_DATE) .appendLiteral('T') .appendPattern("HH") .appendLiteral(":") .appendPattern("mm") .appendLiteral(":") .appendPattern("ss") .appendLiteral(".") .appendPattern("SSS") .appendLiteral('Z') .toFormatter() /** * Converts an instant to a java.util.Date. * * Use only if (really, really) necessary. */ fun Instant.toDate(): Date { return Date(this.toEpochMilli()) }
3
Kotlin
3
5
ed849503e845b9d603598e8d379f6525a7a92ee2
1,243
meistercharts
Apache License 2.0
android/measure/src/main/java/sh/measure/android/performance/ComponentCallbacksCollector.kt
measure-sh
676,897,841
false
{"Kotlin": 863856, "Go": 615450, "TypeScript": 345542, "Swift": 308530, "Shell": 26060, "Objective-C": 17998, "C": 9958, "Python": 7639, "Lua": 1206, "JavaScript": 1053, "CMake": 479, "CSS": 461, "C++": 445}
package sh.measure.android.performance import android.app.Application import android.content.ComponentCallbacks2 import android.content.ComponentCallbacks2.TRIM_MEMORY_BACKGROUND import android.content.ComponentCallbacks2.TRIM_MEMORY_COMPLETE import android.content.ComponentCallbacks2.TRIM_MEMORY_MODERATE import android.content.ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL import android.content.ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW import android.content.ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE import android.content.ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN import android.content.res.Configuration import sh.measure.android.events.EventProcessor import sh.measure.android.events.EventType import sh.measure.android.utils.TimeProvider internal class ComponentCallbacksCollector( private val application: Application, private val eventProcessor: EventProcessor, private val timeProvider: TimeProvider, private val memoryReader: MemoryReader, ) : ComponentCallbacks2 { fun register() { application.registerComponentCallbacks(this) } override fun onLowMemory() { eventProcessor.track( timestamp = timeProvider.currentTimeSinceEpochInMillis, type = EventType.LOW_MEMORY, data = LowMemoryData( java_free_heap = memoryReader.freeHeapSize(), java_max_heap = memoryReader.maxHeapSize(), java_total_heap = memoryReader.totalHeapSize(), native_free_heap = memoryReader.nativeFreeHeapSize(), native_total_heap = memoryReader.nativeTotalHeapSize(), rss = memoryReader.rss(), total_pss = memoryReader.totalPss(), ), ) } override fun onTrimMemory(level: Int) { val trimMemoryData = when (level) { TRIM_MEMORY_UI_HIDDEN -> TrimMemoryData(level = "TRIM_MEMORY_UI_HIDDEN") TRIM_MEMORY_RUNNING_MODERATE -> TrimMemoryData(level = "TRIM_MEMORY_RUNNING_MODERATE") TRIM_MEMORY_RUNNING_LOW -> TrimMemoryData(level = "TRIM_MEMORY_RUNNING_LOW") TRIM_MEMORY_RUNNING_CRITICAL -> TrimMemoryData(level = "TRIM_MEMORY_RUNNING_CRITICAL") TRIM_MEMORY_BACKGROUND -> TrimMemoryData(level = "TRIM_MEMORY_BACKGROUND") TRIM_MEMORY_MODERATE -> TrimMemoryData(level = "TRIM_MEMORY_MODERATE") TRIM_MEMORY_COMPLETE -> TrimMemoryData(level = "TRIM_MEMORY_COMPLETE") else -> TrimMemoryData(level = "TRIM_MEMORY_UNKNOWN") } eventProcessor.track( timestamp = timeProvider.currentTimeSinceEpochInMillis, type = EventType.TRIM_MEMORY, data = trimMemoryData, ) } override fun onConfigurationChanged(newConfig: Configuration) { // no-op } }
80
Kotlin
20
445
f04f6d96c4119aa6009505e52abe9b5cad6a84c9
2,827
measure
Apache License 2.0
src/main/kotlin/app/boboc/springframework/cloud/github/GitHubCloudProperties.kt
boboc-app
848,216,217
false
{"Kotlin": 29752}
package app.boboc.springframework.cloud.github import org.springframework.boot.context.properties.ConfigurationProperties @ConfigurationProperties(GitHubCloudProperties.PROPERTIES_PREFIX) data class GitHubCloudProperties( val token: String = System.getenv("GITHUB_CLOUD_TOKEN") ?: System.getProperty("GITHUB_CLOUD_TOKEN"), val endPointUri: String? = System.getenv("GITHUB_CLOUD_URI") ?: System.getProperty("GITHUB_CLOUD_URI"), ){ companion object{ const val PROPERTIES_PREFIX="github.cloud" } }
0
Kotlin
0
2
d2a46f57776fd11108b490febd4fa3b098a9a44b
520
spring-cloud-github
MIT License
dialog-core/src/main/java/com/akexorcist/instantdialog/core/option/NeutralButtonOption.kt
akexorcist
271,466,252
false
null
package com.akexorcist.instantdialog.core.option import android.os.Bundle import android.view.View import android.widget.Button import com.akexorcist.instantdialog.core.DialogComponent import com.akexorcist.instantdialog.core.R interface NeutralButtonOption : DialogComponent { var neutralButton: Button var neutralMessage: String? var neutralMessageResourceId: Int fun getNeutralButtonResourceId(): Int = R.id.neutralButton override fun bindView(parent: View) { neutralButton = parent.findViewById(getNeutralButtonResourceId()) if (neutralMessageResourceId != 0) { neutralButton.text = neutralButton.context.getString(neutralMessageResourceId) } else if (neutralMessage != null) { neutralButton.text = neutralMessage } } override fun saveState(outState: Bundle) { outState.putString(EXTRA_NEUTRAL_MESSAGE, neutralMessage) outState.putInt(EXTRA_NEUTRAL_MESSAGE_RESOURCE_ID, neutralMessageResourceId) } override fun restoreState(savedInstanceState: Bundle) { neutralMessage = savedInstanceState.getString(EXTRA_NEUTRAL_MESSAGE) neutralMessageResourceId = savedInstanceState.getInt(EXTRA_NEUTRAL_MESSAGE_RESOURCE_ID) } companion object { const val EXTRA_NEUTRAL_MESSAGE = "com.akexorcist.dialog.core.neutralbutton.extra_neutral_message" const val EXTRA_NEUTRAL_MESSAGE_RESOURCE_ID = "com.akexorcist.dialog.core.neutralbutton.extra_neutral_message_resource_id" } }
0
Kotlin
0
4
e3291f552e68ca27aba36bcdaa66cad45cbe0fdd
1,521
InstantDialog
Apache License 2.0
src/main/kotlin/no/nav/tiltaksarrangor/config/LogConfig.kt
navikt
616,496,742
false
null
package no.nav.tiltaksarrangor.config import no.nav.common.audit_log.log.AuditLogger import no.nav.common.audit_log.log.AuditLoggerImpl import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration class LogConfig { @Bean fun auditLogger(): AuditLogger { return AuditLoggerImpl() } }
5
Kotlin
0
2
c2c1c9501375018b40ef0ac94baf44570b1f37c9
355
amt-tiltaksarrangor-bff
MIT License
demo/multiround/src/main/java/com/alessandro/claymore/demo/multiround/allies/generated/AlliesActivity_AutoViewModelModule.kt
alecarnevale
559,250,665
false
{"Kotlin": 92000}
package com.alessandro.claymore.demo.multiround.allies.generated // Not used, @AutoProvides annotation will generate this automatically ;) // after a successful build take a look at :multiround/build/generated/ksp/debug/kotlin/com/alessandro/claymore/demo/multiround /* import androidx.lifecycle.SavedStateHandle import com.alecarnevale.claymore.providers.AutoProvidesKeysProvider import com.alessandro.claymore.demo.multiround.allies.AlliesActivityIntent import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ViewModelComponent @Module @InstallIn(ViewModelComponent::class) class AlliesActivity_AutoViewModelModule { @Provides @AlliesActivityIntent.FirstAlly fun firstAlly( handle: SavedStateHandle, @AlliesActivity_AutoQualifier autoProvidesKeysProvider: com.alecarnevale.claymore.providers.AutoProvidesKeysProvider ): String { return requireNotNull(handle[autoProvidesKeysProvider[AlliesActivityIntent.FirstAlly::class]]) } @Provides @AlliesActivityIntent.SecondAlly fun secondAlly( handle: SavedStateHandle, @AlliesActivity_AutoQualifier autoProvidesKeysProvider: com.alecarnevale.claymore.providers.AutoProvidesKeysProvider ): String { return requireNotNull(handle[autoProvidesKeysProvider[AlliesActivityIntent.SecondAlly::class]]) } } */
0
Kotlin
0
5
f0db25b5b0025ac1448755beb65e971e8f9d7394
1,349
claymore
Apache License 2.0
DesignSystem/src/main/java/com/yourssu/design/system/rule/Rounding.kt
yourssu
364,290,281
false
null
package com.yourssu.design.system.rule
2
Kotlin
0
9
58364077175f882def5108e654f51667b9d3af36
40
YDS-Android
MIT License
app/src/main/java/org/obd/graphs/ui/graph/GraphVirtualScreen.kt
tzebrowski
326,375,780
false
null
package org.obd.graphs.ui.graph import org.obd.graphs.preferences.* private const val VIRTUAL_SCREEN_SELECTION = "pref.graph.virtual.selected" const val PREF_GRAPH_DIALOG = "pref.graph.pids.selected" class GraphVirtualScreen { fun getCurrentVirtualScreen() = Prefs.getString(VIRTUAL_SCREEN_SELECTION, "1")!! fun updateVirtualScreen(screenId: String) { Prefs.updateString(VIRTUAL_SCREEN_SELECTION, screenId) } fun updateVirtualScreenMetrics(newList: List<String>) { Prefs.updateStringSet(getVirtualScreenPrefKey(), newList) } fun getVirtualScreenMetrics(): Set<String> = Prefs.getStringSet(getVirtualScreenPrefKey(), mutableSetOf())!! private fun getVirtualScreenPrefKey(): String = "$PREF_GRAPH_DIALOG.${getCurrentVirtualScreen()}" } val graphVirtualScreen = GraphVirtualScreen()
1
Kotlin
2
8
1d11f7c13f95cacbd40f68596895615b6676f4c0
839
ObdGraphs
Apache License 2.0
skellig-test-step-processing-jdbc/src/test/kotlin/org/skellig/teststep/processor/jdbc/JdbcSelectRequestExecutorTest.kt
skellig-framework
263,021,995
false
{"Kotlin": 1283314, "CSS": 525991, "Java": 270216, "FreeMarker": 66859, "HTML": 11313, "ANTLR": 6165}
package org.skellig.teststep.processor.jdbc import org.junit.jupiter.api.* import org.junit.jupiter.api.Assertions.assertEquals import org.mockito.Mockito import org.mockito.kotlin.* import org.skellig.teststep.processing.exception.TestStepProcessingException import org.skellig.teststep.processor.db.model.DatabaseRequest import java.sql.* import java.time.LocalDate import java.time.LocalDateTime import java.util.concurrent.atomic.AtomicInteger @DisplayName("Execute select request") internal class JdbcSelectRequestExecutorTest { private var executorSelect: JdbcSelectRequestExecutor? = null private var connection: Connection? = null @BeforeEach fun setUp() { connection = mock<Connection>() executorSelect = JdbcSelectRequestExecutor(connection) } @Test @DisplayName("When query provided with no parameters Then check parameters ignored") fun testFindUsingQuery() { val sql = "select query" val databaseRequest = Mockito.mock(DatabaseRequest::class.java) whenever(databaseRequest.query).thenReturn(sql) val resultSet = createResultSet() val statement = mock<PreparedStatement>() whenever(statement.executeQuery()).thenReturn(resultSet) whenever(connection!!.prepareStatement(sql)).thenReturn(statement) val response = executorSelect!!.execute(databaseRequest) as List<Map<*, *>>? Assertions.assertAll( { assertEquals(1, response!!.size) }, { assertEquals(3, response!![0].size) }, { assertEquals("v1", response!![0]["c1"]) }, { assertEquals("v2", response!![0]["c2"]) }, { Assertions.assertNull(response!![0]["c3"]) }, { verify(statement, times(0)).setObject(any(), any()) } ) } @Test @DisplayName("When query provided with parameters Then check parameters applied") fun testFindUsingQueryWithParameters() { val queryParameters = listOf(LocalDateTime.of(2020, 1, 1, 10, 10), 10) val databaseRequest = DatabaseRequest("select * from A where c2 = ? OR c1 > ?", queryParameters) val resultSet = createResultSet() val statement = mock<PreparedStatement>() whenever(statement.executeQuery()).thenReturn(resultSet) whenever(connection!!.prepareStatement(databaseRequest.query)).thenReturn(statement) val response = executorSelect!!.execute(databaseRequest) as List<Map<*, *>>? Assertions.assertAll( { assertEquals(1, response!!.size) }, { verify(statement).setObject(1, Timestamp.valueOf(queryParameters[0] as LocalDateTime)) }, { verify(statement).setObject(2, queryParameters[1]) } ) } @Test @DisplayName("When command provided without filter Then check query created correctly") fun testFindUsingCommandWithoutFilter() { val sql = "SELECT * FROM t1" val databaseRequest = DatabaseRequest("select", "t1", null) val resultSet = createResultSet() val statement = mock<PreparedStatement>() whenever(statement.executeQuery()).thenReturn(resultSet) whenever(connection!!.prepareStatement(sql)).thenReturn(statement) val response = executorSelect!!.execute(databaseRequest) as List<Map<*, *>>? assertEquals(1, response!!.size) } @Test @DisplayName("When query provided And executes with error") fun testExecuteQueryWhenErrorOccurs() { val sql = "SELECT * FROM t1" val databaseRequest = DatabaseRequest(sql) val statement = mock<PreparedStatement>() whenever(connection!!.prepareStatement(sql)).thenReturn(statement) doThrow(RuntimeException("failed query")).whenever(statement).executeQuery() val ex = assertThrows<TestStepProcessingException> { executorSelect!!.execute(databaseRequest) as List<Map<*, *>>? } assertEquals("failed query", ex.message) } @Test @DisplayName("When command provided with filter Then check query created correctly") fun testFindUsingCommandWithFilter() { val sql = "SELECT * FROM t1 WHERE c3 like ? AND c4 in (?) AND c5 = ? AND c6 = ? AND c1 = ? AND c2 > ?" val filter = hashMapOf( Pair("c1", "v1"), Pair( "c2", mapOf( Pair("comparator", ">"), Pair("value", 10), ) ), Pair( "c3", mapOf( Pair("comparator", "like"), Pair("value", "%a%"), ) ), Pair( "c4", mapOf( Pair("comparator", "in"), Pair("value", listOf("a", "b")), ) ), Pair("c5", LocalDateTime.of(2020, 1, 1, 10, 10)), Pair("c6", LocalDate.of(2020, 2, 2)), ) val databaseRequest = DatabaseRequest("select", "t1", filter) val resultSet = createResultSet() val statement = Mockito.mock(PreparedStatement::class.java) whenever(statement.executeQuery()).thenReturn(resultSet) whenever(connection!!.prepareStatement(sql)).thenReturn(statement) val response = executorSelect!!.execute(databaseRequest) as List<Map<*, *>> Assertions.assertAll( { assertEquals(1, response.size) }, { Mockito.verify(statement).setObject(1, "%a%") }, { Mockito.verify(statement).setObject(eq(2), argThat { o -> (o as List<*>).contains("a") && o.contains("b") }) }, { Mockito.verify(statement).setObject(eq(3), argThat { o -> o is Timestamp && o.compareTo(Timestamp.valueOf(filter["c5"] as LocalDateTime?)) == 0 }) }, { Mockito.verify(statement).setObject(eq(4), argThat { o -> o is Date && o.compareTo(Date.valueOf(filter["c6"] as LocalDate?)) == 0 }) }, { Mockito.verify(statement).setObject(5, "v1") }, { Mockito.verify(statement).setObject(6, 10) } ) } private fun createResultSet(): ResultSet { val resultSet = Mockito.mock(ResultSet::class.java) val metaData = Mockito.mock(ResultSetMetaData::class.java) whenever(metaData.columnCount).thenReturn(3) whenever(metaData.getColumnName(1)).thenReturn("c1") whenever(metaData.getColumnName(2)).thenReturn("c2") whenever(metaData.getColumnName(3)).thenReturn("c3") whenever(resultSet.metaData).thenReturn(metaData) whenever(resultSet.getObject("c1")).thenReturn("v1") whenever(resultSet.getObject("c2")).thenReturn("v2") whenever(resultSet.getObject("c3")).thenReturn(null) // has only 1 row val counter = AtomicInteger(0) whenever(resultSet.next()).thenAnswer { counter.incrementAndGet() <= 1 } return resultSet } }
8
Kotlin
0
3
ed375268b0e444f1928f22f4ac27603e9d1fb66b
7,014
skellig-core
Apache License 2.0
app/src/main/java/com/yt/graduation/repository/DetailProductRepository.kt
yusuf-teker
455,260,775
false
null
package com.yt.graduation.repository import android.util.Log import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.* import com.google.firebase.database.ktx.database import com.google.firebase.ktx.Firebase import com.yt.graduation.model.User import com.yt.graduation.util.FirebaseResultListener import com.yt.graduation.util.OnDataReceivedCallback class DetailProductRepository { var auth: FirebaseAuth = FirebaseAuth.getInstance() private lateinit var userRef: DatabaseReference private var user = User() private val userId = auth.currentUser!!.uid private var databaseRef = Firebase.database.reference fun addToFavorites(productKey: String, resultListener: FirebaseResultListener){ if(auth.currentUser != null){ val userId = auth.currentUser!!.uid userRef = databaseRef.child("Users").child(userId) userRef.child("favoriteProducts").get().addOnSuccessListener { val productList = ArrayList<String>() if (it.value!=null){ productList.addAll(it.value as ArrayList<String>) if (!productList.contains(productKey)){ productList.add(productKey) resultListener.onSuccess(true) } else{ productList.remove(productKey) resultListener.onSuccess(false) } Log.i("firebase", "Favorites $productList") userRef.child("favoriteProducts").setValue(productList) }else{ productList.add(productKey) userRef.child("favoriteProducts").setValue(productList) } } } } fun isFavorite(productKey: String,resultListener: FirebaseResultListener){ if(auth.currentUser != null){ val userId = auth.currentUser!!.uid userRef = databaseRef.child("Users").child(userId) userRef.child("favoriteProducts").get().addOnSuccessListener { if (it.value!=null && (it.value as ArrayList<String>).contains(productKey)) resultListener.onSuccess(true) else resultListener.onSuccess(false) } } } fun getOwnerInfo(ownerId: String,callback: OnDataReceiveCallback) { userRef = databaseRef.child("Users").child(ownerId) userRef.addListenerForSingleValueEvent(object : ValueEventListener{ override fun onDataChange(snapshot: DataSnapshot) { val name = snapshot.child("name").value.toString() //User -> userId -> name val imageUrl = snapshot.child("image").value.toString() //User -> userId -> image val id = snapshot.child("uid").value.toString() callback.onDataReceived(arrayListOf(name, imageUrl,id)) } override fun onCancelled(error: DatabaseError) { TODO("Not yet implemented") } }) } //get all chat ids from UserChats // private fun getChatIDs(callback: UsersRepository.OnDataReceiveCallback<String>){ // // val chatIDs = ArrayList<String>() //Contains all chatsUID // // val dbRefUserChats = databaseRef.child("UserChats").child(userId) // dbRefUserChats.addListenerForSingleValueEvent(object: ValueEventListener { // override fun onDataChange(dataSnapshot: DataSnapshot) { // for (ds in dataSnapshot.children){ // chatIDs.add(ds.value.toString()) // Log.d("speeches", ds.key.toString()+" "+ ds.value.toString()) // } // //if there are chatIDs check if any of them is belong to sender and receiver // callback.onDataReceived(chatIDs) // // // Log.d("speeches chatIDs",chatIDs.toString() ) // } // override fun onCancelled(databaseError: DatabaseError) { } // }) //TODO add coroutine after this finish -go to ChatRooms // // // } // fun checkIsThereContactWithProductOwner(productOwnerId: String,callback: OnDataReceivedCallback<String>){ // getChatIDs(object : UsersRepository.OnDataReceiveCallback<String> { // override fun onDataReceived(chatIDs: ArrayList<String>) { // if (chatIDs.size!=0){ // databaseRef.child("ChatRooms").addListenerForSingleValueEvent(object :ValueEventListener{ // override fun onDataChange(snapshot: DataSnapshot) { // for (ds in snapshot.children){ //ds.key -> chatUID'ler // if (chatIDs.contains(ds.key.toString())){ // for (i in ds.children){ // val memberList = i.value as List<String> //Todo make it safe cast // if( memberList.contains(userId) && memberList.contains(productOwnerId) && userId != productOwnerId) { //there is to id in here my id and the other's id // callback.onDataReceived(ds.key.toString()) // return // } // } // callback.onDataReceived("") // } // } // } // override fun onCancelled(error: DatabaseError) { // TODO("Not yet implemented") // } // }) // }else{ // callback.onDataReceived("") // } // } // }) // } interface OnDataReceiveCallback { fun onDataReceived(ownerInfo: ArrayList<String>) } }
0
Kotlin
0
0
8bdc3a2015fcf2beac912509b598d1d72149cf37
5,970
Graduation
MIT License
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsworkload/service/NotificationServiceTests.kt
ministryofjustice
378,843,394
false
null
package uk.gov.justice.digital.hmpps.hmppsworkload.service import io.mockk.every import io.mockk.mockk import io.mockk.slot import io.mockk.verify import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.data.repository.findByIdOrNull import reactor.core.publisher.Flux import reactor.core.publisher.Mono import uk.gov.justice.digital.hmpps.hmppsworkload.client.AssessRisksNeedsApiClient import uk.gov.justice.digital.hmpps.hmppsworkload.client.CommunityApiClient import uk.gov.justice.digital.hmpps.hmppsworkload.client.dto.Contact import uk.gov.justice.digital.hmpps.hmppsworkload.client.dto.Conviction import uk.gov.justice.digital.hmpps.hmppsworkload.client.dto.ConvictionRequirement import uk.gov.justice.digital.hmpps.hmppsworkload.client.dto.CourtAppearance import uk.gov.justice.digital.hmpps.hmppsworkload.client.dto.DeliusStaff import uk.gov.justice.digital.hmpps.hmppsworkload.client.dto.Offence import uk.gov.justice.digital.hmpps.hmppsworkload.client.dto.OffenceDetail import uk.gov.justice.digital.hmpps.hmppsworkload.client.dto.OffenderAssessment import uk.gov.justice.digital.hmpps.hmppsworkload.client.dto.PersonSummary import uk.gov.justice.digital.hmpps.hmppsworkload.client.dto.RequirementCategory import uk.gov.justice.digital.hmpps.hmppsworkload.client.dto.RiskPredictor import uk.gov.justice.digital.hmpps.hmppsworkload.client.dto.RiskSummary import uk.gov.justice.digital.hmpps.hmppsworkload.client.dto.Sentence import uk.gov.justice.digital.hmpps.hmppsworkload.client.dto.SentenceType import uk.gov.justice.digital.hmpps.hmppsworkload.client.dto.StaffName import uk.gov.justice.digital.hmpps.hmppsworkload.domain.AllocateCase import uk.gov.justice.digital.hmpps.hmppsworkload.domain.CaseType import uk.gov.justice.digital.hmpps.hmppsworkload.domain.Tier import uk.gov.justice.digital.hmpps.hmppsworkload.integration.responses.emailResponse import uk.gov.justice.digital.hmpps.hmppsworkload.jpa.entity.CaseDetailsEntity import uk.gov.justice.digital.hmpps.hmppsworkload.jpa.repository.CaseDetailsRepository import uk.gov.service.notify.NotificationClientApi import uk.gov.service.notify.SendEmailResponse import java.math.BigDecimal import java.math.BigInteger import java.time.LocalDate import java.time.LocalDateTime import java.time.ZonedDateTime import java.time.format.DateTimeFormatter import java.util.Optional class NotificationServiceTests { private val notificationClient = mockk<NotificationClientApi>() private val communityApiClient = mockk<CommunityApiClient>() private val hmppsCaseDetailsRepo = mockk<CaseDetailsRepository>() private val assessRisksNeedsApiClient = mockk<AssessRisksNeedsApiClient>() private val templateId = "templateId" private val notificationService = NotificationService( notificationClient, templateId, communityApiClient, assessRisksNeedsApiClient, hmppsCaseDetailsRepo ) private val allocateCase = AllocateCase("CRN1111", BigInteger.TEN, sendEmailCopyToAllocatingOfficer = false, eventNumber = 1) private val personSummary = PersonSummary("John", "Doe") @BeforeEach fun setup() { every { communityApiClient.getAllConvictions(any()) } returns Flux.just( Conviction( Sentence( SentenceType("", ""), BigInteger.ONE, "Minutes", "Description", LocalDate.now(), BigInteger.ONE, LocalDate.now(), null ), null, true, BigInteger.TEN, 1, CourtAppearance( LocalDateTime.now(), "Court 1" ), emptyList() ) ) every { communityApiClient.getInductionContacts(any(), any()) } returns Mono.just(emptyList()) val deliusStaff = DeliusStaff(BigInteger.ONE, "ALLOCATOR1", StaffName("Alli", "Cator"), null, null, null, "<EMAIL>") every { communityApiClient.getStaffByUsername(any()) } returns Mono.just(deliusStaff) every { assessRisksNeedsApiClient.getRiskSummary(any(), any()) } returns Mono.just(Optional.empty()) every { assessRisksNeedsApiClient.getRiskPredictors(any(), any()) } returns Mono.just(emptyList()) every { communityApiClient.getAssessment(any()) } returns Mono.just(Optional.empty()) every { notificationClient.sendEmail(any(), any(), any(), any()) } returns SendEmailResponse(emailResponse()) every { hmppsCaseDetailsRepo.findByIdOrNull(any()) } returns CaseDetailsEntity("", Tier.B3, CaseType.CUSTODY, "Jane", "Doe") every { communityApiClient.getSummaryByCrn(any()) } returns Mono.just(personSummary) } @Test fun `must add case name to email`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirements = emptyList<ConvictionRequirement>() val allocatingOfficerUsername = "ALLOCATOR" val token = "token" notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token).block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals("${personSummary.firstName} ${personSummary.surname}", parameters.captured["case_name"]) } @Test fun `must add crn to email`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirements = emptyList<ConvictionRequirement>() val allocatingOfficerUsername = "ALLOCATOR" val token = "token" notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals(allocateCase.crn, parameters.captured["crn"]) } @Test fun `must add officer name`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirements = emptyList<ConvictionRequirement>() val allocatingOfficerUsername = "ALLOCATOR" val token = "token" notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals("${allocatedOfficer.staff.forenames} ${allocatedOfficer.staff.surname}", parameters.captured["officer_name"]) } @Test fun `must add court name`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirements = emptyList<ConvictionRequirement>() val allocatingOfficerUsername = "ALLOCATOR" val token = "token" val activeConviction = Conviction( Sentence( SentenceType("", ""), BigInteger.ONE, "Minutes", "Description", LocalDate.now(), BigInteger.ONE, LocalDate.now(), null ), null, true, BigInteger.TEN, 1, CourtAppearance( LocalDateTime.now(), "Court 1" ), emptyList() ) val anotherConviction = Conviction( Sentence( SentenceType("", ""), BigInteger.ONE, "Minutes", "Description", LocalDate.now(), BigInteger.ONE, LocalDate.now(), null ), null, true, BigInteger.TEN, 2, CourtAppearance( LocalDateTime.now(), "Court 2" ), emptyList() ) every { communityApiClient.getAllConvictions(any()) } returns Flux.just(activeConviction, anotherConviction) notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals(activeConviction.courtAppearance!!.courtName, parameters.captured["court_name"]) } @Test fun `must add court sentence date`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirements = emptyList<ConvictionRequirement>() val allocatingOfficerUsername = "ALLOCATOR" val token = "token" val activeConviction = Conviction( Sentence( SentenceType("", ""), BigInteger.ONE, "Minutes", "Description", LocalDate.now(), BigInteger.ONE, LocalDate.now(), null ), null, true, BigInteger.TEN, 1, CourtAppearance( LocalDateTime.now(), "Court 1" ), emptyList() ) every { communityApiClient.getAllConvictions(any()) } returns Flux.just(activeConviction) notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals(activeConviction.courtAppearance!!.appearanceDate.format(DateTimeFormatter.ofPattern("d MMMM yyyy")), parameters.captured["sentence_date"]) } @Test fun `must add induction statement no induction appointment needed when case type is custody`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirements = emptyList<ConvictionRequirement>() val allocatingOfficerUsername = "ALLOCATOR" val token = "token" notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals("no initial appointment needed", parameters.captured["induction_statement"]) } @Test fun `must add induction statement booked and due on when initial appointment is booked in the future`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirements = emptyList<ConvictionRequirement>() val allocatingOfficerUsername = "ALLOCATOR" val token = "token" every { hmppsCaseDetailsRepo.findByIdOrNull(any()) } returns CaseDetailsEntity("", Tier.B3, CaseType.COMMUNITY, "Jane", "Doe") val appointment = Contact(ZonedDateTime.now().plusDays(5L)) every { communityApiClient.getInductionContacts(any(), any()) } returns Mono.just(listOf(appointment)) val activeConviction = Conviction( Sentence( SentenceType("", ""), BigInteger.ONE, "Minutes", "Description", LocalDate.now(), BigInteger.ONE, LocalDate.now(), null ), null, true, BigInteger.TEN, 1, CourtAppearance( LocalDateTime.now(), "Court 1" ), emptyList() ) every { communityApiClient.getAllConvictions(any()) } returns Flux.just(activeConviction) notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals("their initial appointment is scheduled for ${appointment.contactStart.format(DateTimeFormatter.ofPattern("d MMMM yyyy"))}", parameters.captured["induction_statement"]) } @Test fun `must add induction statement is overdue and was due on when initial appointment is booked in the past`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirements = emptyList<ConvictionRequirement>() val allocateCase = AllocateCase("CRN1111", BigInteger.TEN, sendEmailCopyToAllocatingOfficer = false, eventNumber = 1) val allocatingOfficerUsername = "ALLOCATOR" val token = "token" every { hmppsCaseDetailsRepo.findByIdOrNull(any()) } returns CaseDetailsEntity("", Tier.B3, CaseType.COMMUNITY, "Jane", "Doe") val appointment = Contact(ZonedDateTime.now().minusDays(5L)) every { communityApiClient.getInductionContacts(any(), any()) } returns Mono.just(listOf(appointment)) val activeConviction = Conviction( Sentence( SentenceType("", ""), BigInteger.ONE, "Minutes", "Description", LocalDate.now(), BigInteger.ONE, LocalDate.now(), null ), null, true, BigInteger.TEN, 1, CourtAppearance( LocalDateTime.now(), "Court 1" ), emptyList() ) every { communityApiClient.getAllConvictions(any()) } returns Flux.just(activeConviction) notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals("their initial appointment was scheduled for ${appointment.contactStart.format(DateTimeFormatter.ofPattern("d MMMM yyyy"))}", parameters.captured["induction_statement"]) } @Test fun `must add induction statement has not been booked and is due on when initial appointment is not booked at all`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirements = emptyList<ConvictionRequirement>() val allocateCase = AllocateCase("CRN1111", BigInteger.TEN, sendEmailCopyToAllocatingOfficer = false, eventNumber = 1) val allocatingOfficerUsername = "ALLOCATOR" val token = "token" every { hmppsCaseDetailsRepo.findByIdOrNull(any()) } returns CaseDetailsEntity("", Tier.B3, CaseType.COMMUNITY, "Jane", "Doe") every { communityApiClient.getInductionContacts(any(), any()) } returns Mono.just(emptyList()) val activeConviction = Conviction( Sentence( SentenceType("", ""), BigInteger.ONE, "Minutes", "Description", LocalDate.now(), BigInteger.ONE, LocalDate.now(), null ), null, true, BigInteger.TEN, 1, CourtAppearance( LocalDateTime.now(), "Court 1" ), emptyList() ) every { communityApiClient.getAllConvictions(any()) } returns Flux.just(activeConviction) notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals("no date found for the initial appointment, please check with your team", parameters.captured["induction_statement"]) } @Test fun `must add offences`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirements = emptyList<ConvictionRequirement>() val allocatingOfficerUsername = "ALLOCATOR" val token = "token" val offence = Offence(true, OffenceDetail("Offence main category", "", "")) val activeConviction = Conviction( Sentence( SentenceType("", ""), BigInteger.ONE, "Minutes", "Description", LocalDate.now(), BigInteger.ONE, LocalDate.now(), null ), null, true, BigInteger.TEN, 1, CourtAppearance( LocalDateTime.now(), "Court 1" ), listOf(offence) ) every { communityApiClient.getAllConvictions(any()) } returns Flux.just(activeConviction) notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals(listOf(offence.detail.mainCategoryDescription), parameters.captured["offences"]) } @Test fun `must add order`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirements = emptyList<ConvictionRequirement>() val allocatingOfficerUsername = "ALLOCATOR" val token = "token" val sentence = Sentence(SentenceType("", ""), BigInteger.ONE, "Minutes", "Sentence Description", LocalDate.now(), BigInteger.ONE, LocalDate.now(), null) val activeConviction = Conviction( sentence, null, true, BigInteger.TEN, 1, CourtAppearance( LocalDateTime.now(), "Court 1" ), emptyList() ) every { communityApiClient.getAllConvictions(any()) } returns Flux.just(activeConviction) notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals("${sentence.description} (${sentence.originalLength} ${sentence.originalLengthUnits})", parameters.captured["order"]) } @Test fun `must add requirements`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirement = ConvictionRequirement( RequirementCategory("MAIN", "Main Category"), RequirementCategory("SUB", "Sub Category"), BigInteger.TEN, BigInteger.ONE, "Year" ) val requirements = listOf(requirement) val allocatingOfficerUsername = "ALLOCATOR" val token = "token" notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals(listOf("${requirement.requirementTypeMainCategory.description}: ${requirement.requirementTypeSubCategory.description} ${requirement.length} ${requirement.lengthUnit}"), parameters.captured["requirements"]) } @Test fun `must add requirements without length`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirement = ConvictionRequirement( RequirementCategory("MAIN", "Main Category"), RequirementCategory("SUB", "Sub Category"), BigInteger.TEN, null, null ) val requirements = listOf(requirement) val allocatingOfficerUsername = "ALLOCATOR" val token = "token" notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals(listOf("${requirement.requirementTypeMainCategory.description}: ${requirement.requirementTypeSubCategory.description}"), parameters.captured["requirements"]) } @Test fun `must add rosh capitalized when it exists`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirements = emptyList<ConvictionRequirement>() val allocatingOfficerUsername = "ALLOCATOR" val token = "token" val riskSummary = RiskSummary("HIGH") every { assessRisksNeedsApiClient.getRiskSummary(allocateCase.crn, token) } returns Mono.just(Optional.of(riskSummary)) notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals("High", parameters.captured["rosh"]) } @Test fun `must add RSR level capitalized when it exists`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirements = emptyList<ConvictionRequirement>() val allocatingOfficerUsername = "ALLOCATOR" val token = "token" val riskPredictor = RiskPredictor(BigDecimal.TEN, "MEDIUM", LocalDateTime.now()) every { assessRisksNeedsApiClient.getRiskPredictors(allocateCase.crn, token) } returns Mono.just(listOf(riskPredictor)) notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals("Medium", parameters.captured["rsrLevel"]) } @Test fun `must add RSR percentage when it exists`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirements = emptyList<ConvictionRequirement>() val allocatingOfficerUsername = "ALLOCATOR" val token = "token" val riskPredictor = RiskPredictor(BigDecimal.TEN, "MEDIUM", LocalDateTime.now()) every { assessRisksNeedsApiClient.getRiskPredictors(allocateCase.crn, token) } returns Mono.just(listOf(riskPredictor)) notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals(riskPredictor.rsrPercentageScore.toString(), parameters.captured["rsrPercentage"]) } @Test fun `must add ogrs percentage when it exists`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirements = emptyList<ConvictionRequirement>() val allocatingOfficerUsername = "ALLOCATOR" val token = "token" val offenderAssessment = OffenderAssessment(LocalDate.now(), 10) every { communityApiClient.getAssessment(any()) } returns Mono.just(Optional.of(offenderAssessment)) notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals(offenderAssessment.ogrsScore.toString(), parameters.captured["ogrsPercentage"]) } @Test fun `must add ogrs level low when its below 49`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirements = emptyList<ConvictionRequirement>() val allocatingOfficerUsername = "ALLOCATOR" val token = "token" val offenderAssessment = OffenderAssessment(LocalDate.now(), 10) every { communityApiClient.getAssessment(any()) } returns Mono.just(Optional.of(offenderAssessment)) notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals("Low", parameters.captured["ogrsLevel"]) } @Test fun `must add ogrs level medium when its between 50 and 74`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirements = emptyList<ConvictionRequirement>() val allocatingOfficerUsername = "ALLOCATOR" val token = "token" val offenderAssessment = OffenderAssessment(LocalDate.now(), 55) every { communityApiClient.getAssessment(any()) } returns Mono.just(Optional.of(offenderAssessment)) notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals("Medium", parameters.captured["ogrsLevel"]) } @Test fun `must add ogrs level high when its between 75 and 89`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirements = emptyList<ConvictionRequirement>() val allocatingOfficerUsername = "ALLOCATOR" val token = "token" val offenderAssessment = OffenderAssessment(LocalDate.now(), 80) every { communityApiClient.getAssessment(any()) } returns Mono.just(Optional.of(offenderAssessment)) notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals("High", parameters.captured["ogrsLevel"]) } @Test fun `must add ogrs level very high when its 90 or more`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirements = emptyList<ConvictionRequirement>() val allocatingOfficerUsername = "ALLOCATOR" val token = "token" val offenderAssessment = OffenderAssessment(LocalDate.now(), 95) every { communityApiClient.getAssessment(any()) } returns Mono.just(Optional.of(offenderAssessment)) notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals("Very High", parameters.captured["ogrsLevel"]) } @Test fun `must add notes when they exist`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirements = emptyList<ConvictionRequirement>() val allocateCase = AllocateCase("CRN1111", BigInteger.TEN, "Some Notes", sendEmailCopyToAllocatingOfficer = false, eventNumber = 1) val allocatingOfficerUsername = "ALLOCATOR" val token = "token" notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals(allocateCase.instructions, parameters.captured["notes"]) } @Test fun `must add allocating officer name`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirements = emptyList<ConvictionRequirement>() val allocateCase = AllocateCase("CRN1111", BigInteger.TEN, "Some Notes", sendEmailCopyToAllocatingOfficer = false, eventNumber = 1) val allocatingOfficerUsername = "ALLOCATOR" val token = "token" val allocatingOfficer = DeliusStaff(BigInteger.ONE, "ALLOCATOR1", StaffName("Alli", "Cator"), null, null, null, "<EMAIL>") every { communityApiClient.getStaffByUsername(any()) } returns Mono.just(allocatingOfficer) notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals("${allocatingOfficer.staff.forenames} ${allocatingOfficer.staff.surname}", parameters.captured["allocatingOfficerName"]) } @Test fun `must add allocating officer grade`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val mappedGrade = "ALLOCATING OFFICER GRADE" allocatedOfficer.grade = mappedGrade every { communityApiClient.getStaffByUsername(any()) } returns Mono.just(allocatedOfficer) val requirements = emptyList<ConvictionRequirement>() val allocateCase = AllocateCase("CRN1111", BigInteger.TEN, "Some Notes", sendEmailCopyToAllocatingOfficer = false, eventNumber = 1) val allocatingOfficerUsername = "ALLOCATOR" val token = "token" notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token) .block() val parameters = slot<MutableMap<String, Any>>() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, capture(parameters), isNull()) } Assertions.assertEquals(mappedGrade, parameters.captured["allocatingOfficerGrade"]) } @Test fun `must email all addresses supplied`() { val allocatedOfficer = DeliusStaff(BigInteger.ONE, "STFFCDE1", StaffName("Sally", "Socks"), null, null, null, "<EMAIL>") val requirements = emptyList<ConvictionRequirement>() val firstEmail = "<EMAIL>" val secondEmail = "<EMAIL>" val allocateCase = AllocateCase("CRN1111", BigInteger.TEN, "instructions", listOf(firstEmail, secondEmail), false, 1) val allocatingOfficerUsername = "ALLOCATOR" val token = "token" notificationService.notifyAllocation(allocatedOfficer, requirements, allocateCase, allocatingOfficerUsername, token).block() verify(exactly = 1) { notificationClient.sendEmail(templateId, allocatedOfficer.email, any(), isNull()) } verify(exactly = 1) { notificationClient.sendEmail(templateId, firstEmail, any(), isNull()) } verify(exactly = 1) { notificationClient.sendEmail(templateId, secondEmail, any(), isNull()) } } }
4
Kotlin
0
0
f92a7903fdfb943e82c070f87797ff55150bc2e2
30,875
hmpps-workload
MIT License
lib/src/test/kotlin/com/w2sv/kotlinutils/extensions/BooleanKtTest.kt
w2sv
559,967,219
false
{"Kotlin": 4239, "Makefile": 351}
package com.w2sv.kotlinutils.extensions import org.junit.Assert.assertEquals import org.junit.Test class BooleanKtTest { @Test fun toInt() { assertEquals(0, false.toInt()) assertEquals(1, true.toInt()) } @Test fun toNonZeroInt() { assertEquals(-1, false.toNonZeroInt()) assertEquals(1, true.toNonZeroInt()) } }
1
Kotlin
0
0
30352388c6690e4d6440d498b99384bb24193229
370
KotlinUtils
MIT License
maestro-ai/src/main/java/maestro/ai/openai/Response.kt
mobile-dev-inc
476,427,476
false
{"Kotlin": 1025452, "TypeScript": 199278, "Swift": 61726, "JavaScript": 16304, "Shell": 14163, "CSS": 2349, "Smarty": 904, "HTML": 358}
package maestro.ai.openai import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class ChatCompletionResponse( val id: String, val `object`: String, val created: Long, val model: String, @SerialName("system_fingerprint") val systemFingerprint: String? = null, val usage: Usage? = null, val choices: List<Choice>, ) @Serializable data class Usage( @SerialName("prompt_tokens") val promptTokens: Int, @SerialName("completion_tokens") val completionTokens: Int? = null, @SerialName("total_tokens") val totalTokens: Int, ) @Serializable data class Choice( val message: Message, @SerialName("finish_details") val finishDetails: FinishDetails? = null, val index: Int, @SerialName("finish_reason") val finishReason: String? = null, ) @Serializable data class Message( val role: String, val content: String, ) @Serializable data class FinishDetails( val type: String, val stop: String? = null, )
374
Kotlin
273
5,808
e957c5ef248afe672c2ba0bda3c555880a3dc990
1,012
maestro
Apache License 2.0
LibFileDownloader/src/main/java/android/qfh/libs/fileDownloader/Log.kt
ylqd
658,024,878
false
null
package android.qfh.libs.fileDownloader import android.util.Log // ============ debug ===================// private const val TAG = "FileDownloadManager" private const val DEBUG = false internal fun logD(msg: String) { if (DEBUG) { Log.d(TAG, msg) } } internal fun logW(msg: String) { if (DEBUG) { Log.w(TAG, msg) } } // ============ debug ===================//
0
Kotlin
0
0
47d80388c714614ce72b468e7ea8b47b578250f6
399
QfhAndroidLibs
Apache License 2.0
src/main/kotlin/com/nofriends/gigachat/config/WebSocketConfiguration.kt
Nhrot22230
831,207,369
false
{"Kotlin": 31285, "HTML": 11725, "JavaScript": 5252, "CSS": 3780, "Dockerfile": 483}
package com.nofriends.gigachat.config import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Configuration import org.springframework.messaging.simp.config.ChannelRegistration import org.springframework.messaging.simp.config.MessageBrokerRegistry import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer import org.springframework.web.socket.config.annotation.StompEndpointRegistry @Configuration @EnableWebSocketMessageBroker class WebSocketConfiguration : WebSocketMessageBrokerConfigurer { @Autowired private lateinit var loggingInterceptor: LoggingInterceptor override fun configureMessageBroker(config: MessageBrokerRegistry) { config.enableSimpleBroker("/topic", "/queue") config.setApplicationDestinationPrefixes("/app") } override fun registerStompEndpoints(registry: StompEndpointRegistry) { registry .addEndpoint("/ws") .setAllowedOriginPatterns("*") .withSockJS() } override fun configureClientInboundChannel(registration: ChannelRegistration) { registration.interceptors(loggingInterceptor) } }
0
Kotlin
0
1
0d5155e5453b0c201bb7da1df0a903133fd8d2c0
1,232
GigaChatBackEnd
MIT License
src/main/kotlin/de/sambalmueslie/openevent/storage/DataObjectRepository.kt
Black-Forrest-Development
542,810,521
false
{"Kotlin": 334759, "TypeScript": 179633, "HTML": 73007, "SCSS": 3950, "Batchfile": 202}
package de.sambalmueslie.openevent.storage import io.micronaut.data.repository.PageableRepository interface DataObjectRepository<T, O : DataObject> : PageableRepository<O, T> { fun findByIdIn(ids: Set<T>): List<O> }
6
Kotlin
0
1
43cf66668db937150ae8f14078437c1e5a7287e2
222
open-event
Apache License 2.0
clevertap-core/src/test/java/com/clevertap/android/sdk/inapp/images/preload/FilePreloaderExecutorsTest.kt
CleverTap
42,078,482
false
{"Java": 1808395, "Kotlin": 1695745, "HTML": 10233}
package com.clevertap.android.sdk.inapp.images.preload import android.graphics.Bitmap import com.clevertap.android.sdk.TestLogger import com.clevertap.android.sdk.inapp.data.CtCacheType import com.clevertap.android.sdk.inapp.images.FileResourceProvider import com.clevertap.android.sdk.task.MockCTExecutors import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.junit.Test import kotlin.test.assertEquals class FilePreloaderExecutorsTest { private val mockBitmap = mockk<Bitmap>() private val byteArray = ByteArray(10) { pos -> pos.toByte() } private val mFileResourceProvider = mockk<FileResourceProvider>() private val executors = MockCTExecutors() private val logger = TestLogger() private val filePreloader = FilePreloaderExecutors( fileResourceProvider = mFileResourceProvider, logger = logger, executor = executors ) @Test fun `preload image fetches images from all urls`() { val urls = mutableListOf("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k") .map { Pair(it, CtCacheType.IMAGE) } val successUrls = mutableListOf<String>() urls.forEach{ every { mFileResourceProvider.fetchInAppImageV1(it.first) } returns mockBitmap } filePreloader.preloadFilesAndCache(urls, { url -> successUrls.add(url.first) },{},{},{}) urls.forEach{ verify { mFileResourceProvider.fetchInAppImageV1(it.first) } } assertEquals(urls.size, successUrls.size) } @Test fun `preload gifs fetches gif from all urls`() { val urls = mutableListOf("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k") .map { Pair(it, CtCacheType.GIF) } val successUrls = mutableListOf<String>() // replace with forEach urls.forEach{ every { mFileResourceProvider.fetchInAppGifV1(it.first) } returns byteArray } filePreloader.preloadFilesAndCache(urls, { url -> successUrls.add(url.first) },{},{},{}) // replace with forEach urls.forEach{ verify { mFileResourceProvider.fetchInAppGifV1(it.first) } } assertEquals(urls.size, successUrls.size) } @Test fun `preload files fetches files from all urls`() { val urls = mutableListOf("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k") .map { Pair(it, CtCacheType.FILES) } val successUrls = mutableListOf<String>() // replace with forEach urls.forEach{ every { mFileResourceProvider.fetchFile(it.first) } returns byteArray } filePreloader.preloadFilesAndCache(urls, { url -> successUrls.add(url.first) },{},{},{}) urls.forEach { verify { mFileResourceProvider.fetchFile(it.first) } } assertEquals(urls.size, successUrls.size) } @Test fun `preloadFilesAndCache invokes all callbacks for images`() { val urls = listOf("a", "b", "c").map { Pair(it, CtCacheType.IMAGE) } val successUrls = mutableListOf<String>() val failureUrls = mutableListOf<String>() val startedUrls = mutableListOf<String>() val finishedStatus = mutableMapOf<String, Boolean>() urls.forEach { every { mFileResourceProvider.fetchInAppImageV1(it.first) } returns if (it.first == "b") null else mockBitmap // Simulate failure for "b" } filePreloader.preloadFilesAndCache( urls, successBlock = { url -> successUrls.add(url.first) }, failureBlock = { url -> failureUrls.add(url.first) }, startedBlock = { url -> startedUrls.add(url.first) }, preloadFinished = { status -> finishedStatus.putAll(status) } ) assertEquals(listOf("a", "c"), successUrls) assertEquals(listOf("b"), failureUrls) assertEquals(listOf("a", "b", "c"), startedUrls) assertEquals(mapOf("a" to true, "b" to false, "c" to true), finishedStatus) } @Test fun `preloadFilesAndCache invokes all callbacks for GIFs`() { val urls = listOf("x", "y", "z").map { Pair(it, CtCacheType.GIF) } val successUrls = mutableListOf<String>() val failureUrls = mutableListOf<String>() val startedUrls = mutableListOf<String>() val finishedStatus = mutableMapOf<String, Boolean>() urls.forEach { every { mFileResourceProvider.fetchInAppGifV1(it.first) } returns if (it.first == "y") null else byteArray // Simulate failure for "y" } filePreloader.preloadFilesAndCache( urls, successBlock = { url -> successUrls.add(url.first) }, failureBlock = { url -> failureUrls.add(url.first) }, startedBlock = { url -> startedUrls.add(url.first) }, preloadFinished = { status -> finishedStatus.putAll(status) } ) assertEquals(listOf("x", "z"), successUrls) assertEquals(listOf("y"), failureUrls) assertEquals(listOf("x", "y", "z"), startedUrls) assertEquals(mapOf("x" to true, "y" to false, "z" to true), finishedStatus) } @Test fun `preloadFilesAndCache invokes all callbacks for files`() { val urls = listOf("p", "q", "r").map { Pair(it, CtCacheType.FILES) } val successUrls = mutableListOf<String>() val failureUrls = mutableListOf<String>() val startedUrls = mutableListOf<String>() val finishedStatus = mutableMapOf<String, Boolean>() urls.forEach { every { mFileResourceProvider.fetchFile(it.first) } returns if (it.first == "q") null else byteArray //Simulate failure for "q" } filePreloader.preloadFilesAndCache( urls, successBlock = { url -> successUrls.add(url.first) }, failureBlock = { url -> failureUrls.add(url.first) }, startedBlock = { url -> startedUrls.add(url.first) }, preloadFinished = { status -> finishedStatus.putAll(status) } ) assertEquals(listOf("p", "r"), successUrls) assertEquals(listOf("q"), failureUrls) assertEquals(listOf("p", "q", "r"), startedUrls) assertEquals(mapOf("p" to true, "q" to false, "r" to true), finishedStatus) } }
9
Java
74
80
2968228861fc6584424c28e30ddc570994465d79
6,602
clevertap-android-sdk
MIT License
features/hiring/ui/src/main/java/io/github/rysanekrivera/ui/viewmodels/HiringViewModel.kt
RysanekRivera
864,401,973
false
{"Kotlin": 59167}
package io.github.rysanekrivera.ui.viewmodels import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import io.github.rysanekrivera.common.uiEvents.UiEvent import io.github.rysanekrivera.common.uistate.UiState import io.github.rysanekrivera.common.utils.updateValue import io.github.rysanekrivera.domain.repositories.HiringRepository import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class HiringViewModel @Inject constructor( private val hiringRepository: HiringRepository ): ViewModel() { private val _state = MutableStateFlow(UiState()) val state = _state.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), _state.value) private val _uiEvents = MutableSharedFlow<UiEvent>() val uiEvents = _uiEvents fun getAllEmployees() = viewModelScope.launch { _state.updateValue { markLoading() } runCatching { hiringRepository.getAllEmployees() }.onSuccess { response -> _state.updateValue { successResponse(response) } }.onFailure { e -> _state.updateValue { errorResponse(e) } } } fun navigateToEmployeeDetails(employeeId: Int) = viewModelScope.launch { _uiEvents.emit(UiEvent.NavigateToEmployeeDetails(employeeId)) } fun onShowEmployeeSnackBar(message: String) = viewModelScope.launch { _uiEvents.emit(UiEvent.ShowSnackBar(message)) } fun onShowAlertDialog( message: String, positiveText: String? = null, negativeText: String? = null, neutralText: String? = null, positiveAction: (() -> Unit)? = null, negativeAction: (() -> Unit)? = null, neutralAction: (() -> Unit)? = null ) = viewModelScope.launch { _uiEvents.emit( UiEvent.ShowAlertDialog( message, positiveText, negativeText, neutralText, positiveAction, negativeAction, neutralAction ) ) } }
0
Kotlin
0
0
c25dfa5774c750fa1d661f2849198a8f04ac3540
2,298
Hiring
Apache License 2.0
app/src/test/java/org/wikipedia/descriptions/DescriptionEditClientTest.kt
wikimedia
13,862,999
false
{"Kotlin": 3495497, "Python": 24797, "Java": 4408, "Jinja": 533, "Shell": 521}
package org.wikipedia.descriptions import kotlinx.coroutines.runBlocking import org.hamcrest.MatcherAssert import org.hamcrest.Matchers import org.junit.Test import org.mockito.Mockito import org.wikipedia.dataclient.WikiSite import org.wikipedia.dataclient.mwapi.MwException import org.wikipedia.dataclient.wikidata.EntityPostResponse import org.wikipedia.page.Namespace import org.wikipedia.page.Page import org.wikipedia.page.PageProperties import org.wikipedia.page.PageTitle import org.wikipedia.test.MockRetrofitTest import java.util.regex.Pattern class DescriptionEditClientTest : MockRetrofitTest() { @Test fun testEditLocalDescriptionWithRegex() { val text = "test test test test {{Short description|This is a description.}} foo foo {{Another template|12345}} foo foo" val newText = text.replaceFirst( DescriptionEditViewModel.TEMPLATE_PARSE_REGEX.toRegex(), "$1" + "New description." + "$3" ) MatcherAssert.assertThat( Pattern.compile(DescriptionEditViewModel.TEMPLATE_PARSE_REGEX).matcher(text).find(), Matchers.`is`(true) ) MatcherAssert.assertThat( newText, Matchers.`is`("test test test test {{Short description|New description.}} foo foo {{Another template|12345}} foo foo") ) } @Test fun testRegexWithNoLocalDescription() { val text = "test test test test foo foo {{Another template|12345}} foo foo" MatcherAssert.assertThat( Pattern.compile(DescriptionEditViewModel.TEMPLATE_PARSE_REGEX).matcher(text).find(), Matchers.`is`(false) ) } @Test @Throws(Throwable::class) fun testRequestPostDescriptionSuccess() { enqueueFromFile("description_edit.json") runBlocking { requestPostDescription() }.run { MatcherAssert.assertThat(entity?.id, Matchers.`is`("Q123")) } } @Test @Throws(Throwable::class) fun testRequestPostLabelSuccess() { enqueueFromFile("label_edit.json") runBlocking { requestPostLabel() }.run { MatcherAssert.assertThat(entity?.id, Matchers.`is`("Q456")) } } @Test @Throws(Throwable::class) fun testRequestAbusefilterWarning() { enqueueFromFile("description_edit_abusefilter_warning.json") val expectedCode = "abusefilter-warning" val expectedMessage = "<b>Warning:</b> This action has been automatically identified as harmful.\nUnconstructive edits will be quickly reverted,\nand egregious or repeated unconstructive editing will result in your account or IP address being blocked.\nIf you believe this action to be constructive, you may submit it again to confirm it.\nA brief description of the abuse rule which your action matched is: Possible vandalism by adding badwords or similar trolling words" runBlocking { try { requestPostDescription() } catch (e: Exception) { MatcherAssert.assertThat(testErrorWithExpectedCodeAndMessage(e, expectedCode, expectedMessage), Matchers.`is`(true)) } } } @Test @Throws(Throwable::class) fun testRequestAbusefilterDisallowed() { enqueueFromFile("description_edit_abusefilter_disallowed.json") val expectedCode = "abusefilter-disallowed" val expectedMessage = "This action has been automatically identified as harmful, and therefore disallowed.\nIf you believe your action was constructive, please inform an administrator of what you were trying to do." runBlocking { try { requestPostDescription() } catch (e: Exception) { MatcherAssert.assertThat(testErrorWithExpectedCodeAndMessage(e, expectedCode, expectedMessage), Matchers.`is`(true)) } } } @Test @Throws(Throwable::class) fun testRequestResponseApiError() { enqueueFromFile("api_error.json") runBlocking { try { requestPostDescription() } catch (e: Exception) { MatcherAssert.assertThat(e, Matchers.notNullValue()) } } } @Test @Throws(Throwable::class) fun testRequestResponseFailure() { enqueueFromFile("description_edit_unknown_site.json") runBlocking { try { requestPostDescription() } catch (e: Exception) { MatcherAssert.assertThat(e, Matchers.notNullValue()) } } } @Test @Throws(Throwable::class) fun testRequestResponseMalformed() { enqueueMalformed() runBlocking { try { requestPostDescription() } catch (e: Exception) { MatcherAssert.assertThat(e, Matchers.notNullValue()) } } } @Test fun testIsEditAllowedSuccess() { val wiki = WikiSite.forLanguageCode("ru") val props = Mockito.mock(PageProperties::class.java) Mockito.`when`(props.wikiBaseItem).thenReturn("Q123") Mockito.`when`(props.canEdit).thenReturn(true) Mockito.`when`(props.descriptionSource).thenReturn("central") Mockito.`when`(props.namespace).thenReturn(Namespace.MAIN) val page = Page(PageTitle("Test", wiki), pageProperties = props) MatcherAssert.assertThat(DescriptionEditUtil.isEditAllowed(page), Matchers.`is`(true)) } @Test fun testIsEditAllowedNoWikiBaseItem() { val wiki = WikiSite.forLanguageCode("ru") val props = Mockito.mock(PageProperties::class.java) Mockito.`when`(props.wikiBaseItem).thenReturn(null) Mockito.`when`(props.namespace).thenReturn(Namespace.MAIN) val page = Page(PageTitle("Test", wiki), pageProperties = props) MatcherAssert.assertThat(DescriptionEditUtil.isEditAllowed(page), Matchers.`is`(false)) } private fun testErrorWithExpectedCodeAndMessage(caught: Exception, expectedCode: String, expectedMessage: String): Boolean { if (caught is MwException) { val error = caught.error return error.hasMessageName(expectedCode) && error.getMessageHtml(expectedCode) == expectedMessage } else { return false } } private suspend fun requestPostDescription(): EntityPostResponse { val pageTitle = PageTitle("foo", WikiSite.forLanguageCode("en")) return apiService.postDescriptionEdit( pageTitle.wikiSite.languageCode, pageTitle.wikiSite.languageCode, pageTitle.wikiSite.dbName(), pageTitle.prefixedText, "some new description", "summary", MOCK_EDIT_TOKEN, null ) } private suspend fun requestPostLabel(): EntityPostResponse { val pageTitle = PageTitle("foo", WikiSite.forLanguageCode("en")) return apiService.postLabelEdit( pageTitle.wikiSite.languageCode, pageTitle.wikiSite.languageCode, pageTitle.wikiSite.dbName(), pageTitle.prefixedText, "some new label", "summary", MOCK_EDIT_TOKEN, null ) } companion object { private const val MOCK_EDIT_TOKEN = "+\\" } }
29
Kotlin
624
2,365
175db9fe3c28084af7290a934f38223eb14934ed
7,306
apps-android-wikipedia
Apache License 2.0
app/src/main/java/com/tanjiajun/jsonrecyclerview/utils/StringUtils.kt
TanJiaJunBeyond
372,248,347
false
null
package com.tanjiajun.jsonrecyclerview.utils import java.util.regex.Pattern /** * Created by TanJiaJun on 5/29/21. */ private val urlPattern: Pattern = Pattern.compile( // 验证是否是http://、https://、ftp://、rtsp://、mms://其中一个 "^((http|https|ftp|rtsp|mms)?://)?" + // 判断字符是否为FTP地址(ftp://user:password@) // 判断字符是否为0到9、小写字母a到z、_、!、~、*、'、(、)、.、&、=、+、$、%、-其中一个,匹配零次或者一次 "(([0-9a-z_!~*'().&=+\$%-]+: )?" + // 判断字符是否为0到9、小写字母a到z、_、!、~、*、'、(、)、.、&、=、+、$、%、-其中一个,匹配一次或者多次 "[0-9a-z_!~*'().&=+\$%-]+" + // @ "@)?" + // 判断字符是否为IP地址,例子:192.168.255.255 // 判断字符是否匹配1+[0到9,匹配两次],例如:192 "((1\\d{2}" + // 或者 "|" + // 判断字符是否匹配2+[0到4,匹配一次]+[0到9,匹配一次],例如:225 "2[0-4]\\d" + // 或者 "|" + // 判断字符是否匹配25+[0到5,匹配一次],例如:255 "25[0-5]" + // 或者 "|" + // 判断字符是否匹配[1到9,匹配一次]+[0到9,匹配一次],例如:25 "[1-9]\\d" + // 或者 "|" + // 判断字符是否匹配1到9,匹配一次,例如:5 "[1-9])" + // 判断字符是否匹配\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d),匹配三次 "(\\.(" + // 判断字符是否匹配1+[0到9,匹配两次],例如:192 "1\\d{2}" + // 或者 "|" + // 判断字符是否匹配2+[0到4,匹配一次]+[0到9,匹配一次],例如:225 "2[0-4]\\d" + // 或者 "|" + // 判断字符是否匹配25+[0到5,匹配一次],例如:255 "25[0-5]" + // 或者 "|" + // 判断字符是否匹配[1到9]+[0到9],例如:25 "[1-9]\\d" + // 或者 "|" + // 判断字符是否匹配0到9,匹配一次,例如:5 "\\d))" + // 匹配三次 "{3}" + // 或者 "|" + // 判断字符是否为域名(Domain Name) // 三级域名或者以上,判断字符是否为0到9、小写字母a到z、_、!、~、*、'、(、)、-其中一个,匹配零次或者多次,然后加上.,例如:www. "([0-9a-z_!~*'()-]+\\.)*" + // 二级域名,长度不能超过63个字符,先判断第一个字符是否为0到9、小写字母a到z其中一个,匹配一次,然后判断第二个字符是否为0到9、小写字母a到z、-其中一个,最多匹配61次,这两个字符匹配零次或者一次,最后判断第三个字符是否为0到9、小写字母a到z其中一个,然后加上. "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]" + // 顶级域名,判断字符是否为小写字母a到z其中一个,匹配最少两次、最多六次,例如:.com、.cn "\\.[a-z]{2,6})" + // 端口号,判断字符是否匹配:+[0到9,匹配最少一次、最多四次],匹配零次或者一次 "(:[0-9]{1,4})?" + // 判断字符是否为斜杠(/),匹配零次或者一次,如果没有文件名,就不需要斜杠 "((/?)|" + // 判断字符是否为0到9、小写字母a到z、大写字母A到Z、_、!、~、*、'、(、)、.、;、?、:、@、&、=、+、$、,、%、#、-其中一个,匹配一次或者多次 "(/[0-9a-zA-Z_!~*'(){}.;?:@&=+\$,%#-]+)+" + // 判断字符是否为斜杠(/),匹配零次或者一次 "/?)\$" ) /** * Determine if it is a URL. * 判断是否为url。 * * @param str The string to be matched. * @return Whether the result is a URL. */ fun isUrl(str: String) = urlPattern.matcher(str).matches() /** * Get hierarchy string. * 得到带有层次结构的的字符串。 * * @param hierarchy The hierarchy. * @return The hierarchy string. */ fun getHierarchyStr(hierarchy: Int): String = StringBuilder() .apply { for (i in 0 until hierarchy) { // 空四格 append("\r\r\r\r") } } .toString() /** * Format the JSON to indent. * 对JSON格式化缩进 * * @param jsonStr The json string. * @return The json string that have been formatted and indented. */ fun jsonFormat(jsonStr: String): String = StringBuilder() .apply { var level = 0 for (i in jsonStr.indices) { val char = jsonStr[i] if (level > 0 && '\n' == toString()[length - 1]) append(getHierarchyStr(level)) when (char) { '{', '[' -> { append(char).append("\n") level++ } ',' -> append(char).append("\n") '}', ']' -> { append("\n") level-- append(getHierarchyStr(level)) append(char) } else -> append(char) } } } .toString()
1
Kotlin
1
29
57fb967b637f160e20fd618fbbd15d8323bccad2
4,211
JSONRecyclerView
Apache License 2.0
ksp-xposed/src/main/java/mufanc/easyhook/api/IXposedEntry.kt
Mufanc
460,466,174
false
{"Kotlin": 26558}
package mufanc.easyhook.api import de.robv.android.xposed.IXposedHookLoadPackage import de.robv.android.xposed.IXposedHookZygoteInit interface IXposedEntry : IXposedHookZygoteInit, IXposedHookLoadPackage
0
Kotlin
3
9
e812a2808b0aab66e83ed3e5e646bdb7f1ffa3dc
206
EasyHook
MIT License
app/src/main/kotlin/com/example/siuang_apps/MainActivity.kt
vernandaspw
811,377,300
false
{"Kotlin": 124}
package com.example.siuang_apps import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity()
0
Kotlin
0
0
4708b7304dc7d6b750f5ebd586b6428adc22e481
124
siuang
Apache License 2.0
app/src/main/java/com/example/kernel/presentation/shared/MainTopAppBar.kt
BENJAHJP
592,411,726
false
null
package com.example.kernel.presentation.shared import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.TopAppBarScrollBehavior import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.unit.dp @OptIn(ExperimentalMaterial3Api::class) @Composable fun MainTopAppBar( scrollBehavior: TopAppBarScrollBehavior? = null, title: String, navigationIcon: ImageVector, actions: ImageVector? = null, onClickNavigation: () -> Unit, onClickAction: () -> Unit ) { TopAppBar( scrollBehavior = scrollBehavior, modifier = Modifier.padding(5.dp), colors = TopAppBarDefaults.smallTopAppBarColors( containerColor = Color.Transparent, navigationIconContentColor = Color.White ), navigationIcon = { Button( modifier = Modifier.size(50.dp), shape = CircleShape, colors = ButtonDefaults.buttonColors( containerColor = Color.White, ), contentPadding = PaddingValues(10.dp), elevation = ButtonDefaults.buttonElevation( defaultElevation = 5.dp, pressedElevation = 5.dp, focusedElevation = 5.dp, hoveredElevation = 5.dp, ), onClick = { onClickNavigation() } ){ Icon( tint = Color.Black, imageVector = navigationIcon, contentDescription = "") } }, actions = { if (actions != null) { Button( modifier = Modifier.size(50.dp), colors = ButtonDefaults.buttonColors( containerColor = Color.White, ), contentPadding = PaddingValues(0.dp), elevation = ButtonDefaults.buttonElevation( defaultElevation = 5.dp, pressedElevation = 5.dp, focusedElevation = 5.dp, hoveredElevation = 5.dp, ), shape = CircleShape , onClick = { onClickAction() }) { Icon( tint = Color.Black, imageVector = actions, contentDescription = "") } } }, title = { Text(text = title) } ) }
0
Kotlin
0
1
9930fb6d6873d82fc941605b642f77369cdd1b8c
3,178
Yum
MIT License
src/test/kotlin/com/southsun/refapp/RefAppApplicationTests.kt
marcinziolo
418,817,955
false
{"Kotlin": 7133}
package com.southsun.refapp import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class RefAppApplicationTests { @Test fun contextLoads() { } }
0
Kotlin
0
0
5be4621e61a05c441e98a8e5877103cf835c1540
216
active-mq-example
Enlightenment License (e16)
fourthline/src/main/java/de/solarisbank/sdk/fourthline/feature/ui/intro/FourthlineIntroViewModel.kt
Solarisbank
336,233,277
false
{"Kotlin": 468986, "Java": 6478, "Shell": 1215}
package de.solarisbank.sdk.fourthline.feature.ui.intro import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import de.solarisbank.sdk.data.utils.IdenthubDispatchers import de.solarisbank.sdk.data.utils.update import de.solarisbank.sdk.domain.model.ResultState import de.solarisbank.sdk.fourthline.data.FourthlineStorage import de.solarisbank.sdk.fourthline.data.dto.TermsAndConditions import de.solarisbank.sdk.fourthline.data.terms.TermsAndConditionsUseCase import de.solarisbank.sdk.logger.IdLogger import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class FourthlineIntroViewModel( private val fourthlineStorage: FourthlineStorage, private val termsAndConditionsUseCase: TermsAndConditionsUseCase, private val dispatchers: IdenthubDispatchers ): ViewModel() { private val viewState = MutableLiveData<FourthlineIntroState>() fun state(): LiveData<FourthlineIntroState> = viewState init { viewState.value = FourthlineIntroState( namirialTerms = fourthlineStorage.namirialTerms, acceptState = ResultState.Unknown() ) } fun onAction(action: FourthlineIntroAction) { when (action) { is FourthlineIntroAction.NextTapped -> { acceptTermsAndContinue() } } } private fun acceptTermsAndContinue() { viewModelScope.launch { try { viewState.update { copy(acceptState = ResultState.Loading()) } withContext(dispatchers.IO) { fourthlineStorage.namirialTerms?.documentId?.let { termsAndConditionsUseCase.acceptNamirialTerms(it) } } viewState.update { copy(acceptState = ResultState.Success(Unit)) } } catch (throwable: Throwable) { IdLogger.error("Error accepting terms", throwable) viewState.update { copy(acceptState = ResultState.Failure(throwable)) } } } } } sealed class FourthlineIntroAction { object NextTapped: FourthlineIntroAction() } data class FourthlineIntroState( val namirialTerms: TermsAndConditions?, val acceptState: ResultState<Unit>, )
0
Kotlin
0
6
1d3ffe547767d49c6a81c4198469c2b491648c83
2,335
identhub-android
MIT License
client/src/test/kotlin/CafetFilesTests.kt
defvs
740,113,757
false
{"Kotlin": 10761}
import dev.defvs.cafet.client.files.CafetFolder.Companion.findSuitableCafetFolders import io.kotest.core.spec.style.FunSpec import kotlin.io.path.Path class CafetFilesTests : FunSpec({ test("Find compatible folders") { val rootFolder = Path("""C:\Users\danie\Desktop\testmusic\""") rootFolder.findSuitableCafetFolders().also { println(it.joinToString()) } } })
0
Kotlin
0
1
21c51ef71ea95761f17cfcfbe9b2ba0a27cf1231
372
cafet
MIT License
app/src/main/java/com/paz/velocity_recorder/db/DataDao.kt
pandegaabyan
721,376,869
false
{"Kotlin": 86077}
package com.paz.velocity_recorder.db import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query @Dao interface DataDao { // rides table @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun addRide(ride: RideEntity): Long @Query("SELECT * FROM rides ORDER BY created_at DESC") fun getLiveRides(): LiveData<List<RideEntity>> @Query("SELECT * FROM rides WHERE is_running ORDER BY created_at ASC LIMIT 1") suspend fun getRunningRide(): RideEntity? @Query( "UPDATE rides SET end_time = :endTime, distance = :distance, " + "max_velocity = :maxVelocity, is_running = :isRunning WHERE id = :id" ) suspend fun updateRide( id: Long, endTime: Long, distance: Int, maxVelocity: Double, isRunning: Boolean = true ) @Query("UPDATE rides SET start_locality = :startLocality, end_locality = :endLocality WHERE id = :id") suspend fun updateRideLocality( id: Long, startLocality: String, endLocality: String, ) @Query("UPDATE rides SET is_running = 0 WHERE is_running") suspend fun stopRunningRide() @Query("DELETE FROM rides WHERE id = :id") suspend fun deleteRide(id: Long) // velocities table @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun addVelocities(velocities: List<VelocityEntity>) @Query("SELECT * FROM velocities WHERE ride_id = :rideId ORDER BY timestamp ASC") fun getLiveVelocities(rideId: Long): LiveData<List<VelocityEntity>> @Query("SELECT * FROM velocities WHERE ride_id = :rideId ORDER BY timestamp ASC") suspend fun getVelocities(rideId: Long): List<VelocityEntity> @Query("DELETE FROM velocities WHERE ride_id = :rideId") suspend fun deleteVelocities(rideId: Long) @Query( "SELECT * FROM (SELECT * FROM velocities WHERE ride_id = :rideId ORDER BY timestamp ASC LIMIT 1)" + " UNION " + "SELECT * FROM (SELECT * FROM velocities WHERE ride_id = :rideId ORDER BY timestamp DESC LIMIT 1)" + "ORDER BY timestamp ASC" ) suspend fun getStartEndVelocities(rideId: Long): List<VelocityEntity> }
0
Kotlin
0
1
9c41eb726896b2a6cb71d5569d2203ee88768acb
2,281
velocity-recorder-app
MIT License
opensrp-unicef-tunisia/src/test/java/org/smartregister/uniceftunisia/reporting/register/ReportRegisterPresenterTest.kt
opensrp
261,193,229
false
{"Java": 364131, "Kotlin": 198622}
package org.smartregister.uniceftunisia.reporting.register import android.app.Activity import io.mockk.justRun import io.mockk.mockkClass import io.mockk.unmockkAll import io.mockk.verify import org.junit.After import org.junit.Assert.assertNotNull import org.junit.Before import org.junit.Test import org.smartregister.uniceftunisia.reporting.ReportGroup class ReportRegisterPresenterTest { private val view: ReportRegisterContract.View = mockkClass(ReportRegisterActivity::class, relaxed = true) private lateinit var reportRegisterPresenter: ReportRegisterPresenter @Before fun `Before every test`() { reportRegisterPresenter = ReportRegisterPresenter(view) } @After fun `After every test`() { unmockkAll() } @Test fun `Should start monthly report`() { justRun { (view as Activity).startActivity(any()) } reportRegisterPresenter.startReport(ReportGroup.MONTHLY_REPORTS) verify {(view as Activity).startActivity(any()) } } @Test fun `Should start annual coverage report`() { justRun { (view as Activity).startActivity(any()) } reportRegisterPresenter.startReport(ReportGroup.ANNUAL_COVERAGE_REPORTS) verify {(view as Activity).startActivity(any()) } } @Test fun `Should return non null view`() { assertNotNull(reportRegisterPresenter.reportRegisterView) } }
13
Java
1
0
09130dc7ddb457d1234d4da20da5234819cfde3c
1,410
opensrp-client-unicef-tunisia
Apache License 2.0
app/src/main/java/com/ijs/abminder/calculator/options/AmortizationFragment.kt
ijscreate
785,375,972
false
{"Kotlin": 868465, "Roff": 59377, "AIDL": 765, "CSS": 156}
package com.ijs.abminder.calculator.options import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TableLayout import android.widget.TableRow import android.widget.TextView import android.widget.Toast import androidx.fragment.app.Fragment import com.calculator.calculatoroptions.R import com.google.android.material.textfield.TextInputEditText import com.google.android.material.textfield.TextInputLayout import com.google.android.material.textview.MaterialTextView import com.ijs.abminder.calculator.CalculatorOptionsActivity import kotlin.math.pow class AmortizationFragment : Fragment() { private lateinit var stepTextView : TextView private lateinit var stepInputLayout : TextInputLayout private lateinit var stepInputEditText : TextInputEditText private lateinit var nextButton : Button private lateinit var tableLayout : TableLayout private var currentStep = 1 private var loanAmount : Double? = null private var interestRate : Double? = null private var loanTerm : Double? = null private var monthlyInterestRate : Double? = null private var totalPayments : Double? = null private var monthlyPayment : Double? = null override fun onCreateView( inflater : LayoutInflater, container : ViewGroup?, savedInstanceState : Bundle?, ) : View? { val rootView = inflater.inflate(R.layout.fragment_amortization_schedule, container, false) stepTextView = rootView.findViewById(R.id.stepTextView) stepInputLayout = rootView.findViewById(R.id.stepInputLayout) stepInputEditText = rootView.findViewById(R.id.stepInputEditText) nextButton = rootView.findViewById(R.id.nextButton) tableLayout = rootView.findViewById(R.id.tableLayoutAmortization) setupStep(currentStep) nextButton.setOnClickListener { handleNextStep() } val desc = """ Calculate an amortization schedule to determine the monthly payments on a loan, including the interest and principal components. Formula: Monthly Payment = (Loan Amount * Monthly Interest Rate) / (1 - (1 + Monthly Interest Rate)^(-Total Payments)) Example: Suppose you take out a loan of ₱100,000 with an interest rate of 5% per annum for 3 years. The monthly payment would be calculated as follows: 1. Calculate the monthly interest rate: Monthly Interest Rate = Annual Interest Rate / 12 = 5% / 12 = 0.05 / 12 = 0.004167 (approximately) 2. Calculate the total number of payments: Total Payments = Loan Term (in years) * 12 = 3 * 12 = 36 3. Calculate the monthly payment using the formula: Monthly Payment = (Loan Amount * Monthly Interest Rate) / (1 - (1 + Monthly Interest Rate)^(-Total Payments)) = (100000 * 0.004167) / (1 - (1 + 0.004167)^(-36)) This calculation yields the monthly payment amount. 4. Generate the amortization schedule, which breaks down each payment into its principal and interest components, along with the remaining balance. Month | Payment | Principal | Interest | Balance -------------------------------------------------------- 1 | ₱2963.57 | ₱588.57 | ₱2375.00 | ₱99411.43 2 | ₱2963.57 | ₱592.10 | ₱2371.47 | ₱98819.33 3 | ₱2963.57 | ₱595.64 | ₱2367.93 | ₱98223.69 ... | ... | ... | ... | ... 36 | ₱2963.57 | ₱2922.85 | ₱40.72 | ₱0.00 This amortization schedule provides a detailed breakdown of each payment, helping you understand how much of each payment goes towards interest and principal, and how the loan balance decreases over time. """.trimIndent() rootView.findViewById<MaterialTextView>(R.id.descriptionTextView).text = desc return rootView } private fun setupStep(step : Int) { when (step) { 1 -> { stepTextView.text = getString(com.ijs.abminder.R.string.step_1_input_loan_amount) stepInputLayout.hint = getString(R.string.loan_amount) stepInputEditText.setText("") } 2 -> { stepTextView.text = getString(com.ijs.abminder.R.string.step_2_input_interest_rate) stepInputLayout.hint = getString(R.string.interest_rate) stepInputEditText.setText("") } 3 -> { stepTextView.text = getString(com.ijs.abminder.R.string.step_3_input_loan_term) stepInputLayout.hint = getString(R.string.loan_term_years) stepInputEditText.setText("") } 4 -> { stepTextView.text = getString(com.ijs.abminder.R.string.step_4_calculate_monthly_interest_rate) stepInputLayout.hint = getString( com.ijs.abminder.R.string.step_4_monthly_interest_rate_hint, interestRate, 12 ) stepInputEditText.setText("") } 5 -> { stepTextView.text = getString(com.ijs.abminder.R.string.step_5_calculate_monthly_payment) stepInputLayout.visibility = View.GONE calculateMonthlyPayment() generateAmortizationTable() } } } private fun handleNextStep() { when (currentStep) { 1 -> { val input = stepInputEditText.text.toString().toDoubleOrNull() if (input != null) { loanAmount = input currentStep = 2 setupStep(currentStep) } else { showInputErrorToast() } } 2 -> { val input = stepInputEditText.text.toString().toDoubleOrNull() if (input != null) { interestRate = input currentStep = 3 setupStep(currentStep) } else { showInputErrorToast() } } 3 -> { val input = stepInputEditText.text.toString().toDoubleOrNull() if (input != null) { loanTerm = input currentStep = 4 setupStep(currentStep) } else { showInputErrorToast() } } 4 -> { val input = stepInputEditText.text.toString().toDoubleOrNull() if (input != null) { val expectedMonthlyInterestRate = interestRate!! / 12 / 100 if (input == expectedMonthlyInterestRate) { monthlyInterestRate = input currentStep = 5 setupStep(currentStep) } else { showMonthlyInterestRateErrorToast() } } else { showInputErrorToast() } } } } private fun calculateMonthlyPayment() { totalPayments = loanTerm!! * 12 val denominator = (1 + monthlyInterestRate!!).pow(totalPayments!!) - 1 monthlyPayment = loanAmount!! * monthlyInterestRate!! * (1 + monthlyInterestRate!!).pow(totalPayments!!) / denominator } private fun generateAmortizationTable() { tableLayout.removeAllViews() // Clear the table // Add table headers val headerRow = TableRow(context) headerRow.addView(createTableCell("Month")) headerRow.addView(createTableCell("Payment")) headerRow.addView(createTableCell("Principal")) headerRow.addView(createTableCell("Interest")) headerRow.addView(createTableCell("Balance")) tableLayout.addView(headerRow) var balance = loanAmount!! for (month in 1..totalPayments!!.toInt()) { val interest = balance * monthlyInterestRate!! val principal = monthlyPayment!! - interest balance -= principal val row = TableRow(context) row.addView(createTableCell(month.toString())) row.addView(createTableCell(String.format("₱%.2f", monthlyPayment))) row.addView(createTableCell(String.format("₱%.2f", principal))) row.addView(createTableCell(String.format("₱%.2f", interest))) row.addView(createTableCell(String.format("₱%.2f", balance))) tableLayout.addView(row) } } private fun createTableCell(text : String) : TextView { val cell = TextView(context) cell.text = text cell.setPadding(16, 16, 16, 16) return cell } private fun showInputErrorToast() { Toast.makeText(requireContext(), R.string.invalid_input, Toast.LENGTH_SHORT).show() } private fun showMonthlyInterestRateErrorToast() { Toast.makeText( requireContext(), com.ijs.abminder.R.string.incorrect_monthly_interest_rate, Toast.LENGTH_SHORT ).show() } override fun onDestroy() { val activity = requireActivity() as CalculatorOptionsActivity activity.toolbar.title = getString(com.ijs.abminder.R.string.calculator) (activity).enableRecyclerView() super.onDestroy() } }
0
Kotlin
0
1
6f85983cdeac02532df43157d7ae570a057a77c9
10,176
ABMinder
MIT License
themes/new-ui/new-ui-standalone/src/main/kotlin/org/jetbrains/jewel/themes/expui/standalone/control/TextArea.kt
JetBrains
440,164,967
false
null
package org.jetbrains.jewel.themes.expui.standalone.control import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsFocusedAsState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.takeOrElse import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.Placeable import androidx.compose.ui.layout.layoutId import androidx.compose.ui.text.TextLayoutResult import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.offset import org.jetbrains.jewel.themes.expui.standalone.style.LocalAreaColors import org.jetbrains.jewel.themes.expui.standalone.style.LocalDefaultTextStyle import org.jetbrains.jewel.themes.expui.standalone.style.areaBackground import org.jetbrains.jewel.themes.expui.standalone.style.areaBorder import org.jetbrains.jewel.themes.expui.standalone.style.areaFocusBorder import kotlin.math.max @Composable fun TextArea( value: String, onValueChange: (String) -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, readOnly: Boolean = false, textStyle: TextStyle = LocalDefaultTextStyle.current, placeholder: @Composable (() -> Unit)? = null, footer: @Composable (() -> Unit)? = null, isError: Boolean = false, visualTransformation: VisualTransformation = VisualTransformation.None, keyboardOptions: KeyboardOptions = KeyboardOptions.Default, keyboardActions: KeyboardActions = KeyboardActions(), maxLines: Int = Int.MAX_VALUE, onTextLayout: (TextLayoutResult) -> Unit = {}, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, shape: Shape = RectangleShape, colors: TextFieldColors = LocalTextFieldColors.current ) { val focused = interactionSource.collectIsFocusedAsState() colors.provideArea(enabled, focused.value, isError) { val currentColors = LocalAreaColors.current val textColor = textStyle.color.takeOrElse { currentColors.text } val mergedTextStyle = textStyle.merge(TextStyle(color = textColor)) BasicTextField( value = value, onValueChange = onValueChange, modifier = modifier.defaultMinSize(minWidth = 270.dp, minHeight = 55.dp), enabled = enabled, readOnly = readOnly, textStyle = mergedTextStyle, keyboardOptions = keyboardOptions, keyboardActions = keyboardActions, singleLine = false, maxLines = maxLines, visualTransformation = visualTransformation, onTextLayout = onTextLayout, interactionSource = interactionSource, cursorBrush = SolidColor(currentColors.text) ) { TextAreaDecorationBox( focused = focused.value, shape = shape, innerTextField = it, placeholder = if (value.isEmpty()) placeholder else null, footer = footer ) } } } @Composable private fun TextAreaDecorationBox( focused: Boolean, shape: Shape, innerTextField: @Composable () -> Unit, placeholder: @Composable (() -> Unit)? = null, footer: @Composable (() -> Unit)? = null ) { Layout( modifier = Modifier.areaBackground(shape = shape).areaFocusBorder(focused, shape = shape) .areaBorder(shape = shape), content = { if (footer != null) { Row(modifier = Modifier.layoutId(FOOTER_ID), horizontalArrangement = Arrangement.Start) { Box(modifier = Modifier.padding(horizontal = 6.dp)) { footer() } } } if (placeholder != null) { Box(modifier = Modifier.layoutId(PLACEHOLDER_ID), contentAlignment = Alignment.Center) { placeholder() } } Box(modifier = Modifier.layoutId(TEXT_FIELD_ID), propagateMinConstraints = true) { innerTextField() } } ) { measurables, incomingConstraints -> // used to calculate the constraints for measuring elements that will be placed in a row var occupiedSpaceVertically = 0 val constraintsWithoutPadding = incomingConstraints.offset( horizontal = -2 * TextAreaPadding.roundToPx(), vertical = -2 * TextAreaPadding.roundToPx() ) val footerConstraints = constraintsWithoutPadding.copy(minWidth = 0, minHeight = 0) val footerPlaceable = measurables.find { it.layoutId == FOOTER_ID }?.measure(footerConstraints) occupiedSpaceVertically += footerPlaceable?.height ?: 0 val textConstraints = constraintsWithoutPadding.offset( vertical = -occupiedSpaceVertically ).copy(minWidth = 0) val textFieldPlaceable = measurables.first { it.layoutId == TEXT_FIELD_ID }.measure(textConstraints) // measure placeholder val placeholderConstraints = textConstraints.copy(minHeight = 0) val placeholderPlaceable = measurables.find { it.layoutId == PLACEHOLDER_ID }?.measure(placeholderConstraints) val width = calculateWidth( footerPlaceable, textFieldPlaceable, placeholderPlaceable, incomingConstraints ) + 2 * TextAreaPadding.roundToPx() val height = calculateHeight( footerPlaceable, textFieldPlaceable, placeholderPlaceable, incomingConstraints ) + 2 * TextAreaPadding.roundToPx() layout(width, height) { place( height, width, footerPlaceable, textFieldPlaceable, placeholderPlaceable, this@Layout ) } } } private fun calculateWidth( footerPlaceable: Placeable?, textFieldPlaceable: Placeable, placeholderPlaceable: Placeable?, constraints: Constraints ): Int { return maxOf( footerPlaceable?.width ?: 0, textFieldPlaceable.width, placeholderPlaceable?.width ?: 0, constraints.minWidth ) } private fun calculateHeight( footerPlaceable: Placeable?, textFieldPlaceable: Placeable, placeholderPlaceable: Placeable?, constraints: Constraints ): Int { val middleSection = maxOf( textFieldPlaceable.height, placeholderPlaceable?.height ?: 0 ) val wrappedHeight = (footerPlaceable?.height ?: 0) + middleSection return max(wrappedHeight, constraints.minHeight) } private fun Placeable.PlacementScope.place( height: Int, width: Int, footerPlaceable: Placeable?, textFieldPlaceable: Placeable, placeholderPlaceable: Placeable?, density: Density ) = with(density) { val padding = TextAreaPadding.roundToPx() // placed center vertically and to the start edge horizontally footerPlaceable?.placeRelative( 0, height - footerPlaceable.height ) // placed center vertically and after the leading icon horizontally if single line text field // placed to the top with padding for multi line text field textFieldPlaceable.placeRelative(padding, padding) // placed similar to the input text above placeholderPlaceable?.placeRelative(padding, padding) } private const val PLACEHOLDER_ID = "Placeholder" private const val TEXT_FIELD_ID = "TextField" private const val FOOTER_ID = "Footer" private val TextAreaPadding = 6.dp
17
Kotlin
11
318
817adc042a029698983c9686d0f1497204bfdf14
8,459
jewel
Apache License 2.0
src/main/kotlin/org/k9m/warehouse/WarehouseApp.kt
k9m
382,888,625
false
null
package org.k9m.warehouse import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.transaction.annotation.EnableTransactionManagement @SpringBootApplication @EnableTransactionManagement class WarehouseApiApplication fun main(args: Array<String>) { runApplication<WarehouseApiApplication>(*args) }
0
Kotlin
0
0
b153a8cd09077cab1c8b0864ebd6307a26b0b052
386
warehouse-api
MIT License
core/src/io/github/tozydev/patek/gui/GuiActions.kt
tozydev
773,615,401
false
{"Kotlin": 128971, "Java": 2674}
@file:Suppress("unused") package io.github.tozydev.patek.gui import io.github.tozydev.patek.event.cancel import io.github.tozydev.patek.gui.slot.ClickInstance import io.github.tozydev.patek.gui.slot.GuiSlot import io.github.tozydev.patek.inventory.orEmpty import org.bukkit.entity.Player import org.bukkit.event.inventory.InventoryAction.COLLECT_TO_CURSOR import org.bukkit.event.inventory.InventoryAction.MOVE_TO_OTHER_INVENTORY import org.bukkit.event.inventory.InventoryAction.UNKNOWN import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.InventoryCloseEvent import org.bukkit.event.inventory.InventoryDragEvent import org.bukkit.event.inventory.InventoryOpenEvent /** * Registers a callback function to be executed when the GUI is opened. * * @param action The callback function that takes the [Gui] instance and the [InventoryOpenEvent] as parameters. */ fun Gui.onOpen(action: (Gui, InventoryOpenEvent) -> Unit) { actions.open += action } /** * Registers a callback function to be executed when the GUI is closed. * * @param action The callback function that takes the [Gui] instance and the [InventoryCloseEvent] as parameters. */ fun Gui.onClose(action: (Gui, InventoryCloseEvent) -> Unit) { actions.close += action } /** * Registers a callback function to be executed when the user drags items when opening the GUI. * * @param action The callback function that takes the [Gui] instance and the [InventoryDragEvent] as parameters. */ fun Gui.onDrag(action: (Gui, InventoryDragEvent) -> Unit) { actions.drag += action } /** * Registers a callback function to be executed when the user clicks in or out of the GUI. * * @param action The callback function that takes the [Gui] instance and the [InventoryClickEvent] as parameters. */ fun Gui.onClick(action: (Gui, InventoryClickEvent) -> Unit) { actions.click += action } internal class GuiActions { val open = mutableListOf<(Gui, InventoryOpenEvent) -> Unit>() val close = mutableListOf<(Gui, InventoryCloseEvent) -> Unit>() val drag = mutableListOf<(Gui, InventoryDragEvent) -> Unit>() val click = mutableListOf<(Gui, InventoryClickEvent) -> Unit>() init { drag += DEFAULT_DRAG_ACTION click += DEFAULT_CLICK_ACTION } fun doOpen( gui: Gui, event: InventoryOpenEvent, ) { for (onOpen in open) { onOpen(gui, event) } } fun doClose( gui: Gui, event: InventoryCloseEvent, ) { for (onClose in close) { onClose(gui, event) } } fun doDrag( gui: Gui, event: InventoryDragEvent, ) { for (onDrag in drag) { onDrag(gui, event) } } fun doClick( gui: Gui, event: InventoryClickEvent, ) { for (onClick in click) { onClick(gui, event) } } companion object { private val DEFAULT_DRAG_ACTION: (Gui, InventoryDragEvent) -> Unit = { _, event -> with(event) { rawSlots.firstOrNull { it < inventory.size }?.let { cancel() } } } private val DEFAULT_CLICK_ACTION: (Gui, InventoryClickEvent) -> Unit = { gui, event -> with(event) { if (rawSlot == slot) { cancel() } if (action == MOVE_TO_OTHER_INVENTORY || action == UNKNOWN) { cancel() } if (action == COLLECT_TO_CURSOR && clickedInventory == inventory) { cancel() } val slot = gui.rendered[event.rawSlot] ?: return@with slot.onClick(createClickInstance(gui, slot)) } } fun InventoryClickEvent.createClickInstance( gui: Gui, slot: GuiSlot, ) = ClickInstance( gui = gui, whoClicked = whoClicked as Player, slot = slot, item = currentItem.orEmpty(), event = this, ) } }
0
Kotlin
0
1
f5b0fd5ba40c51dd53934d3bb5b41052675fb205
4,133
patek
MIT License
server/src/main/kotlin/com/thoughtworks/archguard/change/controller/DiffChangeController.kt
archguard
460,910,110
false
{"Kotlin": 1763628, "Java": 611399, "TypeScript": 11395, "C#": 5593, "Dockerfile": 2549, "C": 1223, "Shell": 926, "JavaScript": 400, "Go": 291, "Scala": 97, "Python": 42, "Rust": 32}
package com.thoughtworks.archguard.change.controller import com.thoughtworks.archguard.change.application.DiffChangeApplicationService import com.thoughtworks.archguard.change.domain.model.DiffChange import com.thoughtworks.archguard.systeminfo.domain.SystemInfoService import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("/api/systems/{systemId}/diff") class DiffChangeController( val diffChangeApplicationService: DiffChangeApplicationService, val systemInfoService: SystemInfoService, ) { @GetMapping("/influence/history") fun historyInfluence(@PathVariable("systemId") systemId: Long): List<DiffChange> { return diffChangeApplicationService.findBySystemId(systemId) } @GetMapping("/influence/commit") fun influenceByCommit( @PathVariable("systemId") systemId: Long, @RequestParam(value = "since", required = true) since: String, @RequestParam(value = "until", required = true) until: String, // todo: refactor version @RequestParam(defaultValue = "1.6.2") scannerVersion: String, ): List<DiffChange> { val systemInfo = systemInfoService.getSystemInfo(systemId) diffChangeApplicationService.execute(systemInfo, since, until, scannerVersion) return diffChangeApplicationService.findBySystemId(systemId) } }
1
Kotlin
89
575
049f3cc8f2c0e2c34e65bb0049f645caa5be9bf8
1,602
archguard
MIT License
kool-editor/src/commonMain/kotlin/de/fabmax/kool/editor/actions/SetDrawGroupAction.kt
kool-engine
81,503,047
false
{"Kotlin": 5929566, "C++": 3256, "CMake": 1870, "HTML": 1464, "JavaScript": 597}
package de.fabmax.kool.editor.actions import de.fabmax.kool.editor.api.GameEntity class SetDrawGroupAction( entities: List<GameEntity>, val applyGroup: Int ) : GameEntityAction(entities) { private val undoGroups = entities.associate { it.id to it.entityData.settings.drawGroupId } override fun doAction() { gameEntities.forEach { it.setDrawGroup(applyGroup) } } override fun undoAction() { gameEntities.forEach { it.setDrawGroup(undoGroups[it.id] ?: 0) } } private fun GameEntity.setDrawGroup(group: Int) { setPersistent(settings.copy(drawGroupId = group)) } }
11
Kotlin
20
303
8d05acd3e72ff2fc115d0939bf021a5f421469a5
626
kool
Apache License 2.0
shared-client/src/commonMain/kotlin/Dependencies.kt
russhwolf
211,318,216
false
null
package com.example.multiplatform.shared.client import io.ktor.client.engine.HttpClientEngine expect val httpClientEngine: HttpClientEngine expect val host: String
0
Kotlin
4
98
5332ce22ac983c634865d371116b14130a4e71d5
166
multiplatform-hello
Apache License 2.0
app/src/main/java/com/astrog/sheduleapp/internal/room/ScheduleDatabase.kt
blast-sky
628,681,758
false
null
package com.astrog.sheduleapp.internal.room import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters import com.astrog.sheduleapp.internal.room.converter.DateTimeConverters import com.astrog.sheduleapp.internal.room.converter.KindOfWorkConverter import com.astrog.sheduleapp.internal.room.entity.LessonEntity import com.astrog.sheduleapp.internal.room.entity.StudyDayEntity @TypeConverters( DateTimeConverters::class, KindOfWorkConverter::class, ) @Database( entities = [ LessonEntity::class, StudyDayEntity::class, ], version = 6, ) abstract class ScheduleDatabase : RoomDatabase() { abstract fun lessonDao(): LessonDao }
0
Kotlin
0
1
9d05d05e54a304e199fb4dab24f18ec4a48c1d58
708
unn-schedule-app
Apache License 2.0
app/src/main/java/com/example/moneypal/utils/UserCard.kt
hyacintheph
508,769,624
false
{"Kotlin": 181976}
package com.example.moneypal.utils import android.net.Uri import androidx.compose.foundation.Image import androidx.compose.foundation.border import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Delete import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import coil.compose.rememberAsyncImagePainter import coil.request.ImageRequest import com.example.moneypal.R import com.example.moneypal.models.UserData import com.example.moneypal.ui.theme.MoneyPalTheme import com.example.moneypal.viewmodels.UserViewModel @Composable fun UserCard( modifier: Modifier = Modifier, userData: UserData = UserData(), type: String = "", userViewModel: UserViewModel = hiltViewModel() ) { MoneyPalTheme { Row(modifier = modifier .fillMaxWidth() .height(100.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween) { Row(modifier = modifier.fillMaxHeight(), verticalAlignment = Alignment.CenterVertically,) { Image( painter = rememberAsyncImagePainter( model = ImageRequest.Builder(LocalContext.current).data(userData.avatar) .placeholder(R.drawable.ic_baseline_image_24) .error(R.drawable.ic_baseline_error_24) .fallback(R.drawable.ic_baseline_broken_image_24) .build() ), contentDescription = stringResource(id = R.string.image_placeholder), contentScale = ContentScale.Crop, modifier = modifier .border( width = 1.dp, color = MaterialTheme.colors.primary, shape = CircleShape ) .size(60.dp) .clip(CircleShape) ) Column(modifier = modifier .fillMaxHeight() .padding(start = 8.dp), verticalArrangement = Arrangement.Center) { Text(text = userData.name!! ) Row() { Icon(modifier = modifier.size(20.dp), painter = painterResource(id = R.drawable.placeholder_image), contentDescription = "type") Text(text = userData.phoneNumber!!) } } } when(type){ "delete" -> IconButton(onClick = {userViewModel.deleteSelectedUser(userData)}) { Icon(imageVector = Icons.Filled.Delete, contentDescription = "delete") } } } } } @Preview(showBackground = true) @Composable fun UserCardPreview() { UserCard() }
0
Kotlin
0
0
0e057d7a14d82e39d01ef467d4ac443b0a471cb8
3,637
MoneyPal
Apache License 2.0
app/src/main/java/com/cwb/androiddevbr/cidadaodebem/ui/main/MainViewModel.kt
brunoha-zz
141,664,946
true
{"Kotlin": 6553, "Java": 667}
package com.cwb.androiddevbr.cidadaodebem.ui.main import androidx.lifecycle.MutableLiveData import com.cwb.androiddevbr.cidadaodebem.ui.base.BaseViewModel class MainViewModel :BaseViewModel(){ val mutableLiveData = MutableLiveData<String>().apply { value = "uhull" } }
0
Kotlin
0
0
59a7b49ad71a327b9d2b9713f9453e5af60919f2
289
cidadaodebem
MIT License
src/main/kotlin/com/github/strindberg/emacssearchandcase/movement/ExchangePointAndMarkHandler.kt
strindberg
497,232,016
false
{"Kotlin": 206743}
package com.github.strindberg.emacssearchandcase.movement import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.actionSystem.EditorActionHandler import com.intellij.openapi.editor.ex.EditorEx class ExchangePointAndMarkHandler : EditorActionHandler() { override fun doExecute(editor: Editor, caret: Caret?, dataContext: DataContext) { val primary = caret ?: editor.caretModel.primaryCaret val ex = editor as EditorEx if (primary.hasSelection()) { val selectionStart = primary.selectionStartPosition val selectionEnd = primary.selectionEndPosition ex.isStickySelection = true // set new start of selection primary.moveToVisualPosition(if (primary.visualPosition == selectionEnd) selectionStart else selectionEnd) primary.setSelection(ex.visualPositionToOffset(selectionStart), ex.visualPositionToOffset(selectionEnd)) } } }
0
Kotlin
0
0
721c2f2603b26621f4d9dc70dbafa44ef22fc29d
1,044
emacs-search-and-case
Apache License 2.0
basic/src/main/java/com/mozhimen/taskk/provider/basic/annors/ATaskQueueName.kt
mozhimen
737,202,327
false
{"Kotlin": 421967, "Java": 6683}
package com.mozhimen.taskk.provider.basic.annors import androidx.annotation.StringDef /** * @ClassName ATaskName * @Description TODO * @Author mozhimen * @Date 2024/8/20 * @Version 1.0 */ @StringDef( ATaskName.TASK_DOWNLOAD, ATaskName.TASK_VERIFY, ATaskName.TASK_UNZIP, ATaskName.TASK_INSTALL, ATaskName.TASK_OPEN, ATaskName.TASK_CLOSE, ATaskName.TASK_UNINSTALL, ATaskName.TASK_DELETE, ATaskQueueName.TASK_RESTART ) @Retention(AnnotationRetention.SOURCE) @Target(AnnotationTarget.TYPE, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FUNCTION) annotation class ATaskQueueName{ companion object{ const val TASK_RESTART = "TASK_RESTART" } }
0
Kotlin
0
3
abfe3e40f0a301bb6e5253a9711f75b9266d3d8a
702
ATaskKit_Provider
Apache License 2.0
frontend-example/modules/material-design/src/jsMain/kotlin/io/github/andrewk2112/kjsbox/frontend/example/materialdesign/designtokens/reference/ReferenceSizes.kt
andrew-k-21-12
497,585,003
false
{"Kotlin": 370134, "JavaScript": 7404, "HTML": 726}
package io.github.andrewk2112.kjsbox.frontend.example.materialdesign.designtokens.reference import io.github.andrewk2112.kjsbox.frontend.core.designtokens.Sizes import kotlinx.css.px class ReferenceSizes : Sizes { val absolute1 = 1.px val absolute4 = 4.px val absolute32 = 32.px val absolute48 = 48.px val absolute72 = 72.px val absolute112 = 112.px val absolute170 = 170.px val absolute280 = 280.px val absolute1240 = 1240.px }
0
Kotlin
0
3
ab6c0e4ee9b0f18fff8c1eb71a188e3d76fd2823
482
kjs-box
MIT License
src/main/kotlin/nucleus/common/impl/registrar/DeferredRegistrar.kt
NiChrosia
430,499,404
false
null
package nucleus.common.impl.registrar import nucleus.common.api.registrar.Registrar open class DeferredRegistrar<K, V>(val backend: () -> MutableMap<K, V>) : Registrar<K, V> { override fun get(key: K): V { val map = backend() return map[key] ?: throw noElementFound(key) } override fun <T : V> register(key: K, value: T): T { val map = backend() map[key] = value return value } }
0
Kotlin
1
0
b73ee4690590ac5fc4657e2a75f48d429797b6b0
441
Nucleus
MIT License
app/src/main/java/org/coepi/android/domain/UnixTime.kt
yibter
260,080,429
true
{"Kotlin": 137981}
package org.coepi.android.domain import android.os.Parcelable import kotlinx.android.parcel.Parcelize import java.util.Date @Parcelize class UnixTime private constructor(val value: Long) : Parcelable { companion object { fun fromValue(value: Long): UnixTime = UnixTime(value) fun minTimestamp(): UnixTime = UnixTime(0) fun now(): UnixTime = UnixTime(Date().time / 1000) } override fun equals(other: Any?): Boolean = other is UnixTime && value == other.value override fun hashCode(): Int = value.hashCode() override fun toString(): String = "$value, ${toDate()}" fun toDate() = Date(value * 1000) }
0
null
0
0
e64a035f5b7a154733ef09db0d8d7c0d5cb5efa2
715
app-android
MIT License
mbway/src/test/java/com/adyen/checkout/mbway/DefaultMBWayDelegateTest.kt
leandromagnabosco
533,836,687
false
null
/* * Copyright (c) 2022 Adyen N.V. * * This file is open source and available under the MIT license. See the LICENSE file for more info. * * Created by josephj on 25/7/2022. */ package com.adyen.checkout.mbway import app.cash.turbine.test import com.adyen.checkout.components.model.paymentmethods.PaymentMethod import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import org.junit.Assert import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.junit.jupiter.MockitoExtension @OptIn(ExperimentalCoroutinesApi::class) @ExtendWith(MockitoExtension::class) internal class DefaultMBWayDelegateTest { private val delegate = DefaultMBWayDelegate( paymentMethod = PaymentMethod(), ) @Nested @DisplayName("when input data changes and") inner class InputDataChangedTest { @Test fun `input is invalid, then output data should be invalid`() = runTest { delegate.outputDataFlow.test { skipItems(1) delegate.onInputDataChanged(MBWayInputData(countryCode = "+1", localPhoneNumber = "04023456")) val mbWayOutputData = awaitItem() Assert.assertEquals("+14023456", mbWayOutputData?.mobilePhoneNumberFieldState?.value) Assert.assertEquals(false, mbWayOutputData?.isValid) cancelAndIgnoreRemainingEvents() } } @Test fun `input is invalid, then component state should be invalid`() = runTest { delegate.componentStateFlow.test { skipItems(1) delegate.onInputDataChanged(MBWayInputData(countryCode = "+23", localPhoneNumber = "0056778")) val componentState = awaitItem() Assert.assertEquals("+2356778", componentState?.data?.paymentMethod?.telephoneNumber) Assert.assertEquals(false, componentState?.isInputValid) Assert.assertEquals(false, componentState?.isValid) cancelAndIgnoreRemainingEvents() } } @Test fun `input is valid, then output data should be propagated`() = runTest { delegate.outputDataFlow.test { skipItems(1) delegate.onInputDataChanged(MBWayInputData(countryCode = "+351", localPhoneNumber = "234567890")) val mbWayOutputData = awaitItem() Assert.assertEquals("+351234567890", mbWayOutputData?.mobilePhoneNumberFieldState?.value) Assert.assertEquals(true, mbWayOutputData?.isValid) cancelAndIgnoreRemainingEvents() } } @Test fun `input is valid, then component state should be propagated`() = runTest { delegate.componentStateFlow.test { skipItems(1) delegate.onInputDataChanged(MBWayInputData(countryCode = "+1", localPhoneNumber = "9257348920")) val componentState = awaitItem() Assert.assertEquals("+19257348920", componentState?.data?.paymentMethod?.telephoneNumber) Assert.assertEquals(true, componentState?.isInputValid) Assert.assertEquals(true, componentState?.isValid) cancelAndIgnoreRemainingEvents() } } } @Nested @DisplayName("when creating component state and") inner class CreateComponentStateTest { @Test fun `output data is invalid, then component state should be invalid`() = runTest { delegate.componentStateFlow.test { skipItems(1) delegate.createComponentState(MBWayOutputData("+7867676")) val componentState = awaitItem() Assert.assertEquals("+7867676", componentState?.data?.paymentMethod?.telephoneNumber) Assert.assertEquals(false, componentState?.isInputValid) Assert.assertEquals(false, componentState?.isValid) cancelAndIgnoreRemainingEvents() } } @Test fun `output data is valid, then component state should be propagated`() = runTest { delegate.componentStateFlow.test { skipItems(1) delegate.createComponentState(MBWayOutputData("+31666666666")) val componentState = awaitItem() Assert.assertEquals("+31666666666", componentState?.data?.paymentMethod?.telephoneNumber) Assert.assertEquals(true, componentState?.isInputValid) Assert.assertEquals(true, componentState?.isValid) cancelAndIgnoreRemainingEvents() } } } }
2
Kotlin
0
0
c154e989a08f1dc76cf90f6949878621cbbfa644
4,812
testsonarcloud
MIT License
executor/invoker/src/commonMain/kotlin/io/github/charlietap/chasm/executor/invoker/instruction/aggregate/AggregateInstructionExecutor.kt
CharlieTap
743,980,037
false
{"Kotlin": 2026253, "WebAssembly": 45714}
@file:Suppress("NOTHING_TO_INLINE") package io.github.charlietap.chasm.executor.invoker.instruction.aggregate import com.github.michaelbull.result.Result import com.github.michaelbull.result.binding import io.github.charlietap.chasm.ast.instruction.AggregateInstruction import io.github.charlietap.chasm.executor.invoker.context.ExecutionContext import io.github.charlietap.chasm.executor.runtime.error.InvocationError internal fun AggregateInstructionExecutor( context: ExecutionContext, instruction: AggregateInstruction, ): Result<Unit, InvocationError> = AggregateInstructionExecutor( context = context, instruction = instruction, structNewExecutor = ::StructNewExecutor, structNewDefaultExecutor = ::StructNewDefaultExecutor, structGetExecutor = ::StructGetExecutor, structSetExecutor = ::StructSetExecutor, arrayNewFixedExecutor = ::ArrayNewFixedExecutor, arrayNewExecutor = ::ArrayNewExecutor, arrayNewDefaultExecutor = ::ArrayNewDefaultExecutor, arrayNewDataExecutor = ::ArrayNewDataExecutor, arrayNewElementExecutor = ::ArrayNewElementExecutor, arrayGetExecutor = ::ArrayGetExecutor, arraySetExecutor = ::ArraySetExecutor, arrayLenExecutor = ::ArrayLenExecutor, refI31Executor = ::RefI31Executor, i31GetExecutor = ::I31GetExecutor, arrayFillExecutor = ::ArrayFillExecutor, arrayCopyExecutor = ::ArrayCopyExecutor, arrayInitDataExecutor = ::ArrayInitDataExecutor, arrayInitElementExecutor = ::ArrayInitElementExecutor, anyConvertExternExecutor = ::AnyConvertExternExecutor, externConvertAnyExecutor = ::ExternConvertAnyExecutor, ) internal inline fun AggregateInstructionExecutor( context: ExecutionContext, instruction: AggregateInstruction, crossinline structNewExecutor: StructNewExecutor, crossinline structNewDefaultExecutor: StructNewDefaultExecutor, crossinline structGetExecutor: StructGetExecutor, crossinline structSetExecutor: StructSetExecutor, crossinline arrayNewFixedExecutor: ArrayNewFixedExecutor, crossinline arrayNewExecutor: ArrayNewExecutor, crossinline arrayNewDefaultExecutor: ArrayNewDefaultExecutor, crossinline arrayNewDataExecutor: ArrayNewDataExecutor, crossinline arrayNewElementExecutor: ArrayNewElementExecutor, crossinline arrayGetExecutor: ArrayGetExecutor, crossinline arraySetExecutor: ArraySetExecutor, crossinline arrayLenExecutor: ArrayLenExecutor, crossinline refI31Executor: RefI31Executor, crossinline i31GetExecutor: I31GetExecutor, crossinline arrayFillExecutor: ArrayFillExecutor, crossinline arrayCopyExecutor: ArrayCopyExecutor, crossinline arrayInitDataExecutor: ArrayInitDataExecutor, crossinline arrayInitElementExecutor: ArrayInitElementExecutor, crossinline anyConvertExternExecutor: AnyConvertExternExecutor, crossinline externConvertAnyExecutor: ExternConvertAnyExecutor, ): Result<Unit, InvocationError> = binding { val (stack, store) = context when (instruction) { is AggregateInstruction.StructNew -> structNewExecutor(store, stack, instruction.typeIndex).bind() is AggregateInstruction.StructNewDefault -> structNewDefaultExecutor(store, stack, instruction.typeIndex).bind() is AggregateInstruction.StructGet -> structGetExecutor(store, stack, instruction.typeIndex, instruction.fieldIndex, true).bind() is AggregateInstruction.StructGetSigned -> structGetExecutor(store, stack, instruction.typeIndex, instruction.fieldIndex, true).bind() is AggregateInstruction.StructGetUnsigned -> structGetExecutor(store, stack, instruction.typeIndex, instruction.fieldIndex, false).bind() is AggregateInstruction.StructSet -> structSetExecutor(store, stack, instruction).bind() is AggregateInstruction.ArrayNewFixed -> arrayNewFixedExecutor(store, stack, instruction.typeIndex, instruction.size).bind() is AggregateInstruction.ArrayNew -> arrayNewExecutor(store, stack, instruction.typeIndex).bind() is AggregateInstruction.ArrayNewDefault -> arrayNewDefaultExecutor(store, stack, instruction.typeIndex).bind() is AggregateInstruction.ArrayNewData -> arrayNewDataExecutor(store, stack, instruction.typeIndex, instruction.dataIndex).bind() is AggregateInstruction.ArrayNewElement -> arrayNewElementExecutor(store, stack, instruction.typeIndex, instruction.elementIndex).bind() is AggregateInstruction.ArrayGet -> arrayGetExecutor(store, stack, instruction.typeIndex, true).bind() is AggregateInstruction.ArrayGetSigned -> arrayGetExecutor(store, stack, instruction.typeIndex, true).bind() is AggregateInstruction.ArrayGetUnsigned -> arrayGetExecutor(store, stack, instruction.typeIndex, false).bind() is AggregateInstruction.ArraySet -> arraySetExecutor(store, stack, instruction.typeIndex).bind() is AggregateInstruction.ArrayLen -> arrayLenExecutor(store, stack).bind() is AggregateInstruction.RefI31 -> refI31Executor(stack).bind() is AggregateInstruction.I31GetSigned -> i31GetExecutor(stack, true).bind() is AggregateInstruction.I31GetUnsigned -> i31GetExecutor(stack, false).bind() is AggregateInstruction.ArrayFill -> arrayFillExecutor(store, stack, instruction.typeIndex).bind() is AggregateInstruction.ArrayCopy -> arrayCopyExecutor(store, stack, instruction.sourceTypeIndex, instruction.destinationTypeIndex).bind() is AggregateInstruction.ArrayInitData -> arrayInitDataExecutor(store, stack, instruction.typeIndex, instruction.dataIndex).bind() is AggregateInstruction.ArrayInitElement -> arrayInitElementExecutor(store, stack, instruction.typeIndex, instruction.elementIndex).bind() is AggregateInstruction.AnyConvertExtern -> anyConvertExternExecutor(stack).bind() is AggregateInstruction.ExternConvertAny -> externConvertAnyExecutor(stack).bind() } }
4
Kotlin
3
61
70772acc37462bb98dae7bcbf1a29f8ed6dbefa7
6,085
chasm
Apache License 2.0
src/main/kotlin/uk/co/ben_gibson/git/link/ui/actions/annotation/CommitBrowserAction.kt
cdambo
419,691,103
true
{"Kotlin": 89867}
package uk.co.ben_gibson.git.link.ui.actions.annotation import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.Project import git4idea.annotate.GitFileAnnotation import uk.co.ben_gibson.git.link.ui.actions.Action import com.intellij.openapi.vcs.annotate.UpToDateLineNumberListener; import uk.co.ben_gibson.git.link.Context import uk.co.ben_gibson.git.link.ContextCommit import uk.co.ben_gibson.git.link.git.Commit class CommitBrowserAction(private val annotation: GitFileAnnotation): Action(Type.BROWSER), UpToDateLineNumberListener { private var lineNumber = -1 override fun buildContext(project: Project, event: AnActionEvent): Context? { val revision = annotation.getLineRevisionNumber(lineNumber) ?: return null return ContextCommit(annotation.file, Commit(revision.toString())) } override fun consume(number: Int) { lineNumber = number } }
0
Kotlin
0
0
2a82df9f0c0d3c83fc599c89745357af8e648dbd
937
GitLink
MIT License
library/src/main/java/cloud/pace/sdk/api/pay/generated/request/paymentMethods/PaymentMethodModelAPI.kt
pace
303,641,261
false
null
/* * PLEASE DO NOT EDIT! * * Generated by SwagGen with Kotlin template. * https://github.com/pace/SwagGen */ package cloud.pace.sdk.api.pay.generated.request.paymentMethods import cloud.pace.sdk.api.pay.PayAPI import cloud.pace.sdk.api.pay.generated.model.* import cloud.pace.sdk.api.request.BaseRequest import retrofit2.Call import retrofit2.http.* object PaymentMethodModelAPI { interface PaymentMethodModelService { /* Returns the model of the Payment Method e.g. "reseller" */ @POST("payment-methods/{paymentMethodId}/model") fun paymentMethodModel( @HeaderMap headers: Map<String, String>, /* ID of the paymentMethod */ @Path("paymentMethodId") paymentMethodId: String, @retrofit2.http.Body body: Body ): Call<PaymentMethodModel> } class Body { var data: RequestPaymentMethodModelBody? = null } open class Request : BaseRequest() { fun paymentMethodModel( paymentMethodId: String, body: Body, readTimeout: Long? = null, additionalHeaders: Map<String, String>? = null, additionalParameters: Map<String, String>? = null ): Call<PaymentMethodModel> { val headers = headers(true, "application/vnd.api+json", "application/vnd.api+json", additionalHeaders) return retrofit(PayAPI.baseUrl, additionalParameters, readTimeout) .create(PaymentMethodModelService::class.java) .paymentMethodModel( headers, paymentMethodId, body ) } } fun PayAPI.PaymentMethodsAPI.paymentMethodModel( paymentMethodId: String, body: Body, readTimeout: Long? = null, additionalHeaders: Map<String, String>? = null, additionalParameters: Map<String, String>? = null ) = Request().paymentMethodModel( paymentMethodId, body, readTimeout, additionalHeaders, additionalParameters ) }
0
Kotlin
1
5
c459c30690f3c2c480986312a3d837698ce028bc
2,088
cloud-sdk-android
MIT License
src/main/java/com/coinpaprika/apiclient/repository/tag/TagApi.kt
MDLlife
191,176,372
true
{"Kotlin": 86987, "Java": 725}
/* * Created by <NAME> on 09.01.19 12:43 */ package com.coinpaprika.apiclient.repository.tag import android.content.Context import com.coinpaprika.apiclient.api.BaseApi import com.coinpaprika.apiclient.api.CoinpaprikaApiFactory import com.coinpaprika.apiclient.entity.TagEntity import com.coinpaprika.apiclient.exception.NetworkConnectionException import com.coinpaprika.apiclient.extensions.handleResponse import io.reactivex.Observable import retrofit2.Response class TagApi constructor( context: Context, private var retrofit: TagApiContract = CoinpaprikaApiFactory() .client() .create(TagApiContract::class.java) ) : BaseApi(context), TagApiContract { override fun getTag(id: String): Observable<Response<TagEntity>> { return Observable.create { emitter -> if (isThereInternetConnection()) { try { retrofit.getTag(id).handleResponse(emitter) } catch (e: Exception) { e.printStackTrace() emitter.onError(NetworkConnectionException(e.cause)) } } else { emitter.onError(NetworkConnectionException()) } } } override fun getTags(): Observable<Response<List<TagEntity>>> { return Observable.create { emitter -> if (isThereInternetConnection()) { try { retrofit.getTags().handleResponse(emitter) } catch (e: Exception) { e.printStackTrace() emitter.onError(NetworkConnectionException(e.cause)) } } else { emitter.onError(NetworkConnectionException()) } } } }
0
Kotlin
1
0
53f56558aaf29c5ab1f16c5f75eb4caa48b1fad2
1,754
coinpaprika-api-kotlin-client
MIT License
src/test/kotlin/no/nav/dagpenger/regel/api/models/SubsumsjonTest.kt
chriswk
341,568,235
true
{"Kotlin": 191164, "HTML": 511, "Dockerfile": 338, "C#": 282, "PHP": 193}
package no.nav.dagpenger.regel.api.models import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import no.nav.dagpenger.events.Problem import org.junit.jupiter.api.Test import java.time.LocalDate import java.time.YearMonth internal class SubsumsjonTest { @Test fun `Map to JSON string`() { Subsumsjon( behovId = BehovId("01DSFTA586H33ESMTYMY6QD4ZD"), faktum = Faktum("aktorId", 1, LocalDate.of(2019, 5, 9)), grunnlagResultat = emptyMap(), minsteinntektResultat = emptyMap(), periodeResultat = emptyMap(), satsResultat = emptyMap(), problem = Problem(title = "problem") ).toJson() shouldBe """{"behovId":"01DSFTA586H33ESMTYMY6QD4ZD","faktum":{"aktorId":"aktorId","vedtakId":1,"beregningsdato":"2019-05-09"},"grunnlagResultat":{},"minsteinntektResultat":{},"periodeResultat":{},"satsResultat":{},"problem":{"type":"about:blank","title":"problem","status":500,"instance":"about:blank"}}""" } @Test fun `Map from JSON string to object`() { val subsumsjon = Subsumsjon.fromJson("""{"behovId":"01DSFTA586H33ESMTYMY6QD4ZD","faktum":{"aktorId":"aktorId","vedtakId":1,"beregningsdato":"2019-05-09","inntektsId":"inntektsId","harAvtjentVerneplikt":true,"oppfyllerKravTilFangstOgFisk":true,"antallBarn":1,"manueltGrunnlag":0,"bruktInntektsPeriode":{"førsteMåned":"2019-05","sisteMåned":"2019-05"}},"grunnlagResultat":{},"minsteinntektResultat":{},"periodeResultat":{},"satsResultat":{},"problem":{"type":"about:blank","title":"problem","status":500,"instance":"about:blank"}}""") subsumsjon shouldNotBe null subsumsjon?.apply { behovId shouldBe BehovId("01DSFTA586H33ESMTYMY6QD4ZD") grunnlagResultat shouldBe emptyMap() periodeResultat shouldBe emptyMap() minsteinntektResultat shouldBe emptyMap() satsResultat shouldBe emptyMap() problem shouldNotBe null } subsumsjon?.faktum?.apply { aktorId shouldBe "aktorId" vedtakId shouldBe 1 beregningsdato shouldBe LocalDate.of(2019, 5, 9) inntektsId shouldBe "inntektsId" harAvtjentVerneplikt shouldBe true oppfyllerKravTilFangstOgFisk shouldBe true antallBarn shouldBe 1 manueltGrunnlag shouldBe 0 bruktInntektsPeriode shouldBe InntektsPeriode(YearMonth.of(2019, 5), YearMonth.of(2019, 5)) } } }
0
null
0
0
b93c7efdac27fcdf0436284bed3b23df15dbacd7
2,507
dp-regel-api
MIT License
src/main/kotlin/nieldw/socially/domain/sagas/RelationshipSaga.kt
nieldw
147,417,454
false
null
package nieldw.socially.domain.sagas import nieldw.socially.domain.InteractionScore import nieldw.socially.domain.RelationshipLevel import nieldw.socially.domain.commands.UpdateRelationshipLevelCommand import nieldw.socially.domain.events.InteractionAddedEvent import org.axonframework.commandhandling.gateway.CommandGateway import org.axonframework.modelling.saga.SagaEventHandler import org.axonframework.modelling.saga.StartSaga import org.axonframework.spring.stereotype.Saga import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Profile @Profile("command") @Saga class RelationshipSaga { @Transient @Autowired private lateinit var commandGateway: CommandGateway private var relationshipInteractionScore = InteractionScore.NONE @StartSaga @SagaEventHandler(associationProperty = "contactId") fun handle(interactionAddedEvent: InteractionAddedEvent) { if (this.relationshipInteractionScore == InteractionScore.NONE) { this.commandGateway.send<UpdateRelationshipLevelCommand>( UpdateRelationshipLevelCommand(interactionAddedEvent.contactId, RelationshipLevel.ACQUAINTANCE, interactionAddedEvent.interactionScore)) } this.relationshipInteractionScore += interactionAddedEvent.interactionScore when { this.relationshipInteractionScore >= InteractionScore(10) -> this.commandGateway.send<UpdateRelationshipLevelCommand>( UpdateRelationshipLevelCommand(interactionAddedEvent.contactId, RelationshipLevel.ASSOCIATE, this.relationshipInteractionScore)) } } }
0
Kotlin
2
9
e3bf090c836d76766a13fab34c6105c0116fbf54
1,670
ContactsAxonDemo
MIT License
core-db/src/androidTest/java/io/novafoundation/nova/core_db/dao/TokenDaoTest.kt
novasamatech
415,834,480
false
null
package io.novafoundation.nova.core_db.dao import androidx.test.ext.junit.runners.AndroidJUnit4 import io.novafoundation.nova.core_db.AppDatabase import kotlinx.coroutines.runBlocking import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class TokenDaoTest : DaoTest<TokenDao>(AppDatabase::tokenDao) { private val currencyDao by dao<CurrencyDao>() private val tokenSymbol = "$" @Test fun getTokenWhenCurrencySelected() = runBlocking { currencyDao.insert(createCurrency(tokenSymbol, true)) val tokenWithCurrency = dao.getToken(tokenSymbol) assert(tokenWithCurrency != null) assert(tokenWithCurrency?.token == null) } @Test fun getTokenWhenCurrencyNotSelected() = runBlocking { currencyDao.insert(createCurrency(tokenSymbol, false)) val token = dao.getToken(tokenSymbol) assert(token == null) } @Test fun getTokensWhenCurrencySelected() = runBlocking { currencyDao.insert(createCurrency(tokenSymbol, true)) val tokensWithCurrencies = dao.getTokens(listOf(tokenSymbol)) assert(tokensWithCurrencies.isNotEmpty()) } @Test fun getTokensWhenCurrencyNotSelected() = runBlocking { currencyDao.insert(createCurrency(tokenSymbol, false)) val tokensWithCurrencies = dao.getTokens(listOf(tokenSymbol)) assert(tokensWithCurrencies.isEmpty()) } @Test fun shouldInsertTokenWithDefaultCurrency() = runBlocking { currencyDao.insert(createCurrency(tokenSymbol, true)) dao.insertTokenWithSelectedCurrency(tokenSymbol) val tokenWithCurrency = dao.getToken(tokenSymbol) assert(tokenWithCurrency != null) } @Test fun shouldInsertTokenWithoutCurrency() = runBlocking { currencyDao.insert(createCurrency(tokenSymbol, false)) dao.insertTokenWithSelectedCurrency(tokenSymbol) val tokenWithCurrency = dao.getToken(tokenSymbol) assert(tokenWithCurrency == null) } }
9
Kotlin
1
5
cf829fc7fe201b1051b850cb9cfe4ffbdc82f754
2,036
nova-wallet-android
Apache License 2.0
composeApp/src/commonMain/kotlin/ru/sportivityteam/vucmirea/assistant/presentation/screens/lesson/LessonSM.kt
SportivityTeam
753,183,017
false
{"Kotlin": 104865, "Swift": 532}
package ru.sportivityteam.vucmirea.assistant.presentation.screens.lesson import ru.sportivityteam.vucmirea.assistant.presentation.ui.mvi.BaseStateScreenModel class LessonSM: BaseStateScreenModel<LessonViewState, LessonViewAction, LessonViewEvent> (initialState = LessonViewState()) { override fun obtainEvent(viewEvent: LessonViewEvent) { TODO("Not yet implemented") } }
0
Kotlin
0
2
0b3d1ea9f7be4a5df754469230bfed0fdc3de5f2
392
assistant-vuc-mirea
MIT License
core/network/src/main/java/dev/sijanrijal/popularmovies/core/network/services/popular/Popular.kt
sijanr
263,267,988
false
{"Kotlin": 87745}
package dev.sijanrijal.popularmovies.core.network.services.popular import com.google.gson.annotations.SerializedName data class PopularMoviesResponse( @SerializedName("pages") val pageNumber: Int = 1, @SerializedName("results") val movies: List<PopularMovies> ) data class PopularMovies( @SerializedName("poster_path") val posterUrl: String?, @SerializedName("backdrop_path") val backdropUrl: String, @SerializedName("overview") val overview: String, @SerializedName("release_date") val releaseDate: String, @SerializedName("title") val title: String, @SerializedName("vote_average") val rating: Float, @SerializedName("id") val movieId: Long )
4
Kotlin
0
0
85da1e7726ecef24868626b65025d1c9628e47a3
683
popular-movies
Apache License 2.0
src/main/kotlin/me/damon/schoolbot/commands/main/dev/ExportErrorLog.kt
day-mon
450,948,808
false
{"Kotlin": 308718, "Dockerfile": 1374}
package me.damon.schoolbot.commands.main.dev import me.damon.schoolbot.Constants import me.damon.schoolbot.objects.command.Command import me.damon.schoolbot.objects.command.CommandCategory import me.damon.schoolbot.objects.command.CommandEvent import net.dv8tion.jda.api.exceptions.ErrorHandler import net.dv8tion.jda.api.requests.ErrorResponse import net.dv8tion.jda.api.utils.FileUpload import org.springframework.stereotype.Component import java.io.File import kotlin.io.path.Path import kotlin.io.path.fileSize @Component class ExportErrorLog : Command( name = "ExportErrorLog", description = "Exports the error log", category = CommandCategory.DEV, commandPrerequisites = "Must be a developer", ) { override suspend fun onExecuteSuspend(event: CommandEvent) { val file = File("schoolbot-error.log") if (file.exists().not()) return event.replyMessage("There is no error log file as of now.") if (file.readLines().isEmpty()) return event.replyMessage("Log file is empty as of now.") // blocking but /shrug val size = Path(file.path).fileSize() if (size > event.jda.selfUser.allowedFileSize) return event.replyMessage("Log file is large to export to discord") val fileUpload: FileUpload = FileUpload.fromData(file) event.user.openPrivateChannel().queue { it.sendMessage("Log file as of ${Constants.CURRENT_TIME}. It currently has a size of `$size` bytes") .addFiles(fileUpload) .queue({ event.replyMessage("Log sent in PMs.") }, ErrorHandler().handle(ErrorResponse.CANNOT_SEND_TO_USER) { event.replyMessage("I cannot send a PM to you.." ) } ) } } }
0
Kotlin
0
2
7fc75f84a247060a53049ca04eb9c61fedf4b3b8
1,797
Schoolbot-kt
Apache License 2.0
serve-app/common/src/main/java/org/evidyaloka/common/ui/boardgradefilter/BoardGradeView.kt
Sunbird-Serve
607,662,046
false
null
package org.evidyaloka.common.ui.boardgradefilter import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.widget.ArrayAdapter import androidx.constraintlayout.widget.ConstraintLayout import org.evidyaloka.common.R import org.evidyaloka.common.databinding.LayoutGradeBoardSelectionBinding import org.evidyaloka.core.model.CourseProvider class BoardGradeView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ConstraintLayout(context, attrs, defStyleAttr) { private var binding = LayoutGradeBoardSelectionBinding.inflate(LayoutInflater.from(context),this) private var courseProviderList: List<CourseProvider> = listOf() fun setGradeSpinner(list: List<Int>,onGradeSelected: (grade: Int) -> Unit){ binding.grade.apply { setAdapter(ArrayAdapter(context, R.layout.spinner_list_item, list)) setOnItemClickListener { parent, view, position, id -> onGradeSelected(list.get(position)) } } } fun setBoard(list: List<CourseProvider>, onBoardSelected: (board: CourseProvider) -> Unit){ courseProviderList = list binding.schoolBoard.apply { setAdapter(ArrayAdapter(context, R.layout.spinner_list_item, list.map { it.name })) setOnItemClickListener { parent, view, position, id -> binding.schoolBoard.setSelection(0) onBoardSelected(courseProviderList[position]) } } } fun setSelectedBoard(board: CourseProvider){ binding.schoolBoard.setText(board.name) } fun setSelectedGrade(grade: Int?){ binding.grade.setText(grade?.toString()) } }
0
Kotlin
1
0
6d8d170333e2d32c808e608863e02e076dc06a73
1,756
serve-beta-android-app
MIT License
src/main/kotlin/dev/emortal/bs/event/Event.kt
emortalmc
384,565,027
false
null
package dev.emortal.bs.event import dev.emortal.bs.game.BlockSumoGame import net.kyori.adventure.text.Component import net.kyori.adventure.text.format.NamedTextColor import net.kyori.adventure.text.format.TextDecoration import java.time.Duration import kotlin.reflect.full.primaryConstructor sealed class Event { companion object { private val constructors = Event::class.sealedSubclasses.mapNotNull { it.primaryConstructor } fun createRandomEvent(): Event { return constructors.random().call() } private val prefix = Component.text() .append(Component.text("EVENT", NamedTextColor.YELLOW, TextDecoration.BOLD)) .append(Component.text(" | ", NamedTextColor.DARK_GRAY)) } abstract val startMessage: Component fun performEvent(game: BlockSumoGame) { eventStarted(game) game.sendMessage(Component.text().append(prefix).append(startMessage)) } abstract fun eventStarted(game: BlockSumoGame) }
8
Kotlin
0
1
f5038c196f3eeed0dd56af0fb80c8b4776f6db59
1,007
BlockSumo
MIT License