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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
library/src/main/java/chihane/jdaddressselector/BottomDialog.kt | mbacuiz | 249,320,016 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "XML": 17, "Kotlin": 14, "Java": 1, "JSON": 1} | package chihane.jdaddressselector
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.view.Gravity
import android.view.WindowManager
import chihane.jdaddressselector.utils.ResourceUtils
class BottomDialog : Dialog {
private var selector: AddressSelector? = null
constructor(context: Context) : super(context, R.style.bottom_dialog) {
init(context)
}
constructor(context: Context, themeResId: Int) : super(context, themeResId) {
init(context)
}
constructor(context: Context, cancelable: Boolean, cancelListener: DialogInterface.OnCancelListener) : super(context, cancelable, cancelListener) {
init(context)
}
private fun init(context: Context) {
selector = AddressSelector(context)
selector?.closeListener = object : CloseListener {
override fun onClose() {
dismiss()
}
}
setContentView(selector!!.view!!)
val window = window
val params = window!!.attributes
params.width = WindowManager.LayoutParams.MATCH_PARENT
params.height = (ResourceUtils.getScreenHeight(context) * 0.8).toInt()
window.attributes = params
window.setGravity(Gravity.BOTTOM)
}
fun setOnAddressSelectedListener(listener: OnAddressSelectedListener) {
this.selector!!.onAddressSelectedListener = listener
}
fun setDef(defCountyCode: Int, defCountyName: String) {
selector?.setDef(defCountyCode, defCountyName)
}
companion object {
@JvmOverloads
fun show(context: Context, listener: OnAddressSelectedListener? = null): BottomDialog {
val dialog = BottomDialog(context, R.style.bottom_dialog)
dialog.selector!!.onAddressSelectedListener = listener
dialog.show()
return dialog
}
}
}
| 1 | null | 1 | 1 | 089fa01d68f2e389574eb5446bad2371efb78572 | 1,909 | JDAddressSelector | MIT License |
src/main/kotlin/dev/ktxvulkan/graphics/vk/pipeline/DepthStencilState.kt | plos-clan | 852,869,100 | false | {"Kotlin": 115750, "GLSL": 615, "Batchfile": 141} | package dev.ktxvulkan.graphics.vk.pipeline
import dev.ktxvulkan.graphics.vk.CompareOp
import org.lwjgl.system.MemoryStack
import org.lwjgl.vulkan.VK10.VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO
import org.lwjgl.vulkan.VkPipelineDepthStencilStateCreateInfo
import org.lwjgl.vulkan.VkStencilOpState
enum class StencilOp(val vkStencilOp: Int) {
STENCIL_OP_KEEP(0),
STENCIL_OP_ZERO(1),
STENCIL_OP_REPLACE(2),
STENCIL_OP_INCREMENT_AND_CLAMP(3),
STENCIL_OP_DECREMENT_AND_CLAMP(4),
STENCIL_OP_INVERT(5),
STENCIL_OP_INCREMENT_AND_WRAP(6),
STENCIL_OP_DECREMENT_AND_WRAP(7)
}
data class StencilOpState(
var failOp: StencilOp = StencilOp.STENCIL_OP_KEEP,
var passOp: StencilOp = StencilOp.STENCIL_OP_KEEP,
var depthFailOp: StencilOp = StencilOp.STENCIL_OP_KEEP,
var compareOp: CompareOp = CompareOp.COMPARE_OP_NEVER,
var compareMask: Int = 0x7ffffff,
var writeMask: Int = 0x7ffffff,
var reference: Int = 0
) : PipelineState {
override val dynamicStates = listOf<DynamicState>()
context(MemoryStack)
fun getVkStencilOpState(): VkStencilOpState {
return VkStencilOpState.calloc(this@MemoryStack)
.failOp(failOp.vkStencilOp)
.passOp(passOp.vkStencilOp)
.depthFailOp(depthFailOp.vkStencilOp)
.compareOp(compareOp.vkCompareOp)
.compareMask(compareMask)
.writeMask(writeMask)
.reference(reference)
}
}
data class DepthStencilState(
val flags: VkPipelineDepthStencilStateCreateFlagBits = VkPipelineDepthStencilStateCreateFlagBits.NONE,
val depthTestEnable: Boolean = true,
val depthWriteEnable: Boolean = true,
val depthCompareOp: CompareOp = CompareOp.COMPARE_OP_LESS,
val depthBoundsTestEnable: Boolean = false,
val stencilTestEnable: Boolean = false,
val front: StencilOpState? = null,
val back: StencilOpState? = null,
val minDepthBounds: Float = 0f,
val maxDepthBounds: Float = 0f
) : PipelineState {
override val dynamicStates = listOf<DynamicState>()
context(MemoryStack)
fun getVkPipelineDepthStencilStateCreateInfo(): VkPipelineDepthStencilStateCreateInfo {
val info = VkPipelineDepthStencilStateCreateInfo.calloc(this@MemoryStack)
info.sType(VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO)
.flags(flags.bits)
.depthTestEnable(depthTestEnable)
.depthWriteEnable(depthWriteEnable)
.depthCompareOp(depthCompareOp.vkCompareOp)
.depthBoundsTestEnable(depthBoundsTestEnable)
.stencilTestEnable(stencilTestEnable)
.minDepthBounds(minDepthBounds)
.maxDepthBounds(maxDepthBounds)
if (front != null) info.front(front.getVkStencilOpState())
if (back != null) info.back(back.getVkStencilOpState())
return info
}
}
@JvmInline
value class VkPipelineDepthStencilStateCreateFlagBits private constructor(val bits: Int) {
infix fun or(other: VkPipelineDepthStencilStateCreateFlagBits) =
VkPipelineDepthStencilStateCreateFlagBits(this.bits or other.bits)
infix fun and(other: VkPipelineDepthStencilStateCreateFlagBits) =
VkPipelineDepthStencilStateCreateFlagBits(this.bits and other.bits)
operator fun contains(other: VkPipelineDepthStencilStateCreateFlagBits) =
(other and this).bits != 0
companion object {
val NONE = VkPipelineDepthStencilStateCreateFlagBits(0)
val VK_PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_DEPTH_ACCESS_BIT_EXT =
VkPipelineDepthStencilStateCreateFlagBits(0x00000001)
val VK_PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_STENCIL_ACCESS_BIT_EXT =
VkPipelineDepthStencilStateCreateFlagBits(0x00000002)
val VK_PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_DEPTH_ACCESS_BIT_ARM =
VK_PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_DEPTH_ACCESS_BIT_EXT
val VK_PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_STENCIL_ACCESS_BIT_ARM =
VK_PIPELINE_DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_STENCIL_ACCESS_BIT_EXT
}
} | 0 | Kotlin | 0 | 2 | 203a15f453bdf9457271218c95b3dfdb364df992 | 4,255 | KtxVulkan | MIT License |
src/main/kotlin/app/trian/cashierservice/entity/ProductCategory.kt | trianapp | 442,201,785 | false | {"Kotlin": 46957} | package app.trian.cashierservice.entity
import com.fasterxml.jackson.annotation.JsonIgnore
import javax.persistence.*
@Entity
@Table
data class ProductCategory(
@Id
@GeneratedValue
var ProductCategoryID:Long,
@Column
var category:String,
@Column
var description:String,
@Column
var createdAt:Long,
@Column
var updatedAt:Long
)
| 0 | Kotlin | 1 | 5 | ad93de4d75851f8abfda89b979a093efc6203997 | 373 | CashierBackend | MIT License |
services/src/main/java/knaufdan/android/services/userinteraction/notification/api/NotificationAction.kt | DanielKnauf | 219,150,024 | false | null | @file:Suppress("unused")
package knaufdan.android.services.userinteraction.notification.api
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.core.app.NotificationCompat
import androidx.core.app.RemoteInput
import knaufdan.android.services.common.Constants.Intent.KEY_NOTIFICATION_ID
import knaufdan.android.services.common.Constants.Intent.KEY_REQUEST_CODE
import kotlin.reflect.KClass
sealed class NotificationAction(
@StringRes val title: Int,
@DrawableRes val icon: Int,
val requestCode: Int,
val action: String = "",
val receiverTarget: KClass<out BroadcastReceiver>,
val extraData: Bundle = Bundle.EMPTY
) {
abstract fun toAndroidAction(context: Context, notificationId: Int): NotificationCompat.Action
class Button(
@StringRes title: Int,
@DrawableRes icon: Int,
requestCode: Int,
action: String = "",
receiverTarget: KClass<out BroadcastReceiver>,
extraData: Bundle = Bundle.EMPTY
) : NotificationAction(
title = title,
icon = icon,
requestCode = requestCode,
action = action,
receiverTarget = receiverTarget,
extraData = extraData
) {
override fun toAndroidAction(
context: Context,
notificationId: Int
): NotificationCompat.Action =
run {
val replyPendingIntent: PendingIntent =
context.createIntentToStartBroadcastReceiver(
receiverTarget = receiverTarget,
requestCode = requestCode,
intentAction = action,
notificationId = notificationId,
extraData = extraData
)
NotificationCompat.Action.Builder(
icon,
context.getString(title),
replyPendingIntent
).build()
}
}
class Reply(
@StringRes title: Int,
@DrawableRes icon: Int,
requestCode: Int,
action: String = "",
receiverTarget: KClass<out BroadcastReceiver>,
extraData: Bundle = Bundle.EMPTY,
private val replyLabel: String,
private val replyKey: String
) : NotificationAction(
title = title,
icon = icon,
requestCode = requestCode,
action = action,
receiverTarget = receiverTarget,
extraData = extraData
) {
override fun toAndroidAction(
context: Context,
notificationId: Int
): NotificationCompat.Action =
run {
val remoteInput: RemoteInput =
RemoteInput.Builder(replyKey).run {
setLabel(replyLabel)
build()
}
val replyPendingIntent: PendingIntent =
context.createIntentToStartBroadcastReceiver(
receiverTarget = receiverTarget,
requestCode = requestCode,
intentAction = action,
notificationId = notificationId,
extraData = extraData
)
NotificationCompat.Action.Builder(
icon,
context.getString(title),
replyPendingIntent
).run {
addRemoteInput(remoteInput)
build()
}
}
}
companion object {
private fun Context.createIntentToStartBroadcastReceiver(
receiverTarget: KClass<out BroadcastReceiver>,
requestCode: Int = 0,
intentAction: String = "",
notificationId: Int = 0,
extraData: Bundle
): PendingIntent =
Intent(
this,
receiverTarget.java
).run {
action = intentAction
flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
putExtra(
KEY_NOTIFICATION_ID,
notificationId
)
putExtra(
KEY_REQUEST_CODE,
requestCode
)
putExtras(extraData)
PendingIntent.getBroadcast(
this@createIntentToStartBroadcastReceiver,
requestCode,
this,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
}
}
}
| 13 | Kotlin | 0 | 0 | cfd7420f6d3caf94641c5ccafcb7440bc6aa8b32 | 4,849 | ArchServices | Apache License 2.0 |
src/test/kotlin/org/dersbian/canalisis/LexerTest.kt | Giuseppe-Bianc | 623,956,196 | false | null | package org.dersbian.canalisis
import org.dersbian.canalisis.syntax.Lexer
import org.dersbian.canalisis.syntax.TokenType
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
class LexerTest {
@Test
fun testAssignmentExpression() {
val lexer = Lexer("x = 5 + 3")
val tokens = lexer.lex()
Assertions.assertEquals(tokens[0].type, TokenType.IDENTIFIER)
Assertions.assertEquals(tokens[0].text, "x")
Assertions.assertEquals(tokens[1].type, TokenType.EQUAL)
Assertions.assertEquals(tokens[2].type, TokenType.NUMBER)
Assertions.assertEquals(tokens[2].text, "5")
Assertions.assertEquals(tokens[3].type, TokenType.PLUS)
Assertions.assertEquals(tokens[4].type, TokenType.NUMBER)
Assertions.assertEquals(tokens[4].text, "3")
}
@Test
fun testArithmeticExpressions() {
val lexer = Lexer("1 + 2 * 3 - 4 / 2")
val tokens = lexer.lex()
Assertions.assertEquals(tokens[0].type, TokenType.NUMBER)
Assertions.assertEquals(tokens[0].text, "1")
Assertions.assertEquals(tokens[1].type, TokenType.PLUS)
Assertions.assertEquals(tokens[2].type, TokenType.NUMBER)
Assertions.assertEquals(tokens[2].text, "2")
Assertions.assertEquals(tokens[3].type, TokenType.MULTIPLY)
Assertions.assertEquals(tokens[4].type, TokenType.NUMBER)
Assertions.assertEquals(tokens[4].text, "3")
Assertions.assertEquals(tokens[5].type, TokenType.MINUS)
Assertions.assertEquals(tokens[6].type, TokenType.NUMBER)
Assertions.assertEquals(tokens[6].text, "4")
Assertions.assertEquals(tokens[7].type, TokenType.DIVIDE)
Assertions.assertEquals(tokens[8].type, TokenType.NUMBER)
Assertions.assertEquals(tokens[8].text, "2")
}
@Test
fun testLogicalExpressions() {
val lexer = Lexer("a && b || !c")
val tokens = lexer.lex()
Assertions.assertEquals(tokens[0].type, TokenType.IDENTIFIER)
Assertions.assertEquals(tokens[0].text, "a")
Assertions.assertEquals(tokens[1].type, TokenType.AND_AND)
Assertions.assertEquals(tokens[2].type, TokenType.IDENTIFIER)
Assertions.assertEquals(tokens[2].text, "b")
Assertions.assertEquals(tokens[3].type, TokenType.OR_OR)
Assertions.assertEquals(tokens[4].type, TokenType.NOT)
Assertions.assertEquals(tokens[5].type, TokenType.IDENTIFIER)
Assertions.assertEquals(tokens[5].text, "c")
}
@Test
fun testComparisonExpressions() {
val lexer = Lexer("x == y != z <= w >= v < u > t")
val tokens = lexer.lex()
Assertions.assertEquals(tokens[0].type, TokenType.IDENTIFIER)
Assertions.assertEquals(tokens[0].text, "x")
Assertions.assertEquals(tokens[1].type, TokenType.EQUAL_EQUAL)
Assertions.assertEquals(tokens[2].type, TokenType.IDENTIFIER)
Assertions.assertEquals(tokens[2].text, "y")
Assertions.assertEquals(tokens[3].type, TokenType.NOT_EQUAL)
Assertions.assertEquals(tokens[4].type, TokenType.IDENTIFIER)
Assertions.assertEquals(tokens[4].text, "z")
Assertions.assertEquals(tokens[5].type, TokenType.LESS_EQUAL)
Assertions.assertEquals(tokens[6].type, TokenType.IDENTIFIER)
Assertions.assertEquals(tokens[6].text, "w")
Assertions.assertEquals(tokens[7].type, TokenType.GREATER_EQUAL)
Assertions.assertEquals(tokens[8].type, TokenType.IDENTIFIER)
Assertions.assertEquals(tokens[8].text, "v")
Assertions.assertEquals(tokens[9].type, TokenType.LESS)
Assertions.assertEquals(tokens[10].type, TokenType.IDENTIFIER)
Assertions.assertEquals(tokens[10].text, "u")
Assertions.assertEquals(tokens[11].type, TokenType.GREATER)
Assertions.assertEquals(tokens[12].type, TokenType.IDENTIFIER)
Assertions.assertEquals(tokens[12].text, "t")
}
@Test
fun testUnsupportedCharacters() {
val input = "#$^"
val lexer = Lexer(input)
val tokens = lexer.lex()
Assertions.assertEquals(tokens[0].type, TokenType.NULL)
Assertions.assertEquals(tokens[1].type, TokenType.NULL)
Assertions.assertEquals(tokens[2].type, TokenType.NULL)
Assertions.assertEquals(tokens[0].text, "#")
Assertions.assertEquals(tokens[1].text, "$")
Assertions.assertEquals(tokens[2].text, "^")
}
@Test
fun testUnsupportedCharactersDiagnostic() {
val input = "#$^"
val lexer = Lexer(input)
val tokens = lexer.lex()
Assertions.assertEquals(tokens[0].type, TokenType.NULL)
Assertions.assertEquals(tokens[1].type, TokenType.NULL)
Assertions.assertEquals(tokens[2].type, TokenType.NULL)
Assertions.assertEquals(
lexer.diagnostics, listOf(
"ERROR: bad character input: '#'",
"ERROR: bad character input: '$'",
"ERROR: bad character input: '^'"
)
)
}
@Test
fun inputInsufficiente() {
val lexer = Lexer("")
val tokens = lexer.lex()
Assertions.assertEquals(0, lexer.length)
}
} | 0 | Kotlin | 0 | 0 | 85fed8571780660298ecb8ebb77c9e2230c8fece | 5,202 | Derblk | MIT License |
migratedb-integration-tests/src/main/java/migratedb/v1/integrationtest/database/DbSystem.kt | daniel-huss | 456,543,899 | false | {"Maven POM": 13, "Markdown": 1, "Text": 7, "Ignore List": 3, "Git Attributes": 1, "AsciiDoc": 3, "Kotlin": 140, "XML": 7, "Java": 473, "Gradle": 5, "Shell": 2, "Batchfile": 2, "INI": 1, "SQL": 1, "Groovy": 3, "Java Properties": 5, "YAML": 2} | /*
* Copyright 2022-2023 The MigrateDB contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package migratedb.v1.integrationtest.database
import migratedb.v1.core.api.internal.database.base.DatabaseType
import migratedb.v1.integrationtest.database.mutation.IndependentDatabaseMutation
import migratedb.v1.integrationtest.util.base.SafeIdentifier
import migratedb.v1.integrationtest.util.base.SafeIdentifier.Companion.asSafeIdentifier
import migratedb.v1.integrationtest.util.container.SharedResources
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.Arguments.arguments
import org.junit.jupiter.params.provider.ArgumentsProvider
import java.util.stream.Stream
import javax.sql.DataSource
/**
* Adapter for the various supported database systems.
*/
interface DbSystem {
interface Handle : AutoCloseable {
val type: DatabaseType
/**
* Creates the schema or database with the given name if it doesn't exist. Some database systems don't support
* either schema-level or database-level isolation, so it's undefined whether the namespace will be implemented
* at the schema or at the database level.
*
* @return The identifier that must be used to qualify tables in the namespace. This can be null, which means
* that qualified names are not supported.
*/
fun createNamespaceIfNotExists(namespace: SafeIdentifier): SafeIdentifier?
/**
* Drops an existing schema or database.
*/
fun dropNamespaceIfExists(namespace: SafeIdentifier)
/**
* Connects to the database with administrative privileges.
*/
fun newAdminConnection(namespace: SafeIdentifier): DataSource
/**
* Generates a new database mutation within [schema] (or the current schema, if null) that is independent from
* all previously generated database mutations in the same schema.
*/
fun nextMutation(schema: SafeIdentifier?): IndependentDatabaseMutation
/**
* Normalizes the case of an identifier.
*/
fun normalizeCase(s: CharSequence): String = s.toString().uppercase()
/**
* Normalizes the case of an identifier.
*/
fun normalizeCase(s: SafeIdentifier): SafeIdentifier = normalizeCase(s.toString()).asSafeIdentifier()
}
fun get(sharedResources: SharedResources): Handle
class All : ArgumentsProvider {
override fun provideArguments(context: ExtensionContext): Stream<Arguments> = Stream.of(
CockroachDb.entries,
Db2.entries,
Derby.entries,
Firebird.entries,
H2.entries,
Hsqldb.entries,
Informix.entries,
MariaDb.entries,
MySql.entries,
Oracle.entries,
Postgres.entries,
SqlServer.entries,
Sqlite.entries,
).flatMap { it.stream() }.map { arguments(it) }
}
class JustOneForDebugging : ArgumentsProvider {
override fun provideArguments(context: ExtensionContext): Stream<Arguments> = Stream.of(
SomeInMemoryDb
).map { arguments(it) }
}
}
| 0 | Java | 0 | 0 | 97ce486d14df4669846a53e5a046a9a87f77788d | 3,827 | migratedb | Apache License 2.0 |
src/main/java/ru/greenpix/monitoring/pinger/netty/MinecraftConnectionExtension.kt | GreenpixDev | 617,089,975 | false | {"Java": 55924, "Kotlin": 15209} | package ru.greenpix.monitoring.pinger.netty
import reactor.netty.Connection
import ru.greenpix.monitoring.pinger.join
import ru.greenpix.monitoring.pinger.protocol.ProtocolType
var Connection.state: ProtocolType
get() = channel().attr(NetworkManager.PROTOCOL_ATTRIBUTE_KEY).get()
set(value) = channel().attr(NetworkManager.PROTOCOL_ATTRIBUTE_KEY).set(value)
suspend fun Connection.close() {
channel().close()
onDispose().join()
} | 1 | null | 1 | 1 | 143286e485419977712d94323d59942551010489 | 448 | MonitoringPinger | Apache License 2.0 |
airbyte-cdk/java/airbyte-cdk/s3-destinations/src/testFixtures/kotlin/io/airbyte/cdk/integrations/destination/s3/S3AvroParquetDestinationAcceptanceTest.kt | tim-werner | 511,419,970 | false | {"Java Properties": 8, "Shell": 57, "Markdown": 1170, "Batchfile": 1, "Makefile": 3, "JavaScript": 31, "CSS": 9, "Python": 4183, "Kotlin": 845, "Java": 723, "INI": 10, "Dockerfile": 27, "HTML": 7, "SQL": 527, "PLpgSQL": 8, "TSQL": 1, "PLSQL": 2} | /*
* Copyright (c) 2023 Airbyte, Inc., all rights reserved.
*/
package io.airbyte.cdk.integrations.destination.s3
import com.fasterxml.jackson.databind.JsonNode
import io.airbyte.cdk.integrations.destination.s3.avro.JsonSchemaType
import io.airbyte.cdk.integrations.standardtest.destination.argproviders.NumberDataTypeTestArgumentProvider
import io.airbyte.commons.json.Jsons
import io.airbyte.commons.resources.MoreResources
import io.airbyte.protocol.models.v0.AirbyteCatalog
import io.airbyte.protocol.models.v0.AirbyteMessage
import io.airbyte.protocol.models.v0.AirbyteStream
import io.airbyte.protocol.models.v0.CatalogHelpers
import java.io.IOException
import java.util.*
import org.apache.avro.Schema
import org.apache.avro.generic.GenericData
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ArgumentsSource
abstract class S3AvroParquetDestinationAcceptanceTest
protected constructor(fileUploadFormat: FileUploadFormat) :
S3DestinationAcceptanceTest(fileUploadFormat) {
@ParameterizedTest
@ArgumentsSource(NumberDataTypeTestArgumentProvider::class)
@Throws(Exception::class)
fun testNumberDataType(catalogFileName: String, messagesFileName: String) {
val catalog = readCatalogFromFile(catalogFileName)
val messages = readMessagesFromFile(messagesFileName)
val config = this.getConfig()
val defaultSchema = getDefaultSchema(config)
val configuredCatalog = CatalogHelpers.toDefaultConfiguredCatalog(catalog)
runSyncAndVerifyStateOutput(config, messages, configuredCatalog, false)
for (stream in catalog.streams) {
val streamName = stream.name
val schema = if (stream.namespace != null) stream.namespace else defaultSchema!!
val actualSchemaTypes = retrieveDataTypesFromPersistedFiles(streamName, schema)
val expectedSchemaTypes = retrieveExpectedDataTypes(stream)
Assertions.assertEquals(expectedSchemaTypes, actualSchemaTypes)
}
}
private fun retrieveExpectedDataTypes(stream: AirbyteStream): Map<String, Set<Schema.Type>> {
val iterableNames = Iterable { stream.jsonSchema["properties"].fieldNames() }
val nameToNode: Map<String, JsonNode> =
iterableNames.associateWith { name: String -> getJsonNode(stream, name) }
return nameToNode.entries.associate { it.key to getExpectedSchemaType(it.value) }
}
private fun getJsonNode(stream: AirbyteStream, name: String): JsonNode {
val properties = stream.jsonSchema["properties"]
if (properties.size() == 1) {
return properties["data"]
}
return properties[name]["items"]
}
private fun getExpectedSchemaType(fieldDefinition: JsonNode): Set<Schema.Type> {
val typeProperty =
if (fieldDefinition["type"] == null) fieldDefinition["\$ref"]
else fieldDefinition["type"]
val airbyteTypeProperty = fieldDefinition["airbyte_type"]
val airbyteTypePropertyText = airbyteTypeProperty?.asText()
return JsonSchemaType.entries
.toTypedArray()
.filter { value: JsonSchemaType ->
value.jsonSchemaType == typeProperty.asText() &&
compareAirbyteTypes(airbyteTypePropertyText, value)
}
.map { obj: JsonSchemaType -> obj.avroType }
.toSet()
}
private fun compareAirbyteTypes(
airbyteTypePropertyText: String?,
value: JsonSchemaType
): Boolean {
if (airbyteTypePropertyText == null) {
return value.jsonSchemaAirbyteType == null
}
return airbyteTypePropertyText == value.jsonSchemaAirbyteType
}
@Throws(IOException::class)
private fun readCatalogFromFile(catalogFilename: String): AirbyteCatalog {
return Jsons.deserialize(
MoreResources.readResource(catalogFilename),
AirbyteCatalog::class.java
)
}
@Throws(IOException::class)
private fun readMessagesFromFile(messagesFilename: String): List<AirbyteMessage> {
return MoreResources.readResource(messagesFilename).trim().lines().map { record ->
Jsons.deserialize(record, AirbyteMessage::class.java)
}
}
@Throws(Exception::class)
protected abstract fun retrieveDataTypesFromPersistedFiles(
streamName: String,
namespace: String
): Map<String, Set<Schema.Type>>
protected fun getTypes(record: GenericData.Record): Map<String, Set<Schema.Type>> {
val fieldList =
record.schema.fields.filter { field: Schema.Field ->
!field.name().startsWith("_airbyte")
}
return if (fieldList.size == 1) {
fieldList.associate {
it.name() to
it.schema()
.types
.map { obj: Schema -> obj.type }
.filter { type: Schema.Type -> type != Schema.Type.NULL }
.toSet()
}
} else {
fieldList.associate {
it.name() to
it.schema()
.types
.filter { type: Schema -> type.type != Schema.Type.NULL }
.flatMap { type: Schema -> type.elementType.types }
.map { obj: Schema -> obj.type }
.filter { type: Schema.Type -> type != Schema.Type.NULL }
.toSet()
}
}
}
}
| 1 | null | 1 | 1 | b2e7895ed3e1ca7c1600ae1c23578dd1024f20ff | 5,628 | airbyte | MIT License |
identity/data/src/main/java/com/timecat/identity/data/block/type/IdentityType.kt | LinXueyuanStdio | 324,718,951 | false | {"Java": 208407, "Kotlin": 165348} | package com.timecat.identity.data.block.type
import androidx.annotation.IntDef
/**
* @author 林学渊
* @email [email protected]
* @date 2021/2/6
* @description 方块
* 方块就是身份,identity
* 最基本的方块是身份
* 然后有可养成的方块
* @usage null
*/
@IntDef(
IDENTITY_Base,
IDENTITY_Cube
)
@Retention(AnnotationRetention.SOURCE)
annotation class IdentityType
const val IDENTITY_Base: Int = 0 //基础,不可养成,用于简单的权限控制
const val IDENTITY_Cube: Int = 1 //方块,没有动画形象、语音等其他资源,而只有工具属性,用于功能的打包组织和出售
| 1 | null | 1 | 1 | 3258d40c4b2cba45a5e380556bf460f7fd52f823 | 484 | TimeCatIdentity | Apache License 2.0 |
app/src/main/java/com/foreveross/atwork/modules/discussion/adapter/DiscussionFeaturesInManagerAdapter.kt | AoEiuV020 | 421,650,297 | false | {"Java": 8618305, "Kotlin": 1733509, "JavaScript": 719597, "CSS": 277438, "HTML": 111559} | package com.foreveross.atwork.modules.discussion.adapter
import android.view.View
import android.view.ViewGroup
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.module.DraggableModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.foreveross.atwork.infrastructure.model.discussion.template.DiscussionFeature
import com.foreveross.atwork.modules.discussion.component.DiscussionFeatureInManagerItemView
class DiscussionFeaturesInManagerAdapter(featureList: MutableList<DiscussionFeature>) : BaseQuickAdapter<DiscussionFeature, DiscussionFeaturesInManagerAdapter.DiscussionFeatureViewHolder>(-1, featureList), DraggableModule {
override fun onCreateDefViewHolder(parent: ViewGroup, viewType: Int): DiscussionFeatureViewHolder {
val itemView = DiscussionFeatureInManagerItemView(context)
return DiscussionFeatureViewHolder(itemView)
}
override fun convert(helper: DiscussionFeatureViewHolder, item: DiscussionFeature) {
helper.featureItemView.refreshItem(item)
}
class DiscussionFeatureViewHolder (itemView: View) : BaseViewHolder(itemView) {
var featureItemView: DiscussionFeatureInManagerItemView = itemView as DiscussionFeatureInManagerItemView
}
} | 1 | null | 1 | 1 | 1c4ca5bdaea6d5230d851fb008cf2578a23b2ce5 | 1,281 | w6s_lite_android | MIT License |
app/src/main/java/com/diches/dichboxmobile/tools/ViewDecorators.kt | Andrew1407 | 337,825,246 | false | null | package com.diches.dichboxmobile.tools
import android.graphics.Color
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.widget.TextView
fun decorateView(
element: TextView,
prefix: String,
parameters: Pair<String, Int>
) {
val (value, color) = parameters
val text = prefix + value
val spannable = SpannableString(text)
spannable.setSpan(
ForegroundColorSpan(color),
prefix.length, text.length,
Spannable.SPAN_INCLUSIVE_INCLUSIVE
)
element.text = spannable
}
fun fillView(element: TextView, parameters: Pair<String, String>) {
val (text, color) = parameters
element.text = text
element.setTextColor(Color.parseColor(color))
}
| 0 | Kotlin | 0 | 0 | 11eea3cb4c29586e1077c253c78aa5b5117d02e4 | 800 | DichBoxMobile | MIT License |
common/src/main/java/io/github/caimucheng/leaf/common/icon/Needle.kt | CaiMuCheng | 684,525,233 | false | {"Kotlin": 427280, "Batchfile": 69} | @file:Suppress("UnusedReceiverParameter")
package io.github.caimucheng.leaf.common.icon
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.materialIcon
import androidx.compose.material.icons.materialPath
import androidx.compose.ui.graphics.vector.ImageVector
val Icons.Filled.Needle: ImageVector
get() {
if (_needle != null) {
return _needle!!
}
_needle = materialIcon(name = "Needle") {
materialPath {
moveTo(11.15f, 15.18f)
lineTo(9.73f, 13.77f)
lineTo(11.15f, 12.35f)
lineTo(12.56f, 13.77f)
lineTo(13.97f, 12.35f)
lineTo(12.56f, 10.94f)
lineTo(13.97f, 9.53f)
lineTo(15.39f, 10.94f)
lineTo(16.8f, 9.53f)
lineTo(13.97f, 6.7f)
lineTo(6.9f, 13.77f)
lineTo(9.73f, 16.6f)
moveTo(3.08f, 19f)
lineTo(6.2f, 15.89f)
lineTo(4.08f, 13.77f)
lineTo(13.97f, 3.87f)
lineTo(16.1f, 6f)
lineTo(17.5f, 4.58f)
lineTo(16.1f, 3.16f)
lineTo(17.5f, 1.75f)
lineTo(21.75f, 6f)
lineTo(20.34f, 7.4f)
lineTo(18.92f, 6f)
lineTo(17.5f, 7.4f)
lineTo(19.63f, 9.53f)
lineTo(9.73f, 19.42f)
lineTo(7.61f, 17.3f)
lineTo(3.08f, 21.84f)
lineTo(3.08f, 19f)
close()
}
}
return _needle!!
}
private var _needle: ImageVector? = null | 3 | Kotlin | 5 | 22 | 8d1e5b590cf70e677849cba90d5df0b80abb9f5d | 1,691 | Leaf-IDE | Apache License 2.0 |
app/src/main/java/com/example/clubdeportivo/screens/PayFeeAdminScreen.kt | tiago-appdev | 803,323,597 | false | {"Kotlin": 38452} | package com.example.clubdeportivo.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.navigation.NavController
import com.example.clubdeportivo.navigation.AppScreens
@Composable
fun PayFeeAdmin(navController: NavController) {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = "Pantalla Pagar Cuota")
Button(onClick = {
navController.navigate(AppScreens.MenuAdminScreen.route)
}) {
Text(text = "Atras!")
}
}
} | 0 | Kotlin | 0 | 0 | 6832d9f705d5c3d6b0f1ce844e04a996df71c5fe | 929 | club-deportivo-android | MIT License |
kotlin/app/src/main/java/tw/idv/woofdog/easycashaccount/adapters/DbContentAdapter.kt | woofdogtw | 786,331,884 | false | {"Kotlin": 222661, "JavaScript": 740} | package tw.idv.woofdog.easycashaccount.adapters
import android.app.Activity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import tw.idv.woofdog.easycashaccount.activities.DbTypeFragment
import tw.idv.woofdog.easycashaccount.activities.TransactionFragment
class DbContentAdapter(
fragmentManager: FragmentManager,
lifecycle: Lifecycle,
private val parentActivity: Activity,
private val typeListAdapter: TypeListAdapter,
private val transListAdapter: TransListAdapter
) :
FragmentStateAdapter(fragmentManager, lifecycle) {
override fun getItemCount(): Int {
return 2
}
override fun createFragment(position: Int): Fragment {
return when (position) {
1 -> {
typeFragment = DbTypeFragment(parentActivity, typeListAdapter, transListAdapter)
typeFragment
}
else -> {
transFragment = TransactionFragment(parentActivity, transListAdapter)
transFragment
}
}
}
lateinit var typeFragment: DbTypeFragment
lateinit var transFragment: TransactionFragment
}
| 0 | Kotlin | 0 | 0 | 18a3ac7f70d7dbbe50613ba43c1071cd63f489c1 | 1,261 | easycashaccount | MIT License |
RecyclerViewTest/app/src/main/java/com/example/recyclerviewtest/Fruit.kt | 1802024110 | 533,118,787 | false | null | package com.example.recyclerviewtest
class Fruit(val name:String,val imageId:Int) {
} | 0 | Kotlin | 1 | 0 | 12bb3ec2ddf5c0700f781a3146a388bb662a22fd | 86 | Android_Learn | Apache License 2.0 |
src/main/java/com/maddyhome/idea/vim/helper/SearchHelperKt.kt | JetBrains | 1,459,486 | false | null | /*
* Copyright 2003-2023 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.helper
import com.maddyhome.idea.vim.api.globalOptions
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.common.Direction
import com.maddyhome.idea.vim.helper.SearchHelper.findPositionOfFirstCharacter
private data class State(val position: Int, val trigger: Char, val inQuote: Boolean?, val lastOpenSingleQuotePos: Int)
// bounds are considered inside corresponding quotes
internal fun checkInString(chars: CharSequence, currentPos: Int, str: Boolean): Boolean {
val begin = findPositionOfFirstCharacter(chars, currentPos, setOf('\n'), false, Direction.BACKWARDS)?.second?.plus(1) ?: 0
val changes = quoteChanges(chars, begin)
// TODO: here we need to keep only the latest element in beforePos (if any) and
// don't need atAndAfterPos to be eagerly collected
var (beforePos, atAndAfterPos) = changes.partition { it.position < currentPos }
var (atPos, afterPos) = atAndAfterPos.partition { it.position == currentPos }
assert(atPos.size <= 1) { "Multiple characters at position $currentPos in string $chars" }
if (atPos.isNotEmpty()) {
val atPosChange = atPos[0]
if (afterPos.isEmpty()) {
// it is situation when cursor is on closing quote, so we must consider that we are inside quotes pair
afterPos = afterPos.toMutableList()
afterPos.add(atPosChange)
} else {
// it is situation when cursor is on opening quote, so we must consider that we are inside quotes pair
beforePos = beforePos.toMutableList()
beforePos.add(atPosChange)
}
}
val lastBeforePos = beforePos.lastOrNull()
// if opening quote was found before pos (inQuote=true), it doesn't mean pos is in string, we need
// to find closing quote to be sure
var posInQuote = lastBeforePos?.inQuote?.let { if (it) null else it }
val lastOpenSingleQuotePosBeforeCurrentPos = lastBeforePos?.lastOpenSingleQuotePos ?: -1
var posInChar = if (lastOpenSingleQuotePosBeforeCurrentPos == -1) false else null
var inQuote: Boolean? = null
for ((_, trigger, inQuoteAfter, lastOpenSingleQuotePosAfter) in afterPos) {
inQuote = inQuoteAfter
if (posInQuote != null && posInChar != null) break
if (posInQuote == null && inQuoteAfter != null) {
// if we found double quote
if (trigger == '"') {
// then previously it has opposite value
posInQuote = !inQuoteAfter
// if we found single quote
} else if (trigger == '\'') {
// then we found closing single quote
posInQuote = inQuoteAfter
}
}
if (posInChar == null && lastOpenSingleQuotePosAfter != lastOpenSingleQuotePosBeforeCurrentPos) {
// if we found double quote and we reset position of last single quote
if (trigger == '"' && lastOpenSingleQuotePosAfter == -1) {
// then it means previously there supposed to be open single quote
posInChar = false
// if we found single quote
} else if (trigger == '\'') {
// if we reset position of last single quote
// it means we found closing single quote
// else it means we found opening single quote
posInChar = lastOpenSingleQuotePosAfter == -1
}
}
}
return if (str) posInQuote != null && posInQuote && (inQuote == null || !inQuote) else posInChar != null && posInChar
}
// yields changes of inQuote and lastOpenSingleQuotePos during while iterating over chars
// rules are that:
// - escaped quotes are skipped
// - single quoted group may enclose only one character, maybe escaped,
// - so distance between opening and closing single quotes cannot be more than 3
// - bounds are considered inside corresponding quotes
private fun quoteChanges(chars: CharSequence, begin: Int) = sequence {
// position of last found unpaired single quote
var lastOpenSingleQuotePos = -1
// whether we are in double quotes
// true - definitely yes
// false - definitely no
// null - maybe yes, in case we found such combination: '"
// in that situation it may be double quote inside single quotes, so we cannot threat it as double quote pair open/close
var inQuote: Boolean? = false
val charsToSearch = setOf('\'', '"', '\n')
var found = findPositionOfFirstCharacter(chars, begin, charsToSearch, false, Direction.FORWARDS)
while (found != null && found.first != '\n') {
val i = found.second
val c = found.first
when (c) {
'"' -> {
// if [maybe] in quote, then we know we found closing quote, so now we surely are not in quote
if (inQuote == null || inQuote) {
// we just found closing double quote
inQuote = false
// reset last found single quote, as it was in string literal
lastOpenSingleQuotePos = -1
// if we previously found unclosed single quote
} else if (lastOpenSingleQuotePos >= 0) {
// ...but we are too far from it
if (i - lastOpenSingleQuotePos > 2) {
// then it definitely was not opening single quote
lastOpenSingleQuotePos = -1
// and we found opening double quote
inQuote = true
} else {
// else we don't know if we inside double or single quotes or not
inQuote = null
}
// we were not in double nor in single quote, so now we are in double quote
} else {
inQuote = true
}
}
'\'' -> {
// if we previously found unclosed single quote
if (lastOpenSingleQuotePos >= 0) {
// ...but we are too far from it
if (i - lastOpenSingleQuotePos > 3) {
// ... forget about it and threat current one as unclosed
lastOpenSingleQuotePos = i
} else {
// else we found closing single quote
lastOpenSingleQuotePos = -1
// and if we didn't know whether we are in double quote or not
if (inQuote == null) {
// then now we are definitely not in
inQuote = false
}
}
} else {
// we found opening single quote
lastOpenSingleQuotePos = i
}
}
}
yield(State(i, c, inQuote, lastOpenSingleQuotePos))
found =
findPositionOfFirstCharacter(chars, i + Direction.FORWARDS.toInt(), charsToSearch, false, Direction.FORWARDS)
}
}
/**
* Check ignorecase and smartcase options to see if a case insensitive search should be performed with the given pattern.
*
* When ignorecase is not set, this will always return false - perform a case sensitive search.
*
* Otherwise, check smartcase. When set, the search will be case insensitive if the pattern contains only lowercase
* characters, and case sensitive (returns false) if the pattern contains any lowercase characters.
*
* The smartcase option can be ignored, e.g. when searching for the whole word under the cursor. This always performs a
* case insensitive search, so `\<Work\>` will match `Work` and `work`. But when choosing the same pattern from search
* history, the smartcase option is applied, and `\<Work\>` will only match `Work`.
*/
internal fun shouldIgnoreCase(pattern: String, ignoreSmartCaseOption: Boolean): Boolean {
val sc = injector.globalOptions().smartcase && !ignoreSmartCaseOption
return injector.globalOptions().ignorecase && !(sc && containsUpperCase(pattern))
}
private fun containsUpperCase(pattern: String): Boolean {
for (i in pattern.indices) {
if (Character.isUpperCase(pattern[i]) && (i == 0 || pattern[i - 1] != '\\')) {
return true
}
}
return false
}
| 7 | null | 724 | 8,914 | 948520f90aa96569955d221a61089a63b718f071 | 7,803 | ideavim | MIT License |
forceupdate/src/main/java/com/android/forceupdate/ui/ForceUpdateProviderFactory.kt | Abdulrahman-AlGhamdi | 344,500,974 | false | null | package com.android.forceupdate.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.android.forceupdate.repository.install.InstallRepositoryImpl
import com.android.forceupdate.repository.download.DownloadRepositoryImpl
internal class ForceUpdateProviderFactory(
private val downloadRepositoryImpl: DownloadRepositoryImpl,
private val forceUpdateRepositoryImpl: InstallRepositoryImpl
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return ForceUpdateViewModel(downloadRepositoryImpl, forceUpdateRepositoryImpl) as T
}
} | 0 | Kotlin | 2 | 2 | 7274b5014000eb4c46060dd08df7039970d7702b | 634 | ForceUpdate | Apache License 2.0 |
core/src/net/brenig/pixelescape/game/data/constants/ScoreboardNames.kt | jbrenig | 77,611,951 | false | null | package net.brenig.pixelescape.game.data.constants
/**
* contains constant Strings
*/
object ScoreboardNames {
const val SCOREBOARD_CLASSIC = "classic"
const val SCOREBOARD_ARCADE = "arcade"
const val SCOREBOARD_SPEED = "speed"
const val SCOREBOARD_FLASH = "flash"
const val SCOREBOARD_BLINK = "blink"
const val SCOREBOARD_DRAG = "drag"
}
| 0 | Kotlin | 0 | 0 | a6845db6ad2e3a89b8b6068133a60a3f5b32d9d8 | 367 | PixelEscape | MIT License |
mediator/src/test/kotlin/no/nav/dagpenger/quiz/mediator/integration/NyProsessfaktaBehovLøserTest.kt | navikt | 292,224,937 | false | {"Kotlin": 953879, "Dockerfile": 616} | package no.nav.dagpenger.quiz.mediator.integration
import no.nav.dagpenger.quiz.mediator.db.FaktumTable
import no.nav.dagpenger.quiz.mediator.db.ProsessRepositoryPostgres
import no.nav.dagpenger.quiz.mediator.db.ResultatRecord
import no.nav.dagpenger.quiz.mediator.helpers.Postgres
import no.nav.dagpenger.quiz.mediator.meldinger.FaktumSvarService
import no.nav.dagpenger.quiz.mediator.meldinger.NyProsessBehovLøser
import no.nav.dagpenger.quiz.mediator.soknad.dagpenger.Dagpenger
import no.nav.dagpenger.quiz.mediator.soknad.innsending.Innsending
import no.nav.helse.rapids_rivers.testsupport.TestRapid
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertDoesNotThrow
import java.time.LocalDateTime
import java.util.UUID
internal class NyProsessfaktaBehovLøserTest : SøknadBesvarer() {
@BeforeEach
fun setup() {
Postgres.withMigratedDb {
Dagpenger.registrer { FaktumTable(it.fakta) }
Innsending.registrer { FaktumTable(it.fakta) }
val søknadPersistence = ProsessRepositoryPostgres()
val resultatPersistence = ResultatRecord()
testRapid = TestRapid().also {
FaktumSvarService(
prosessRepository = søknadPersistence,
resultatPersistence = resultatPersistence,
rapidsConnection = it,
)
NyProsessBehovLøser(søknadPersistence, it)
}
}
}
@AfterEach
fun reset() {
testRapid.reset()
}
@Test
fun `Hent alle fakta happy path`() {
withSøknad(nySøknadBehov("Dagpenger")) { _ ->
assertEquals(2, testRapid.inspektør.size)
melding(0).let {
assertEquals("behov", it["@event_name"].asText())
assertEquals(
listOf("NySøknad"),
it["@behov"].map { it.asText() },
)
assertFalse(it["@løsning"]["NySøknad"].isNull, "NySøknad behov skal besvares med søknad id")
}
melding(1).let {
assertEquals("søker_oppgave", it["@event_name"].asText())
assertFalse { it.toString().contains(""""svar":""") }
}
}
}
@Test
fun `Oppretter ny prosess for innsending`() {
val uuid = triggNySøknadsprosess(nySøknadBehov("Innsending"))
assertEquals(2, testRapid.inspektør.size)
assertDoesNotThrow {
UUID.fromString(uuid)
}
assertEquals("faktum.generell-innsending.hvorfor", testRapid.inspektør.message(1)["seksjoner"][0]["fakta"][0]["beskrivendeId"].asText())
}
@Test
fun `Ignore nysøknad med fakta`() {
testRapid.sendTestMessage(ferdigNySøknadløsning)
assertEquals(0, testRapid.inspektør.size)
}
private val søknadUUID = UUID.randomUUID()
private val ferdigNySøknadløsning =
//language=JSON
"""
{
"@event_name": "behov",
"@behov" : ["NySøknad"],
"@opprettet": "${LocalDateTime.now()}",
"@id": "${UUID.randomUUID()}",
"søknad_uuid": "$søknadUUID",
"ident": "123456789",
"@løsning": {
"NySøknad" : "$søknadUUID"
}
}
""".trimIndent()
private fun nySøknadBehov(prosessnavn: String) =
//language=JSON
"""
{
"@event_name": "behov",
"@behov" : ["NySøknad"],
"@opprettet": "${LocalDateTime.now()}",
"@id": "${UUID.randomUUID()}",
"søknad_uuid": "$søknadUUID",
"ident": "123456789",
"prosessnavn": "$prosessnavn"
}
""".trimIndent()
}
| 6 | Kotlin | 0 | 0 | 48c6249d0586552257281b1bccef039c34c74945 | 3,910 | dp-quiz | MIT License |
localization-gradle-plugin/src/com/hendraanggrian/localization/LocalizeJvmTask.kt | hendraanggrian | 178,171,302 | false | null | package com.hendraanggrian.localization
import com.google.common.collect.Ordering
import com.hendraanggrian.localization.internal.AbstractLocalizeTask
import java.util.Collections
import java.util.Enumeration
import java.util.Locale
import java.util.Properties
import java.util.TreeSet
/** Task to write properties files which will then be used as [java.util.ResourceBundle]. */
open class LocalizeJvmTask : AbstractLocalizeTask() {
final override fun onGenerateLocale(column: String, locale: Locale) {
val properties = SortedProperties()
table.get().rowKeySet().forEach { row -> properties[row] = table.get()[row, column] }
outputDirectory.get().mkdirs()
val outputFile = outputDirectory.get().resolve("${resourceName.get()}${getSuffix(locale, '_')}.properties")
outputFile.write { properties.store(it, getFileComment(false)) }
}
/**
* Sorted properties that reportedly only works on Java 8.
* See [StackOverflow](https://stackoverflow.com/a/52127284/1567541).
*/
private class SortedProperties : Properties() {
companion object {
const val serialVersionUID = 1L
}
override val keys: MutableSet<Any> get() = Collections.unmodifiableSet(TreeSet(super.keys))
override val entries: MutableSet<MutableMap.MutableEntry<Any, Any>>
get() {
val set1 = super.entries
val set2 = LinkedHashSet<MutableMap.MutableEntry<Any, Any>>(set1.size)
set1.sortedWith(Ordering.from { o1, o2 -> "${o1.key}".compareTo("${o2.key}") })
.forEach { set2.add(it) }
return set2
}
override fun keys(): Enumeration<Any> = Collections.enumeration(TreeSet(super.keys))
}
}
| 0 | Kotlin | 0 | 0 | ca6db0018f7ed2fefa68413400763536c3f1646e | 1,782 | localization-gradle-plugin | Apache License 2.0 |
source/app/src/main/java/com/apion/apionhome/data/model/User.kt | viet06061999 | 471,421,323 | true | {"Kotlin": 161735, "Java": 51216} | package com.apion.apionhome.data.model
import android.os.Parcelable
import com.apion.apionhome.data.model.community.Participant
import com.google.gson.annotations.SerializedName
import kotlinx.parcelize.Parcelize
@Parcelize
data class User(
@SerializedName("id")
val id: Int,
@SerializedName("name")
val name: String,
@SerializedName("remember_token")
val token: String,
@SerializedName("phone")
val phone: String,
@SerializedName("referal")
val refer: String?,
@SerializedName("dob")
val dateOfBirth: String,
@SerializedName("address")
val address: String,
@SerializedName("avatar")
val avatar: String,
@SerializedName("sex")
val sex: String,
@SerializedName("academicLevel")
val academicLevel: String,
@SerializedName("job")
val job: String,
@SerializedName("pincode")
val pincode: String,
@SerializedName("isFirst")
val isFirst: String,
@SerializedName("position")
val position: String,
@SerializedName("permission")
val permission: String,
@SerializedName("email")
val email: String,
@SerializedName("facebook_id")
val facebook_id: String,
@SerializedName("created_at")
val created_at: String,
@SerializedName("updated_at")
val updated_at: String,
@SerializedName("my_staff")
val myStaff: List<User>?,
@SerializedName("boss")
val boss: User? = null,
@SerializedName("house_sold")
val houseSold: List<House>?,
@SerializedName("my_houses")
val myHouses: List<House>?,
@SerializedName("participants")
val participants: List<Participant>?,
@SerializedName("houses_bookmark")
val bookmarks: List<BookMark>?,
) : GeneraEntity, Parcelable {
override fun areItemsTheSame(newItem: GeneraEntity): Boolean =
newItem is User && this.id == newItem.id
override fun areContentsTheSame(newItem: GeneraEntity): Boolean =
newItem is User && this == newItem
}
| 0 | null | 0 | 0 | 24ddb088ffd985dcd34e3e8deeb5edcc1d717558 | 1,973 | apion_home | Apache License 2.0 |
classfile/src/main/kotlin/org/tinygears/bat/classfile/attribute/AttributeMap.kt | TinyGearsOrg | 562,774,371 | false | {"Kotlin": 1879358, "Smali": 712514, "ANTLR": 26362, "Shell": 12090} | /*
* Copyright (c) 2020-2022 Thomas Neidhart.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tinygears.bat.classfile.attribute
import org.tinygears.bat.classfile.io.ClassDataInput
import org.tinygears.bat.classfile.io.ClassDataOutput
import org.tinygears.bat.classfile.io.ClassFileContent
import org.tinygears.bat.classfile.io.contentSize
import org.tinygears.bat.util.mutableListOfCapacity
import java.util.*
data class AttributeMap constructor(private var _attributes: MutableList<Attribute> = mutableListOfCapacity(0))
: ClassFileContent(), Sequence<Attribute> {
private val typeToAttributeMap: MutableMap<AttributeType, Attribute> by lazy { EnumMap(AttributeType::class.java) }
init {
for (attribute in _attributes) {
addAttributeToTypeMap(attribute)
}
}
override val contentSize: Int
get() = _attributes.contentSize()
val size: Int
get() = _attributes.size
operator fun get(index: Int): Attribute {
return _attributes[index]
}
internal operator fun <T : Attribute> get(type: AttributeType): T? {
require(type != AttributeType.UNKNOWN) { "attributeType 'UNKNOWN' not supported for retrieval" }
@Suppress("UNCHECKED_CAST")
return typeToAttributeMap[type] as T?
}
override fun iterator(): Iterator<Attribute> {
return _attributes.iterator()
}
internal fun removeAttribute(attribute: Attribute) {
_attributes.remove(attribute)
typeToAttributeMap.remove(attribute.type)
}
internal fun addAttribute(attribute: Attribute) {
_attributes.add(attribute)
addAttributeToTypeMap(attribute)
}
private fun addAttributeToTypeMap(attribute: Attribute) {
// UNKNOWN attributes are not supported by the type cache
if (attribute.type != AttributeType.UNKNOWN) {
typeToAttributeMap[attribute.type] = attribute
}
}
private fun read(input: ClassDataInput) {
val attributeCount = input.readUnsignedShort()
_attributes = mutableListOfCapacity(attributeCount)
for (i in 0 until attributeCount) {
addAttribute(Attribute.readAttribute(input, input.classFile))
}
}
override fun write(output: ClassDataOutput) {
output.writeShort(_attributes.size)
for (attribute in _attributes) {
attribute.write(output)
}
}
companion object {
internal fun empty(): AttributeMap {
return AttributeMap()
}
internal fun read(input: ClassDataInput): AttributeMap {
val attributeMap = AttributeMap()
attributeMap.read(input)
return attributeMap
}
}
} | 0 | Kotlin | 0 | 0 | 50083893ad93820f9cf221598692e81dda05d150 | 3,269 | bat | Apache License 2.0 |
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/Drop.kt | Konyaco | 574,321,009 | false | null |
package com.konyaco.fluent.icons.regular
import androidx.compose.ui.graphics.vector.ImageVector
import com.konyaco.fluent.icons.Icons
import com.konyaco.fluent.icons.fluentIcon
import com.konyaco.fluent.icons.fluentPath
public val Icons.Regular.Drop: ImageVector
get() {
if (_drop != null) {
return _drop!!
}
_drop = fluentIcon(name = "Regular.Drop") {
fluentPath {
moveTo(11.47f, 2.22f)
curveToRelative(0.3f, -0.3f, 0.77f, -0.3f, 1.06f, 0.0f)
curveToRelative(0.4f, 0.4f, 2.0f, 2.13f, 3.5f, 4.36f)
curveTo(17.5f, 8.78f, 19.0f, 11.63f, 19.0f, 14.25f)
curveToRelative(0.0f, 2.52f, -0.75f, 4.48f, -2.04f, 5.8f)
arcTo(6.78f, 6.78f, 0.0f, false, true, 12.0f, 22.0f)
arcToRelative(6.78f, 6.78f, 0.0f, false, true, -4.96f, -1.94f)
curveTo(5.74f, 18.73f, 5.0f, 16.77f, 5.0f, 14.25f)
curveToRelative(0.0f, -2.62f, 1.5f, -5.46f, 2.97f, -7.67f)
curveToRelative(1.5f, -2.23f, 3.1f, -3.96f, 3.5f, -4.36f)
close()
moveTo(9.22f, 7.42f)
curveToRelative(-1.46f, 2.17f, -2.72f, 4.7f, -2.72f, 6.83f)
curveToRelative(0.0f, 2.23f, 0.65f, 3.77f, 1.62f, 4.76f)
curveToRelative(0.96f, 0.98f, 2.32f, 1.49f, 3.88f, 1.49f)
reflectiveCurveToRelative(2.92f, -0.5f, 3.88f, -1.5f)
curveToRelative(0.97f, -0.98f, 1.62f, -2.52f, 1.62f, -4.75f)
curveToRelative(0.0f, -2.13f, -1.26f, -4.66f, -2.72f, -6.83f)
arcTo(33.36f, 33.36f, 0.0f, false, false, 12.0f, 3.85f)
curveToRelative(-0.65f, 0.73f, -1.74f, 2.02f, -2.78f, 3.57f)
close()
}
}
return _drop!!
}
private var _drop: ImageVector? = null
| 1 | Kotlin | 3 | 83 | 9e86d93bf1f9ca63a93a913c990e95f13d8ede5a | 1,883 | compose-fluent-ui | Apache License 2.0 |
src/test/kotlin/nl/dirkgroot/structurizr/dsl/support/StructurizrDSLLexerTest.kt | dirkgroot | 561,786,663 | false | {"Kotlin": 75934, "Lex": 2535, "ASL": 463} | package nl.dirkgroot.structurizr.dsl.support
import com.intellij.psi.tree.IElementType
import nl.dirkgroot.structurizr.dsl.lang.SDLexerAdapter
fun String.tokenize(): Iterable<Pair<IElementType, String>> {
val lexer = SDLexerAdapter()
lexer.start(this)
return generateSequence {
val token = lexer.tokenType
val text = lexer.tokenText
lexer.advance()
token?.let { token to text }
}.toList()
}
| 11 | Kotlin | 3 | 54 | 9bcbcfab6c1e7ef8258dc7c21f049e555b119237 | 442 | structurizr-dsl-intellij-plugin | MIT License |
cryptography-providers/apple/src/commonMain/kotlin/algorithms/CCAesIvCipher.kt | whyoleg | 492,907,371 | false | {"Kotlin": 1074574, "JavaScript": 318} | /*
* Copyright (c) 2024 <NAME>. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.whyoleg.cryptography.providers.apple.algorithms
import dev.whyoleg.cryptography.providers.apple.internal.*
import dev.whyoleg.cryptography.providers.base.algorithms.*
import dev.whyoleg.cryptography.providers.base.operations.*
import dev.whyoleg.cryptography.random.*
import platform.CoreCrypto.*
internal class CCAesIvCipher(
private val algorithm: CCAlgorithm,
private val mode: CCMode,
private val padding: CCPadding,
private val key: ByteArray,
private val ivSize: Int,
private val validateCiphertextInputSize: (Int) -> Unit = {},
) : BaseAesIvCipher {
override fun createEncryptFunction(): CipherFunction {
val iv = CryptographyRandom.nextBytes(ivSize)
return BaseAesImplicitIvEncryptFunction(iv, createEncryptFunctionWithIv(iv))
}
override fun createDecryptFunction(): CipherFunction {
return BaseAesImplicitIvDecryptFunction(ivSize, ::createDecryptFunctionWithIv)
}
override fun createEncryptFunctionWithIv(iv: ByteArray): CipherFunction {
require(iv.size == ivSize) { "IV size is wrong" }
return CCCipherFunction(
algorithm = algorithm,
mode = mode,
padding = padding,
operation = kCCEncrypt,
blockSize = kCCBlockSizeAES128.toInt(),
key = key,
iv = iv,
ivStartIndex = 0
)
}
private fun createDecryptFunctionWithIv(iv: ByteArray, startIndex: Int): CipherFunction {
require(iv.size - startIndex >= ivSize) { "IV size is wrong" }
return CCCipherFunction(
algorithm = algorithm,
mode = mode,
padding = padding,
operation = kCCDecrypt,
blockSize = kCCBlockSizeAES128.toInt(),
key = key,
iv = iv,
ivStartIndex = startIndex,
validateFullInputSize = validateCiphertextInputSize
)
}
override fun createDecryptFunctionWithIv(iv: ByteArray): CipherFunction {
return createDecryptFunctionWithIv(iv, 0)
}
}
| 10 | Kotlin | 20 | 302 | 69b77a88b4b81109704475ed02be48d263d1a1c8 | 2,171 | cryptography-kotlin | Apache License 2.0 |
Fase-1/API/self-order-management/src/main/kotlin/com/fiap/selfordermanagement/application/ports/incoming/LoadPaymentUseCase.kt | FIAP-3SOAT-G15 | 686,372,615 | false | {"Kotlin": 117337, "HCL": 2087, "Makefile": 622} | package com.fiap.selfordermanagement.application.ports.incoming
import com.fiap.selfordermanagement.application.domain.entities.Payment
interface LoadPaymentUseCase {
fun getByOrderNumber(orderNumber: Long): Payment
fun findAll(): List<Payment>
fun findByOrderNumber(orderNumber: Long): Payment?
}
| 3 | Kotlin | 0 | 4 | 2e1f4ccfbc2eb379639b72709fe28105665ee6d3 | 314 | tech-challenge | MIT License |
intellij-plugin/jvm-core/testSrc/com/jetbrains/edu/jvm/courseGeneration/JvmCourseGenerationTestBase.kt | JetBrains | 43,696,115 | false | {"Kotlin": 4929631, "HTML": 3417303, "Python": 18771, "Java": 13512, "CSS": 12216, "JavaScript": 302, "Shell": 71} | package com.jetbrains.edu.jvm.courseGeneration
import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl
import com.jetbrains.edu.jvm.JdkProjectSettings
import com.jetbrains.edu.learning.courseGeneration.CourseGenerationTestBase
abstract class JvmCourseGenerationTestBase : CourseGenerationTestBase<JdkProjectSettings>() {
override val defaultSettings: JdkProjectSettings get() = JdkProjectSettings.emptySettings()
override fun tearDown() {
JavaAwareProjectJdkTableImpl.removeInternalJdkInTests()
super.tearDown()
}
}
| 6 | Kotlin | 44 | 135 | b00e7100e8658a07e79700a20ffe576872d494db | 552 | educational-plugin | Apache License 2.0 |
src/jsMain/kotlin/content/Footer.kt | develNerd | 441,737,587 | false | {"JavaScript": 7937280, "Kotlin": 48492, "Shell": 11402, "Batchfile": 5242, "HTML": 5211, "CSS": 2988} | package content
import androidx.compose.runtime.Composable
import org.jetbrains.compose.web.attributes.ATarget
import org.jetbrains.compose.web.attributes.target
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.css.keywords.auto
import org.jetbrains.compose.web.dom.*
import style.FooterStyle.footerStyle
import style.FooterStyle.openSourceFooterStyle
import style.MainStyle
import style.ProjectsStyle
import style.mainColor
@Composable
fun footer() {
Section(
attrs = {
style {
position(Position.Relative)
height(auto)
}
}
) {
Div(
attrs = {
classes(footerStyle)
}
) {
val socials = listOf(
SocialMedia(name = "email", icon = "ic_email.svg", link = ""),
SocialMedia(name = "develNerd", icon = "ic_github_social.svg", link = "https://github.com/develNerd"),
SocialMedia(
name = "@linkName",
icon = "ic_instagram.svg",
link = "https://www.instagram.com/"
),
SocialMedia(name = "@twitter", icon = "ic_twitter.svg", link = "https://twitter.com/_edem"),
SocialMedia(
name = "name",
icon = "ic_linkedin.svg",
link = "https://www.linkedin.com/in/"
),
)
socials.forEach { social ->
socialInfoItem(social.icon, social.name, social.link)
}
}
}
}
@Composable
fun openSourceFooter() {
Section(
attrs = {
style {
position(Position.Fixed)
property("bottom","0")
height(auto)
width(100.percent)
}
}
) {
Div(
attrs = {
classes(openSourceFooterStyle)
style {
display(DisplayStyle.Flex)
flexDirection(FlexDirection.Row)
justifyContent(JustifyContent.Center)
alignItems(AlignItems.Center)
height(auto)
width(auto)
}
}
) {
A(href = "https://github.com/develNerd/JC-PortfolioSite/tree/main",
attrs = {
target(ATarget.Blank)
}) {
P(attrs = {
classes(MainStyle.normalTextsInfo)
style {
marginTop(10.px)
color(Color.white)
}
}) {
Text("Built with Jetpack Compose. Clone Here")
}
}
}
}
}
@Composable
fun socialInfoItem(icon: String, name: String, link: String) {
Div(
attrs = {
style {
display(DisplayStyle.Flex)
flexDirection(FlexDirection.Row)
justifyContent(JustifyContent.Center)
alignItems(AlignItems.Center)
padding(5.px)
height(auto)
width(auto)
}
}
) {
A(href = link, attrs = {
classes(ProjectsStyle.projectGitLink)
target(ATarget.Blank)
style {
display(DisplayStyle.Flex)
flexDirection(FlexDirection.Row)
justifyContent(JustifyContent.Center)
alignItems(AlignItems.Center)
padding(5.px)
height(auto)
width(auto)
margin(20.px)
}
}) {
Img(src = icon, attrs = {
style {
width(20.px)
height(20.px)
}
})
P(attrs = {
style {
textAlign("center")
fontWeight(300)
margin(5.px)
property("font-family", "Open Sans, sans-serif")
property("color", "white")
property("font-size", "small")
}
}) {
Text(name)
}
}
}
}
data class SocialMedia(val name: String, val icon: String, val link: String = "")
| 1 | JavaScript | 0 | 2 | 2da43a9286a4a5ca09d59626ca871e964f61fde3 | 4,410 | JC-PortfolioSite | MIT License |
src/main/kotlin/br/com/zup/academy/erombi/service/KeyService.kt | erombi | 407,315,906 | true | {"Kotlin": 69988} | package br.com.zup.academy.erombi.service
import br.com.zup.academy.erombi.ConsultaKeyPorClienteResponse
import br.com.zup.academy.erombi.NovaKeyResponse
import br.com.zup.academy.erombi.RemoveKeyResponse
import br.com.zup.academy.erombi.TipoConta
import br.com.zup.academy.erombi.client.BcbClient
import br.com.zup.academy.erombi.client.ErpItauClient
import br.com.zup.academy.erombi.client.request.BankAccountRequest
import br.com.zup.academy.erombi.client.request.CreatePixKeyRequest
import br.com.zup.academy.erombi.client.request.DeletePixKeyRequest
import br.com.zup.academy.erombi.client.request.OwnerRequest
import br.com.zup.academy.erombi.model.Instituicao
import br.com.zup.academy.erombi.model.Key
import br.com.zup.academy.erombi.model.TipoPessoa
import br.com.zup.academy.erombi.model.Titular
import br.com.zup.academy.erombi.repository.KeyRepository
import br.com.zup.academy.erombi.service.form.ConsultaKeyPorClienteForm
import br.com.zup.academy.erombi.service.form.NovaKeyForm
import br.com.zup.academy.erombi.service.form.RemoveKeyForm
import com.google.protobuf.Timestamp
import io.grpc.Status
import io.grpc.StatusRuntimeException
import io.micronaut.http.HttpStatus
import io.micronaut.http.client.exceptions.HttpClientResponseException
import io.micronaut.validation.Validated
import io.micronaut.validation.validator.Validator
import jakarta.inject.Singleton
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.*
import javax.validation.Valid
import kotlin.random.Random
@Validated
@Singleton
class KeyService(
val client: ErpItauClient,
val repository: KeyRepository,
val validator: Validator,
val clientBcb: BcbClient
) {
private val logger: Logger = LoggerFactory.getLogger(KeyService::class.java)
fun validaESalva(@Valid form : NovaKeyForm): NovaKeyResponse {
try {
val contaClienteItau = client.pesquisaContasPorCliente(form.tipoConta!!.toPorExtenso(), form.uuidCliente!!)
contaClienteItau?.let {
val response = clientBcb.cadastraNoBancoCentral(
CreatePixKeyRequest(
form.tipoKey!!.name,
form.key!!,
BankAccountRequest(
100000,
"0001",
100000,
form.tipoConta.name
),
OwnerRequest(
TipoPessoa.NATURAL_PERSON.name,
contaClienteItau.titular.nome,
contaClienteItau.titular.cpf
)
)
)
val key = Key(
form.tipoKey,
response.key,
form.tipoConta,
Instituicao(
response.bankAccount.participant,
contaClienteItau.instituicao.nome,
contaClienteItau.instituicao.ispb
),
contaClienteItau.agencia,
contaClienteItau.numero,
Titular(
contaClienteItau.titular.id,
contaClienteItau.titular.nome,
contaClienteItau.titular.cpf
)
)
repository.save(key)
return NovaKeyResponse.newBuilder()
.setPixId(key.id.toString())
.build()
} ?: throw StatusRuntimeException(
Status.INVALID_ARGUMENT
.withDescription("Conta não encontrada !")
)
} catch (e : HttpClientResponseException) {
if (e.response.status == HttpStatus.UNPROCESSABLE_ENTITY) {
throw Status.INVALID_ARGUMENT
.withDescription("Chave já cadastrada no Banco Central")
.asRuntimeException()
}
logger.error("Ocorreu um erro inesperado")
throw StatusRuntimeException(Status.INTERNAL.withDescription("Ocorreu um erro inesperado !"))
} catch (e: Exception) {
throw e
}
}
fun validaERemove(form: RemoveKeyForm): RemoveKeyResponse {
val errors = validator.validate(form)
if (errors.isNotEmpty()) {
val primeiroErro = errors.first()
with(primeiroErro) {
if (message == "Key não encontrada ou em formato inválido !")
throw StatusRuntimeException(Status.NOT_FOUND.withDescription(message))
if (message == "Cliente inexistente !")
throw StatusRuntimeException(Status.NOT_FOUND.withDescription(message))
throw StatusRuntimeException(Status.INVALID_ARGUMENT.withDescription(message))
}
}
val key = repository.findById(UUID.fromString(form.idKey)).get()
try {
val response = clientBcb.deletaDoBancoCentral(key.key,
DeletePixKeyRequest(
key.key,
key.instituicao.participant
)
)
repository.deleteByIdAndTitularUuidCliente(UUID.fromString(form.idKey), form.idCliente)
return RemoveKeyResponse.newBuilder().build()
} catch (e: HttpClientResponseException) {
logger.warn("Não foi possivel deletar key do banco central")
throw StatusRuntimeException(Status.INVALID_ARGUMENT.withDescription("Não foi possível deletar a chave !"))
}
}
fun validaEConsultaPorCliente(@Valid form: ConsultaKeyPorClienteForm): List<ConsultaKeyPorClienteResponse.KeyDescription> {
val keys = repository.findAllByTitularUuidCliente(form.idCliente)
return mapeiaParaConsultaResponse(keys)
}
private fun mapeiaParaConsultaResponse(keys: Set<Key>): List<ConsultaKeyPorClienteResponse.KeyDescription> {
return keys.map { key ->
ConsultaKeyPorClienteResponse.KeyDescription.newBuilder()
.setClienteId(key.titular.uuidCliente)
.setPixId(key.id.toString())
.setTipoKey(key.tipoKey)
.setTipoConta(key.tipoConta)
.setCriadoEm(
Timestamp.newBuilder()
.setNanos(key.criadoEm.nano)
.setSeconds(key.criadoEm.second.toLong())
.build()
)
.build()
}
}
}
fun TipoConta.toPorExtenso(): String {
return when(this) {
(TipoConta.UNKNOWN_TIPO_CONTA) -> "UNKNOWN_TIPO_CONTA"
(TipoConta.CACC) -> "CONTA_CORRENTE"
(TipoConta.SVGS) -> "CONTA_POUPANCA"
else -> ""
}
} | 0 | Kotlin | 0 | 0 | 866137288add21f493eba8d0a1b940a14ee4c2b5 | 6,846 | orange-talents-07-template-pix-keymanager-grpc | Apache License 2.0 |
containers/src/commonMain/kotlin/io/github/aeckar/parsing/containers/Removable.kt | aeckar | 834,956,853 | false | {"Kotlin": 138999, "ANTLR": 18047} | package io.github.aeckar.parsing.containers
/**
* A removable object.
*/
public fun interface Removable {
public fun remove()
} | 0 | Kotlin | 0 | 1 | a5b3a41138097e690035d8a49e6f401c35fe93b9 | 134 | modular-parsers | MIT License |
ide-common/src/main/java/org/digma/intellij/plugin/common/AsynchronousBackgroundTask.kt | digma-ai | 472,408,329 | false | null | package org.digma.intellij.plugin.common
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import org.digma.intellij.plugin.log.Log
import java.util.concurrent.locks.ReentrantLock
@Suppress("DialogTitle")
class AsynchronousBackgroundTask(private val lock: ReentrantLock, private val task: Runnable) : Task.Backgroundable(null, "Loading recent activity data") {
private val logger: Logger = Logger.getInstance(AsynchronousBackgroundTask::class.java)
override fun run(indicator: ProgressIndicator) {
if (lock.tryLock()) {
try {
task.run()
} finally {
lock.unlock()
}
} else {
// Previous task is still in progress, skip this task
Log.log(logger::warn, "New task was skip because previous task is still in progress.")
}
}
}
| 264 | Kotlin | 4 | 7 | ec199eb6f3eca60536282b9fe2c9fbca3e581b45 | 944 | digma-intellij-plugin | MIT License |
data/src/main/kotlin/io/timemates/backend/data/authorization/db/TableVerificationsDataSource.kt | timemates | 575,534,781 | false | {"Kotlin": 441365, "Dockerfile": 859} | package io.timemates.backend.data.authorization.db
import io.timemates.backend.data.authorization.db.entities.DbVerification
import io.timemates.backend.data.authorization.db.mapper.DbVerificationsMapper
import io.timemates.backend.data.authorization.db.table.VerificationSessionsTable
import io.timemates.backend.data.authorization.db.table.VerificationSessionsTable.ATTEMPTS
import io.timemates.backend.data.authorization.db.table.VerificationSessionsTable.VERIFICATION_HASH
import io.timemates.backend.exposed.suspendedTransaction
import io.timemates.backend.exposed.update
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.transactions.transaction
class TableVerificationsDataSource(
private val database: Database,
private val verificationsMapper: DbVerificationsMapper,
) {
init {
transaction(database) {
SchemaUtils.create(VerificationSessionsTable)
}
}
suspend fun add(
emailAddress: String,
verificationToken: String,
code: String,
time: Long,
attempts: Int,
): Unit = suspendedTransaction(database) {
VerificationSessionsTable.insert {
it[EMAIL] = emailAddress
it[VERIFICATION_HASH] = verificationToken
it[IS_CONFIRMED] = false
it[CONFIRMATION_CODE] = code
it[ATTEMPTS] = attempts
it[INIT_TIME] = time
}
}
suspend fun getVerification(verificationHash: String): DbVerification? = suspendedTransaction(database) {
VerificationSessionsTable.select { VERIFICATION_HASH eq verificationHash }
.singleOrNull()
?.let(verificationsMapper::resultRowToDbVerification)
}
suspend fun decreaseAttempts(verificationHash: String): Unit = suspendedTransaction(database) {
val current = VerificationSessionsTable.select { VERIFICATION_HASH eq verificationHash }
.singleOrNull()
?.get(ATTEMPTS)
?: error("Cannot decrease number of attempts, as there is no such verification session")
VerificationSessionsTable.update(VERIFICATION_HASH eq verificationHash) {
it[ATTEMPTS] = current - 1
}
}
suspend fun getAttempts(email: String, afterTime: Long): Int = try {
suspendedTransaction(database) {
VerificationSessionsTable.select {
VerificationSessionsTable.EMAIL eq email and
(VerificationSessionsTable.INIT_TIME greater afterTime)
}.sumOf { it[ATTEMPTS] }
}
} catch (e: Throwable) {
e.printStackTrace()
0
}
suspend fun getSessionsCount(
email: String,
afterTime: Long,
): Int = suspendedTransaction(database) {
VerificationSessionsTable.select {
VerificationSessionsTable.EMAIL eq email and
(VerificationSessionsTable.INIT_TIME greater afterTime)
}.count().toInt()
}
suspend fun setAsConfirmed(verificationHash: String): Boolean = suspendedTransaction(database) {
VerificationSessionsTable.update(VERIFICATION_HASH eq verificationHash) {
it[IS_CONFIRMED] = true
} > 0
}
suspend fun remove(verificationHash: String): Unit = suspendedTransaction(database) {
VerificationSessionsTable.deleteWhere { VERIFICATION_HASH eq verificationHash }
}
} | 17 | Kotlin | 0 | 8 | ba66b305eebf276c6f72131a2500c7f47cc5d7e3 | 3,444 | backend | MIT License |
app/src/main/kotlin/com/simplemobiletools/calendar/pro/activities/EventTypePickerActivity.kt | GiridharanS1729 | 724,120,449 | false | {"Kotlin": 796515, "Ruby": 909} | package com.simplemobiletools.calendar.pro.activities
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.simplemobiletools.calendar.pro.R
import com.simplemobiletools.calendar.pro.extensions.launchNewEventIntent
import com.simplemobiletools.calendar.pro.extensions.launchNewTaskIntent
import com.simplemobiletools.commons.dialogs.RadioGroupDialog
import com.simplemobiletools.commons.models.RadioItem
class EventTypePickerActivity : AppCompatActivity() {
private val TYPE_EVENT = 0
private val TYPE_TASK = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val items = arrayListOf(
RadioItem(TYPE_EVENT, getString(R.string.event)),
RadioItem(TYPE_TASK, getString(R.string.task))
)
RadioGroupDialog(this, items = items, cancelCallback = { dialogCancelled() }) {
val checkedId = it as Int
if (checkedId == TYPE_EVENT) {
launchNewEventIntent()
} else if (checkedId == TYPE_TASK) {
launchNewTaskIntent()
}
finish()
}
}
private fun dialogCancelled() {
finish()
}
}
| 0 | Kotlin | 0 | 1 | 2e539105f60e2bb7eda892f458619789918f0361 | 1,224 | Event_Calendar | MIT License |
src/main/kotlin/info/firozansari/store/exceptions/InvalidReferenceSyntaxException.kt | firozansar | 445,798,203 | false | {"Kotlin": 125172} | package info.firozansari.store.exceptions
class InvalidReferenceSyntaxException : Exception("Invalid reference syntax, it should begin with Book")
| 0 | Kotlin | 0 | 0 | f570953f9c1108107675dec777a1f0355d8a5af5 | 148 | Kotlin-TDD | The Unlicense |
query/src/main/kotlin/me/rasztabiga/thesis/query/domain/query/mapper/RestaurantOrderMapper.kt | BartlomiejRasztabiga | 604,846,079 | false | {"Kotlin": 368953, "TypeScript": 109077, "Python": 10389, "Dockerfile": 1695, "Shell": 662, "JavaScript": 639, "CSS": 59} | package me.rasztabiga.thesis.query.domain.query.mapper
import me.rasztabiga.thesis.query.adapter.`in`.rest.api.RestaurantOrderResponse
import me.rasztabiga.thesis.query.domain.query.entity.RestaurantOrderEntity
import me.rasztabiga.thesis.shared.domain.command.event.RestaurantOrderCreatedEvent
import java.time.Instant
object RestaurantOrderMapper {
fun mapToEntity(event: RestaurantOrderCreatedEvent): RestaurantOrderEntity {
return RestaurantOrderEntity(
id = event.restaurantOrderId,
orderId = event.orderId,
restaurantId = event.restaurantId,
items = event.items,
status = RestaurantOrderEntity.OrderStatus.NEW,
createdAt = Instant.now()
)
}
fun mapToResponse(entity: RestaurantOrderEntity): RestaurantOrderResponse {
return RestaurantOrderResponse(
restaurantOrderId = entity.id,
orderId = entity.orderId,
items = entity.items,
status = RestaurantOrderResponse.RestaurantOrderStatus.valueOf(entity.status.name),
createdAt = entity.createdAt
)
}
}
| 4 | Kotlin | 0 | 2 | dbb3b329f06f951b9531b03cc41d1e1e52bf7422 | 1,137 | thesis | MIT License |
kotlin/friends_tree/src/main/kotlin/Main.kt | pradyotprksh | 385,586,594 | false | {"Kotlin": 2932498, "Dart": 1066884, "Python": 319755, "Rust": 180589, "Swift": 149003, "C++": 113494, "JavaScript": 103891, "CMake": 94132, "HTML": 57188, "Go": 45704, "CSS": 18615, "SCSS": 17864, "Less": 17245, "Ruby": 13609, "Dockerfile": 9772, "C": 8043, "Shell": 7657, "PowerShell": 3045, "Nix": 2616, "Makefile": 1480, "PHP": 1241, "Objective-C": 380, "Handlebars": 354} | import models.Person
fun main() {
val friendsTree = FriendsTree()
friendsTree.addUser(Person(name = "<NAME>", username = "pradyotprksh", emailId = "<EMAIL>"))
friendsTree.addUser(Person(name = "Ramesh", username = "ramesh4", emailId = "<EMAIL>"))
friendsTree.addUser(Person(name = "Suresh", username = "suresh", emailId = "<EMAIL>"))
friendsTree.addUser(Person(name = "Raj", username = "raj1996", emailId = "<EMAIL>"))
friendsTree.addUser(Person(name = "Ankit", username = "ankit8", emailId = "<EMAIL>"))
friendsTree.addUser(Person(name = "Sourav", username = "sourav67", emailId = "<EMAIL>"))
friendsTree.addFriend("pradyotprksh", "suresh")
friendsTree.addFriend("ramesh4", "suresh")
friendsTree.addFriend("suresh", "sourav67")
friendsTree.addFriend("suresh", "ankit8")
// friendsTree.addFriend("raj1996", "ankit8")
println("Get User Details")
println(friendsTree.searchUser("pradyotprksh"))
println(friendsTree.searchUser("ramesh4"))
println(friendsTree.searchUser("suresh"))
println(friendsTree.searchUser("raj1996"))
println(friendsTree.searchUser("ankit8"))
println(friendsTree.searchUser("sourav67"))
println("Get 1st Friend List")
friendsTree.get1stFriends("suresh").forEach { println(it) }
println("Get 2nd Friend List")
friendsTree.get2ndFriends("suresh").forEach { println(it) }
println("Get 3rd Friend List")
friendsTree.get3rdFriends("suresh").forEach { println(it) }
println("Is Connected")
println(friendsTree.isConnected(firstUsername = "pradyotprksh", secondUsername = "suresh"))
println(friendsTree.isConnected(firstUsername = "pradyotprksh", secondUsername = "raj1996"))
} | 0 | Kotlin | 11 | 24 | a31e612a63e1dc42ed4cf2f50db90b8613fb5177 | 1,709 | development_learning | MIT License |
kcrud-base/src/main/kotlin/kcrud/base/domain/rbac/plugin/WithRbac.kt | perracodex | 682,128,013 | false | {"Kotlin": 374975, "CSS": 2363, "HTML": 582} | /*
* Copyright (c) 2024 <NAME>. All rights reserved.
* This work is licensed under the terms of the MIT license.
* For a copy, see <https://opensource.org/licenses/MIT>
*/
package kcrud.base.domain.rbac.plugin
import io.ktor.server.routing.*
import kcrud.base.domain.rbac.plugin.annotation.RbacAPI
import kcrud.base.domain.rbac.types.RbacLevel
import kcrud.base.domain.rbac.types.RbacResource
/**
* DSL function for applying RBAC authorization to Ktor routes.
*
* @param resource The RBAC resource associated with the route, defining the scope of access control.
* @param level The RBAC level required for accessing the route, defining the degree of access control.
* @param build The routing logic to be applied within the RBAC-authorized route.
* @return The created Route object configured with RBAC constraints.
*/
@OptIn(RbacAPI::class)
fun Route.withRbac(resource: RbacResource, level: RbacLevel, build: Route.() -> Unit): Route {
return rbacAuthorizedRoute(resource = resource, level = level, build = build)
}
| 0 | Kotlin | 0 | 1 | 982ebb53ff47c6b46bbcf60fa0a901a02a2a675f | 1,035 | Kcrud | MIT License |
client/app/src/main/java/com/example/healthc/data/dto/food/SearchFoodIngredientDto.kt | Solution-Challenge-HealthC | 601,915,784 | false | null | package com.example.healthc.data.dto.food
import com.example.healthc.domain.model.food.Ingredient
import com.example.healthc.domain.model.food.SearchFoodIngredient
data class SearchFoodIngredientDto(
val number: Int,
val offset: Int,
val results: List<IngredientDto>,
val totalResults: Int
){
fun toSearchFoodIngredient() : SearchFoodIngredient = SearchFoodIngredient(
number = number,
offset = offset,
results = results.map{ it.toIngredient() },
totalResults = totalResults
)
}
data class IngredientDto(
val id: Int,
val image: String,
val name: String
){
fun toIngredient() : Ingredient = Ingredient(
id = id,
image = image,
name = name
)
} | 2 | Kotlin | 0 | 2 | 21c45b6fd672074616945e45f0807e0ce43b06b8 | 745 | HealthC_Android | MIT License |
src/main/kotlin/com/fobgochod/endpoints/action/http/ReformatDataAction.kt | fobgochod | 686,046,719 | false | {"Kotlin": 125996, "Java": 113739} | package com.fobgochod.endpoints.action.http
import com.fobgochod.endpoints.action.EndpointsAction
import com.fobgochod.endpoints.util.EndpointsBundle
import com.fobgochod.endpoints.util.GsonUtils
import com.fobgochod.endpoints.view.http.editor.HttpTextField
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys
import com.intellij.openapi.project.Project
class ReformatDataAction : EndpointsAction() {
init {
templatePresentation.icon = AllIcons.Json.Object
templatePresentation.text = EndpointsBundle.message("action.http.test.json.format.text")
}
override fun actionPerformed(e: AnActionEvent, project: Project) {
val component = e.dataContext.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT)
if (component is HttpTextField) {
component.text = GsonUtils.format(component.text)
}
}
}
| 0 | Kotlin | 0 | 0 | 7a1e2f84bc2f21ec42d009be0f6981782557fe08 | 955 | endpoints | Apache License 2.0 |
app/src/main/java/com/froggie/design/repository/api/DesignAPI.kt | ucdevinda123 | 387,638,747 | false | null | package com.froggie.design.repository.api
import com.froggie.design.repository.data.FeaturedDesignResponse
import com.froggie.design.repository.data.PopularDesignResponse
import com.froggie.design.repository.data.RecentDesignResponse
import retrofit2.http.GET
interface DesignAPI {
companion object {
const val BASE_URL =
"https://firebasestorage.googleapis.com/v0/b/lottiefiles-test.appspot.com/o/"
}
@GET("featuredAnimations.json?alt=media&token=<PASSWORD>")
suspend fun getFeaturedAnimations(): FeaturedDesignResponse
@GET("popularAnimations.json?alt=media&token=<PASSWORD>")
suspend fun getPopularAnimations(): PopularDesignResponse
@GET("recentAnimations.json?alt=media&token=<PASSWORD>")
suspend fun getRecentAnimations(): RecentDesignResponse
} | 0 | Kotlin | 0 | 1 | 87196c1f8ce41db55aade42ea76f721ff7593422 | 809 | froggie-mvvm | Apache License 2.0 |
kgl-vma/src/nativeMain/kotlin/com/kgl/vma/enums/AllocationCreate.kt | ArcheCraft | 444,160,602 | true | {"Kotlin": 898353, "C": 10037} | package com.kgl.vma.enums
import com.kgl.vma.utils.*
import cvma.*
actual enum class AllocationCreate(override val value: UInt) : VmaFlag<AllocationCreate> {
DEDICATED_MEMORY(VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT),
NEVER_ALLOCATE(VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT),
MAPPED(VMA_ALLOCATION_CREATE_MAPPED_BIT),
CAN_BECOME_LOST(VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT),
CAN_MAKE_OTHER_LOST(VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT),
USER_DATA_COPY_STRING(VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT),
UPPER_ADDRESS(VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT),
DONT_BIND(VMA_ALLOCATION_CREATE_DONT_BIND_BIT),
STRATEGY_BEST_FIT(VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT),
STRATEGY_WORST_FIT(VMA_ALLOCATION_CREATE_STRATEGY_WORST_FIT_BIT),
STRATEGY_FIRST_FIT(VMA_ALLOCATION_CREATE_STRATEGY_FIRST_FIT_BIT),
STRATEGY_MIN_MEMORY(VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT),
STRATEGY_MIN_TIME(VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT),
STRATEGY_MIN_FRAGMENTATION(VMA_ALLOCATION_CREATE_STRATEGY_MIN_FRAGMENTATION_BIT);
actual companion object{
private val enumLookUpMap: Map<UInt, AllocationCreate> =
enumValues<AllocationCreate>().associateBy { it.value }
fun fromMultiple(value: UInt): VmaFlag<AllocationCreate>? = if (value == 0u) null else VmaFlag(value)
fun from(value: UInt): AllocationCreate = enumLookUpMap[value]!!
}
}
actual val AllocationCreate.Companion.STRATEGY_MASK: VmaFlag<AllocationCreate>
get() = VmaFlag(VMA_ALLOCATION_CREATE_STRATEGY_MASK)
| 0 | Kotlin | 0 | 0 | 8abab21ec63105c633d800cba1b9347b6a7df43d | 1,513 | kgl | Apache License 2.0 |
client/src/commonMain/kotlin/com/lightningkite/lightningdb/sockets.kt | lightningkite | 512,032,499 | false | {"Kotlin": 2140003, "TypeScript": 38628, "Ruby": 873, "JavaScript": 118} | package com.lightningkite.lightningdb
import com.lightningkite.kiteui.*
import com.lightningkite.kiteui.reactive.*
import com.lightningkite.uuid
import kotlinx.serialization.json.Json
private val shared = HashMap<String, TypedWebSocket<MultiplexMessage, MultiplexMessage>>()
fun multiplexSocket(url: String, path: String, params: Map<String, List<String>>, json: Json, pingTime: Long = 30_000L): RetryWebsocket {
val shared = shared.getOrPut(url) {
val s = retryWebsocket(url, pingTime)
s.typed(json, MultiplexMessage.serializer(), MultiplexMessage.serializer())
}
val channelOpen = Property(false)
val channel = uuid().toString()
return object : RetryWebsocket {
init {
shared.onMessage { message ->
if (message.channel == channel) {
if (message.start) {
channelOpen.value = true
onOpenList.forEach { it() }
}
message.data?.let { data ->
onMessageList.forEach { it(data) }
}
if (message.end) {
channelOpen.value = false
onCloseList.forEach { it(-1) }
}
}
}
shared.onClose {
channelOpen.value = false
}
}
override val connected: Readable<Boolean>
get() = channelOpen
val shouldBeOn = Property(0)
override fun start(): () -> Unit {
shouldBeOn.value++
val parent = shared.start()
return {
parent()
shouldBeOn.value--
}
}
val lifecycle = CalculationContext.Standard().apply {
reactiveScope {
val shouldBeOn = shouldBeOn.await() > 0
val isOn = channelOpen.await()
val parentConnected = shared.connected.await()
if (shouldBeOn && parentConnected && !isOn) {
shared.send(
MultiplexMessage(
channel = channel,
path = path,
queryParams = params,
start = true
)
)
} else if (!shouldBeOn && parentConnected && isOn) {
shared.send(
MultiplexMessage(
channel = channel,
path = path,
queryParams = params,
end = true
)
)
}
}
}
override fun close(code: Short, reason: String) {
shared.send(
MultiplexMessage(
channel = channel,
path = path,
queryParams = params,
end = true
)
)
lifecycle.cancel()
}
override fun send(data: Blob) = throw UnsupportedOperationException()
override fun send(data: String) {
shared.send(
MultiplexMessage(
channel = channel,
data = data,
)
)
}
val onOpenList = ArrayList<() -> Unit>()
val onMessageList = ArrayList<(String) -> Unit>()
val onCloseList = ArrayList<(Short) -> Unit>()
override fun onOpen(action: () -> Unit) {
onOpenList.add(action)
}
override fun onMessage(action: (String) -> Unit) {
onMessageList.add(action)
}
override fun onBinaryMessage(action: (Blob) -> Unit) = throw UnsupportedOperationException()
override fun onClose(action: (Short) -> Unit) {
onCloseList.add(action)
}
}
}
| 3 | Kotlin | 1 | 4 | ed4bda24609f676bb3317507275ea9bac1eda554 | 3,976 | lightning-server | MIT License |
app/src/main/java/com/dede/nativetools/netspeed/service/NetSpeedNotificationHelper.kt | hushenghao | 242,718,110 | false | null | package com.dede.nativetools.netspeed.service
import android.app.KeyguardManager
import android.app.Notification
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.Settings
import android.widget.RemoteViews
import androidx.core.app.NotificationChannelCompat
import androidx.core.app.NotificationChannelGroupCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.graphics.drawable.IconCompat
import androidx.navigation.NavDeepLinkBuilder
import com.dede.nativetools.R
import com.dede.nativetools.netspeed.NetSpeedConfiguration
import com.dede.nativetools.netspeed.utils.NetFormatter
import com.dede.nativetools.netspeed.utils.NetTextIconFactory
import com.dede.nativetools.netspeed.utils.NetworkUsageUtil
import com.dede.nativetools.util.*
/**
* 网速通知
*/
object NetSpeedNotificationHelper {
private const val CHANNEL_GROUP_ID = "net_speed_channel_group"
private const val CHANNEL_ID_DEFAULT = "net_speed_channel_default"
private const val CHANNEL_ID_SILENCE = "net_speed_channel_silence"
private fun isSecure(context: Context): Boolean {
val keyguardManager = context.requireSystemService<KeyguardManager>()
return keyguardManager.isDeviceSecure || keyguardManager.isKeyguardSecure
}
/**
* 锁屏通知显示设置
*/
fun goLockHideNotificationSetting(context: Context) {
val intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && isSecure(context)) {
Intent(
Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS,
Settings.EXTRA_APP_PACKAGE to context.packageName,
Settings.EXTRA_CHANNEL_ID to CHANNEL_ID_DEFAULT
)
} else {
// Settings.ACTION_NOTIFICATION_SETTINGS
Intent("android.settings.NOTIFICATION_SETTINGS")
}
intent.newTask().launchActivity(context)
}
fun goNotificationSetting(context: Context) {
val packageName = context.packageName
val intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Intent(
Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS,
Settings.EXTRA_APP_PACKAGE to packageName,
Settings.EXTRA_CHANNEL_ID to CHANNEL_ID_DEFAULT
)
} else {
Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, "package:$packageName")
}
intent.newTask().launchActivity(context)
}
fun areNotificationEnabled(context: Context): Boolean {
val notificationManagerCompat = NotificationManagerCompat.from(context)
val areNotificationsEnabled = notificationManagerCompat.areNotificationsEnabled()
var channelDisabled = false
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel =
notificationManagerCompat.getNotificationChannel(CHANNEL_ID_DEFAULT)
if (notificationChannel != null) {
val importance = notificationChannel.importance
channelDisabled = importance <= NotificationManagerCompat.IMPORTANCE_MIN
}
}
return areNotificationsEnabled && !channelDisabled
}
/**
* 获取数据使用量
*/
private fun getUsageText(context: Context, configuration: NetSpeedConfiguration): String? {
if (!Logic.checkAppOps(context)) {
return null
}
val todayBytes: Long
val monthBytes: Long
if (configuration.justMobileUsage) {
todayBytes = NetworkUsageUtil.todayMobileUsageBytes(context)
monthBytes = NetworkUsageUtil.monthMobileUsageBytes(context)
} else {
todayBytes = NetworkUsageUtil.todayNetworkUsageBytes(context)
monthBytes = NetworkUsageUtil.monthNetworkUsageBytes(context)
}
return context.getString(
R.string.notify_net_speed_sub,
NetFormatter.format(
todayBytes,
NetFormatter.FLAG_BYTE,
NetFormatter.ACCURACY_EXACT
).splicing(),
NetFormatter.format(
monthBytes,
NetFormatter.FLAG_BYTE,
NetFormatter.ACCURACY_EXACT
).splicing()
)
}
/**
* 系统版本>=S 且 targetVersion>=S 时,返回true
*/
fun itSSAbove(context: Context): Boolean {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&
// https://developer.android.google.cn/about/versions/12/behavior-changes-12#custom-notifications
context.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.S
}
/**
* 创建网速通知
*
* @param context 上下文
* @param configuration 配置
* @param rxSpeed 下行网速
* @param txSpeed 上行网速
*/
fun createNotification(
context: Context,
configuration: NetSpeedConfiguration,
rxSpeed: Long = 0L,
txSpeed: Long = 0L,
): Notification {
createChannels(context)
val builder = if (configuration.showBlankNotification) {
// 显示透明图标,并降低通知优先级
NotificationCompat.Builder(context, CHANNEL_ID_SILENCE)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setSmallIcon(createBlankIcon(configuration))
} else {
NotificationCompat.Builder(context, CHANNEL_ID_DEFAULT)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setSmallIcon(createIconCompat(configuration, rxSpeed, txSpeed))
}
builder.setOnlyAlertOnce(false)
.setOngoing(true)
.setLocalOnly(true)
.setShowWhen(false)
.setCategory(null)
.setSound(null)
.setBadgeIconType(NotificationCompat.BADGE_ICON_NONE)
.setColorized(false)
if (configuration.hideLockNotification) {
builder.setVisibility(NotificationCompat.VISIBILITY_SECRET)
} else {
builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
}
var pendingFlag = PendingIntent.FLAG_UPDATE_CURRENT
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
// https://developer.android.com/about/versions/12/behavior-changes-all#foreground-service-notification-delay
@Suppress("WrongConstant")
builder.foregroundServiceBehavior = NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE
// https://developer.android.com/about/versions/12/behavior-changes-12#pending-intent-mutability
pendingFlag = PendingIntent.FLAG_MUTABLE
}
if (configuration.hideNotification && !itSSAbove(context)) {
// context.applicationInfo.targetSdkVersion < Build.VERSION_CODES.S
// https://developer.android.google.cn/about/versions/12/behavior-changes-12#custom-notifications
val remoteViews = RemoteViews(context.packageName, R.layout.notification_empty_view)
builder.setCustomContentView(remoteViews)
} else {
val downloadSpeedStr: String =
NetFormatter.format(rxSpeed, NetFormatter.FLAG_FULL, NetFormatter.ACCURACY_EXACT)
.splicing()
val uploadSpeedStr: String =
NetFormatter.format(txSpeed, NetFormatter.FLAG_FULL, NetFormatter.ACCURACY_EXACT)
.splicing()
val contentStr =
context.getString(R.string.notify_net_speed_msg, uploadSpeedStr, downloadSpeedStr)
builder.setContentTitle(contentStr)
if (configuration.usage) {
val usageText = getUsageText(context, configuration)
builder.setContentText(usageText)
}
if (configuration.quickCloseable) {
val closePending = Intent(NetSpeedService.ACTION_CLOSE)
.toPendingBroadcast(context, pendingFlag)
builder.addAction(closePending.toNotificationCompatAction(R.string.action_close))
}
}
if (configuration.notifyClickable) {
// 默认启动应用首页
val pendingIntent = NavDeepLinkBuilder(context)
.setGraph(R.navigation.nav_graph)
.setDestination(R.id.netSpeed)
.createPendingIntent()
builder.setContentIntent(pendingIntent)
}
return builder.build()
}
private var notificationChannelCreated = false
private fun createChannels(context: Context) {
if (notificationChannelCreated) {
return
}
val manager = NotificationManagerCompat.from(context)
val channelGroup = NotificationChannelGroupCompat.Builder(CHANNEL_GROUP_ID)
.setName(context.getString(R.string.label_net_speed_service))
.setDescription(context.getString(R.string.desc_net_speed_notify))
.build()
manager.createNotificationChannelGroup(channelGroup)
val channelSilence = context.createChannel(true)
manager.createNotificationChannel(channelSilence)
val channelDefault = context.createChannel(false)
manager.createNotificationChannel(channelDefault)
notificationChannelCreated = true
}
private fun Context.createChannel(isSilence: Boolean): NotificationChannelCompat {
val builder = if (isSilence) {
NotificationChannelCompat.Builder(
CHANNEL_ID_SILENCE,
NotificationManagerCompat.IMPORTANCE_LOW
).setName(this.getString(R.string.label_net_speed_silence_channel))
} else {
NotificationChannelCompat.Builder(
CHANNEL_ID_DEFAULT,
NotificationManagerCompat.IMPORTANCE_DEFAULT
).setName(this.getString(R.string.label_net_speed_default_channel))
}
return builder.setDescription(this.getString(R.string.desc_net_speed_notify))
.setShowBadge(false)
.setGroup(CHANNEL_GROUP_ID)
.setVibrationEnabled(false)
.setLightsEnabled(false)
.setSound(null, null)
.build()
}
private fun createIconCompat(
configuration: NetSpeedConfiguration,
rxSpeed: Long,
txSpeed: Long,
): IconCompat {
val bitmap = NetTextIconFactory.create(rxSpeed, txSpeed, configuration)
return IconCompat.createWithBitmap(bitmap)
}
private fun createBlankIcon(configuration: NetSpeedConfiguration): IconCompat {
val bitmap = NetTextIconFactory.createBlank(configuration)
return IconCompat.createWithBitmap(bitmap)
}
} | 1 | Kotlin | 2 | 15 | 5cd7fb44d88117a828e977853ffb1105dc913a61 | 10,716 | NativeTools | Apache License 2.0 |
modules/dataset-reinstaller/src/main/kotlin/vdi/module/reinstaller/DatasetReinstaller.kt | VEuPathDB | 575,990,672 | false | {"Kotlin": 454067, "Java": 165401, "RAML": 80483, "Makefile": 1707, "Dockerfile": 1001, "Shell": 423} | package vdi.module.reinstaller
import vdi.component.modules.VDIServiceModule
/**
* Dataset Reinstaller
*
* VDI module that scans the connected application databases for datasets in the
* [InstallStatus.ReadyForReinstall] state, uninstalls them to remove any broken
* state, then reinstalls them.
*
* @since 1.0.0
*
* @author <NAME> - https://github.com/foxcapades
*/
sealed interface DatasetReinstaller : VDIServiceModule | 6 | Kotlin | 0 | 0 | 63ae72c611b226043d329d30c5fb332c46dbe158 | 433 | vdi-service | Apache License 2.0 |
app/src/main/java/com/decoverri/treasuregeneratorpf/adapters/TreasureGridAdapter.kt | decoverri | 594,117,400 | false | null | package com.decoverri.treasuregeneratorpf.adapters
import android.app.Activity
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import androidx.core.content.ContextCompat
import com.decoverri.treasuregeneratorpf.R
import com.decoverri.treasuregeneratorpf.model.TreasureType
class TreasureGridAdapter(private val context: Context, private val treasureTypes: List<TreasureType>) : BaseAdapter() {
override fun getCount(): Int {
return treasureTypes.size
}
override fun getItem(position: Int): Any {
return treasureTypes[position];
}
override fun getItemId(position: Int): Long {
return position.toLong();
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val view = LayoutInflater.from(context).inflate(R.layout.treasure_type_card, parent, false);
val treasureType = treasureTypes[position];
val image = view.findViewById<ImageView>(R.id.treasure_image)
image.setImageDrawable(ContextCompat.getDrawable(context, context.resources.getIdentifier("type_" + treasureType.letter.lowercase(), "drawable", context.packageName)))
return view;
}
}
| 0 | Kotlin | 0 | 0 | 8cef487bf61964c7d1c1ac141ae56ea45e54fa4a | 1,314 | treasure-generator-pf-android | MIT License |
demo/src/main/java/ovh/plrapps/mapcompose/demo/ui/screens/Home.kt | p-lr | 359,208,603 | false | null | package ovh.plrapps.mapcompose.demo.ui.screens
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import ovh.plrapps.mapcompose.demo.R
import ovh.plrapps.mapcompose.demo.ui.MainDestinations
@Composable
fun Home(demoListState: LazyListState, onDemoSelected: (dest: MainDestinations) -> Unit) {
Scaffold(
topBar = {
TopAppBar(
title = { Text(stringResource(R.string.app_name)) },
backgroundColor = MaterialTheme.colors.primarySurface,
)
}
) {
LazyColumn(state = demoListState) {
MainDestinations.values().map { dest ->
item {
Text(
text = dest.title,
modifier = Modifier
.fillMaxWidth()
.clickable { onDemoSelected.invoke(dest) }
.padding(16.dp),
textAlign = TextAlign.Center
)
Divider(thickness = 1.dp)
}
}
}
}
} | 4 | null | 7 | 96 | e65762b45cc7418cbae54e0673405d109da7aadd | 1,532 | MapCompose | Apache License 2.0 |
bitapp/src/main/java/com/atech/bit/ui/screens/attendance/attendance_screen/AttendanceEvent.kt | aiyu-ayaan | 489,575,997 | false | null | package com.atech.bit.ui.screens.attendance.attendance_screen
import com.atech.core.data_source.room.attendance.Sort
import com.atech.core.datasource.room.attendance.AttendanceModel
import com.atech.core.usecase.SyllabusUIModel
sealed interface AttendanceEvent {
data class ChangeAttendanceValue(
val attendanceModel: AttendanceModel,
val value: Int = 1,
val isPresent: Boolean = true
) : AttendanceEvent
data class UndoAttendanceState(
val attendanceModel: AttendanceModel
) : AttendanceEvent
data class DeleteAttendance(
val attendanceModel: AttendanceModel
) : AttendanceEvent
data class ArchiveAttendance(
val attendanceModel: AttendanceModel
) : AttendanceEvent
data object RestorerAttendance : AttendanceEvent
data class ItemSelectedClick(
val attendanceModel: AttendanceModel,
val isAdded: Boolean = true
) : AttendanceEvent
data class SelectAllClick(
val attendanceModelList: List<AttendanceModel>,
val isAdded: Boolean = true
) :
AttendanceEvent
data object ClearSelection : AttendanceEvent
data object SelectedItemToArchive : AttendanceEvent
data object DeleteSelectedItems : AttendanceEvent
data class AddFromSyllabusItemClick(
val model: SyllabusUIModel,
val isAdded: Boolean
) : AttendanceEvent
data class ArchiveItemClick(
val attendanceModel: AttendanceModel,
val isAdded: Boolean = true
) : AttendanceEvent
data class ArchiveSelectAllClick(
val attendanceModelList: List<AttendanceModel>,
val isAdded: Boolean = true
) : AttendanceEvent
data object ArchiveScreenUnArchiveSelectedItems : AttendanceEvent
data object ArchiveScreenDeleteSelectedItems : AttendanceEvent
data class UpdateSettings(val percentage: Int, val sort: Sort) : AttendanceEvent
data object UpdateIsLibraryCardVisible : AttendanceEvent
} | 10 | null | 5 | 17 | f5d1c6689b7f2cdeb039d5cc3563549e77acd5ae | 1,979 | BIT-App | MIT License |
app/src/main/java/it/andrearosa/kickstarter/db/models/UserModel.kt | andrea-rosa | 149,014,587 | false | null | package it.andrearosa.kickstarter.db.models
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
@Entity(tableName = "users")
data class UserModel(
@PrimaryKey val id: Int,
@ColumnInfo(name = "name") val name: String,
@ColumnInfo(name = "username") val username: String,
@ColumnInfo(name = "email") val email: String
) | 0 | Kotlin | 0 | 0 | d80652bc50999e78e8a13a7e67a6a219fc6ba640 | 439 | kickstarter-android-kt | MIT License |
src/main/kotlin/dev/interfiber/karpet/server/player/PlayerCraftingHandler.kt | KarpetPowered | 490,243,114 | false | {"Kotlin": 68475, "Shell": 362} | package dev.interfiber.karpet.server.player
import dev.interfiber.karpet.server.recipes.InventoryConstants
import dev.interfiber.karpet.server.recipes.MinecraftRecipe
import mu.KotlinLogging
import net.minestom.server.entity.Player
import net.minestom.server.inventory.click.ClickType
import net.minestom.server.inventory.condition.InventoryConditionResult
import net.minestom.server.item.ItemStack
import java.util.concurrent.atomic.AtomicReference
private val logger = KotlinLogging.logger {}
/**
* Handle player crafting
* The entire portable player crafting system written from the ground up
* @author Interfiber
*/
class PlayerCraftingHandler {
/**
* Check if a slot id is in the crafting grid
* @author Interfiber
*/
private fun indexCraft(index: Int): Boolean {
return index == InventoryConstants.PortableInventorySlot1 || index == InventoryConstants.PortableInventorySlot2 || index == InventoryConstants.PortableInventorySlot3 || index == InventoryConstants.PortableInventorySlot4
}
/**
* Called when a player opens their portable crafting grid
* @author Interfiber
*/
fun addCraftEvent(player: Player, Recipes: List<MinecraftRecipe>) {
val selectedItems = HashMap<Int, ItemStack>()
selectedItems[InventoryConstants.PortableInventorySlot1] = ItemStack.AIR
selectedItems[InventoryConstants.PortableInventorySlot2] = ItemStack.AIR
selectedItems[InventoryConstants.PortableInventorySlot3] = ItemStack.AIR
selectedItems[InventoryConstants.PortableInventorySlot4] = ItemStack.AIR
val recipeOutputID = AtomicReference("")
player.inventory.addInventoryCondition { targetPlayer: Player, slot: Int, _: ClickType, inventoryConditionResult: InventoryConditionResult ->
if (slot == InventoryConstants.PortableInventoryOutputSlot && recipeOutputID.get() != null) {
// Clear memory of crafting
selectedItems.clear()
selectedItems[InventoryConstants.PortableInventorySlot1] = ItemStack.AIR
selectedItems[InventoryConstants.PortableInventorySlot2] = ItemStack.AIR
selectedItems[InventoryConstants.PortableInventorySlot3] = ItemStack.AIR
selectedItems[InventoryConstants.PortableInventorySlot4] = ItemStack.AIR
// Clear inventory
targetPlayer.inventory.setItemStack(InventoryConstants.PortableInventorySlot1, ItemStack.AIR)
targetPlayer.inventory.setItemStack(InventoryConstants.PortableInventorySlot2, ItemStack.AIR)
targetPlayer.inventory.setItemStack(InventoryConstants.PortableInventorySlot3, ItemStack.AIR)
targetPlayer.inventory.setItemStack(InventoryConstants.PortableInventorySlot4, ItemStack.AIR)
// Update inventory
player.inventory.update()
// Log craft to console (Server admin can view everything being crafted)
logger.info(player.username + " crafted a $recipeOutputID")
return@addInventoryCondition
}
if (indexCraft(slot)) {
// Get the current clicked item
val cursorItem = inventoryConditionResult.cursorItem
if (cursorItem.isAir) {
selectedItems[slot] = ItemStack.AIR
} else {
selectedItems[slot] = ItemStack.of(cursorItem.material(), 1)
}
// Query all loaded recipes
// Basically loop over all provided recipes, until we find one with the same item stucture as the current
// crafting table, when we find it set the crafting table output item and break the loop. Once the item is clicked we clear the grid
for (z in Recipes.indices) {
val recipe: MinecraftRecipe = Recipes[z]
if (recipe.canCraftInPortableCrafting()) {
val values: Collection<ItemStack> = selectedItems.values
val itemsList: List<ItemStack> = ArrayList(values)
if (recipe.portableItems?.equals(itemsList) == true) {
val resultItem: ItemStack? = recipe.result // TODO calculate the amount for items crafted
if (resultItem != null) {
targetPlayer.inventory
.setItemStack(InventoryConstants.PortableInventoryOutputSlot, resultItem)
}
recipeOutputID.set(recipe.recipeID)
break
} else {
recipeOutputID.set(null)
targetPlayer.inventory
.setItemStack(InventoryConstants.PortableInventoryOutputSlot, ItemStack.AIR)
}
}
}
}
inventoryConditionResult.isCancel = false
}
}
}
| 0 | Kotlin | 1 | 8 | 1d0c1c2df4ad65d043150ebbb80b033c6ca86679 | 5,063 | Karpet | MIT License |
app/src/main/kotlin/com/melardev/android/crud/datasource/common/repositories/TodoRepository.kt | melardev | 197,663,622 | false | {"Kotlin": 41146} | package com.melardev.android.crud.datasource.common.repositories
import com.melardev.android.crud.datasource.common.entities.Todo
interface TodoRepository : BaseRepository<Todo>
| 0 | Kotlin | 4 | 7 | 957cbe30ffa320f82f2343d5c6137fd884911976 | 181 | Android_Kotlin_MVVM_Dagger_RxRetrofit_DataBinding_Crud | MIT License |
app/src/main/java/com/stocksexchange/android/model/CurrencyMarketPreviewDataSources.kt | libertaria-project | 183,030,087 | true | {"Kotlin": 2210140} | package com.stocksexchange.android.model
/**
* An enumeration of all possible data sources
* of currency market preview sources.
*/
enum class CurrencyMarketPreviewDataSources {
PRICE_CHART,
DEPTH_CHART,
ORDERBOOK,
TRADES
} | 0 | Kotlin | 0 | 0 | 35a7f9a61f52f68ab3267da24da3c1d77d84e9c3 | 245 | Android-app | MIT License |
butterfly/src/main/java/zlc/season/butterfly/AgileLauncherManager.kt | ssseasonnn | 452,103,571 | false | {"Kotlin": 108624} | package zlc.season.butterfly
import android.app.Activity
import android.os.Bundle
import zlc.season.butterfly.internal.ButterflyHelper.application
import zlc.season.butterfly.internal.key
import zlc.season.claritypotion.ActivityLifecycleCallbacksAdapter
object AgileLauncherManager {
private const val OLD_ACTIVITY_KEY = "old_activity_key"
private val launcherMap = mutableMapOf<String, MutableList<AgileLauncher>>()
private val saveInstanceStateMap = mutableMapOf<String, Boolean>()
init {
application.registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacksAdapter() {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
if (savedInstanceState != null) {
val oldKey = savedInstanceState.getString(OLD_ACTIVITY_KEY)
if (!oldKey.isNullOrEmpty()) {
updateKey(oldKey, activity.key())
}
}
}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
super.onActivitySaveInstanceState(activity, outState)
val key = activity.key()
if (containsKey(key)) {
outState.putString(OLD_ACTIVITY_KEY, key)
}
updateSaveInstanceState(key)
}
override fun onActivityDestroyed(activity: Activity) {
super.onActivityDestroyed(activity)
handleActivityDestroy(activity.key())
}
})
}
@Synchronized
private fun updateSaveInstanceState(key: String) {
saveInstanceStateMap[key] = true
}
@Synchronized
private fun handleActivityDestroy(key: String) {
if (saveInstanceStateMap[key] == null) {
launcherMap.remove(key)
}
saveInstanceStateMap.remove(key)
}
@Synchronized
private fun updateKey(oldKey: String, newKey: String) {
val oldLauncher = launcherMap.remove(oldKey)
oldLauncher?.let {
launcherMap[newKey] = oldLauncher
}
}
@Synchronized
fun containsKey(key: String): Boolean {
return launcherMap[key] != null
}
@Synchronized
fun addLauncher(key: String, launcher: AgileLauncher) {
val list = launcherMap.getOrPut(key) { mutableListOf() }
if (list.find { it.agileRequest.scheme == launcher.agileRequest.scheme } == null) {
list.add(launcher)
}
}
@Synchronized
fun getLauncher(key: String, scheme: String): AgileLauncher? {
return launcherMap[key]?.find { it.agileRequest.scheme == scheme }
}
} | 5 | Kotlin | 16 | 215 | 42475a7a4387c6bf0b9fbf5214bc5302d894fa7a | 2,705 | Butterfly | Apache License 2.0 |
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/NeuterSolid.kt | DevSrSouza | 311,134,756 | false | {"Kotlin": 36719092} | package compose.icons.lineawesomeicons
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 compose.icons.LineAwesomeIcons
public val LineAwesomeIcons.NeuterSolid: ImageVector
get() {
if (_neuterSolid != null) {
return _neuterSolid!!
}
_neuterSolid = Builder(name = "NeuterSolid", defaultWidth = 32.0.dp, defaultHeight =
32.0.dp, viewportWidth = 32.0f, viewportHeight = 32.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(16.0f, 4.0f)
curveTo(11.594f, 4.0f, 8.0f, 7.594f, 8.0f, 12.0f)
curveTo(8.0f, 16.066f, 11.066f, 19.438f, 15.0f, 19.938f)
lineTo(15.0f, 28.0f)
lineTo(17.0f, 28.0f)
lineTo(17.0f, 19.938f)
curveTo(20.934f, 19.438f, 24.0f, 16.066f, 24.0f, 12.0f)
curveTo(24.0f, 7.594f, 20.406f, 4.0f, 16.0f, 4.0f)
close()
moveTo(16.0f, 6.0f)
curveTo(19.324f, 6.0f, 22.0f, 8.676f, 22.0f, 12.0f)
curveTo(22.0f, 15.324f, 19.324f, 18.0f, 16.0f, 18.0f)
curveTo(12.676f, 18.0f, 10.0f, 15.324f, 10.0f, 12.0f)
curveTo(10.0f, 8.676f, 12.676f, 6.0f, 16.0f, 6.0f)
close()
}
}
.build()
return _neuterSolid!!
}
private var _neuterSolid: ImageVector? = null
| 17 | Kotlin | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 2,018 | compose-icons | MIT License |
sample/app/src/main/java/dev/tuongnt/tinder/data/api/dto/ResultApiDto.kt | alanrb | 296,359,249 | false | null | package dev.tuongnt.tinder.data.api.dto
/**
* Created by <NAME>Alan) on 9/13/20.
* Copyright (c) 2020 Buuuk. All rights reserved.
*/
data class ResultApiDto(
val results: List<UserResultApiDto>
) | 0 | null | 0 | 0 | 4b70d16f40078747704a263b140f31fae03a5ce8 | 204 | Android-motion-layout | Apache License 2.0 |
src/test/kotlin/no/nav/omsorgspenger/testutils/DataSourceExtension.kt | navikt | 293,469,365 | false | {"Kotlin": 598600, "Dockerfile": 223} | package no.nav.omsorgspenger.testutils
import no.nav.omsorgspenger.DataSourceBuilder
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.api.extension.ParameterContext
import org.junit.jupiter.api.extension.ParameterResolver
import org.testcontainers.containers.PostgreSQLContainer
import javax.sql.DataSource
internal class DataSourceExtension : ParameterResolver {
private val postgreSQLContainer = PostgreSQLContainer("postgres:12.2")
.withDatabaseName("postgresl")
.withUsername("postgresl")
.withPassword("postgresql")
init {
postgreSQLContainer.start()
}
private val dataSource = DataSourceBuilder(
env = mapOf(
"DATABASE_HOST" to postgreSQLContainer.host,
"DATABASE_PORT" to postgreSQLContainer.firstMappedPort.toString(),
"DATABASE_DATABASE" to postgreSQLContainer.databaseName,
"DATABASE_USERNAME" to postgreSQLContainer.username,
"DATABASE_PASSWORD" to postgreSQLContainer.password
)
).build()
override fun supportsParameter(parameterContext: ParameterContext, extensionContext: ExtensionContext): Boolean {
return parameterContext.parameter.type == DataSource::class.java
}
override fun resolveParameter(parameterContext: ParameterContext, extensionContext: ExtensionContext): Any {
return dataSource
}
} | 1 | Kotlin | 1 | 2 | 378101129956af238282bb37bfee2af0ec9a0bec | 1,411 | omsorgspenger-rammemeldinger | MIT License |
src/main/kotlin/dto/ClusterDto.kt | GeorgHoffmeyer | 210,186,519 | false | null | package dto
import java.math.BigDecimal
data class ClusterDto(
val from : Long,
var till : Long,
val sum : BigDecimal,
val avg : BigDecimal,
val max : BigDecimal,
val min : BigDecimal,
val maxTimestamp : Long,
val minTimestamp : Long,
val itemCount : Int
) | 0 | Kotlin | 0 | 0 | c5fdd2ac7fabfd615fb2d725966741b5ba8fb0bf | 294 | timeseries | MIT License |
app/src/main/java/com/cuongpm/todoapp/ui/component/adapter/TaskAdapter.kt | cuongpm | 149,412,311 | false | null | package com.cuongpm.todoapp.ui.component.adapter
import android.databinding.DataBindingUtil
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.cuongpm.todoapp.R
import com.cuongpm.todoapp.data.local.TaskEntity
import com.cuongpm.todoapp.databinding.ItemTaskBinding
import com.cuongpm.todoapp.ui.main.tasks.TaskViewModel
/**
* Created by cuongpm on 9/23/18.
*/
class TaskAdapter(
private var tasks: List<TaskEntity>,
private val taskViewModel: TaskViewModel
) : RecyclerView.Adapter<TaskAdapter.TaskViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskViewHolder {
val binding = DataBindingUtil.inflate<ItemTaskBinding>(LayoutInflater.from(parent.context),
R.layout.item_task, parent, false)
return TaskViewHolder(binding)
}
override fun getItemCount() = tasks.size
override fun onBindViewHolder(holder: TaskViewHolder, position: Int) = holder.bind(tasks[position])
class TaskViewHolder(val binding: ItemTaskBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(taskEntity: TaskEntity) {
with(binding)
{
task = taskEntity
// listener = selectNetworkListener
executePendingBindings()
}
}
}
fun setData(tasks: List<TaskEntity>) {
this.tasks = tasks
notifyDataSetChanged()
}
}
| 9 | Kotlin | 6 | 17 | 4d869496f96573a5797ca69b213b83eac15d9df9 | 1,491 | android-minimal-todo | MIT License |
Problems/Between two numbers/src/Task.kt | lbalmaceda | 230,185,187 | false | {"HTML": 36858, "Kotlin": 28731, "JavaScript": 5252, "CSS": 3780, "Java": 214, "Assembly": 129} | import java.util.*
fun main(args: Array<String>) {
val scanner = Scanner(System.`in`)
val input = scanner.nextInt()
if(input in scanner.nextInt()..scanner.nextInt()){
println("YES")
} else {
println("NO")
}
} | 0 | HTML | 0 | 0 | 22c02de6756cd7622b27b7bc7747d564c2faf8eb | 246 | hyp-flashcards | MIT License |
replica-core/src/jvmTest/kotlin/me/aartikov/replica/keyed/physical/OnReplicaTest.kt | aartikov | 438,253,231 | false | {"HTML": 3233987, "Kotlin": 685239, "CSS": 29063, "JavaScript": 19875} | package me.aartikov.replica.keyed.physical
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import me.aartikov.replica.keyed.utils.KeyedReplicaProvider
import me.aartikov.replica.utils.MainCoroutineRule
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Rule
import org.junit.Test
@OptIn(ExperimentalCoroutinesApi::class)
class OnReplicaTest {
private val replicaProvider = KeyedReplicaProvider()
companion object {
private const val DEFAULT_KEY = 0
}
@get:Rule
var mainCoroutineRule = MainCoroutineRule()
@Test
fun `makes action on existing replica`() = runTest {
val replica = replicaProvider.replica()
replica.setData(DEFAULT_KEY, KeyedReplicaProvider.testData(DEFAULT_KEY))
replica.onReplica(DEFAULT_KEY) { clear() }
val childReplicaState = replica.getCurrentState(DEFAULT_KEY)
assertNull(childReplicaState?.data?.value)
}
@Test
fun `create child replica than makes action on it`() = runTest {
val replica = replicaProvider.replica()
replica.onReplica(DEFAULT_KEY) { setData(KeyedReplicaProvider.testData(DEFAULT_KEY)) }
val childReplicaState = replica.getCurrentState(DEFAULT_KEY)
assertNotNull(childReplicaState?.data?.value)
}
} | 0 | HTML | 1 | 33 | dc55d0cb727b6854224ceb8b1a1d0d87c7faaddf | 1,351 | Replica | MIT License |
app/src/main/java/io/github/tonnyl/mango/ui/user/UserProfilePresenter.kt | huannan | 101,136,956 | true | {"Kotlin": 250939, "HTML": 27144} | package io.github.tonnyl.mango.ui.user
import io.github.tonnyl.mango.data.User
import io.github.tonnyl.mango.data.repository.AuthUserRepository
import io.github.tonnyl.mango.data.repository.UserRepository
import io.github.tonnyl.mango.util.AccessTokenManager
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
/**
* Created by lizhaotailang on 2017/6/28.
*
* Listens to user action from the ui [io.github.tonnyl.mango.ui.user.UserProfileFragment],
* retrieves the data and update the ui as required.
*/
class UserProfilePresenter(view: UserProfileContract.View, user: User) : UserProfileContract.Presenter {
private var mView: UserProfileContract.View = view
private var mCompositeDisposable: CompositeDisposable
private var mFollowingChecked = false
private var mIsFollowing = false
private var mUser = user
companion object {
@JvmField
val EXTRA_USER = "EXTRA_USER"
}
init {
mView.setPresenter(this)
mCompositeDisposable = CompositeDisposable()
}
override fun subscribe() {
mView.showUserInfo(mUser)
if (AccessTokenManager.accessToken?.id == mUser.id) {
mView.setFollowable(false)
getUpdatedUserInfo()
} else {
checkFollowing()
}
}
override fun unsubscribe() {
mCompositeDisposable.clear()
}
override fun checkFollowing() {
val disposable = UserRepository.checkFollowing(mUser.id)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
if (it.code() == 204) {
mIsFollowing = true
mView.setFollowing(true)
} else if (it.code() == 404) {
mIsFollowing = false
mView.setFollowing(false)
}
mFollowingChecked = true
mView.setFollowable(true)
}, {
mFollowingChecked = false
mView.setFollowable(false)
})
mCompositeDisposable.add(disposable)
}
override fun toggleFollow() {
if (mIsFollowing) {
UserRepository.unfollow(mUser.id)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
mIsFollowing = false
mView.setFollowing(false)
}, {
mView.showNetworkError()
it.printStackTrace()
})
} else {
UserRepository.follow(mUser.id)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
mIsFollowing = true
mView.setFollowing(true)
}, {
mView.showNetworkError()
it.printStackTrace()
})
}
}
override fun getUser(): User {
return mUser
}
private fun getUpdatedUserInfo() {
val disposable = AuthUserRepository.refreshAuthenticatedUser()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
mUser = it
mView.showUserInfo(it)
}, {
it.printStackTrace()
})
mCompositeDisposable.add(disposable)
}
} | 0 | Kotlin | 0 | 0 | a03c2a43d1cf45cf891093e5adfaa945de87ba2e | 3,750 | Mango | MIT License |
app/src/test/java/com/flatstack/android/login/LoginMapperTest.kt | fs | 17,365,445 | false | null | package com.flatstack.android.login
import com.flatstack.android.graphql.mutation.LoginMutation
import com.flatstack.android.model.entities.Session
import org.junit.Test
import org.junit.jupiter.api.Assertions.assertEquals
internal class LoginMapperTest {
@Test
fun mapLogin() {
val expectedAccessToken = "access_token"
val expectedSignin = LoginMutation.Signin(accessToken = expectedAccessToken)
val expectedSession = Session(accessToken = expectedAccessToken)
val actualSession = LoginMapper().mapLogin(expectedSignin)
assertEquals(actualSession, expectedSession)
}
} | 8 | Kotlin | 18 | 74 | 43a49c34e277a4937140f1ab9b162b43ad85e276 | 625 | android-base | MIT License |
app/src/main/java/cn/liyuyu/datastoreext/App.kt | li-yu | 327,850,005 | false | {"Kotlin": 8221} | package cn.liyuyu.datastoreext
import android.app.Application
import cn.liyuyu.datastoreext.core.DsPreferences
import com.google.gson.Gson
class App : Application() {
override fun onCreate() {
super.onCreate()
DsPreferences.converter = GsonConverter(Gson())
}
} | 0 | Kotlin | 0 | 2 | 7f4ca90c9249ae4d3ec292944f21485797e5206a | 287 | DsPreferences | Apache License 2.0 |
kotlin-utils/src/main/kotlin/xyz/lbres/kotlinutils/longarray/ext/LongArrayExt.kt | lbressler13 | 507,666,582 | false | {"Kotlin": 350067} | package xyz.lbres.kotlinutils.longarray.ext
/**
* Assign all indices to have the same value
*
* @param value [Long]: value to assign
*/
fun LongArray.setAllValues(value: Long) {
indices.forEach { set(it, value) }
}
/**
* Get number of elements matching a specific value
*
* @param element [Long]: value to match
* @return [Int]: number of elements with the given value
*/
fun LongArray.countElement(element: Long) = this.count { it == element }
| 0 | Kotlin | 0 | 1 | c6a0bdbb65b783363fa8c23b898114eddb048b72 | 460 | kotlin-utils | MIT License |
app/src/main/java/com/codelabs/state/WellnessTask.kt | PedroSanz93 | 718,774,381 | false | {"Kotlin": 16558} | package com.codelabs.state
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
data class WellnessTask(
val id: Int,
val label: String,
var initialChecked: Boolean=false){
var checked by mutableStateOf(initialChecked)
}
| 0 | Kotlin | 0 | 0 | 7b3f02f2dc0d3f600af2bdc5c76d64b9c5642b81 | 316 | Practica_05_MUESTRA | Apache License 2.0 |
core/usecases/src/main/kotlin/scene/symbol/trackSymbolInScene/SynchronizeTrackedSymbolsWithProseUseCase.kt | Soyle-Productions | 239,407,827 | false | null | package com.soyle.stories.usecase.scene.symbol.trackSymbolInScene
import com.soyle.stories.domain.prose.MentionedSymbolId
import com.soyle.stories.domain.prose.Prose
import com.soyle.stories.domain.scene.*
import com.soyle.stories.domain.scene.events.SceneEvent
import com.soyle.stories.domain.scene.events.SymbolTrackedInScene
import com.soyle.stories.domain.scene.events.TrackedSymbolRemoved
import com.soyle.stories.usecase.prose.ProseRepository
import com.soyle.stories.usecase.scene.SceneRepository
import com.soyle.stories.usecase.theme.ThemeRepository
class SynchronizeTrackedSymbolsWithProseUseCase(
private val sceneRepository: SceneRepository,
private val proseRepository: ProseRepository,
private val themeRepository: ThemeRepository
) : SynchronizeTrackedSymbolsWithProse {
override suspend fun invoke(proseId: Prose.Id, output: SynchronizeTrackedSymbolsWithProse.OutputPort) {
val scene = sceneRepository.getSceneThatOwnsProse(proseId) ?: return
val prose = proseRepository.getProseOrError(proseId)
val symbolMentions = prose.mentions.mapNotNull { it.entityId as? MentionedSymbolId }
val symbolIds = symbolMentions.map { it.id }.toSet()
val themes = themeRepository.getThemesById(symbolMentions.map { it.themeId }.toSet())
val symbols = themes.flatMap { theme ->
theme.symbols.asSequence().filter { it.id in symbolIds }
.map { theme to it }
}
val events = mutableListOf<SceneEvent>()
val sceneWithSymbols = symbols.fold(scene) { nextScene, (theme, symbol) ->
val update = nextScene.withSymbolTracked(theme, symbol)
when (update) {
is WithoutChange -> {
}
is Updated -> events.add(update.event)
}
update.scene
}
val sceneWithoutSymbols = sceneWithSymbols.trackedSymbols.fold(sceneWithSymbols) { nextScene, trackedSymbol ->
if (! trackedSymbol.isPinned && trackedSymbol.symbolId !in symbolIds) {
val update = nextScene.withoutSymbolTracked(trackedSymbol.symbolId)
when (update) {
is WithoutChange -> {
}
is Updated -> events.add(update.event)
}
update.scene
} else nextScene
}
if (events.isNotEmpty()) {
sceneRepository.updateScene(sceneWithoutSymbols)
output.symbolTrackedInScene(
SynchronizeTrackedSymbolsWithProse.ResponseModel(
events.filterIsInstance<SymbolTrackedInScene>(),
events.filterIsInstance<TrackedSymbolRemoved>(),
)
)
}
}
} | 45 | Kotlin | 0 | 9 | 1a110536865250dcd8d29270d003315062f2b032 | 2,766 | soyle-stories | Apache License 2.0 |
app/src/main/java/com/mithun/simplebible/ui/BaseCollapsibleFragment.kt | mithun17 | 315,563,631 | false | null | package com.mithun.simplebible.ui
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupWithNavController
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.appbar.CollapsingToolbarLayout
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.mithun.simplebible.R
import com.mithun.simplebible.utilities.gone
import com.mithun.simplebible.utilities.visible
import kotlin.math.abs
/**
* Fragments that use a collapsible toolbar should extend this Base class
*/
open class BaseCollapsibleFragment : Fragment() {
protected lateinit var toolbar: Toolbar
protected lateinit var toolbarTextView: TextView
protected lateinit var collapsingToolbar: CollapsingToolbarLayout
protected lateinit var appBarLayout: AppBarLayout
protected var toolbarTitle: String = ""
protected var fabSelection: FloatingActionButton? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val navController = findNavController()
val appBarConfiguration = AppBarConfiguration(navController.graph)
toolbar = view.findViewById(R.id.toolbar)
toolbarTextView = view.findViewById(R.id.tvToolbar)
collapsingToolbar = view.findViewById(R.id.ctbAppBar)
fabSelection = view.findViewById(R.id.fabSelectBook)
collapsingToolbar.setupWithNavController(toolbar, navController, appBarConfiguration)
toolbarTextView.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(view.context, R.drawable.ic_arrow_drop_down_24), null)
toolbarTextView.gone
appBarLayout = view.findViewById(R.id.collapsible_toolbar)
appBarLayout.addOnOffsetChangedListener(
AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
if (abs(verticalOffset) - appBarLayout.totalScrollRange == 0) {
// Collapsed
// set navigation icon colors
toolbar.navigationIcon?.colorFilter = PorterDuffColorFilter(ContextCompat.getColor(requireContext(), R.color.primaryText), PorterDuff.Mode.SRC_ATOP)
collapsingToolbar.title = null
toolbarTextView.visible
fabSelection?.gone
} else {
// Expanded
toolbar.navigationIcon?.colorFilter = PorterDuffColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP)
toolbarTextView.gone
collapsingToolbar.title = toolbarTitle
fabSelection?.visible
}
}
)
with(requireActivity() as AppCompatActivity) {
setSupportActionBar(toolbar)
toolbarTextView.text = supportActionBar?.title
supportActionBar?.title = null
}
}
protected fun setTitle(title: String) {
toolbarTitle = title
toolbarTextView.text = title
collapsingToolbar.title = title
}
protected fun setSelectionClickListener(callback: () -> Unit) {
toolbarTextView.setOnClickListener {
callback.invoke()
}
}
override fun onResume() {
super.onResume()
appBarLayout.visible
}
override fun onStop() {
super.onStop()
appBarLayout.gone
}
}
| 1 | Kotlin | 5 | 25 | e899d72b7f7c9082ac3c3831fcbb4e3a2ac62ee2 | 3,807 | SimpleBible | MIT License |
device/src/main/java/org/watsi/enrollment/device/repositories/HouseholdRepositoryImpl.kt | Meso-Health | 227,515,211 | false | null | package org.watsi.enrollment.device.repositories
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Single
import io.reactivex.schedulers.Schedulers
import okhttp3.OkHttpClient
import org.threeten.bp.Clock
import org.threeten.bp.Instant
import org.watsi.enrollment.device.api.CoverageApi
import org.watsi.enrollment.device.api.SyncHouseholdApi
import org.watsi.enrollment.device.db.daos.DeltaDao
import org.watsi.enrollment.device.db.daos.HouseholdDao
import org.watsi.enrollment.device.db.daos.MemberDao
import org.watsi.enrollment.device.db.models.DeltaModel
import org.watsi.enrollment.device.db.models.HouseholdEnrollmentRecordModel
import org.watsi.enrollment.device.db.models.HouseholdModel
import org.watsi.enrollment.device.db.models.MemberEnrollmentRecordModel
import org.watsi.enrollment.device.db.models.MemberModel
import org.watsi.enrollment.device.db.models.MembershipPaymentModel
import org.watsi.enrollment.device.managers.PreferencesManager
import org.watsi.enrollment.device.managers.SessionManager
import org.watsi.enrollment.domain.entities.Delta
import org.watsi.enrollment.domain.entities.Household
import org.watsi.enrollment.domain.relations.HouseholdWithExtras
import org.watsi.enrollment.domain.relations.HouseholdWithMembers
import org.watsi.enrollment.domain.relations.HouseholdWithMembersAndPayments
import org.watsi.enrollment.domain.repositories.HouseholdRepository
import java.util.UUID
class HouseholdRepositoryImpl(
private val householdDao: HouseholdDao,
private val deltaDao: DeltaDao,
private val memberDao: MemberDao,
private val api: CoverageApi,
private val sessionManager: SessionManager,
private val clock: Clock,
private val okHttpClient: OkHttpClient,
private val preferencesManager: PreferencesManager
) : HouseholdRepository {
override fun get(householdId: UUID): Flowable<HouseholdWithMembersAndPayments> {
return householdDao.getFlowable(householdId).map {
it.toHouseholdWithMembersAndPayments()
}
}
override fun createdOrEditedAfter(instant: Instant): Flowable<List<HouseholdWithMembers>> {
return householdDao.createdOrEditedAfter(instant).map { it.map { it.toHouseholdWithMembers() } }
}
override fun save(household: Household): Completable {
return Completable.fromAction {
// TODO: Create abstraction for creating these DeltaModels
householdDao.insertWithDelta(
HouseholdModel.fromHousehold(household, clock),
DeltaModel(
action = Delta.Action.ADD,
modelName = Delta.ModelName.HOUSEHOLD,
modelId = household.id,
synced = false,
createdAt = Instant.now(clock),
updatedAt = Instant.now(clock),
field = null)
)
}.subscribeOn(Schedulers.io())
}
override fun fetch(): Completable {
return sessionManager.currentAuthenticationToken()?.let { token ->
Completable.fromAction {
// This first check is to make sure we don't overwrite any members who've been
// recently edited before the server request is made (since there's a strong possibility
// they won't sync in time and we don't want them to be overwritten)
val unsyncedMemberIds = deltaDao.unsyncedModelIds(Delta.ModelName.MEMBER, Delta.Action.EDIT).blockingGet()
val householdsFromServer = api.fetchHouseholds(token.getHeaderString()).blockingGet()
val clientMembers = memberDao.all().blockingFirst()
val clientMembersById = clientMembers.groupBy { it.id }
// Convert server data to entities
val householdsWithExtras = householdsFromServer.map {
HouseholdWithExtras(
household = Household(
id = it.id,
enrolledAt = it.enrolledAt,
administrativeDivisionId = it.administrativeDivisionId,
address = it.address
),
activeHouseholdEnrollmentRecord = it.activeHouseholdEnrollmentRecord?.toHouseholdEnrollmentRecord(),
members = it.members.map { memberApi ->
val persistedMember = clientMembersById[memberApi.id]?.firstOrNull()?.toMember()
memberApi.toMember(persistedMember)
},
memberEnrollmentRecords = it.memberEnrollmentRecords.map { it.toMemberEnrollmentRecord() },
membershipPayments = it.activeMembershipPayments.map { it.toMembershipPayment() }
)
}
// Convert entities to models
val householdModels = householdsWithExtras.map {
HouseholdModel.fromHousehold(it.household, clock)
}
// This second check is to make sure we check for any new member edits made during server request
val additionalUnsyncedMemberIds = deltaDao.unsyncedModelIds(Delta.ModelName.MEMBER, Delta.Action.EDIT).blockingGet()
val memberModels = householdsWithExtras.map {
it.members.map { member ->
MemberModel.fromMember(member, clock)
}
}.flatten().filterNot {
unsyncedMemberIds.contains(it.id) ||
additionalUnsyncedMemberIds.contains(it.id)
}
val householdEnrollmentRecordModels = householdsWithExtras.mapNotNull {
it.activeHouseholdEnrollmentRecord?.let { householdEnrollmentRecord ->
HouseholdEnrollmentRecordModel.fromHouseholdEnrollmentRecord(householdEnrollmentRecord, clock)
}
}
val memberEnrollmentRecordModels = householdsWithExtras.map {
it.memberEnrollmentRecords.map { memberEnrollmentRecord ->
MemberEnrollmentRecordModel.fromMemberEnrollmentRecord(memberEnrollmentRecord, clock)
}
}.flatten()
val paymentModels = householdsWithExtras.map {
it.membershipPayments.map { membershipPayment ->
MembershipPaymentModel.fromMembershipPayment(membershipPayment, clock)
}
}.flatten()
// Save models
householdDao.upsert(
householdModels = householdModels,
memberModels = memberModels,
householdEnrollmentRecordModels = householdEnrollmentRecordModels,
memberEnrollmentRecordModels = memberEnrollmentRecordModels,
paymentModels = paymentModels
)
preferencesManager.updateHouseholdsLastFetched(clock.instant())
}.subscribeOn(Schedulers.io())
} ?: Completable.error(Exception("Current token is null while calling HouseholdRepositoryImpl.fetch"))
}
override fun sync(deltas: List<Delta>): Completable {
return sessionManager.currentAuthenticationToken()?.let { authToken ->
householdDao.get(deltas.first().modelId).flatMap {
val household = it.toHousehold()
if (deltas.any { it.action == Delta.Action.ADD }) {
api.postHousehold(authToken.getHeaderString(), SyncHouseholdApi(household))
} else {
Single.error(
IllegalStateException("Deltas with actions ${deltas.map { it.action }} not supported for Household")
)
}
}.toCompletable().subscribeOn(Schedulers.io())
} ?: Completable.error(Exception("Current token is null while calling HouseholdRepositoryImpl.sync"))
}
override fun deleteAll(): Completable {
return Completable.fromAction {
okHttpClient.cache()?.evictAll()
householdDao.deleteAll()
}.subscribeOn(Schedulers.io())
}
}
| 0 | Kotlin | 3 | 1 | bba562b15e5e34d3239f417c45c6ec4755510c68 | 8,329 | meso-enrollment | Apache License 2.0 |
lpDevice/src/main/java/com/angcyo/laserpacker/device/firmware/LPBinBean.kt | angcyo | 229,037,684 | false | null | package com.angcyo.engrave.firmware
/** LpBin数据结构, 拼接在原始bin文件后面的额外信息
*
* @author <a href="mailto:<EMAIL>">angcyo</a>
* @since 2022/11/04
*/
data class LPBinBean(
/**n:固件名称*/
val n: String?,
/**t:构建时间*/
val t: Long,
/**v:固件版本*/
val v: Long,
/**d:版本描述*/
val d: String?,
/**r:升级范围[xx~xx xx~xx]*/
val r: String?,
/**固件内容数据的md5*/
val md5: String?,
)
| 0 | null | 4 | 4 | 9b2d016c90f8cd6823fbcb675f3ef23a360e183c | 398 | UICoreEx | MIT License |
TheMovieDBDagger_v3_Animation/app/src/main/java/com/androidavanzado/popcorn/api/TheMovieDBService.kt | miguelcamposedu | 261,391,292 | false | null | package com.androidavanzado.popcorn.api
import com.androidavanzado.popcorn.api.response.PersonDetail
import com.androidavanzado.popcorn.api.response.PopularMoviesResponse
import com.androidavanzado.popcorn.api.response.PopularPeopleResponse
import retrofit2.Call
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Path
interface TheMovieDBService {
@GET("movie/popular")
suspend fun getPopularMovies(): Response<PopularMoviesResponse>
@GET("person/popular")
suspend fun getPopularPeople(): Response<PopularPeopleResponse>
@GET("person/{person_id}")
suspend fun getPersonDetail(@Path("person_id") idPerson: Int): Response<PersonDetail>
} | 0 | Kotlin | 0 | 0 | 919c6738203d900c9c96b16f32ba66e915ec266b | 688 | kotlinintroduccion | MIT License |
app/src/main/java/xyz/sentrionic/harmony/util/PreferenceKeys.kt | sentrionic | 220,498,638 | false | {"Kotlin": 325826} | package xyz.sentrionic.harmony.util
class PreferenceKeys {
companion object{
// Shared Preference Files:
const val APP_PREFERENCES: String = "xyz.sentrionic.harmony.APP_PREFERENCES"
// Shared Preference Keys
const val PREVIOUS_AUTH_USER: String = "xyz.sentrionic.harmony.PREVIOUS_AUTH_USER"
const val STORY_FILTER: String = "xyz.sentrionic.harmony.STORY_FILTER"
const val STORY_ORDER: String = "xyz.sentrionic.harmony.STORY_ORDER"
}
} | 0 | Kotlin | 0 | 1 | 0751148a2566ad11098ddd7f122cade7c1792dc3 | 494 | HarmonyApp | MIT License |
src/view/PainelTabuleiro.kt | wellfurtado | 854,312,293 | false | {"Kotlin": 8635} | package view
import model.Tabuleiro
import java.awt.GridLayout
import javax.swing.JPanel
class PainelTabuleiro(tabuleiro: Tabuleiro) : JPanel() {
init {
layout = GridLayout(tabuleiro.qtdeLinhas, tabuleiro.qtdeColunas)
tabuleiro.forEachCampo { campo ->
val botao = BotaoCampo(campo)
add(botao)
}
}
} | 0 | Kotlin | 0 | 0 | 5ec40f585683431f3f43ddde6f5925a51bb05520 | 357 | CampoMinado | MIT License |
week6/src/test/kotlin/com/comento/example/dao/ExampleClientRestTest.kt | Biewoom | 528,485,200 | false | null | package com.comento.example.dao
import com.comento.example.dao.client.example.ExampleClient
import com.comento.example.dao.client.example.ExampleClientFallback
import com.comento.example.dao.client.example.MessageDto
import com.comento.example.toJson
import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.client.WireMock.aResponse
import com.github.tomakehurst.wiremock.client.WireMock.anyUrl
import com.github.tomakehurst.wiremock.client.WireMock.equalToJson
import com.github.tomakehurst.wiremock.client.WireMock.get
import com.github.tomakehurst.wiremock.client.WireMock.post
import io.kotest.matchers.shouldBe
import org.apache.http.HttpStatus
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.client.RestClientTest
import org.springframework.cloud.netflix.hystrix.HystrixCircuitBreakerAutoConfiguration
import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration
import org.springframework.cloud.openfeign.FeignAutoConfiguration
import org.springframework.context.annotation.Import
private const val portNumber: Int = 100
@RestClientTest(
properties = [
"feign.client.config.exampleClient.url=http://localhost:$portNumber",
"logging.level.root=debug"
],
components = [ExampleClient::class]
)
@Import(RibbonAutoConfiguration::class, HystrixCircuitBreakerAutoConfiguration::class, FeignAutoConfiguration::class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
internal class ExampleClientRestTest {
private val wireMockServer: WireMockServer = WireMockServer(portNumber)
@Autowired
private lateinit var exampleClientSut: ExampleClient
@BeforeAll
fun setUp(){
wireMockServer.start()
}
@DisplayName("test example clinet")
@Test
fun `success test`(){
// given
wireMockServer.stubFor(
get(anyUrl())
.willReturn(aResponse()
.withHeader("Content-Type", "application/json; charset=utf-8")
.withStatus(HttpStatus.SC_OK)
.withBody(listOf(MessageDto("mock", "mock")).toJson()))
)
// when
val res = exampleClientSut.getAllMessage()
val res1 = exampleClientSut.getAllMessage()
val res2 = exampleClientSut.getAllMessage()
// then
res.size shouldBe 1
res.first().id shouldBe "mock"
}
@DisplayName("fallback client test")
@Test
fun `fallback test`(){
// given
wireMockServer.stubFor(
get(anyUrl())
.willReturn(aResponse()
.withHeader("Content-Type", "application/json; charset=utf-8")
.withStatus(HttpStatus.SC_NOT_FOUND))
)
// when
val res = exampleClientSut.getAllMessage()
// then
res shouldBe ExampleClientFallback().getAllMessage()
}
@DisplayName("test example client2")
@Test
fun `success test2`(){
// given
wireMockServer.stubFor(
get(anyUrl())
.willReturn(aResponse()
.withHeader("Content-Type", "application/json; charset=utf-8")
.withStatus(HttpStatus.SC_OK)
.withFixedDelay(3001)
.withBody(MessageDto("mock", "mock").toJson()))
)
// when
val res = exampleClientSut.getOneMessage("mock")
// then
res.id shouldBe "mock"
}
@DisplayName("test example client3")
@Test
fun `success test3`(){
// given
val messageDto = MessageDto("id1","text")
wireMockServer.stubFor(
post(anyUrl())
.withRequestBody(equalToJson(messageDto.toJson(),true,true))
.willReturn(aResponse()
.withStatus(HttpStatus.SC_OK)
.withHeader("Content-Type", "application/json")
.withBody(messageDto.toJson())
)
)
// when
val res = exampleClientSut.sendMessages(messageDto)
// then
res.id shouldBe "id1"
res.text shouldBe "text"
}
} | 0 | Kotlin | 0 | 0 | 6d1c57944eb4968da48d91b5ec82c46087084523 | 4,357 | comento_server | MIT License |
core/navigation/src/main/java/st/slex/csplashscreen/core/navigation/navigator/NavigatorImpl.kt | stslex | 413,161,718 | false | {"Kotlin": 305839, "Ruby": 1145} | package st.slex.csplashscreen.core.navigation.navigator
import androidx.navigation.NavHostController
import st.slex.csplashscreen.core.core.Logger
class NavigatorImpl(
private val navHostController: NavHostController
) : Navigator {
override fun invoke(target: NavigationTarget) {
Logger.d("process $target", TAG)
when (target) {
NavigationTarget.PopBackStack -> popBackStack()
is NavigationTarget.Screen -> navigateScreen(target)
}
}
private fun popBackStack() {
navHostController.popBackStack()
}
private fun navigateScreen(target: NavigationTarget.Screen) {
val currentRoute = navHostController.currentDestination?.route ?: return
try {
navHostController.navigate(target.screen) {
if (target.options.isSingleTop.not()) return@navigate
popUpTo(currentRoute) {
inclusive = true
saveState = true
}
launchSingleTop = true
}
} catch (exception: Exception) {
Logger.e(exception, TAG, "screen: ${target.screen}")
}
}
companion object {
private const val TAG = "NAVIGATION"
}
} | 4 | Kotlin | 0 | 4 | 5b2d29d07996b08956cda6a4c9d355c726128ae3 | 1,251 | CSplashScreen | Apache License 2.0 |
auth-service/src/test/kotlin/de/alxgrk/ApplicationTest.kt | alxgrk | 520,474,867 | false | {"Kotlin": 117999, "TypeScript": 71187, "CSS": 1456, "HTML": 365, "Shell": 105} | package de.alxgrk
import io.ktor.http.*
import kotlin.test.*
import io.ktor.server.testing.*
import io.ktor.client.request.*
class ApplicationTest {
@Test
fun testRoot() = testApplication {
val client = createClient {
followRedirects = false
expectSuccess = false
}
val response = client.get("/login-github")
assertEquals(HttpStatusCode.Found, response.status)
assertTrue(response.headers["Location"]!!.startsWith("https://github.com/"))
}
}
| 0 | Kotlin | 0 | 0 | 4cf85dbead025ef0eae3e6f33dd9aaf6fe4a1ad5 | 520 | redis-dev-to-hackathon-auction-system | MIT License |
ktmidi-jvm-desktop/src/jvmMain/kotlin/dev/atsushieno/alsakt/AlsaSequencer.kt | atsushieno | 340,913,447 | false | null | package dev.atsushieno.alsakt
import dev.atsushieno.alsa.javacpp.*
import dev.atsushieno.alsa.javacpp.global.Alsa
import dev.atsushieno.alsa.javacpp.global.HackyPoll
import dev.atsushieno.ktmidi.MidiTransportProtocol
import dev.atsushieno.ktmidi.Ump
import dev.atsushieno.ktmidi.sizeInInts
import dev.atsushieno.ktmidi.umpSizeInInts
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import org.bytedeco.javacpp.BytePointer
import org.bytedeco.javacpp.Loader
import org.bytedeco.javacpp.Loader.sizeof
import java.nio.ByteBuffer
@Suppress("unused")
class AlsaSequencer(
val ioType: Int, ioMode: Int,
val driverName: String = "default"
) : AutoCloseable {
private val seq: snd_seq_t
private var driverNameHandle : BytePointer? = null
internal val sequencerHandle : snd_seq_t?
get() = seq
override fun close() {
if (midiEventParserOutput != null) {
Alsa.snd_midi_event_free(midiEventParserOutput)
midiEventParserOutput = null
}
driverNameHandle?.deallocate()
driverNameHandle = null
portNameHandle?.deallocate()
portNameHandle = null
nameHandle?.deallocate()
nameHandle = null
if (seq != null)
Alsa.snd_seq_close(seq)
}
val name :String
get() = Alsa.snd_seq_name(seq).string
val sequencerType: Int
get() = Alsa.snd_seq_type(seq)
fun setNonBlockingMode(toNonBlockingMode: Boolean) {
Alsa.snd_seq_nonblock(seq, if (toNonBlockingMode) 1 else 0)
}
val currentClientId: Int
get() = Alsa.snd_seq_client_id(seq)
var inputBufferSize: Long
get() = Alsa.snd_seq_get_input_buffer_size(seq)
set(value) { Alsa.snd_seq_set_input_buffer_size(seq, value) }
var outputBufferSize: Long
get() = Alsa.snd_seq_get_output_buffer_size(seq)
set(value) { Alsa.snd_seq_set_output_buffer_size(seq, value) }
val targetPortType: Int
get() = AlsaPortType.MidiGeneric or AlsaPortType.Synth or AlsaPortType.Application
fun queryNextClient(client: AlsaClientInfo): Boolean {
val ret = Alsa.snd_seq_query_next_client(seq, client.handle)
return ret >= 0
}
fun queryNextPort(port: AlsaPortInfo): Boolean {
val ret = Alsa.snd_seq_query_next_port(seq, port.handle)
return ret >= 0
}
var clientInfo: AlsaClientInfo
get() {
val info = AlsaClientInfo()
val ret = Alsa.snd_seq_get_client_info(seq, info.handle)
if (ret != 0)
throw AlsaException(ret)
return info
}
set(value) {
val ret = Alsa.snd_seq_set_client_info(seq, value.handle)
if (ret != 0)
throw AlsaException(ret)
}
@Deprecated("Use getAnyClient()", ReplaceWith("getAnyClient(client)"))
fun getClient(client: Int): AlsaClientInfo = getAnyClient(client)
fun getAnyClient(client: Int): AlsaClientInfo {
val info = AlsaClientInfo()
val ret = Alsa.snd_seq_get_any_client_info(seq, client, info.handle)
if (ret != 0)
throw AlsaException(ret)
return info
}
fun getPortInfo(port: Int): AlsaPortInfo {
val info = AlsaPortInfo()
val err = Alsa.snd_seq_get_port_info(seq, port, info.handle)
if (err != 0)
throw AlsaException(err)
return info
}
@Deprecated("Use getAnyPortInfo() instead", ReplaceWith("getAnyPortInfo(client, port)"))
fun getPort(client: Int, port: Int): AlsaPortInfo = getAnyPortInfo(client, port)
fun getAnyPortInfo(client: Int, port: Int): AlsaPortInfo {
val info = AlsaPortInfo()
val err = Alsa.snd_seq_get_any_port_info(seq, client, port, info.handle)
if (err != 0)
throw AlsaException(err)
return info
}
fun setPortInfo(port: Int, info: AlsaPortInfo) {
val err = Alsa.snd_seq_set_port_info(seq, port, info.handle)
if (err != 0)
throw AlsaException(err)
}
private var portNameHandle : BytePointer? = null
fun createSimplePort(name: String?, caps: Int, type: Int): Int {
portNameHandle?.deallocate()
portNameHandle = if (name == null) null else BytePointer(name)
return Alsa.snd_seq_create_simple_port(seq, portNameHandle, caps, type)
}
fun deleteSimplePort(port: Int) {
val ret = Alsa.snd_seq_delete_simple_port(seq, port)
if (ret != 0)
throw AlsaException(ret)
}
private var nameHandle: BytePointer? = null
fun setClientName(name: String) {
if (name == null)
throw IllegalArgumentException("name is null")
nameHandle?.deallocate()
nameHandle = BytePointer(name)
Alsa.snd_seq_set_client_name(seq, nameHandle)
}
//#region Subscription
fun subscribePort(subs: AlsaPortSubscription) {
val err = Alsa.snd_seq_subscribe_port(seq, subs.handle)
if (err != 0)
throw AlsaException(err)
}
fun unsubscribePort(sub: AlsaPortSubscription) {
Alsa.snd_seq_unsubscribe_port(seq, sub.handle)
}
fun queryPortSubscribers(query: AlsaSubscriptionQuery): Boolean {
val ret = Alsa.snd_seq_query_port_subscribers(seq, query.handle)
return ret == 0
}
// simplified SubscribePort()
// formerly connectFrom()
fun connectSource(portToReceive: Int, sourceClient: Int, sourcePort: Int) {
val err = Alsa.snd_seq_connect_from(seq, portToReceive, sourceClient, sourcePort)
if (err != 0)
throw AlsaException(err)
}
// simplified SubscribePort()
// formerly connectTo()
fun connectDestination(portToSendFrom: Int, destinationClient: Int, destinationPort: Int) {
val err = Alsa.snd_seq_connect_to(seq, portToSendFrom, destinationClient, destinationPort)
if (err != 0)
throw AlsaException (err)
}
// simplified UnsubscribePort()
// formerly disconnectFrom()
fun disconnectSource(portToReceive: Int, sourceClient: Int, sourcePort: Int) {
val err = Alsa.snd_seq_disconnect_from(seq, portToReceive, sourceClient, sourcePort)
if (err != 0)
throw AlsaException(err)
}
// simplified UnsubscribePort()
// formerly disconnectTo
fun disconnectDestination(portToSendFrom: Int, destinationClient: Int, destinationPort: Int) {
val err = Alsa.snd_seq_disconnect_to(seq, portToSendFrom, destinationClient, destinationPort)
if (err != 0)
throw AlsaException(err)
}
//#endregion // Subscription
fun resetPoolInput() {
Alsa.snd_seq_reset_pool_input(seq)
}
fun resetPoolOutput() {
Alsa.snd_seq_reset_pool_output(seq)
}
//#region Events
private val midiEventBufferSize : Long = 256
private var eventBufferOutput = BytePointer(midiEventBufferSize)
private var midiEventParserOutput: snd_midi_event_t? = null
// FIXME: should this be moved to AlsaMidiApi? It's a bit too high level.
fun send(port: Int, data: ByteArray, index: Int, count: Int) {
val midiProtocol = clientInfo.midiVersion
if (midiProtocol == MidiTransportProtocol.UMP)
sendUmp(port, data, index, count)
else
sendMidi1(port, data, index, count)
}
private fun sendMidi1(port: Int, data: ByteArray, index: Int, count: Int) {
if (midiEventParserOutput == null) {
val ptr = snd_midi_event_t()
val ret = Alsa.snd_midi_event_new(midiEventBufferSize, ptr)
if (ret < 0)
throw AlsaException(ret.toInt())
midiEventParserOutput = ptr
}
val buffer = ByteBuffer.wrap(data)
val pointer = BytePointer(buffer)
val ev = snd_seq_event_t(eventBufferOutput)
var i = index
while (i < index + count) {
val ret = Alsa.snd_midi_event_encode(
midiEventParserOutput, pointer.position(i.toLong()), index + count - i.toLong(), ev)
if (ret < 0)
throw AlsaException(ret.toInt())
if (ret > 0) {
eventBufferOutput.put(seq_evt_off_source_port, port.toByte())
eventBufferOutput.put(seq_evt_off_dest_client, AddressSubscribers.toByte())
eventBufferOutput.put(seq_evt_off_dest_port, AddressUnknown.toByte())
eventBufferOutput.put(seq_evt_off_queue, QueueDirect.toByte())
// FIXME: should we provide error handler and catch it?
val ret = Alsa.snd_seq_event_output_direct(seq, ev)
if (ret < 0)
throw AlsaException(ret)
}
i += ret.toInt()
}
}
private fun sendUmp(port: Int, data: ByteArray, index: Int, count: Int) {
if (midiEventParserOutput == null) {
val ptr = snd_midi_event_t()
Alsa.snd_midi_event_new(midiEventBufferSize, ptr)
midiEventParserOutput = ptr
}
val ev = snd_seq_ump_event_t()
val source = snd_seq_addr_t()
source.client(clientInfo.client.toByte())
source.port(port.toByte())
ev.source(source)
val dest = snd_seq_addr_t()
dest.client(AddressSubscribers.toByte())
dest.port(AddressUnknown.toByte())
ev.queue(QueueDirect.toByte())
ev.type(Alsa.SND_SEQ_EVENT_NONE.toByte())
Ump.fromBytes(data, index, count).forEach { ump ->
val size = ump.sizeInInts
ev.ump(0, ump.int1)
if (size > 1)
ev.ump(1, ump.int2)
if (size > 2)
ev.ump(2, ump.int3)
if (size > 3)
ev.ump(3, ump.int4)
// FIXME: should we provide error handler and catch it?
Alsa.snd_seq_ump_event_output_direct(seq, ev)
}
}
private val defaultInputTimeout = -1
fun startListening(
applicationPort: Int,
buffer: ByteArray,
onReceived: (ByteArray, Int, Int) -> Unit,
timeout: Int = defaultInputTimeout
) = SequencerLoopContext(this, midiEventBufferSize).apply { startListening(applicationPort, buffer, onReceived, timeout) }
fun stopListening(loop: SequencerLoopContext) { loop.stopListening() }
class SequencerLoopContext(private val sequencer: AlsaSequencer, private val midiEventBufferSize: Long) {
private val seq: snd_seq_t = sequencer.sequencerHandle!!
private var eventLoopStopped = false
private lateinit var eventLoopBuffer: ByteArray
private var inputTimeout: Int = 0
private var eventLoopTask: Job? = null
private lateinit var onReceived: (ByteArray, Int, Int) -> Unit
fun startListening(
applicationPort: Int,
buffer: ByteArray,
onReceived: (ByteArray, Int, Int) -> Unit,
timeout: Int
) {
eventLoopBuffer = buffer
inputTimeout = timeout
this.onReceived = onReceived
eventLoopTask = GlobalScope.launch { eventLoop(applicationPort) }
}
fun stopListening() {
eventLoopStopped = true
}
private fun eventLoop(port: Int) {
val pollfdSizeDummy = 8
val count = Alsa.snd_seq_poll_descriptors_count(seq, POLLIN.toShort())
val pollfdArrayRef = BytePointer((count * pollfdSizeDummy).toLong())
val fd = pollfd()
fd.put<BytePointer>(pollfdArrayRef)
val ret = Alsa.snd_seq_poll_descriptors(seq, fd, count, POLLIN.toShort())
if (ret < 0)
throw AlsaException(ret)
val midiProtocol = sequencer.clientInfo.midiVersion
while (!eventLoopStopped) {
val rt = HackyPoll.poll(fd, count.toLong(), inputTimeout)
if (rt > 0) {
if (midiProtocol == 2) {
val len = receiveUmp(port, eventLoopBuffer, 0, eventLoopBuffer.size)
onReceived(eventLoopBuffer, 0, len)
} else {
val len = receiveMidi1(port, eventLoopBuffer, 0, eventLoopBuffer.size)
onReceived(eventLoopBuffer, 0, len)
}
}
}
}
private var midiEventParserInput: snd_midi_event_t? = null
private fun receiveMidi1(port: Int, data: ByteArray, index: Int, count: Int): Int {
var received = 0
if (midiEventParserInput == null) {
val ptr = snd_midi_event_t()
Alsa.snd_midi_event_new(midiEventBufferSize, ptr)
midiEventParserInput = ptr
}
var remaining = true
while (remaining && index + received < count) {
val sevt = snd_seq_event_t()
val ret = Alsa.snd_seq_event_input(seq, sevt)
remaining = Alsa.snd_seq_event_input_pending(seq, 0) > 0
if (ret < 0)
throw AlsaException(ret)
val converted = Alsa.snd_midi_event_decode(
midiEventParserInput,
ByteBuffer.wrap(data, index + received, data.size - index - received),
(count - received).toLong(),
sevt
)
if (converted > 0)
received += converted.toInt()
}
return received
}
private fun receiveUmp(port: Int, data: ByteArray, index: Int, count: Int): Int {
var received = 0
val numEvents = Alsa.snd_seq_event_input_pending(seq, 1)
var eventsProcessed = 0
while (index + received < count) {
val sevt = snd_seq_ump_event_t()
val ret = Alsa.snd_seq_ump_event_input(seq, sevt)
if (ret < 0)
throw AlsaException(ret)
val size = umpSizeInInts(sevt.ump(0))
val bytes = sevt.ump().asByteBuffer()
bytes.get(data, index + received, size * 4)
received += size * 4
if (++eventsProcessed == numEvents)
break
}
return received
}
}
//#endregion
companion object {
const val ClientSystem = 0
const val POLLIN = 1
private val seq_evt_size: Int
private val seq_evt_off_source_port: Long
private val seq_evt_off_dest_client: Long
private val seq_evt_off_dest_port: Long
private val seq_evt_off_queue: Long
const val AddressUnknown = 253
const val AddressSubscribers = 254
const val AddressBroadcast = 255
const val QueueDirect = 253
init {
Loader.load(snd_seq_t::class.java) // FIXME: this should not be required...
seq_evt_size = sizeof(snd_seq_event_t::class.java)
seq_evt_off_source_port =
snd_seq_event_t.offsetof(snd_seq_event_t::class.java, "source") +
snd_seq_event_t.offsetof(snd_seq_addr_t::class.java, "port").toLong()
seq_evt_off_dest_client =
snd_seq_event_t.offsetof(snd_seq_event_t::class.java, "dest") +
snd_seq_event_t.offsetof(snd_seq_addr_t::class.java, "client").toLong()
seq_evt_off_dest_port =
snd_seq_event_t.offsetof(snd_seq_event_t::class.java, "dest") +
snd_seq_event_t.offsetof(snd_seq_addr_t::class.java, "port").toLong()
seq_evt_off_queue = snd_seq_event_t.offsetof(snd_seq_event_t::class.java, "queue").toLong()
}
}
init {
val ptr = snd_seq_t()
val err = Alsa.snd_seq_open(ptr, driverName, ioType, ioMode)
if (err != 0)
throw AlsaException(err)
seq = ptr
}
}
| 9 | null | 6 | 69 | 48792a4826cea47edbec7eabcd62d5a489dd374e | 16,026 | ktmidi | MIT License |
product/src/main/java/com/jiaqiao/product/ext/StringExt.kt | wjiaqiao | 681,493,695 | false | {"Kotlin": 399702} | package com.jiaqiao.product.ext
fun String.toIntDef(def: Int = 0): Int {
return this.toIntOrNull() ?: def
}
fun String.toFloatDef(def: Float = 0f): Float {
return this.toFloatOrNull() ?: def
}
fun String.toDoubleDef(def: Double = 0.0): Double {
return this.toDoubleOrNull() ?: def
}
fun String.toShortDef(def: Short = 0): Short {
return this.toShortOrNull() ?: def
}
| 0 | Kotlin | 0 | 0 | 9fb0847eabc38766ce27bcc80c40c9c3ef6f0d79 | 387 | product-kotlin | Apache License 2.0 |
app/src/main/java/bruhcollective/itaysonlab/jetispot/ui/AppNavigation.kt | iTaysonLab | 482,292,329 | false | {"Kotlin": 442702, "Java": 87616} | package bruhcollective.itaysonlab.jetispot.ui
import android.content.Intent
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Warning
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import androidx.navigation.compose.dialog
import androidx.navigation.navDeepLink
import bruhcollective.itaysonlab.jetispot.R
import bruhcollective.itaysonlab.jetispot.core.SpAuthManager
import bruhcollective.itaysonlab.jetispot.core.SpSessionManager
import bruhcollective.itaysonlab.jetispot.core.api.SpInternalApi
import bruhcollective.itaysonlab.jetispot.ui.bottomsheets.jump_to_artist.JumpToArtistBottomSheet
import bruhcollective.itaysonlab.jetispot.ui.screens.BottomSheet
import bruhcollective.itaysonlab.jetispot.ui.screens.Dialog
import bruhcollective.itaysonlab.jetispot.ui.screens.Screen
import bruhcollective.itaysonlab.jetispot.ui.screens.auth.AuthScreen
import bruhcollective.itaysonlab.jetispot.ui.screens.config.ConfigScreen
import bruhcollective.itaysonlab.jetispot.ui.screens.config.NormalizationConfigScreen
import bruhcollective.itaysonlab.jetispot.ui.screens.config.QualityConfigScreen
import bruhcollective.itaysonlab.jetispot.ui.screens.config.StorageScreen
import bruhcollective.itaysonlab.jetispot.ui.screens.dac.DacRendererScreen
import bruhcollective.itaysonlab.jetispot.ui.screens.dynamic.DynamicSpIdScreen
import bruhcollective.itaysonlab.jetispot.ui.screens.search.SearchScreen
import bruhcollective.itaysonlab.jetispot.ui.screens.yourlibrary2.YourLibraryContainerScreen
import com.google.accompanist.navigation.material.ExperimentalMaterialNavigationApi
import com.google.accompanist.navigation.material.bottomSheet
import soup.compose.material.motion.animation.materialSharedAxisXIn
import soup.compose.material.motion.animation.materialSharedAxisXOut
import soup.compose.material.motion.animation.rememberSlideDistance
import soup.compose.material.motion.navigation.MaterialMotionNavHost
import soup.compose.material.motion.navigation.composable
@OptIn(ExperimentalMaterialNavigationApi::class, ExperimentalAnimationApi::class)
@Composable
fun AppNavigation(
navController: NavHostController,
sessionManager: SpSessionManager,
authManager: SpAuthManager,
modifier: Modifier
) {
val slideDistance = rememberSlideDistance()
LaunchedEffect(Unit) {
if (sessionManager.isSignedIn()) return@LaunchedEffect
authManager.authStored()
navController.navigate(if (sessionManager.isSignedIn()) Screen.Feed.route else Screen.Authorization.route) {
popUpTo(Screen.NavGraph.route)
}
}
MaterialMotionNavHost(
navController = navController,
startDestination = Screen.CoreLoading.route,
route = Screen.NavGraph.route,
modifier = modifier,
enterTransition = {
materialSharedAxisXIn(forward = true, slideDistance)
}, exitTransition = {
materialSharedAxisXOut(forward = true, slideDistance)
}, popEnterTransition = {
materialSharedAxisXIn(forward = false, slideDistance)
}, popExitTransition = {
materialSharedAxisXOut(forward = false, slideDistance)
}
) {
composable(Screen.CoreLoading.route) {
Box(Modifier.fillMaxSize()) {
CircularProgressIndicator(modifier = Modifier
.align(Alignment.Center)
.size(56.dp))
}
}
composable(Screen.Authorization.route) {
AuthScreen()
}
composable(Screen.Feed.route) {
DacRendererScreen("", true, {
getDacHome(SpInternalApi.buildDacRequestForHome(it))
})
}
composable(Screen.SpotifyIdRedirect.route, deepLinks = listOf(navDeepLink {
uriPattern = Screen.deeplinkCapable[Screen.SpotifyIdRedirect]
action = Intent.ACTION_VIEW
})) {
val fullUrl = it.arguments?.getString("uri")
val dpLinkType = it.arguments?.getString("type")
val dpLinkTypeId = it.arguments?.getString("typeId")
val uri = fullUrl ?: "$dpLinkType:$dpLinkTypeId"
DynamicSpIdScreen(uri, "spotify:$uri")
}
composable(Screen.DacViewCurrentPlan.route) {
DacRendererScreen(stringResource(id = Screen.DacViewCurrentPlan.title), false, {
getPlanOverview()
})
}
composable(Screen.DacViewAllPlans.route) {
DacRendererScreen(stringResource(id = Screen.DacViewAllPlans.title), false, {
getAllPlans()
})
}
composable(Screen.Config.route) { ConfigScreen() }
composable(Screen.StorageConfig.route) { StorageScreen() }
composable(Screen.QualityConfig.route) { QualityConfigScreen() }
composable(Screen.NormalizationConfig.route) { NormalizationConfigScreen() }
composable(Screen.Search.route) { SearchScreen() }
composable(Screen.Library.route) { YourLibraryContainerScreen() }
dialog(Dialog.AuthDisclaimer.route) {
AlertDialog(onDismissRequest = { navController.popBackStack() }, icon = {
Icon(Icons.Rounded.Warning, null)
}, title = {
Text(stringResource(id = R.string.auth_disclaimer))
}, text = {
Text(stringResource(id = R.string.auth_disclaimer_text))
}, confirmButton = {
TextButton(onClick = { navController.popBackStack() }) {
Text(stringResource(id = R.string.logout_confirm))
}
})
}
dialog(Dialog.Logout.route) {
AlertDialog(onDismissRequest = { navController.popBackStack() }, icon = {
Icon(Icons.Rounded.Warning, null)
}, title = {
Text(stringResource(id = R.string.logout_title))
}, text = {
Text(stringResource(id = R.string.logout_message))
}, confirmButton = {
TextButton(onClick = {
navController.popBackStack()
authManager.reset()
android.os.Process.killProcess(android.os.Process.myPid()) // TODO: maybe dynamic restart the session instances?
}) {
Text(stringResource(id = R.string.logout_confirm))
}
}, dismissButton = {
TextButton(onClick = { navController.popBackStack() }) {
Text(stringResource(id = R.string.logout_cancel))
}
})
}
bottomSheet(BottomSheet.JumpToArtist.route) { entry ->
val data = remember { entry.arguments!!.getString("artistIdsAndRoles")!! }
JumpToArtistBottomSheet(data = data)
}
}
} | 15 | Kotlin | 18 | 344 | 6173bfa7872ae89664fdac9e42cf36538fe71166 | 6,964 | jetispot | Apache License 2.0 |
nebulosa-indi-client/src/main/kotlin/nebulosa/indi/client/device/INDIDevice.kt | tiagohm | 568,578,345 | false | {"Kotlin": 2262424, "TypeScript": 377437, "HTML": 198335, "SCSS": 10342, "Python": 2817, "JavaScript": 1165} | package nebulosa.indi.client.device
import nebulosa.indi.client.INDIClient
import nebulosa.indi.client.device.cameras.INDICamera
import nebulosa.indi.device.*
import nebulosa.indi.device.camera.Camera
import nebulosa.indi.device.filterwheel.FilterWheel
import nebulosa.indi.device.focuser.Focuser
import nebulosa.indi.device.mount.Mount
import nebulosa.indi.device.rotator.Rotator
import nebulosa.indi.protocol.*
import nebulosa.indi.protocol.Vector
import nebulosa.log.loggerFor
import java.util.*
internal abstract class INDIDevice : Device {
abstract override val sender: INDIClient
override val properties = linkedMapOf<String, PropertyVector<*, *>>()
override val messages = LinkedList<String>()
override val id = UUID.randomUUID().toString()
@Volatile override var connected = false
protected set
private fun addMessageAndFireEvent(text: String) {
synchronized(messages) {
messages.addFirst(text)
sender.fireOnEventReceived(DeviceMessageReceived(this, text))
if (messages.size > 100) {
messages.removeLast()
}
}
}
override fun handleMessage(message: INDIProtocol) {
when (message) {
is SwitchVector<*> -> {
when (message.name) {
"CONNECTION" -> {
val connected = message["CONNECT"]?.value ?: false
if (connected != this.connected) {
if (connected) {
this.connected = true
sender.fireOnEventReceived(DeviceConnected(this))
ask()
} else if (this.connected) {
this.connected = false
sender.fireOnEventReceived(DeviceDisconnected(this))
}
} else if (!connected && message.state == PropertyState.ALERT) {
sender.fireOnEventReceived(DeviceConnectionFailed(this))
}
}
}
}
is DelProperty -> {
val property = properties.remove(message.name) ?: return
sender.fireOnEventReceived(DevicePropertyDeleted(property))
}
is Message -> {
addMessageAndFireEvent("[%s]: %s".format(message.timestamp, message.message))
}
else -> Unit
}
if (message is Vector<*>) {
handleVectorMessage(message)
}
}
private fun handleVectorMessage(message: Vector<*>) {
when (message) {
is DefVector<*> -> {
val property = when (message) {
is DefLightVector -> return
is DefNumberVector -> {
val properties = LinkedHashMap<String, NumberProperty>()
for (e in message) {
val property = NumberProperty(e.name, e.label, e.value)
properties[property.name] = property
}
NumberPropertyVector(
this,
message.name, message.label, message.group,
message.perm, message.state,
properties,
)
}
is DefSwitchVector -> {
val properties = LinkedHashMap<String, SwitchProperty>()
for (e in message) {
val property = SwitchProperty(e.name, e.label, e.value)
properties[property.name] = property
}
SwitchPropertyVector(
this,
message.name, message.label, message.group,
message.perm, message.rule, message.state,
properties,
)
}
is DefTextVector -> {
val properties = LinkedHashMap<String, TextProperty>()
for (e in message) {
val property = TextProperty(e.name, e.label, e.value)
properties[property.name] = property
}
TextPropertyVector(
this,
message.name, message.label, message.group,
message.perm, message.state,
properties,
)
}
else -> return
}
properties[property.name] = property
sender.fireOnEventReceived(DevicePropertyChanged(property))
}
is SetVector<*> -> {
val property = when (message) {
is SetLightVector -> return
is SetNumberVector -> {
val vector = properties[message.name] as? NumberPropertyVector ?: return
vector.state = message.state
for (e in message) {
val property = vector[e.name] ?: continue
property.value = e.value
}
vector
}
is SetSwitchVector -> {
val vector = properties[message.name] as? SwitchPropertyVector ?: return
vector.state = message.state
for (e in message) {
val property = vector[e.name] ?: continue
property.value = e.value
}
vector
}
is SetTextVector -> {
val vector = properties[message.name] as? TextPropertyVector ?: return
vector.state = message.state
for (e in message) {
val property = vector[e.name] ?: continue
property.value = e.value
}
vector
}
else -> return
}
sender.fireOnEventReceived(DevicePropertyChanged(property))
}
else -> return
}
}
override fun snoop(devices: Iterable<Device?>) {
val ccd = devices.firstOrNull { it is Camera }?.name ?: ""
val telescope = devices.firstOrNull { it is Mount }?.name ?: ""
val focuser = devices.firstOrNull { it is Focuser }?.name ?: ""
val filter = devices.firstOrNull { it is FilterWheel }?.name ?: ""
val rotator = devices.firstOrNull { it is Rotator }?.name ?: ""
LOG.info(
"$name is snooping devices. ccd={}, telescope={}, focuser={}, filter={}, rotator={}",
ccd, telescope, focuser, filter, rotator
)
if (this is Camera) {
sendNewText(
"ACTIVE_DEVICES",
"ACTIVE_TELESCOPE" to telescope, "ACTIVE_ROTATOR" to rotator,
"ACTIVE_FOCUSER" to focuser, "ACTIVE_FILTER" to filter,
)
}
}
override fun connect() {
if (!connected) {
sendNewSwitch("CONNECTION", "CONNECT" to true)
}
}
override fun disconnect() {
sendNewSwitch("CONNECTION", "DISCONNECT" to true)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is INDICamera) return false
if (sender != other.sender) return false
if (name != other.name) return false
return true
}
override fun hashCode(): Int {
var result = sender.hashCode()
result = 31 * result + name.hashCode()
return result
}
companion object {
@JvmStatic private val LOG = loggerFor<INDIDevice>()
}
}
| 4 | Kotlin | 1 | 2 | 64201aa97326943b36f470c06a9ac4b5b57f0a14 | 8,222 | nebulosa | MIT License |
app/src/main/java/com/nqmgaming/furniture/util/TwiceBackHandler.kt | nqmgaming | 803,271,824 | false | {"Kotlin": 242867} | package com.nqmgaming.furniture.util
import androidx.activity.OnBackPressedCallback
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.lifecycle.compose.LocalLifecycleOwner
import kotlinx.coroutines.delay
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
@Composable
fun TwiceBackHandler(
enabled: Boolean = true,
duration: Duration = 2.seconds,
onFirstBack: () -> Unit,
onBack: () -> Unit
) {
val currentOnBack by rememberUpdatedState(onBack)
val currentOnFirstBack by rememberUpdatedState(onFirstBack)
var exit by remember { mutableStateOf(false) }
LaunchedEffect(key1 = exit) {
if (exit) {
delay(duration.inWholeMilliseconds)
exit = false
}
}
val backCallback = remember {
object : OnBackPressedCallback(enabled) {
override fun handleOnBackPressed() {
if (exit) {
currentOnBack()
} else {
exit = true
currentOnFirstBack()
}
}
}
}
SideEffect {
backCallback.isEnabled = enabled
}
val backDispatcher = checkNotNull(LocalOnBackPressedDispatcherOwner.current) {
"No OnBackPressedDispatcherOwner was provided via LocalOnBackPressedDispatcherOwner"
}.onBackPressedDispatcher
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner, backDispatcher) {
backDispatcher.addCallback(lifecycleOwner, backCallback)
onDispose {
backCallback.remove()
}
}
} | 0 | Kotlin | 0 | 1 | 360930eccee2b2539dc688e38c7acd0ed1739a6a | 2,042 | furniture-shopping-asm | MIT License |
src/nl/hannahsten/texifyidea/psi/LatexParameterTextUtil.kt | Hannah-Sten | 62,398,769 | false | null | package nl.hannahsten.texifyidea.psi
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import nl.hannahsten.texifyidea.lang.commands.LatexGlossariesCommand
import nl.hannahsten.texifyidea.reference.BibtexIdReference
import nl.hannahsten.texifyidea.reference.LatexEnvironmentReference
import nl.hannahsten.texifyidea.reference.LatexGlossaryReference
import nl.hannahsten.texifyidea.reference.LatexLabelParameterReference
import nl.hannahsten.texifyidea.util.firstParentOfType
import nl.hannahsten.texifyidea.util.isFigureLabel
import nl.hannahsten.texifyidea.util.labels.extractLabelName
import nl.hannahsten.texifyidea.util.labels.getLabelDefinitionCommands
import nl.hannahsten.texifyidea.util.labels.getLabelReferenceCommands
import nl.hannahsten.texifyidea.util.magic.CommandMagic
import nl.hannahsten.texifyidea.util.magic.EnvironmentMagic
import nl.hannahsten.texifyidea.util.parentOfType
import nl.hannahsten.texifyidea.util.remove
/**
* If the normal text is the parameter of a \ref-like command, get the references to the label declaration.
*/
@Suppress("RemoveExplicitTypeArguments") // Somehow they are needed
fun getReferences(element: LatexParameterText): Array<PsiReference> {
// If the command is a label reference
// NOTE When adding options here, also update getNameIdentifier below
return when {
element.project.getLabelReferenceCommands().contains(element.firstParentOfType(LatexCommands::class)?.name) -> {
arrayOf<PsiReference>(LatexLabelParameterReference(element))
}
// If the command is a bibliography reference
CommandMagic.bibliographyReference.contains(element.firstParentOfType(LatexCommands::class)?.name) -> {
arrayOf<PsiReference>(BibtexIdReference(element))
}
// If the command is an \end command (references to \begin)
element.firstParentOfType(LatexEndCommand::class) != null -> {
arrayOf<PsiReference>(LatexEnvironmentReference(element))
}
// If the command is a glossary reference
CommandMagic.glossaryReference.contains(element.firstParentOfType(LatexCommands::class)?.name) -> {
arrayOf<PsiReference>(LatexGlossaryReference(element))
}
else -> {
emptyArray<PsiReference>()
}
}
}
/**
* If [getReferences] returns one reference return that one, null otherwise.
*/
fun getReference(element: LatexParameterText): PsiReference? {
val references = getReferences(element)
return if (references.size != 1) {
null
}
else {
references[0]
}
}
fun getNameIdentifier(element: LatexParameterText): PsiElement? {
// Because we do not want to trigger the NonAsciiCharactersInspection when the LatexParameterText is not an identifier
// (think non-ASCII characters in a \section command), we return null here when the element is not an identifier
// It is important not to return null for any identifier, otherwise exceptions like "Throwable: null byMemberInplaceRenamer" may occur
val name = element.firstParentOfType(LatexCommands::class)?.name
val environmentName = element.firstParentOfType(LatexEnvironment::class)?.environmentName
if (!CommandMagic.labelReferenceWithoutCustomCommands.contains(name) &&
!CommandMagic.labelDefinitionsWithoutCustomCommands.contains(name) &&
!CommandMagic.bibliographyReference.contains(name) &&
!CommandMagic.labelAsParameter.contains(name) &&
!CommandMagic.glossaryEntry.contains(name) &&
!EnvironmentMagic.labelAsParameter.contains(environmentName) &&
element.firstParentOfType(LatexEndCommand::class) == null &&
element.firstParentOfType(LatexBeginCommand::class) == null
) {
return null
}
return element
}
fun setName(element: LatexParameterText, name: String): PsiElement {
/**
* Build a new PSI element where [old] is replaced with [new] and replace the old PSI element
*/
fun replaceInCommand(command: LatexCommands?, old: String, new: String) {
// This could go wrong in so many cases
val labelText = command?.text?.replaceFirst(old, new) ?: "${command?.name}{$new}"
val newElement = LatexPsiHelper(element.project).createFromText(labelText).firstChild
val oldNode = command?.node
val newNode = newElement.node
if (oldNode == null) {
command?.parent?.node?.addChild(newNode)
}
else {
command.parent.node.replaceChild(oldNode, newNode)
}
}
val command = element.firstParentOfType(LatexCommands::class)
val environment = element.firstParentOfType(LatexEnvironment::class)
// If we want to rename a label
if (CommandMagic.reference.contains(command?.name) || element.project.getLabelDefinitionCommands()
.contains(command?.name)
) {
// Get a new psi element for the complete label command (\label included),
// because if we replace the complete command instead of just the normal text
// then the indices will be updated, which is necessary for the reference resolve to work
val oldLabel = element.extractLabelName()
replaceInCommand(command, oldLabel, name)
}
else if (CommandMagic.labelAsParameter.contains(command?.name) || EnvironmentMagic.labelAsParameter.contains(
environment?.environmentName
)
) {
val helper = LatexPsiHelper(element.project)
// If the label name is inside a group, keep the group
val value = if (element.parentOfType(LatexParameterGroupText::class) != null) {
"{$name}"
}
else {
name
}
helper.setOptionalParameter(command ?: environment!!.beginCommand, "label", value)
}
else if (CommandMagic.glossaryReference.contains(command?.name) || CommandMagic.glossaryEntry.contains(command?.name)) {
// This assumes that glossary entry commands (e.g. \newglossaryentry) as well as glossary references (e.g. \gls)
// have the glossary label as their first required parameter. This is true for all currently supported glossary
// commands, but might change in the future.
if (command != null) {
val glossaryLabel = LatexGlossariesCommand.extractGlossaryLabel(command) ?: ""
replaceInCommand(command, glossaryLabel, name)
}
}
else if (element.firstParentOfType(LatexEndCommand::class) != null || element.firstParentOfType(LatexBeginCommand::class) != null) {
// We are renaming an environment, text in \begin or \end
val newElement = LatexPsiHelper(element.project).createFromText(name).firstChild
val oldNode = element.node
val newNode = newElement.node
if (oldNode == null) {
element.parent.node.addChild(newNode)
}
else {
element.parent.node.replaceChild(oldNode, newNode)
}
}
// Else, element is not renamable
return element
}
fun getName(element: LatexParameterText): String {
return element.text ?: ""
}
val LatexParameterText.command: PsiElement?
get() {
return this.firstParentOfType(LatexCommands::class)?.firstChild
}
fun delete(element: LatexParameterText) {
val cmd = element.parentOfType(LatexCommands::class) ?: return
if (cmd.isFigureLabel()) {
// Look for the NoMathContent that is around the environment, because that is the PsiElement that has the
// whitespace and other normal text as siblings.
cmd.parentOfType(LatexEnvironment::class)
?.parentOfType(LatexNoMathContent::class)
?.remove()
}
}
| 4 | null | 70 | 782 | 8db48e3ac9bbb413ff1514349ee0ce1351d94b66 | 7,709 | TeXiFy-IDEA | MIT License |
wow-core/src/main/kotlin/me/ahoo/wow/modeling/command/AggregateCommandDispatcher.kt | Ahoo-Wang | 628,167,080 | false | {"Kotlin": 1902621, "Java": 34050, "TypeScript": 31834, "HTML": 11619, "Lua": 3978, "JavaScript": 2288, "Dockerfile": 820, "SCSS": 500, "Less": 342} | /*
* Copyright [2021-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)].
* 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 me.ahoo.wow.modeling.command
import me.ahoo.wow.api.modeling.NamedAggregate
import me.ahoo.wow.command.ServerCommandExchange
import me.ahoo.wow.ioc.ServiceProvider
import me.ahoo.wow.messaging.dispatcher.AggregateMessageDispatcher
import me.ahoo.wow.messaging.dispatcher.MessageParallelism
import me.ahoo.wow.messaging.dispatcher.MessageParallelism.toGroupKey
import me.ahoo.wow.modeling.matedata.AggregateMetadata
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.core.scheduler.Scheduler
/**
* Aggregate Command Dispatcher Grouped by NamedAggregate.
* ----
* One AggregateId binds one Worker(Thread).
* One Worker can be bound by multiple aggregateIds.
* Workers have aggregate ID affinity.
*
* @author ahoo wang
*/
@Suppress("LongParameterList")
class AggregateCommandDispatcher<C : Any, S : Any>(
val aggregateMetadata: AggregateMetadata<C, S>,
override val parallelism: Int = MessageParallelism.DEFAULT_PARALLELISM,
override val scheduler: Scheduler,
override val messageFlux: Flux<ServerCommandExchange<*>>,
override val name: String =
"${aggregateMetadata.aggregateName}-${AggregateCommandDispatcher::class.simpleName!!}",
private val aggregateProcessorFactory: AggregateProcessorFactory,
private val commandHandler: CommandHandler,
private val serviceProvider: ServiceProvider
) : AggregateMessageDispatcher<ServerCommandExchange<*>>() {
override val namedAggregate: NamedAggregate
get() = aggregateMetadata.namedAggregate
override fun handleExchange(exchange: ServerCommandExchange<*>): Mono<Void> {
val aggregateId = exchange.message.aggregateId
val aggregateProcessor =
aggregateProcessorFactory.create(aggregateId, aggregateMetadata)
exchange.setServiceProvider(serviceProvider)
.setAggregateProcessor(aggregateProcessor)
return commandHandler.handle(exchange)
}
override fun ServerCommandExchange<*>.toGroupKey(): Int {
return message.toGroupKey(parallelism)
}
}
| 6 | Kotlin | 8 | 98 | eed438bab2ae009edf3a1db03396de402885c681 | 2,711 | Wow | Apache License 2.0 |
src/test/kotlin/uk/gov/justice/digital/hmpps/prisonperson/controller/ReferenceDataCodeControllerIntTest.kt | ministryofjustice | 805,355,441 | false | null | package uk.gov.justice.digital.hmpps.prisonperson.controller
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import uk.gov.justice.digital.hmpps.prisonperson.integration.IntegrationTestBase
class ReferenceDataCodeControllerIntTest : IntegrationTestBase() {
@DisplayName("GET /reference-data/domains/{domain}/codes")
@Nested
inner class GetReferenceDataCodesTest {
@Nested
inner class Security {
@Test
fun `access forbidden when no authority`() {
webTestClient.get().uri("/reference-data/domains/TEST/codes")
.exchange()
.expectStatus().isUnauthorized
}
@Test
fun `access forbidden with wrong role`() {
webTestClient.get().uri("/reference-data/domains/TEST/codes")
.headers(setAuthorisation(roles = listOf("ROLE_IS_WRONG")))
.exchange()
.expectStatus().isForbidden
}
}
@Nested
inner class HappyPath {
@Test
fun `can retrieve reference data codes`() {
webTestClient.get().uri("/reference-data/domains/TEST/codes")
.headers(setAuthorisation(roles = listOf("ROLE_PRISON_PERSON_API__REFERENCE_DATA__RO")))
.exchange()
.expectStatus().isOk
.expectBody().json(
"""
[
{
"domain": "TEST",
"code": "ORANGE",
"description": "Orange",
"listSequence": 1,
"isActive": true,
"createdAt": "2024-07-11T17:00:00+0100",
"createdBy": "OMS_OWNER"
},
{
"domain": "TEST",
"code": "BROWN",
"description": "Brown",
"listSequence": 0,
"isActive": true,
"createdAt": "2024-07-11T17:00:00+0100",
"createdBy": "OMS_OWNER"
},
{
"domain": "TEST",
"code": "RED",
"description": "Red",
"listSequence": 0,
"isActive": true,
"createdAt": "2024-07-11T17:00:00+0100",
"createdBy": "OMS_OWNER"
},
{
"domain": "TEST",
"code": "WHITE",
"description": "White",
"listSequence": 0,
"isActive": true,
"createdAt": "2024-07-11T17:00:00+0100",
"createdBy": "OMS_OWNER"
}
]
""".trimIndent(),
)
}
}
}
@DisplayName("GET /reference-data/domains/{domain}/codes/{code}")
@Nested
inner class GetReferenceDataCodeTest {
@Nested
inner class Security {
@Test
fun `access forbidden when no authority`() {
webTestClient.get().uri("/reference-data/domains/TEST/codes/ORANGE")
.exchange()
.expectStatus().isUnauthorized
}
@Test
fun `access forbidden with wrong role`() {
webTestClient.get().uri("/reference-data/domains/TEST/codes/ORANGE")
.headers(setAuthorisation(roles = listOf("ROLE_IS_WRONG")))
.exchange()
.expectStatus().isForbidden
}
}
@Nested
inner class HappyPath {
@Test
fun `can retrieve reference data code`() {
webTestClient.get().uri("/reference-data/domains/TEST/codes/ORANGE")
.headers(setAuthorisation(roles = listOf("ROLE_PRISON_PERSON_API__REFERENCE_DATA__RO")))
.exchange()
.expectStatus().isOk
.expectBody().json(
"""
{
"domain": "TEST",
"code": "ORANGE",
"description": "Orange",
"listSequence": 1,
"isActive": true,
"createdAt": "2024-07-11T17:00:00+0100",
"createdBy": "OMS_OWNER"
}
""".trimIndent(),
)
}
}
@Nested
inner class NotFound {
@Test
fun `receive a 404 when no reference data code found`() {
webTestClient.get().uri("/reference-data/domains/TEST/codes/UNKNOWN")
.headers(setAuthorisation(roles = listOf("ROLE_PRISON_PERSON_API__REFERENCE_DATA__RO")))
.exchange()
.expectStatus().isNotFound
}
}
}
}
| 2 | null | 0 | 1 | b6243b3cc37f12bfb2499ce35e4ff01ab9c86bbb | 4,506 | hmpps-prison-person-api | MIT License |
shared/src/iosMain/kotlin/com/hoc081098/github_search_kmm/presentation/presentationModule.kt | hoc081098 | 512,522,703 | false | {"Kotlin": 224324, "Swift": 22749, "Ruby": 2321, "Shell": 137} | package com.hoc081098.github_search_kmm.presentation
import org.koin.core.module.dsl.factoryOf
import org.koin.dsl.module
val presentationModule = module {
factoryOf(GithubSearchViewModel::create)
}
| 38 | Kotlin | 19 | 212 | 483a514b7e539d40e283aef53db7882bfcc8b699 | 203 | GithubSearchKMM-Compose-SwiftUI | MIT License |
app/src/main/java/de/leomeyer/wifichecker/CheckJobService.kt | leomeyer | 487,288,213 | false | null | package de.leomeyer.wifichecker
import android.app.job.JobInfo
import android.app.job.JobParameters
import android.app.job.JobScheduler
import android.app.job.JobService
import android.content.ComponentName
import android.content.Context
import android.content.SharedPreferences
import android.util.Log
class CheckJobService : JobService() {
companion object {
const val JOB_ID: Int = 0x20000
var runCounter: Int = 0
fun checkPeriodicJob(context: Context, sharedPref: SharedPreferences) {
// periodic check enabled?
val period = sharedPref.getString(WifiCheckerService.PREF_PERIODIC_CHECK, "0")?.toInt()
if (period == null)
return
if (period > 0) {
// reschedule next job execution
val jobInfo = JobInfo.Builder(CheckJobService.JOB_ID, ComponentName(context, CheckJobService::class.java))
.setMinimumLatency(period.toLong())
.setOverrideDeadline(period.toLong() + 1000)
.build()
var jobScheduler = context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
jobScheduler.schedule(jobInfo)
Log.d("WifiCheckerService", "Periodic check job scheduled to run in $period milliseconds")
} else {
Log.d("WifiCheckerService", "Periodic check job is disabled")
}
}
}
override fun onStartJob(p0: JobParameters?): Boolean {
runCounter++
if (WifiCheckerService.instance != null) {
WifiCheckerService.instance?.checkWifi(applicationContext)
Log.d("WifiCheckerService", "Check completed")
} else {
Log.d("WifiCheckerService", "Check failed: WifiCheckerService instance was null")
}
return true
}
override fun onStopJob(p0: JobParameters?): Boolean {
// TODO("Not yet implemented")
return true
}
} | 0 | Kotlin | 0 | 0 | 134582c1a460ac1e1bb39d81ea9a4d44c70919db | 1,989 | AndroidWifiChecker | The Unlicense |
src/main/kotlin/com/xethlyx/robloxsync/bungee/RobloxData.kt | xethlyx | 403,856,537 | false | {"Kotlin": 24102, "Java": 1791} | package com.xethlyx.robloxsync.bungee
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import java.io.InputStream
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
class RobloxData(robloxData: JsonObject) {
var description: String = robloxData.get("description")!!.asString
var created: String = robloxData.get("created")!!.asString
var isBanned: Boolean = robloxData.get("isBanned")!!.asBoolean
var id: Number = robloxData.get("id")!!.asNumber
var username: String = robloxData.get("name")!!.asString
var displayName: String = robloxData.get("displayName")!!.asString
companion object {
fun from(username: String): RobloxData? {
val request = URL("https://api.roblox.com/users/get-by-username?username=$username").openConnection()
request.connect()
val jsonParser = JsonParser()
val jsonObject = jsonParser.parse(InputStreamReader(request.content as InputStream)).asJsonObject
if (jsonObject.has("success") && !jsonObject.get("success").asBoolean) {
return null
}
val id = jsonObject.get("Id").asNumber
return from(id)
}
fun from(id: Number): RobloxData? {
val request = URL("https://users.roblox.com/v1/users/$id").openConnection() as HttpURLConnection
request.connect()
if (request.responseCode != 200) return null
val jsonParser = JsonParser()
val robloxData = jsonParser.parse(InputStreamReader(request.content as InputStream)).asJsonObject
return RobloxData(robloxData)
}
}
} | 0 | Kotlin | 0 | 0 | 2383802b632d5c6fe076ac7017ae0ee6ba9113b1 | 1,694 | roblox-sync | MIT License |
src/main/kotlin/ru/hse/spb/sd/full_metal_rogue/logic/map/FileMapLoader.kt | alefedor | 173,711,727 | false | null | package ru.hse.spb.sd.full_metal_rogue.logic.map
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.lang.Exception
import java.nio.file.Files
import java.nio.file.Paths
import javax.swing.JOptionPane
/**
* Handles save/load of game map to a save file.
*/
object FileMapLoader {
private const val SAVE_NAME = "save.txt"
/**
* Loads map from the save file.
*/
fun loadMap() = try {
ObjectInputStream(FileInputStream(SAVE_NAME)).use { it.readObject() as MutableGameMap }
} catch (exception: Exception) {
showErrorDialog("Unable to load previous save.")
null
}
/**
* Deletes save file.
*/
fun deleteMap() {
Files.deleteIfExists(Paths.get(SAVE_NAME))
}
/**
* Writes map to the save file.
*/
fun saveMap(map: GameMap) = try {
ObjectOutputStream(FileOutputStream(SAVE_NAME)).use { it.writeObject(map) }
true
} catch (exception: Exception) {
showErrorDialog("Unable to save the game.")
false
}
private fun showErrorDialog(message: String) =
JOptionPane.showMessageDialog(null, message, "", JOptionPane.ERROR_MESSAGE)
}
| 0 | Kotlin | 0 | 0 | aa693d6d078083d9fedccd77a6e7c27205971335 | 1,264 | full_metal_rogue | MIT License |
reporter/src/main/kotlin/model/EvaluatedProcessedDeclaredLicense.kt | mercedes-benz | 246,283,016 | true | {"Kotlin": 1936701, "JavaScript": 310482, "HTML": 27680, "CSS": 25864, "Python": 21638, "Shell": 5460, "Dockerfile": 4679, "Ruby": 3545, "ANTLR": 1938, "Go": 328, "Rust": 280} | /*
* Copyright (C) 2017-2020 HERE Europe B.V.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package com.here.ort.reporter.model
import com.here.ort.spdx.SpdxExpression
import com.here.ort.utils.ProcessedDeclaredLicense
/**
* The evaluated form of a [ProcessedDeclaredLicense] used by the [EvaluatedModel].
*/
data class EvaluatedProcessedDeclaredLicense(
val spdxExpression: SpdxExpression?,
val mappedLicenses: List<LicenseId>,
val unmappedLicenses: List<LicenseId>
)
| 0 | null | 1 | 0 | 5babc890a34127d4ab20177d823eb31fd76f79a1 | 1,074 | oss-review-toolkit | Apache License 2.0 |
library/src/androidMain/kotlin/dev/bluefalcon/BluetoothService.kt | Reedyuk | 202,539,590 | false | {"Kotlin": 67013, "Ruby": 2028} | package dev.bluefalcon
import android.bluetooth.BluetoothGattService
import kotlinx.coroutines.flow.MutableStateFlow
actual class BluetoothService(val service: BluetoothGattService) {
actual val name: String?
get() = service.uuid.toString()
actual val characteristics: List<BluetoothCharacteristic>
get() = service.characteristics.map {
BluetoothCharacteristic(it)
}
internal actual val _characteristicsFlow = MutableStateFlow<List<BluetoothCharacteristic>>(emptyList())
} | 6 | Kotlin | 43 | 330 | 968c6a65e3fe4ad186967eafe3725b95b3476662 | 522 | blue-falcon | Apache License 2.0 |
src/main/kotlin/aoc/year2022/Day01.kt | SackCastellon | 573,157,155 | false | {"Kotlin": 62581} | package aoc.year2022
import aoc.Puzzle
/**
* [Day 1 - Advent of Code 2022](https://adventofcode.com/2022/day/1)
*/
object Day01 : Puzzle<Int, Int> {
override fun solvePartOne(input: String): Int =
input.parse().maxOf { it.lines().sumOf(String::toInt) }
override fun solvePartTwo(input: String): Int =
input.parse().map { it.lines().sumOf(String::toInt) }.sortedDescending().take(3).sum()
private fun String.parse() = split(Regex("(\\r?\\n){2}"))
}
| 0 | Kotlin | 0 | 0 | 75b0430f14d62bb99c7251a642db61f3c6874a9e | 482 | advent-of-code | Apache License 2.0 |
shared/data/episodes/implementation/src/commonMain/kotlin/com/thomaskioko/tvmaniac/episodes/implementation/EpisodeImageCacheImpl.kt | c0de-wizard | 361,393,353 | false | null | package com.thomaskioko.tvmaniac.episodes.implementation
import com.thomaskioko.tvmaniac.core.db.Episode_image
import com.thomaskioko.tvmaniac.core.db.TvManiacDatabase
import com.thomaskioko.tvmaniac.episodes.api.EpisodeImageCache
class EpisodeImageCacheImpl(
private val database: TvManiacDatabase
) : EpisodeImageCache {
private val episodeQueries get() = database.episodeImageQueries
override fun insert(entity: Episode_image) {
database.transaction {
episodeQueries.insertOrReplace(
trakt_id = entity.trakt_id,
tmdb_id = entity.tmdb_id,
image_url = entity.image_url
)
}
}
override fun insert(list: List<Episode_image>) {
list.map { insert(it) }
}
}
| 3 | Kotlin | 10 | 88 | e613080658265c2cb8bb184c88d2057fe011e58f | 779 | tv-maniac | Apache License 2.0 |
ktor-core/src/org/jetbrains/ktor/application/ApplicationLifecycle.kt | cy6erGn0m | 40,906,748 | true | {"Kotlin": 635453} | package org.jetbrains.ktor.application
/**
* Represents application lifecycle and provides access to [Application]
*/
interface ApplicationLifecycle {
/**
* Running [Application]
*/
val application : Application
/**
* Stops an application and frees any resources associated with it
*/
fun dispose()
} | 0 | Kotlin | 0 | 0 | 2d3b4f0b813b05370b22fae4c0d83d99122f604f | 340 | ktor | Apache License 2.0 |
app/src/main/java/com/example/androiddevchallenge/LoginUI.kt | allenzhangp | 347,091,303 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.paddingFromBaseline
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import androidx.navigation.compose.navigate
import com.example.androiddevchallenge.ui.theme.gridPadding
import com.example.androiddevchallenge.ui.theme.screenPadding
@Composable
fun Login(navigator: NavHostController) {
var email by remember { mutableStateOf("") }
var passWord by remember { mutableStateOf("") }
Surface(Modifier.fillMaxSize().background(color = MaterialTheme.colors.background)) {
Box {
Image(
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop,
painter = painterResource(id = R.drawable.ic_login),
contentDescription = "Login image"
)
Column(
Modifier
.fillMaxWidth()
.align(Alignment.Center),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text("LOG IN", style = MaterialTheme.typography.h1)
TextField(
modifier = Modifier
.padding(top = 32.dp, start = screenPadding, end = screenPadding)
.height(56.dp)
.fillMaxWidth(),
value = email,
placeholder = {
Text(
text = "Email address",
style = MaterialTheme.typography.body1
)
},
colors = TextFieldDefaults.textFieldColors(
backgroundColor = MaterialTheme.colors.surface,
unfocusedIndicatorColor = MaterialTheme.colors.onSurface
),
onValueChange = { email = it },
shape = RoundedCornerShape(topStart = 4.dp, topEnd = 4.dp),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email)
)
TextField(
modifier = Modifier
.padding(top = gridPadding, start = screenPadding, end = screenPadding)
.height(56.dp)
.fillMaxWidth(),
value = passWord,
placeholder = {
Text(
text = "Password",
style = MaterialTheme.typography.body1
)
},
colors = TextFieldDefaults.textFieldColors(
backgroundColor = MaterialTheme.colors.surface,
unfocusedIndicatorColor = MaterialTheme.colors.onSurface
),
shape = RoundedCornerShape(topStart = 4.dp, topEnd = 4.dp),
onValueChange = { passWord = it },
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)
)
MyButton(
modifier = Modifier.padding(top = gridPadding),
onClick = { navigator.navigate("home") }
) {
Text(text = "LOG IN")
}
// val annotatedString =
// AnnotatedString.Builder("Don't have an account? Sign up")
// .apply {
// addStyle(
// style = SpanStyle(textDecoration = TextDecoration.Underline),
// 23,
// 30
// )
// }.toAnnotatedString()
Text(
text = buildAnnotatedString {
withStyle(style = SpanStyle()) {
append("Don't have an account?")
}
withStyle(style = SpanStyle(textDecoration = TextDecoration.Underline)) {
append("Sign up")
}
},
style = MaterialTheme.typography.body1,
textAlign = TextAlign.Center,
color = MaterialTheme.colors.onBackground,
modifier = Modifier
.padding(horizontal = 16.dp)
.paddingFromBaseline(top = 32.dp, bottom = 0.dp),
)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 7f80c2482d051db24c9cb2e8f29bc8e9bce79bcd | 6,757 | ComposeChanllenge3 | Apache License 2.0 |
shared/src/commonMain/kotlin/com/kaushalvasava/apps/instagram/models/Notification.kt | KaushalVasava | 726,410,594 | false | {"Kotlin": 173109, "Swift": 342} | package com.kaushalvasava.apps.instagram.models
import kotlinx.serialization.Serializable
@Serializable
data class Notification(
val id: String,
val image: String,
val title: String,
val timeDate: Long,
val actionBy: String
)
| 0 | Kotlin | 6 | 21 | 4d42da9067004807d8a6d559201f1228f961207d | 248 | XPhotogram_KMP | The Unlicense |
app/src/androidTest/kotlin/com/github/feed/sample/flow/main/MainScreenFailureTest.kt | markspit93 | 105,769,386 | false | null | package com.github.feed.sample.flow.main
import android.support.test.filters.SmallTest
import android.support.test.runner.AndroidJUnit4
import com.github.feed.sample.BaseInstrumentationTest
import com.github.feed.sample.R
import com.github.feed.sample.data.repository.datasource.event.remote.RemoteEventDataSourceBehaviour
import com.github.feed.sample.ui.main.MainActivity
import com.github.feed.sample.util.toastIsShown
import org.junit.BeforeClass
import org.junit.Test
import org.junit.runner.RunWith
@SmallTest
@RunWith(AndroidJUnit4::class)
class MainScreenFailureTest : BaseInstrumentationTest<MainActivity>(MainActivity::class.java) {
companion object {
@JvmStatic
@BeforeClass
fun setupClass() {
RemoteEventDataSourceBehaviour.eventsConfig = RemoteEventDataSourceBehaviour.EventConfig.RATE_LIMIT_EXCEEDED
}
}
@Test
fun showLimiExceededError() {
// Arrange
// Act
// Assert
toastIsShown(testRule.activity, R.string.error_rate_limit)
}
}
| 0 | Kotlin | 0 | 0 | f37bbf8656e2e3964212fd12d4ce3864df553590 | 1,047 | Github-Feed-Sample | Apache License 2.0 |
app/src/main/java/com/javalon/roomie/Person.kt | ezechuka | 464,356,968 | false | {"Kotlin": 13735} | package com.javalon.roomie
import com.javalon.AddConverter
//@AddConverter(name = "PeopleConverter")
//data class Person(val firstName: String, val lastName: List<String>) | 0 | Kotlin | 0 | 15 | ae1bbb303353008dca310b07b17decb7cc250b06 | 173 | roomie | MIT License |
ffmpeg-recorder/src/main/java/com/github/windsekirun/naraeaudiorecorder/ffmpeg/FFmpegRecordFinder.kt | WindSekirun | 164,206,852 | false | null | package com.github.windsekirun.naraeaudiorecorder.ffmpeg
import com.github.windsekirun.naraeaudiorecorder.recorder.AudioRecorder
import com.github.windsekirun.naraeaudiorecorder.recorder.PcmAudioRecorder
import com.github.windsekirun.naraeaudiorecorder.recorder.WavAudioRecorder
import com.github.windsekirun.naraeaudiorecorder.recorder.finder.RecordFinder
import com.github.windsekirun.naraeaudiorecorder.writer.RecordWriter
import java.io.File
/**
* Default + FFmpeg settings of [RecordFinder]
*/
class FFmpegRecordFinder : RecordFinder {
/**
* see [RecordFinder.find]
*/
override fun find(extension: String, file: File, writer: RecordWriter): AudioRecorder {
return when (extension) {
"wav" -> WavAudioRecorder(file, writer)
"pcm" -> PcmAudioRecorder(file, writer)
"aac" -> FFmpegAudioRecorder(file, writer)
"mp3" -> FFmpegAudioRecorder(file, writer)
"m4a" -> FFmpegAudioRecorder(file, writer)
"wma" -> FFmpegAudioRecorder(file, writer)
"flac" -> FFmpegAudioRecorder(file, writer)
else -> PcmAudioRecorder(file, writer)
}
}
} | 9 | Kotlin | 19 | 85 | dd59377b2a41db32b4244e4d0135d0c7e82bdad6 | 1,168 | NaraeAudioRecorder | Apache License 2.0 |
daggercore/src/main/java/com/islamversity/daggercore/modules/domain/CalligraphyModule.kt | islamversity | 282,670,969 | false | null | package com.islamversity.daggercore.modules.domain
import com.islamversity.core.Mapper
import com.islamversity.db.Calligraphy
import com.islamversity.db.datasource.CalligraphyLocalDataSource
import com.islamversity.domain.repo.CalligraphyRepo
import com.islamversity.domain.repo.CalligraphyRepoImpl
import dagger.Module
import dagger.Provides
@Module
object CalligraphyModule {
@Provides
@JvmStatic
fun provideCalligraphyRepoImpl(
ds : CalligraphyLocalDataSource,
mapper: Mapper<Calligraphy, com.islamversity.domain.model.Calligraphy>
) : CalligraphyRepo =
CalligraphyRepoImpl(ds,mapper)
} | 15 | Kotlin | 7 | 21 | ab825e4951facd7779e0c3fcb0e68720d68a0fa1 | 632 | Reyan | Apache License 2.0 |
PracticeDraw3/app/src/main/java/com/hencoder/hencoderpracticedraw3/practice/Practice08SetTextSkewXView.kt | dayfan0810 | 196,541,616 | true | {"Kotlin": 176191, "Java": 61673} | package com.hencoder.hencoderpracticedraw3.practice
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
class Practice08SetTextSkewXView : View {
internal var paint = Paint(Paint.ANTI_ALIAS_FLAG)
internal var text = "Hello HenCoder"
constructor(context: Context) : super(context) {}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}
init {
paint.textSize = 60f
// 使用 Paint.setTextSkewX() 来让文字倾斜
paint.textSkewX = -0.5f
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.drawText(text, 50f, 100f, paint)
}
}
| 0 | Kotlin | 0 | 0 | 704e50900ad06d7f8571930a694f36a59e506baa | 848 | HenCoderPractice | Apache License 2.0 |
src/main/kotlin/lox/Resolver.kt | zupzup | 126,516,242 | false | null | package lox
import java.util.HashMap
import java.util.Stack
private enum class FunctionType {
NONE,
FUNCTION,
METHOD,
INITIALIZER
}
private enum class ClassType {
NONE,
CLASS,
SUBCLASS
}
internal class Resolver(private val interpreter: Interpreter) : Expr.Visitor<Unit>, Stmt.Visitor<Unit> {
private var currentClass = ClassType.NONE
private val scopes = Stack<MutableMap<String, Boolean>>()
private var currentFunction = FunctionType.NONE
override fun visitSuperExpr(expr: Expr.Super) {
if (currentClass == ClassType.NONE) {
Lox.error(expr.keyword, "Cannot use 'super' outside of a class.")
} else if (currentClass != ClassType.SUBCLASS) {
Lox.error(expr.keyword, "Cannot use 'super' in a class with no superclass.")
}
resolveLocal(expr, expr.keyword)
return
}
override fun visitThisExpr(expr: Expr.This) {
if (currentClass == ClassType.NONE) {
Lox.error(expr.keyword, "Cannot use 'this' outside of a class.")
return
}
resolveLocal(expr, expr.keyword)
return
}
override fun visitSetExpr(expr: Expr.Set) {
resolve(expr.value)
resolve(expr.obj)
return
}
override fun visitClassStmt(stmt: Stmt.Class) {
declare(stmt.name)
define(stmt.name)
val enclosingClass = currentClass
currentClass = ClassType.CLASS
if (stmt.superclass != null) {
currentClass = ClassType.SUBCLASS
beginScope()
scopes.peek()["super"] = true
resolve(stmt.superclass)
}
beginScope()
scopes.peek()["this"] = true
for (method in stmt.methods) {
var declaration = FunctionType.METHOD
if (method.name.lexeme == "init") {
declaration = FunctionType.INITIALIZER
}
resolveFunction(method, declaration)
}
endScope()
if (stmt.superclass != null) endScope()
currentClass = enclosingClass
return
}
override fun visitGetExpr(expr: Expr.Get) {
resolve(expr.obj)
return
}
override fun visitAssignExpr(expr: Expr.Assign) {
resolve(expr.value)
resolveLocal(expr, expr.name)
return
}
override fun visitBinaryExpr(expr: Expr.Binary) {
resolve(expr.left)
resolve(expr.right)
return
}
override fun visitCallExpr(expr: Expr.Call) {
resolve(expr.callee)
for (argument in expr.arguments) {
resolve(argument)
}
return
}
override fun visitGroupingExpr(expr: Expr.Grouping) {
resolve(expr.expression)
return
}
override fun visitLiteralExpr(expr: Expr.Literal) {
return
}
override fun visitLogicalExpr(expr: Expr.Logical) {
resolve(expr.left)
resolve(expr.right)
return
}
override fun visitUnaryExpr(expr: Expr.Unary) {
resolve(expr.right)
return
}
override fun visitVariableExpr(expr: Expr.Variable) {
if (!scopes.isEmpty() &&
scopes.peek()[expr.name.lexeme] == false) {
Lox.error(expr.name,
"Cannot read local variable in its own initializer.")
}
resolveLocal(expr, expr.name)
return
}
private fun resolveLocal(expr: Expr, name: Token) {
for (i in scopes.size - 1 downTo 0) {
if (scopes[i].containsKey(name.lexeme)) {
interpreter.resolve(expr, scopes.size - 1 - i)
return
}
}
// Not found. Assume it is global.
}
override fun visitBlockStmt(stmt: Stmt.Block) {
beginScope()
resolve(stmt.statements)
endScope()
return
}
fun resolve(statements: List<Stmt?>) {
for (statement in statements) {
resolve(statement)
}
}
private fun resolve(stmt: Stmt?) {
stmt!!.accept(this)
}
private fun beginScope() {
scopes.push(HashMap())
}
private fun endScope() {
scopes.pop()
}
override fun visitExpressionStmt(stmt: Stmt.Expression) {
resolve(stmt.expression)
return
}
override fun visitFunctionStmt(stmt: Stmt.Function) {
declare(stmt.name)
define(stmt.name)
resolveFunction(stmt, FunctionType.FUNCTION)
return
}
private fun resolveFunction(function: Stmt.Function, type: FunctionType) {
val enclosingFunction = currentFunction
currentFunction = type
beginScope()
for (param in function.parameters) {
declare(param)
define(param)
}
resolve(function.body)
endScope()
currentFunction = enclosingFunction
}
override fun visitIfStmt(stmt: Stmt.If) {
resolve(stmt.condition)
resolve(stmt.thenBranch)
if (stmt.elseBranch != null) resolve(stmt.elseBranch)
return
}
override fun visitPrintStmt(stmt: Stmt.Print) {
resolve(stmt.expression)
return
}
override fun visitReturnStmt(stmt: Stmt.Return) {
if (currentFunction == FunctionType.NONE) {
Lox.error(stmt.keyword, "Cannot return from top-level code.")
}
if (stmt.value != null) {
if (currentFunction == FunctionType.INITIALIZER) {
Lox.error(stmt.keyword, "Cannot return a value from an initializer.")
}
resolve(stmt.value)
}
return
}
override fun visitVarStmt(stmt: Stmt.Var) {
declare(stmt.name)
if (stmt.initializer != null) {
resolve(stmt.initializer)
}
define(stmt.name)
return
}
private fun declare(name: Token) {
if (scopes.isEmpty()) return
val scope = scopes.peek()
if (scope.containsKey(name.lexeme)) {
Lox.error(name,
"Variable with this name already declared in this scope.")
}
scope[name.lexeme] = false
}
private fun define(name: Token) {
if (scopes.isEmpty()) return
scopes.peek()[name.lexeme] = true
}
private fun resolve(expr: Expr) {
expr.accept(this)
}
override fun visitWhileStmt(stmt: Stmt.While) {
resolve(stmt.condition)
resolve(stmt.body)
return
}
} | 0 | Kotlin | 0 | 0 | 3ca5ebfef3ce5388b50351b6893c073c00e2edbb | 6,503 | crafting-interpreters-kotlin | Apache License 2.0 |
src/aws/lambdas/incremental_distribution/src/main/java/uk/nhs/nhsx/virology/persistence/TestOrder.kt | nhsx-mirror | 287,267,780 | true | {"Kotlin": 1307116, "HCL": 350528, "Ruby": 278734, "Java": 114825, "JavaScript": 8765, "Python": 8418, "Shell": 3088, "Dockerfile": 2996, "HTML": 1487, "Makefile": 542} | package uk.nhs.nhsx.virology.persistence
import uk.nhs.nhsx.virology.CtaToken
import uk.nhs.nhsx.virology.DiagnosisKeySubmissionToken
import uk.nhs.nhsx.virology.TestResultPollingToken
class TestOrder(
val ctaToken: CtaToken,
val downloadCounter: Int,
val testResultPollingToken: TestResultPollingToken,
val diagnosisKeySubmissionToken: DiagnosisKeySubmissionToken
) {
constructor(
ctaToken: CtaToken,
testResultPollingToken: TestResultPollingToken,
diagnosisKeySubmissionToken: DiagnosisKeySubmissionToken
) : this(ctaToken, 0, testResultPollingToken, diagnosisKeySubmissionToken)
}
| 0 | Kotlin | 0 | 0 | 0479f8af23e89d9e296c0d5f3e34f3a854601ea2 | 634 | covid19-app-system-public | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.