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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
compiler/testData/diagnostics/tests/script/varInScript.kts | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | // FIR_IDENTICAL
// FILE: script.kts
fun main(): Boolean {
var liteProfileReached = false
return liteProfileReached
} | 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 126 | kotlin | Apache License 2.0 |
package/android/src/main/java/com/mrousavy/camera/core/extensions/CameraInfo+id.kt | mrousavy | 340,402,576 | false | null | package com.mrousavy.camera.core.extensions
import android.annotation.SuppressLint
import androidx.camera.core.CameraInfo
import androidx.camera.core.impl.CameraInfoInternal
val CameraInfo.id: String?
@SuppressLint("RestrictedApi")
get() {
val infoInternal = this as? CameraInfoInternal
if (infoInternal != null) {
return infoInternal.cameraId
}
return null
}
| 176 | null | 1092 | 7,476 | 02ae227964ceee6fe413ee49eb944e11d6fcd722 | 390 | react-native-vision-camera | MIT License |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/dynamodb/TablePropsDsl.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 70198112} | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.dynamodb
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.Boolean
import kotlin.Number
import kotlin.String
import kotlin.Unit
import kotlin.collections.Collection
import kotlin.collections.MutableList
import software.amazon.awscdk.Duration
import software.amazon.awscdk.RemovalPolicy
import software.amazon.awscdk.services.dynamodb.Attribute
import software.amazon.awscdk.services.dynamodb.BillingMode
import software.amazon.awscdk.services.dynamodb.StreamViewType
import software.amazon.awscdk.services.dynamodb.TableClass
import software.amazon.awscdk.services.dynamodb.TableEncryption
import software.amazon.awscdk.services.dynamodb.TableProps
import software.amazon.awscdk.services.kinesis.IStream
import software.amazon.awscdk.services.kms.IKey
/**
* Properties for a DynamoDB Table.
*
* Example:
*
* ```
* import software.amazon.awscdk.services.cloudwatch.*;
* Table table = Table.Builder.create(this, "Table")
* .partitionKey(Attribute.builder().name("id").type(AttributeType.STRING).build())
* .build();
* IMetric metric = table.metricThrottledRequestsForOperations(OperationsMetricOptions.builder()
* .operations(List.of(Operation.PUT_ITEM))
* .period(Duration.minutes(1))
* .build());
* Alarm.Builder.create(this, "Alarm")
* .metric(metric)
* .evaluationPeriods(1)
* .threshold(1)
* .build();
* ```
*/
@CdkDslMarker
public class TablePropsDsl {
private val cdkBuilder: TableProps.Builder = TableProps.builder()
private val _replicationRegions: MutableList<String> = mutableListOf()
/**
* @param billingMode Specify how you are charged for read and write throughput and how you manage
* capacity.
*/
public fun billingMode(billingMode: BillingMode) {
cdkBuilder.billingMode(billingMode)
}
/**
* @param contributorInsightsEnabled Whether CloudWatch contributor insights is enabled.
*/
public fun contributorInsightsEnabled(contributorInsightsEnabled: Boolean) {
cdkBuilder.contributorInsightsEnabled(contributorInsightsEnabled)
}
/**
* @param deletionProtection Enables deletion protection for the table.
*/
public fun deletionProtection(deletionProtection: Boolean) {
cdkBuilder.deletionProtection(deletionProtection)
}
/**
* @param encryption Whether server-side encryption with an AWS managed customer master key is
* enabled.
* This property cannot be set if `serverSideEncryption` is set.
*
*
* **NOTE**: if you set this to `CUSTOMER_MANAGED` and `encryptionKey` is not
* specified, the key that the Tablet generates for you will be created with
* default permissions. If you are using CDKv2, these permissions will be
* sufficient to enable the key for use with DynamoDB tables. If you are
* using CDKv1, make sure the feature flag
* `@aws-cdk/aws-kms:defaultKeyPolicies` is set to `true` in your `cdk.json`.
*/
public fun encryption(encryption: TableEncryption) {
cdkBuilder.encryption(encryption)
}
/**
* @param encryptionKey External KMS key to use for table encryption.
* This property can only be set if `encryption` is set to `TableEncryption.CUSTOMER_MANAGED`.
*/
public fun encryptionKey(encryptionKey: IKey) {
cdkBuilder.encryptionKey(encryptionKey)
}
/**
* @param kinesisStream Kinesis Data Stream to capture item-level changes for the table.
*/
public fun kinesisStream(kinesisStream: IStream) {
cdkBuilder.kinesisStream(kinesisStream)
}
/**
* @param partitionKey Partition key attribute definition.
*/
public fun partitionKey(partitionKey: AttributeDsl.() -> Unit = {}) {
val builder = AttributeDsl()
builder.apply(partitionKey)
cdkBuilder.partitionKey(builder.build())
}
/**
* @param partitionKey Partition key attribute definition.
*/
public fun partitionKey(partitionKey: Attribute) {
cdkBuilder.partitionKey(partitionKey)
}
/**
* @param pointInTimeRecovery Whether point-in-time recovery is enabled.
*/
public fun pointInTimeRecovery(pointInTimeRecovery: Boolean) {
cdkBuilder.pointInTimeRecovery(pointInTimeRecovery)
}
/**
* @param readCapacity The read capacity for the table.
* Careful if you add Global Secondary Indexes, as
* those will share the table's provisioned throughput.
*
* Can only be provided if billingMode is Provisioned.
*/
public fun readCapacity(readCapacity: Number) {
cdkBuilder.readCapacity(readCapacity)
}
/**
* @param removalPolicy The removal policy to apply to the DynamoDB Table.
*/
public fun removalPolicy(removalPolicy: RemovalPolicy) {
cdkBuilder.removalPolicy(removalPolicy)
}
/**
* @param replicationRegions Regions where replica tables will be created.
*/
public fun replicationRegions(vararg replicationRegions: String) {
_replicationRegions.addAll(listOf(*replicationRegions))
}
/**
* @param replicationRegions Regions where replica tables will be created.
*/
public fun replicationRegions(replicationRegions: Collection<String>) {
_replicationRegions.addAll(replicationRegions)
}
/**
* @param replicationTimeout The timeout for a table replication operation in a single region.
*/
public fun replicationTimeout(replicationTimeout: Duration) {
cdkBuilder.replicationTimeout(replicationTimeout)
}
/**
* @param sortKey Sort key attribute definition.
*/
public fun sortKey(sortKey: AttributeDsl.() -> Unit = {}) {
val builder = AttributeDsl()
builder.apply(sortKey)
cdkBuilder.sortKey(builder.build())
}
/**
* @param sortKey Sort key attribute definition.
*/
public fun sortKey(sortKey: Attribute) {
cdkBuilder.sortKey(sortKey)
}
/**
* @param stream When an item in the table is modified, StreamViewType determines what information
* is written to the stream for this table.
*/
public fun stream(stream: StreamViewType) {
cdkBuilder.stream(stream)
}
/**
* @param tableClass Specify the table class.
*/
public fun tableClass(tableClass: TableClass) {
cdkBuilder.tableClass(tableClass)
}
/**
* @param tableName Enforces a particular physical table name.
*/
public fun tableName(tableName: String) {
cdkBuilder.tableName(tableName)
}
/**
* @param timeToLiveAttribute The name of TTL attribute.
*/
public fun timeToLiveAttribute(timeToLiveAttribute: String) {
cdkBuilder.timeToLiveAttribute(timeToLiveAttribute)
}
/**
* @param waitForReplicationToFinish Indicates whether CloudFormation stack waits for replication
* to finish.
* If set to false, the CloudFormation resource will mark the resource as
* created and replication will be completed asynchronously. This property is
* ignored if replicationRegions property is not set.
*
* WARNING:
* DO NOT UNSET this property if adding/removing multiple replicationRegions
* in one deployment, as CloudFormation only supports one region replication
* at a time. CDK overcomes this limitation by waiting for replication to
* finish before starting new replicationRegion.
*
* If the custom resource which handles replication has a physical resource
* ID with the format `region` instead of `tablename-region` (this would happen
* if the custom resource hasn't received an event since v1.91.0), DO NOT SET
* this property to false without making a change to the table name.
* This will cause the existing replicas to be deleted.
*/
public fun waitForReplicationToFinish(waitForReplicationToFinish: Boolean) {
cdkBuilder.waitForReplicationToFinish(waitForReplicationToFinish)
}
/**
* @param writeCapacity The write capacity for the table.
* Careful if you add Global Secondary Indexes, as
* those will share the table's provisioned throughput.
*
* Can only be provided if billingMode is Provisioned.
*/
public fun writeCapacity(writeCapacity: Number) {
cdkBuilder.writeCapacity(writeCapacity)
}
public fun build(): TableProps {
if(_replicationRegions.isNotEmpty()) cdkBuilder.replicationRegions(_replicationRegions)
return cdkBuilder.build()
}
}
| 3 | Kotlin | 0 | 3 | c59c6292cf08f0fc3280d61e7f8cff813a608a62 | 8,325 | awscdk-dsl-kotlin | Apache License 2.0 |
platform-core/src/test/kotlin/org/dashj/platform/sdk/platform/PlatformNetwork.kt | dashevo | 258,569,335 | false | null | package org.dashj.platform.sdk.platform
import java.util.Date
import org.bitcoinj.params.SchnappsDevNetParams
import org.bitcoinj.wallet.DerivationPathFactory
import org.bitcoinj.wallet.DeterministicKeyChain
import org.bitcoinj.wallet.DeterministicSeed
import org.bitcoinj.wallet.KeyChainGroup
import org.bitcoinj.wallet.Wallet
import org.junit.jupiter.api.AfterEach
open class PlatformNetwork {
val platform = Platform(SchnappsDevNetParams.get())
val assetLockTxId: String
val seed: String
val wallet: Wallet
init {
when {
platform.params.id.contains("test") -> {
assetLockTxId = "1175bf329cf6d35839f67aa57da87636a76b4837ce76b46ababa2a415be8d866"
seed = "mango air virus pigeon crowd attract review lemon lion assume lab rain"
}
platform.params.id.contains("schnapps") -> {
assetLockTxId = "1175bf329cf6d35839f67aa57da87636a76b4837ce76b46ababa2a415be8d866"
seed = "quantum alarm evoke estate siege play moon spoon later paddle rifle ancient"
}
else -> {
assetLockTxId = ""
seed = ""
}
}
wallet = Wallet(
platform.params,
KeyChainGroup.builder(platform.params)
.addChain(
DeterministicKeyChain.builder()
.accountPath(DerivationPathFactory.get(platform.params).bip44DerivationPath(0))
.seed(DeterministicSeed(seed, null, "", Date().time))
.build()
)
.build()
)
wallet.initializeAuthenticationKeyChains(wallet.keyChainSeed, null)
}
@AfterEach
fun afterEachTest() {
println(platform.client.reportNetworkStatus())
}
init {
println("initializing platform")
platform.useValidNodes()
}
}
| 1 | Kotlin | 3 | 4 | 3e5eef0e3768a0e6ca9b422b52820a9d28f14a06 | 1,929 | android-dashpay | MIT License |
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/objc/ObjCDataGenerator.kt | JetBrains | 58,957,623 | false | null | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan.llvm.objc
import llvm.*
import org.jetbrains.kotlin.backend.konan.llvm.*
import org.jetbrains.kotlin.descriptors.konan.CurrentKlibModuleOrigin
/**
* This class provides methods to generate Objective-C RTTI and other data.
* It is mostly based on `clang/lib/CodeGen/CGObjCMac.cpp`, and supports only subset of operations
* required for our purposes (thus simplified).
*
* [finishModule] must be called exactly once after all required data was generated.
*/
internal class ObjCDataGenerator(val codegen: CodeGenerator) {
val context = codegen.context
val llvm = codegen.llvm
fun finishModule() {
addModuleClassList(
definedClasses,
"OBJC_LABEL_CLASS_$",
"__DATA,__objc_classlist,regular,no_dead_strip"
)
}
private val selectorRefs = mutableMapOf<String, ConstPointer>()
private val classRefs = mutableMapOf<String, ConstPointer>()
fun genSelectorRef(selector: String): ConstPointer = selectorRefs.getOrPut(selector) {
val literal = selectors.get(selector)
val global = codegen.staticData.placeGlobal("OBJC_SELECTOR_REFERENCES_", literal)
global.setLinkage(LLVMLinkage.LLVMPrivateLinkage)
LLVMSetExternallyInitialized(global.llvmGlobal, 1)
global.setAlignment(codegen.runtime.pointerAlignment)
global.setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip")
llvm.compilerUsedGlobals += global.llvmGlobal
global.pointer
}
fun genClassRef(name: String): ConstPointer = classRefs.getOrPut(name) {
val classGlobal = getClassGlobal(name, isMetaclass = false)
val global = codegen.staticData.placeGlobal("OBJC_CLASSLIST_REFERENCES_\$_", classGlobal).also {
it.setLinkage(LLVMLinkage.LLVMPrivateLinkage)
it.setSection("__DATA,__objc_classrefs,regular,no_dead_strip")
it.setAlignment(codegen.runtime.pointerAlignment)
}
llvm.compilerUsedGlobals += global.pointer.llvm
global.pointer.bitcast(pointerType(llvm.int8PtrType))
}
private val classObjectType = codegen.runtime.objCClassObjectType
fun exportClass(name: String) {
llvm.usedGlobals += getClassGlobal(name, isMetaclass = false).llvm
llvm.usedGlobals += getClassGlobal(name, isMetaclass = true).llvm
}
private fun getClassGlobal(name: String, isMetaclass: Boolean): ConstPointer {
val prefix = if (isMetaclass) {
"OBJC_METACLASS_\$_"
} else {
"OBJC_CLASS_\$_"
}
val globalName = prefix + name
// TODO: refactor usages and use [Global] class.
val llvmGlobal = LLVMGetNamedGlobal(llvm.module, globalName) ?:
codegen.importGlobal(globalName, classObjectType, CurrentKlibModuleOrigin)
return constPointer(llvmGlobal)
}
private val emptyCache = constPointer(
codegen.importGlobal(
"_objc_empty_cache",
codegen.runtime.objCCache,
CurrentKlibModuleOrigin
)
)
fun emitEmptyClass(name: String, superName: String) {
emitClass(name, superName, instanceMethods = emptyList())
}
class Method(val selector: String, val encoding: String, val imp: ConstPointer)
fun emitClass(name: String, superName: String, instanceMethods: List<Method>) {
val runtime = llvm.runtime
val classRoType = runtime.objCClassRoType
val methodType = runtime.objCMethodType
val methodListType = runtime.objCMethodListType
val protocolListType = runtime.objCProtocolListType
val ivarListType = runtime.objCIVarListType
val propListType = runtime.objCPropListType
val classNameLiteral = classNames.get(name)
fun emitInstanceMethodList(): ConstPointer {
if (instanceMethods.isEmpty()) return NullPointer(methodListType)
val methodStructs = instanceMethods.map {
Struct(methodType, selectors.get(it.selector), encodings.get(it.encoding), it.imp.bitcast(llvm.int8PtrType))
}
val methodList = llvm.struct(
llvm.constInt32(LLVMABISizeOfType(codegen.llvmTargetData, methodType).toInt()),
llvm.constInt32(instanceMethods.size),
ConstArray(methodType, methodStructs)
)
val globalName = "\u0001l_OBJC_\$_INSTANCE_METHODS_$name"
val global = llvm.staticData.placeGlobal(globalName, methodList).also {
it.setLinkage(LLVMLinkage.LLVMPrivateLinkage)
it.setAlignment(runtime.pointerAlignment)
it.setSection("__DATA, __objc_const")
}
llvm.compilerUsedGlobals += global.llvmGlobal
return global.pointer.bitcast(pointerType(methodListType))
}
fun buildClassRo(isMetaclass: Boolean): ConstPointer {
// TODO: add NonFragileABI_Class_CompiledByARC flag?
val flags: Int
val start: Int
val size: Int
// TODO: stop using hard-coded values.
if (isMetaclass) {
flags = 1
start = 40
size = 40
} else {
flags = 0
start = 8
size = 8
}
val fields = mutableListOf<ConstValue>()
fields += llvm.constInt32(flags)
fields += llvm.constInt32(start)
fields += llvm.constInt32(size)
fields += NullPointer(llvm.int8Type) // ivar layout name
fields += classNameLiteral
fields += if (isMetaclass) NullPointer(methodListType) else emitInstanceMethodList()
fields += NullPointer(protocolListType)
fields += NullPointer(ivarListType)
fields += NullPointer(llvm.int8Type) // ivar layout
fields += NullPointer(propListType)
val roValue = Struct(classRoType, fields)
val roLabel = if (isMetaclass) {
"\u0001l_OBJC_METACLASS_RO_\$_"
} else {
"\u0001l_OBJC_CLASS_RO_\$_"
} + name
val roGlobal = llvm.staticData.placeGlobal(roLabel, roValue).also {
it.setLinkage(LLVMLinkage.LLVMPrivateLinkage)
it.setAlignment(runtime.pointerAlignment)
it.setSection("__DATA, __objc_const")
}
return roGlobal.pointer
}
fun buildClassObject(
isMetaclass: Boolean,
isa: ConstPointer,
superClass: ConstPointer,
classRo: ConstPointer
): ConstPointer {
val fields = mutableListOf<ConstValue>()
fields += isa
fields += superClass
fields += emptyCache
val vtableEntryType = pointerType(functionType(llvm.int8PtrType, false, llvm.int8PtrType, llvm.int8PtrType))
fields += NullPointer(vtableEntryType) // empty vtable
fields += classRo
val classObjectValue = Struct(classObjectType, fields)
val classGlobal = getClassGlobal(name, isMetaclass = isMetaclass)
LLVMSetInitializer(classGlobal.llvm, classObjectValue.llvm)
LLVMSetSection(classGlobal.llvm, "__DATA, __objc_data")
LLVMSetAlignment(classGlobal.llvm, LLVMABIAlignmentOfType(runtime.targetData, classObjectType))
llvm.usedGlobals.add(classGlobal.llvm)
return classGlobal
}
val metaclassObject = buildClassObject(
isMetaclass = true,
isa = getClassGlobal("NSObject", isMetaclass = true),
superClass = getClassGlobal(superName, isMetaclass = true),
classRo = buildClassRo(isMetaclass = true)
)
val classObject = buildClassObject(
isMetaclass = false,
isa = metaclassObject,
superClass = getClassGlobal(superName, isMetaclass = false),
classRo = buildClassRo(isMetaclass = false)
)
definedClasses.add(classObject)
}
private val definedClasses = mutableListOf<ConstPointer>()
private fun addModuleClassList(elements: List<ConstPointer>, name: String, section: String) {
if (elements.isEmpty()) return
val global = llvm.staticData.placeGlobalArray(
name,
llvm.int8PtrType,
elements.map { it.bitcast(llvm.int8PtrType) }
)
global.setAlignment(
LLVMABIAlignmentOfType(
llvm.runtime.targetData,
LLVMGetInitializer(global.llvmGlobal)!!.type
)
)
global.setSection(section)
llvm.compilerUsedGlobals += global.llvmGlobal
}
private val classNames = CStringLiteralsTable(classNameGenerator)
private val selectors = CStringLiteralsTable(selectorGenerator)
private val encodings = CStringLiteralsTable(encodingGenerator)
private inner class CStringLiteralsTable(val generator: CStringLiteralsGenerator) {
private val literals = mutableMapOf<String, ConstPointer>()
fun get(value: String) = literals.getOrPut(value) {
val globalPointer = generator.generate(llvm.module, llvm, value)
llvm.compilerUsedGlobals += globalPointer.llvm
globalPointer.getElementPtr(llvm, 0)
}
}
companion object {
val classNameGenerator =
CStringLiteralsGenerator("OBJC_CLASS_NAME_", "__TEXT,__objc_classname,cstring_literals")
val selectorGenerator =
CStringLiteralsGenerator("OBJC_METH_VAR_NAME_", "__TEXT,__objc_methname,cstring_literals")
private val encodingGenerator =
CStringLiteralsGenerator("OBJC_METH_VAR_TYPE_", "__TEXT,__objc_methtype,cstring_literals")
}
class CStringLiteralsGenerator(val label: String, val section: String) {
fun generate(module: LLVMModuleRef, llvm: Llvm, value: String): ConstPointer {
val bytes = value.toByteArray(Charsets.UTF_8).map { llvm.constInt8(it) } + llvm.constInt8(0)
val initializer = ConstArray(llvm.int8Type, bytes)
val llvmGlobal = LLVMAddGlobal(module, initializer.llvmType, label)!!
LLVMSetInitializer(llvmGlobal, initializer.llvm)
LLVMSetGlobalConstant(llvmGlobal, 1)
LLVMSetLinkage(llvmGlobal, LLVMLinkage.LLVMPrivateLinkage)
LLVMSetSection(llvmGlobal, section)
LLVMSetUnnamedAddr(llvmGlobal, 1)
LLVMSetAlignment(llvmGlobal, 1)
return constPointer(llvmGlobal)
}
}
}
| 181 | null | 625 | 7,100 | 9fb0a75ab17e9d8cddd2c3d1802a1cdd83774dfa | 10,986 | kotlin-native | Apache License 2.0 |
ui/src/main/java/com/pyamsoft/pydroid/ui/internal/datapolicy/DataPolicyViewState.kt | pyamsoft | 48,562,480 | false | null | /*
* Copyright 2023 pyamsoft
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.pydroid.ui.internal.datapolicy
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import com.pyamsoft.pydroid.arch.UiViewState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/** State for showing the required data policy disclosure */
@Stable
public interface DataPolicyViewState : UiViewState {
/** Have we accepted the data policy? */
public val isAccepted: StateFlow<AcceptedState>
/** States of acceptance */
@Stable
@Immutable
public enum class AcceptedState {
NONE,
ACCEPTED,
REJECTED
}
}
@Stable
internal class MutableDataPolicyViewState internal constructor() : DataPolicyViewState {
override val isAccepted = MutableStateFlow(DataPolicyViewState.AcceptedState.NONE)
}
| 1 | null | 7 | 22 | 767ca731e17654e65f131185b2064045b0d39039 | 1,478 | pydroid | Apache License 2.0 |
plugin/src/main/kotlin/dev/triumphteam/triumphchat/locale/DefaultMessage.kt | TriumphTeam | 294,288,510 | false | {"Kotlin": 128629} | /*
* MIT License
*
* Copyright (c) 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package dev.triumphteam.triumphchat.locale
import dev.triumphteam.triumphchat.TriumphChat
import org.bukkit.plugin.java.JavaPlugin
/**
* This class is temporary until I a better way to handle messages
* Soon™
*/
enum class DefaultMessage(
private val en: String
) {
COMMAND_WRONG_USAGE("&cWrong usage!"),
COMMAND_NO_PERMISSION("&cYou don't have permission to use this command!"),
MESSAGE_RECIPIENT_NO_EXIST("&cThe player &7{recipient} &cis not online!"),
REPLY_NO_REPLY_TARGET("&cYou don't have a recipient to reply to!");
fun getMessage(): String {
return when (plugin.locale.language) {
else -> en
}
}
companion object {
private val plugin = JavaPlugin.getPlugin(dev.triumphteam.triumphchat.TriumphChat::class.java)
}
} | 0 | Kotlin | 2 | 2 | fa22204ac59d5eff46f26089e4eae9e7f3593d29 | 1,932 | triumph-chat | MIT License |
mobile/android/apollo_graphql_tutorial/apollo-kotlin-tutorial/compose/start/app/src/main/java/com/example/rocketreserver/LaunchList.kt | jannahio | 317,110,349 | false | {"Kotlin": 127765, "Swift": 105938, "Vue": 43847, "CSS": 7047, "TypeScript": 5720, "JavaScript": 2346, "Java": 1296, "Ruby": 1122, "HTML": 909} | @file:OptIn(ExperimentalMaterial3Api::class)
package com.example.rocketreserver
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ListItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.res.painterResource
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import android.util.Log
@Composable
fun LaunchList(onLaunchClick: (launchId: String) -> Unit) {
var launchList by remember { mutableStateOf(emptyList<LaunchListQuery.Launch>()) }
LaunchedEffect(Unit) {
val response = apolloClient.query(LaunchListQuery()).execute()
Log.d("LaunchList", "Success ${response.data}")
launchList = response.data?.launches?.launches?.filterNotNull() ?: emptyList()
}
LazyColumn {
items(
launchList.count(),
contentType = { mutableStateOf(emptyList<LaunchListQuery.Launch>()) }
) { index ->
val launch = launchList[index]
LaunchItem(launch = launch, onClick = onLaunchClick)
}
}
}
@Composable
//private fun LaunchItem(launchId: String, onClick: (launchId: String) -> Unit) {
private fun LaunchItem(launch: LaunchListQuery.Launch, onClick: (launchId: String) -> Unit) {
ListItem(
modifier = Modifier.clickable { onClick(launch.id) },
headlineText = {
// Mission name
// Text(text = "Launch ${launch.id}")
Text(text = launch.mission?.name ?: "")
},
supportingText = {
// Site
Text(text = "Site...")
},
leadingContent = {
// Mission patch
// Image(
// modifier = Modifier.size(68.dp, 68.dp),
// painter = painterResource(R.drawable.ic_placeholder),
// contentDescription = "Mission patch"
// )
AsyncImage(
modifier = Modifier.size(68.dp, 68.dp),
model = launch.mission?.missionPatch,
placeholder = painterResource(R.drawable.ic_placeholder),
error = painterResource(R.drawable.ic_placeholder),
contentDescription = "Mission patch"
)
}
)
}
@Composable
private fun LoadingItem() {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
CircularProgressIndicator()
}
}
| 0 | Kotlin | 0 | 0 | b590b8c1fa1d05fcfdfa1bd399ebaf5b52d95ad3 | 3,189 | frontend | MIT License |
app/src/main/kotlin/com/aripuca/finhelper/ui/screens/investment/InvestmentViewModel.kt | vitalnik | 585,713,413 | false | {"Kotlin": 260035} | package com.aripuca.finhelper.ui.screens.investment
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.res.stringResource
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.aripuca.finhelper.R
import com.aripuca.finhelper.calculations.InvestmentCalculator
import com.aripuca.finhelper.calculations.YearlyTableItem
import com.aripuca.finhelper.extensions.checkRange
import com.aripuca.finhelper.extensions.toCurrency
import com.aripuca.finhelper.extensions.toIsoString
import com.aripuca.finhelper.services.LocalStorage
import com.aripuca.finhelper.services.analytics.AnalyticsClient
import com.aripuca.finhelper.services.analytics.FirebaseAnalyticsClient
import com.aripuca.finhelper.services.history.AppDatabase
import com.aripuca.finhelper.services.history.InvestmentHistoryEntity
import com.aripuca.finhelper.services.history.MortgageHistoryEntity
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import java.util.Date
import javax.inject.Inject
enum class Frequency(val value: Int) {
WEEKLY(52), MONTHLY(12), QUARTERLY(4), ANNUALLY(1);
companion object {
fun Int.getFrequency(): Frequency =
when (this) {
52 -> WEEKLY
12 -> MONTHLY
4 -> QUARTERLY
else -> ANNUALLY
}
@Composable
fun Frequency.getText(): String =
when (this) {
WEEKLY -> stringResource(R.string.weekly_option)
MONTHLY -> stringResource(R.string.monthly_option)
QUARTERLY -> stringResource(R.string.quarterly_option)
ANNUALLY -> stringResource(R.string.annually_option)
}
@Composable
fun Frequency.getText2(): String =
when (this) {
WEEKLY -> stringResource(R.string.weekly_option2)
MONTHLY -> stringResource(R.string.monthly_option2)
QUARTERLY -> stringResource(R.string.quarterly_option2)
ANNUALLY -> stringResource(R.string.annually_option2)
}
}
}
@HiltViewModel
class InvestmentViewModel @Inject constructor(
private val localStorage: LocalStorage,
private val analyticsClient: AnalyticsClient,
private val appDatabase: AppDatabase,
) : ViewModel() {
// history
val investmentHistoryFlow = appDatabase.investmentHistoryDao().getAllAsFlow()
val selectedHistoryItemIndex = mutableStateOf(localStorage.getInvestmentHistorySelectedIndex(0))
val saveHistoryItemEnabled = mutableStateOf(false)
// input fields
val initialInvestmentInput = mutableStateOf(localStorage.getInvestmentInitialBalance("5000"))
val interestRateInput = mutableStateOf(localStorage.getInvestmentInterestRate("7"))
val inputValid = mutableStateOf(false)
// number of time periods elapsed
val yearsToGrowInput = mutableStateOf(localStorage.getInvestmentYearsToGrow("10"))
val regularContributionInput = mutableStateOf(localStorage.getInvestmentRegularAddition("100"))
val regularAdditionFrequencyInput = mutableStateOf(
localStorage.getInvestmentRegularAdditionFrequency(
Frequency.MONTHLY.value
)
)
// calculated fields
val totalInvestment = mutableStateOf("")
val totalInterestEarned = mutableStateOf("")
val totalValue = mutableStateOf("")
val yearlyTable = mutableStateOf<List<YearlyTableItem>>(listOf())
val principalPercent = mutableStateOf(50.0)
fun logScreenView() {
analyticsClient.log(FirebaseAnalyticsClient.INVESTMENT_SCREEN_VIEW)
}
fun calculateInvestment() {
validateRequiredFields()
if (!inputValid.value) {
return
}
viewModelScope.launch {
val investmentCalculator = InvestmentCalculator(
initialPrincipalBalance = initialInvestmentInput.value.toDoubleOrNull() ?: 0.0,
regularAddition = regularContributionInput.value.toDoubleOrNull() ?: 0.0,
regularAdditionFrequency = regularAdditionFrequencyInput.value.toDouble(),
interestRate = interestRateInput.value.toDoubleOrNull() ?: 0.0,
numberOfTimesInterestApplied = regularAdditionFrequencyInput.value.toDouble(),
yearsToGrow = yearsToGrowInput.value.toIntOrNull() ?: 0,
)
investmentCalculator.calculate()
totalValue.value = investmentCalculator.totalValue.toCurrency()
totalInterestEarned.value = investmentCalculator.totalInterestEarned.toCurrency()
totalInvestment.value = investmentCalculator.totalInvestment.toCurrency()
yearlyTable.value = investmentCalculator.yearlyTable
principalPercent.value = investmentCalculator.principalPercent
saveUserInputInLocalStorage()
}
}
private fun saveUserInputInLocalStorage() {
localStorage.saveString(
LocalStorage.INVESTMENT_INITIAL_BALANCE, initialInvestmentInput.value
)
localStorage.saveString(
LocalStorage.INVESTMENT_REGULAR_ADDITION,
regularContributionInput.value
)
localStorage.saveString(LocalStorage.INVESTMENT_INTEREST_RATE, interestRateInput.value)
localStorage.saveString(LocalStorage.INVESTMENT_YEARS_TO_GROW, yearsToGrowInput.value)
localStorage.saveString(
LocalStorage.INVESTMENT_REGULAR_ADDITION_FREQUENCY,
regularAdditionFrequencyInput.value.toString()
)
localStorage.saveInt(
LocalStorage.INVESTMENT_HISTORY_SELECTED_INDEX,
selectedHistoryItemIndex.value
)
}
private fun validateInitialInvestment(textValue: String): Boolean {
val value = textValue.toDoubleOrNull() ?: 0.0
return value.checkRange(max = 1_000_000_000.0)
}
private fun validateRegularContribution(textValue: String): Boolean {
val value = textValue.toDoubleOrNull() ?: 0.0
return value.checkRange(max = 1_000_000.0)
}
private fun validateInterestRate(textValue: String): Boolean {
val value = textValue.toDoubleOrNull() ?: 0.0
return value.checkRange(max = 100.0)
}
private fun validateYearsToGrow(textValue: String): Boolean {
val value = textValue.toDoubleOrNull() ?: 0.0
return value.checkRange(max = 100.0)
}
fun addHistoryItem() {
viewModelScope.launch {
val historyEntity = InvestmentHistoryEntity(
title = "Investment history item",
initialInvestment = initialInvestmentInput.value,
interestRate = interestRateInput.value,
numberOfYears = yearsToGrowInput.value,
regularContribution = regularContributionInput.value,
contributionFrequency = regularAdditionFrequencyInput.value.toString(),
createdAt = Date().toIsoString(),
updatedAt = Date().toIsoString(),
)
appDatabase.investmentHistoryDao().insert(historyEntity)
val historyList: List<InvestmentHistoryEntity> =
appDatabase.investmentHistoryDao().getAll()
selectedHistoryItemIndex.value = historyList.count() - 1
analyticsClient.log(FirebaseAnalyticsClient.INVESTMENT_HISTORY_ADDED)
}
}
fun saveHistoryItem() {
viewModelScope.launch {
val historyList: List<InvestmentHistoryEntity> =
appDatabase.investmentHistoryDao().getAll()
if (historyList.isNotEmpty() && selectedHistoryItemIndex.value < historyList.count()) {
val selectedHistoryItem = historyList[selectedHistoryItemIndex.value].copy()
val historyEntity = InvestmentHistoryEntity(
id = selectedHistoryItem.id,
title = selectedHistoryItem.title,
initialInvestment = initialInvestmentInput.value,
interestRate = interestRateInput.value,
numberOfYears = yearsToGrowInput.value,
regularContribution = regularContributionInput.value,
contributionFrequency = regularAdditionFrequencyInput.value.toString(),
createdAt = selectedHistoryItem.createdAt,
updatedAt = Date().toIsoString(),
)
appDatabase.investmentHistoryDao().update(historyEntity)
}
setSaveHistoryItemEnabled()
analyticsClient.log(FirebaseAnalyticsClient.INVESTMENT_HISTORY_SAVED)
}
}
fun deleteHistoryItem() {
viewModelScope.launch {
val historyList: List<InvestmentHistoryEntity> =
appDatabase.investmentHistoryDao().getAll()
if (historyList.isNotEmpty() && selectedHistoryItemIndex.value < historyList.count()) {
val selectedHistoryItem = historyList[selectedHistoryItemIndex.value]
appDatabase.investmentHistoryDao().deleteById(selectedHistoryItem.id)
if (selectedHistoryItemIndex.value == historyList.count() - 1) {
decrementSelectedHistoryItemIndex(logAnalytics = false)
}
analyticsClient.log(FirebaseAnalyticsClient.INVESTMENT_HISTORY_DELETED)
}
}
}
fun setSelectedHistoryItemIndex(index: Int) {
selectedHistoryItemIndex.value = index
}
fun decrementSelectedHistoryItemIndex(logAnalytics: Boolean = true) {
viewModelScope.launch {
val historyList: List<InvestmentHistoryEntity> =
appDatabase.investmentHistoryDao().getAll()
if (selectedHistoryItemIndex.value > 0 && historyList.isNotEmpty()) {
selectedHistoryItemIndex.value--
} else {
if (selectedHistoryItemIndex.value == 0 && historyList.isNotEmpty()) {
selectedHistoryItemIndex.value = historyList.count() - 1
}
}
if (logAnalytics) {
analyticsClient.log(FirebaseAnalyticsClient.INVESTMENT_HISTORY_SCROLL)
}
}
}
fun incrementSelectedHistoryItemIndex() {
viewModelScope.launch {
val historyList: List<InvestmentHistoryEntity> =
appDatabase.investmentHistoryDao().getAll()
if (selectedHistoryItemIndex.value < historyList.count() - 1) {
selectedHistoryItemIndex.value++
} else {
if (selectedHistoryItemIndex.value == historyList.count() - 1) {
selectedHistoryItemIndex.value = 0
}
}
analyticsClient.log(FirebaseAnalyticsClient.INVESTMENT_HISTORY_SCROLL)
}
}
fun loadHistoryItem(historyList: List<InvestmentHistoryEntity>) {
if (historyList.isNotEmpty() && selectedHistoryItemIndex.value < historyList.count()) {
val selectedHistoryItem = historyList[selectedHistoryItemIndex.value]
initialInvestmentInput.value = selectedHistoryItem.initialInvestment
interestRateInput.value = selectedHistoryItem.interestRate
yearsToGrowInput.value = selectedHistoryItem.numberOfYears
regularContributionInput.value = selectedHistoryItem.regularContribution
regularAdditionFrequencyInput.value =
selectedHistoryItem.contributionFrequency.toInt()
setSaveHistoryItemEnabled()
calculateInvestment()
}
}
fun updateInitialInvestment(value: String) {
if (value.isEmpty()) {
inputValid.value = false
initialInvestmentInput.value = value
return
}
if (validateInitialInvestment(value)) {
initialInvestmentInput.value = value
setSaveHistoryItemEnabled()
calculateInvestment()
}
}
fun updateInterestRate(value: String) {
if (value.isEmpty() || (value.toDoubleOrNull() ?: 0.0) == 0.0) {
inputValid.value = false
interestRateInput.value = value
return
}
if (validateInterestRate(value)) {
interestRateInput.value = value
setSaveHistoryItemEnabled()
calculateInvestment()
}
}
fun updateRegularContribution(value: String) {
if (value.isEmpty()) {
inputValid.value = false
regularContributionInput.value = value
return
}
if (validateRegularContribution(value)) {
regularContributionInput.value = value
setSaveHistoryItemEnabled()
calculateInvestment()
}
}
fun updateYearsToGrow(value: String) {
if (value.isEmpty() || (value.toIntOrNull() ?: 0) == 0) {
inputValid.value = false
yearsToGrowInput.value = ""
return
}
if (validateYearsToGrow(value)) {
yearsToGrowInput.value = value
setSaveHistoryItemEnabled()
calculateInvestment()
}
}
fun updateRegularAdditionFrequency(frequency: Frequency) {
regularAdditionFrequencyInput.value = frequency.value
setSaveHistoryItemEnabled()
calculateInvestment()
}
private fun setSaveHistoryItemEnabled() {
viewModelScope.launch {
val historyList: List<InvestmentHistoryEntity> =
appDatabase.investmentHistoryDao().getAll()
if (historyList.isNotEmpty()) {
val selectedHistoryItem = historyList[selectedHistoryItemIndex.value]
saveHistoryItemEnabled.value =
selectedHistoryItem.initialInvestment != initialInvestmentInput.value ||
selectedHistoryItem.interestRate != interestRateInput.value ||
selectedHistoryItem.numberOfYears != yearsToGrowInput.value ||
selectedHistoryItem.regularContribution != regularContributionInput.value ||
selectedHistoryItem.contributionFrequency != regularAdditionFrequencyInput.value.toString()
}
}
}
private fun validateRequiredFields() {
inputValid.value =
!(initialInvestmentInput.value.isEmpty() ||
interestRateInput.value.isEmpty() ||
(interestRateInput.value.toDoubleOrNull() ?: 0.0) == 0.0 ||
regularContributionInput.value.isEmpty()
) && !((initialInvestmentInput.value.toDoubleOrNull() ?: 0.0) == 0.0 &&
(regularContributionInput.value.toDoubleOrNull() ?: 0.0) == 0.0)
}
} | 0 | Kotlin | 0 | 1 | 6c89e2a8a501c6906cc19572622c40d48e09bfb1 | 14,873 | FinHelperOpenSource | Apache License 2.0 |
domain/src/main/kotlin/com/astrainteractive/astraclans/domain/dto/mapping/PlayerDTOMapper.kt | Astra-Interactive | 525,464,505 | false | null | package com.astrainteractive.astraclans.domain.dto.mapping
import com.astrainteractive.astraclans.domain.dto.PlayerDTO
import com.astrainteractive.astraclans.domain.entities.PlayerDAO
import ru.astrainteractive.astralibs.domain.mapping.IMapper
interface IPlayerDTOMapper : IMapper<PlayerDAO, PlayerDTO>, ExposedMapper<PlayerDAO, PlayerDTO>
object PlayerDTOMapper : IPlayerDTOMapper {
override fun toDTO(it: PlayerDAO): PlayerDTO {
return PlayerDTO(
minecraftUUID = it.minecraftUUID,
totalExperience = it.experience,
health = it.health,
foodLevel = it.foodLevel,
lastServerName = it.lastServerName,
items = it.items,
enderChestItems = it.enderChestItems,
effects = it.effects
)
}
@Deprecated("Use toEsposed")
override fun fromDTO(it: PlayerDTO): PlayerDAO {
return PlayerDAO.new(toExposed(it))
}
override fun toExposed(it: PlayerDTO): PlayerDAO.() -> Unit = {
this.minecraftUUID = it.minecraftUUID
this.experience = it.totalExperience
this.health = it.health
this.foodLevel = it.foodLevel
this.lastServerName = it.lastServerName
this.items = it.items
this.enderChestItems = it.enderChestItems
this.effects = it.effects
}
} | 0 | Kotlin | 0 | 0 | 5069aa6fe6a56e3c309e2e597147bcd671493391 | 1,338 | AstraSync | MIT License |
keel-ec2-plugin/src/test/kotlin/com/netflix/spinnaker/keel/ec2/resource/ClusterHandlerTests.kt | spinnaker | 107,462,081 | false | null | package com.netflix.spinnaker.keel.ec2.resource
import com.netflix.spinnaker.keel.api.DeployHealth.AUTO
import com.netflix.spinnaker.keel.api.DeployHealth.NONE
import com.netflix.spinnaker.keel.api.Environment
import com.netflix.spinnaker.keel.api.Exportable
import com.netflix.spinnaker.keel.api.Highlander
import com.netflix.spinnaker.keel.api.Moniker
import com.netflix.spinnaker.keel.api.RedBlack
import com.netflix.spinnaker.keel.api.StaggeredRegion
import com.netflix.spinnaker.keel.api.SubnetAwareLocations
import com.netflix.spinnaker.keel.api.SubnetAwareRegionSpec
import com.netflix.spinnaker.keel.api.ec2.CLOUD_PROVIDER
import com.netflix.spinnaker.keel.api.ec2.Capacity
import com.netflix.spinnaker.keel.api.ec2.ClusterDependencies
import com.netflix.spinnaker.keel.api.ec2.ClusterSpec
import com.netflix.spinnaker.keel.api.ec2.ClusterSpec.ServerGroupSpec
import com.netflix.spinnaker.keel.api.ec2.CustomizedMetricSpecification
import com.netflix.spinnaker.keel.api.ec2.EC2_CLUSTER_V1_1
import com.netflix.spinnaker.keel.api.ec2.LaunchConfigurationSpec
import com.netflix.spinnaker.keel.api.ec2.Scaling
import com.netflix.spinnaker.keel.api.ec2.ServerGroup
import com.netflix.spinnaker.keel.api.ec2.ServerGroup.InstanceCounts
import com.netflix.spinnaker.keel.api.ec2.ServerGroup.LaunchConfiguration
import com.netflix.spinnaker.keel.api.ec2.TargetTrackingPolicy
import com.netflix.spinnaker.keel.api.ec2.VirtualMachineImage
import com.netflix.spinnaker.keel.api.ec2.byRegion
import com.netflix.spinnaker.keel.api.ec2.resolve
import com.netflix.spinnaker.keel.api.ec2.resolveCapacity
import com.netflix.spinnaker.keel.api.events.ArtifactVersionDeployed
import com.netflix.spinnaker.keel.api.events.ArtifactVersionDeploying
import com.netflix.spinnaker.keel.api.plugins.Resolver
import com.netflix.spinnaker.keel.api.support.EventPublisher
import com.netflix.spinnaker.keel.clouddriver.CloudDriverCache
import com.netflix.spinnaker.keel.clouddriver.CloudDriverService
import com.netflix.spinnaker.keel.clouddriver.model.ActiveServerGroup
import com.netflix.spinnaker.keel.clouddriver.model.CustomizedMetricSpecificationModel
import com.netflix.spinnaker.keel.clouddriver.model.Network
import com.netflix.spinnaker.keel.clouddriver.model.SecurityGroupSummary
import com.netflix.spinnaker.keel.clouddriver.model.ServerGroupCollection
import com.netflix.spinnaker.keel.clouddriver.model.Subnet
import com.netflix.spinnaker.keel.diff.DefaultResourceDiff
import com.netflix.spinnaker.keel.model.OrchestrationRequest
import com.netflix.spinnaker.keel.orca.ClusterExportHelper
import com.netflix.spinnaker.keel.orca.OrcaService
import com.netflix.spinnaker.keel.orca.OrcaTaskLauncher
import com.netflix.spinnaker.keel.orca.TaskRefResponse
import com.netflix.spinnaker.keel.persistence.KeelRepository
import com.netflix.spinnaker.keel.retrofit.RETROFIT_NOT_FOUND
import com.netflix.spinnaker.keel.test.resource
import de.huxhorn.sulky.ulid.ULID
import dev.minutest.junit.JUnit5Minutests
import dev.minutest.rootContext
import io.mockk.clearAllMocks
import io.mockk.mockk
import io.mockk.slot
import kotlinx.coroutines.runBlocking
import strikt.api.Assertion
import strikt.api.expectCatching
import strikt.api.expectThat
import strikt.assertions.all
import strikt.assertions.containsExactly
import strikt.assertions.containsExactlyInAnyOrder
import strikt.assertions.containsKey
import strikt.assertions.get
import strikt.assertions.hasSize
import strikt.assertions.isA
import strikt.assertions.isEqualTo
import strikt.assertions.isFalse
import strikt.assertions.isNotEmpty
import strikt.assertions.isNotNull
import strikt.assertions.isNull
import strikt.assertions.isSuccess
import strikt.assertions.isTrue
import strikt.assertions.map
import java.time.Clock
import java.time.Duration
import java.util.UUID.randomUUID
import io.mockk.coEvery as every
import io.mockk.coVerify as verify
@Suppress("MemberVisibilityCanBePrivate")
internal class ClusterHandlerTests : JUnit5Minutests {
val cloudDriverService = mockk<CloudDriverService>()
val cloudDriverCache = mockk<CloudDriverCache>()
val orcaService = mockk<OrcaService>()
val normalizers = emptyList<Resolver<ClusterSpec>>()
val clock = Clock.systemUTC()!!
val publisher: EventPublisher = mockk(relaxUnitFun = true)
val repository = mockk<KeelRepository>()
val taskLauncher = OrcaTaskLauncher(
orcaService,
repository,
publisher
)
val clusterExportHelper = mockk<ClusterExportHelper>(relaxed = true)
val blockDeviceConfig = BlockDeviceConfig(VolumeDefaultConfiguration())
val vpcWest = Network(CLOUD_PROVIDER, "vpc-1452353", "vpc0", "test", "us-west-2")
val vpcEast = Network(CLOUD_PROVIDER, "vpc-4342589", "vpc0", "test", "us-east-1")
val sg1West = SecurityGroupSummary("keel", "sg-325234532", "vpc-1")
val sg2West = SecurityGroupSummary("keel-elb", "sg-235425234", "vpc-1")
val sg1East = SecurityGroupSummary("keel", "sg-279585936", "vpc-1")
val sg2East = SecurityGroupSummary("keel-elb", "sg-610264122", "vpc-1")
val subnet1West = Subnet("subnet-1", vpcWest.id, vpcWest.account, vpcWest.region, "${vpcWest.region}a", "internal (vpc0)")
val subnet2West = Subnet("subnet-2", vpcWest.id, vpcWest.account, vpcWest.region, "${vpcWest.region}b", "internal (vpc0)")
val subnet3West = Subnet("subnet-3", vpcWest.id, vpcWest.account, vpcWest.region, "${vpcWest.region}c", "internal (vpc0)")
val subnet1East = Subnet("subnet-1", vpcEast.id, vpcEast.account, vpcEast.region, "${vpcEast.region}c", "internal (vpc0)")
val subnet2East = Subnet("subnet-2", vpcEast.id, vpcEast.account, vpcEast.region, "${vpcEast.region}d", "internal (vpc0)")
val subnet3East = Subnet("subnet-3", vpcEast.id, vpcEast.account, vpcEast.region, "${vpcEast.region}e", "internal (vpc0)")
val targetTrackingPolicyName = "keel-test-target-tracking-policy"
val spec = clusterSpec()
fun clusterSpec(instanceType: String = "r4.8xlarge") =
ClusterSpec(
moniker = Moniker(app = "keel", stack = "test"),
locations = SubnetAwareLocations(
account = vpcWest.account,
vpc = "vpc0",
subnet = subnet1West.purpose!!,
regions = listOf(vpcWest, vpcEast).map { subnet ->
SubnetAwareRegionSpec(
name = subnet.region,
availabilityZones = listOf("a", "b", "c").map { "${subnet.region}$it" }.toSet()
)
}.toSet()
),
deployWith = RedBlack(
stagger = listOf(
StaggeredRegion(region = vpcWest.region, hours = "10-14", pauseTime = Duration.ofMinutes(30)),
StaggeredRegion(region = vpcEast.region, hours = "16-02")
)
),
_defaults = ServerGroupSpec(
launchConfiguration = LaunchConfigurationSpec(
image = VirtualMachineImage(
id = "ami-123543254134",
appVersion = "keel-0.287.0-h208.fe2e8a1",
baseImageVersion = "nflx-base-5.308.0-h1044.b4b3f78"
),
instanceType = instanceType,
ebsOptimized = false,
iamRole = LaunchConfiguration.defaultIamRoleFor("keel"),
keyPair = "nf-keypair-test-fake",
instanceMonitoring = false
),
capacity = Capacity(1, 6),
scaling = Scaling(
targetTrackingPolicies = setOf(
TargetTrackingPolicy(
name = targetTrackingPolicyName,
targetValue = 560.0,
disableScaleIn = true,
customMetricSpec = CustomizedMetricSpecification(
name = "RPS per instance",
namespace = "SPIN/ACH",
statistic = "Average"
)
)
)
),
dependencies = ClusterDependencies(
loadBalancerNames = setOf("keel-test-frontend"),
securityGroupNames = setOf(sg1West.name, sg2West.name)
)
)
)
val serverGroups = spec.resolve()
val serverGroupEast = serverGroups.first { it.location.region == "us-east-1" }
val serverGroupWest = serverGroups.first { it.location.region == "us-west-2" }
val resource = resource(
kind = EC2_CLUSTER_V1_1.kind,
spec = spec
)
val activeServerGroupResponseEast = serverGroupEast.toCloudDriverResponse(vpcEast, listOf(subnet1East, subnet2East, subnet3East), listOf(sg1East, sg2East))
val activeServerGroupResponseWest = serverGroupWest.toCloudDriverResponse(vpcWest, listOf(subnet1West, subnet2West, subnet3West), listOf(sg1West, sg2West))
val exportable = Exportable(
cloudProvider = "aws",
account = spec.locations.account,
user = "<EMAIL>",
moniker = spec.moniker,
regions = spec.locations.regions.map { it.name }.toSet(),
kind = EC2_CLUSTER_V1_1.kind
)
fun tests() = rootContext<ClusterHandler> {
fixture {
ClusterHandler(
cloudDriverService,
cloudDriverCache,
orcaService,
taskLauncher,
clock,
publisher,
normalizers,
clusterExportHelper,
blockDeviceConfig
)
}
before {
with(cloudDriverCache) {
every { defaultKeyPairForAccount("test") } returns "nf-keypair-test-{{region}}"
every { networkBy(vpcWest.id) } returns vpcWest
every { subnetBy(subnet1West.id) } returns subnet1West
every { subnetBy(subnet2West.id) } returns subnet2West
every { subnetBy(subnet3West.id) } returns subnet3West
every { subnetBy(vpcWest.account, vpcWest.region, subnet1West.purpose!!) } returns subnet1West
every { securityGroupById(vpcWest.account, vpcWest.region, sg1West.id) } returns sg1West
every { securityGroupById(vpcWest.account, vpcWest.region, sg2West.id) } returns sg2West
every { securityGroupByName(vpcWest.account, vpcWest.region, sg1West.name) } returns sg1West
every { securityGroupByName(vpcWest.account, vpcWest.region, sg2West.name) } returns sg2West
every { availabilityZonesBy(vpcWest.account, vpcWest.id, subnet1West.purpose!!, vpcWest.region) } returns
setOf(subnet1West.availabilityZone)
every { networkBy(vpcEast.id) } returns vpcEast
every { subnetBy(subnet1East.id) } returns subnet1East
every { subnetBy(subnet2East.id) } returns subnet2East
every { subnetBy(subnet3East.id) } returns subnet3East
every { subnetBy(vpcEast.account, vpcEast.region, subnet1East.purpose!!) } returns subnet1East
every { securityGroupById(vpcEast.account, vpcEast.region, sg1East.id) } returns sg1East
every { securityGroupById(vpcEast.account, vpcEast.region, sg2East.id) } returns sg2East
every { securityGroupByName(vpcEast.account, vpcEast.region, sg1East.name) } returns sg1East
every { securityGroupByName(vpcEast.account, vpcEast.region, sg2East.name) } returns sg2East
every { availabilityZonesBy(vpcEast.account, vpcEast.id, subnet1East.purpose!!, vpcEast.region) } returns
setOf(subnet1East.availabilityZone)
}
every { orcaService.orchestrate(resource.serviceAccount, any()) } returns TaskRefResponse("/tasks/${randomUUID()}")
every { repository.environmentFor(any()) } returns Environment("test")
every {
clusterExportHelper.discoverDeploymentStrategy("aws", "test", "keel", any())
} returns RedBlack()
}
after {
clearAllMocks()
}
context("no server groups exist and the cluster doesn't exist") {
before {
every { cloudDriverService.activeServerGroup(any(), "us-east-1") } throws RETROFIT_NOT_FOUND
every { cloudDriverService.activeServerGroup(any(), "us-west-2") } throws RETROFIT_NOT_FOUND
every { cloudDriverService.listServerGroups(any(), any(), any(), any()) } throws RETROFIT_NOT_FOUND
}
test("the current model can be calculated correctly as no server groups") {
val current = runBlocking {
current(resource)
}
expectThat(current)
.hasSize(0)
}
}
context("the cluster does not exist or has no active server groups") {
before {
every { cloudDriverService.activeServerGroup(any(), "us-east-1") } returns activeServerGroupResponseEast
every { cloudDriverService.activeServerGroup(any(), "us-west-2") } throws RETROFIT_NOT_FOUND
every { cloudDriverService.listServerGroups(any(), any(), any(), any()) } returns
ServerGroupCollection(vpcEast.account, setOf(activeServerGroupResponseEast.toAllServerGroupsResponse()))
}
test("the current model is null") {
val current = runBlocking {
current(resource)
}
expectThat(current)
.hasSize(1)
.not()
.containsKey("us-west-2")
}
test("annealing a staggered cluster with simple capacity doesn't attempt to upsertScalingPolicy") {
val slot = slot<OrchestrationRequest>()
every { orcaService.orchestrate(resource.serviceAccount, capture(slot)) } answers { TaskRefResponse(ULID().nextULID()) }
runBlocking {
upsert(
resource,
DefaultResourceDiff(
serverGroups.map {
it.copy(scaling = Scaling(), capacity = Capacity(2, 2, 2))
}.byRegion(),
emptyMap()
)
)
}
// slot will only contain the last orchestration request made, which should
// always be for the second staggered region (east).
expectThat(slot.captured.job.size).isEqualTo(2)
expectThat(slot.captured.job.first()) {
// east is waiting for west
get("type").isEqualTo("dependsOnExecution")
}
expectThat(slot.captured.job[1]) {
get("type").isEqualTo("createServerGroup")
get("refId").isEqualTo("2")
get("requisiteStageRefIds")
.isA<List<String>>()
.isEqualTo(listOf("1"))
get("availabilityZones")
.isA<Map<String, Set<String>>>()
.hasSize(1)
.containsKey("us-east-1")
get("restrictExecutionDuringTimeWindow").isEqualTo(true)
}
}
test("annealing a diff creates staggered server groups with scaling policies upserted in the same orchestration") {
val slot = slot<OrchestrationRequest>()
every { orcaService.orchestrate(resource.serviceAccount, capture(slot)) } answers { TaskRefResponse(ULID().nextULID()) }
runBlocking {
upsert(resource, DefaultResourceDiff(serverGroups.byRegion(), emptyMap()))
}
expectThat(slot.captured.job.size).isEqualTo(3)
expectThat(slot.captured.job.first()) {
// east is waiting for west
get("type").isEqualTo("dependsOnExecution")
}
expectThat(slot.captured.job[1]) {
get("type").isEqualTo("createServerGroup")
get("refId").isEqualTo("2")
get("requisiteStageRefIds")
.isA<List<String>>()
.isEqualTo(listOf("1"))
get("availabilityZones")
.isA<Map<String, Set<String>>>()
.hasSize(1)
.containsKey("us-east-1")
get("restrictExecutionDuringTimeWindow").isEqualTo(true)
}
expectThat(slot.captured.job[2]) {
get("type").isEqualTo("upsertScalingPolicy")
get("refId").isEqualTo("3")
get("requisiteStageRefIds")
.isA<List<String>>()
.isEqualTo(listOf("2"))
get("restrictExecutionDuringTimeWindow").isNull()
}
}
}
context("the cluster has healthy active server groups") {
before {
every { cloudDriverService.activeServerGroup(any(), "us-east-1") } returns activeServerGroupResponseEast
every { cloudDriverService.activeServerGroup(any(), "us-west-2") } returns activeServerGroupResponseWest
every { cloudDriverService.listServerGroups(any(), any(), any(), any()) } returns
ServerGroupCollection(
vpcEast.account,
setOf(activeServerGroupResponseEast.toAllServerGroupsResponse(), activeServerGroupResponseWest.toAllServerGroupsResponse()))
}
// TODO: test for multiple server group response
derivedContext<Map<String, ServerGroup>>("fetching the current server group state") {
deriveFixture {
runBlocking {
current(resource)
}
}
test("the current model is converted to a set of server group") {
expectThat(this).isNotEmpty()
}
test("the server group name is derived correctly") {
expectThat(values)
.map { it.name }
.containsExactlyInAnyOrder(
activeServerGroupResponseEast.name,
activeServerGroupResponseWest.name
)
}
test("an event is fired if all server groups have the same artifact version") {
verify { publisher.publishEvent(ofType<ArtifactVersionDeployed>()) }
}
}
}
context("the cluster has unhealthy active server groups") {
before {
val instanceCounts = InstanceCounts(1, 0, 0, 1, 0, 0)
val east = serverGroupEast.toCloudDriverResponse(
vpc = vpcEast,
subnets = listOf(subnet1East, subnet2East, subnet3East),
securityGroups = listOf(sg1East, sg2East),
instanceCounts = instanceCounts
)
val west = serverGroupWest.toCloudDriverResponse(
vpc = vpcWest,
subnets = listOf(subnet1West, subnet2West, subnet3West),
securityGroups = listOf(sg1West, sg2West),
instanceCounts = instanceCounts
)
every { cloudDriverService.activeServerGroup(any(), "us-east-1") } returns east
every { cloudDriverService.activeServerGroup(any(), "us-west-2") } returns west
every { cloudDriverService.listServerGroups(any(), any(), any(), any()) } returns
ServerGroupCollection(
vpcEast.account,
setOf(east.toAllServerGroupsResponse(), west.toAllServerGroupsResponse()))
}
derivedContext<Map<String, ServerGroup>>("fetching the current server group state") {
deriveFixture {
runBlocking {
current(resource)
}
}
test("a deployed event is not fired") {
verify(exactly = 0) { publisher.publishEvent(ofType<ArtifactVersionDeployed>()) }
}
}
}
context("the cluster has active server groups with different app versions") {
before {
val west = activeServerGroupResponseWest.withOlderAppVersion()
every { cloudDriverService.activeServerGroup(any(), "us-east-1") } returns activeServerGroupResponseEast
every { cloudDriverService.activeServerGroup(any(), "us-west-2") } returns west
every { cloudDriverService.listServerGroups(any(), any(), any(), any()) } returns
ServerGroupCollection(
vpcEast.account,
setOf(activeServerGroupResponseEast.toAllServerGroupsResponse(), west.toAllServerGroupsResponse()))
runBlocking {
current(resource)
}
}
test("no event is fired indicating an app version is deployed") {
verify(exactly = 0) { publisher.publishEvent(ofType<ArtifactVersionDeployed>()) }
}
}
context("the cluster has active server groups with missing app version tag in one region") {
before {
val west = activeServerGroupResponseWest.withMissingAppVersion()
every { cloudDriverService.activeServerGroup(any(), "us-east-1") } returns activeServerGroupResponseEast
every { cloudDriverService.activeServerGroup(any(), "us-west-2") } returns west
every { cloudDriverService.listServerGroups(any(), any(), any(), any()) } returns
ServerGroupCollection(
vpcEast.account,
setOf(activeServerGroupResponseEast.toAllServerGroupsResponse(), west.toAllServerGroupsResponse()))
}
test("app version is null in the region with missing tag") {
val current = runBlocking {
current(resource)
}
expectThat(current).containsKey("us-west-2")
expectThat(current["us-west-2"]!!.launchConfiguration.appVersion).isNull()
}
test("no exception is thrown") {
expectCatching {
current(resource)
}.isSuccess()
}
test("no event is fired indicating an app version is deployed") {
runBlocking {
current(resource)
}
verify(exactly = 0) { publisher.publishEvent(ofType<ArtifactVersionDeployed>()) }
}
test("applying the diff creates a server group in the region with missing tag") {
val slot = slot<OrchestrationRequest>()
every { orcaService.orchestrate(resource.serviceAccount, capture(slot)) } answers { TaskRefResponse(ULID().nextULID()) }
val modified = setOf(
serverGroupEast.copy(name = activeServerGroupResponseEast.name),
serverGroupWest.copy(name = activeServerGroupResponseWest.name).withMissingAppVersion()
)
val diff = DefaultResourceDiff(
serverGroups.byRegion(),
modified.byRegion()
)
runBlocking {
upsert(resource, diff)
}
expectThat(slot.captured.job.first()) {
get("type").isEqualTo("createServerGroup")
get { get("availabilityZones") }.isA<Map<String, String>>().containsKey("us-west-2")
}
}
}
context("the cluster has too many enabled server groups in one region") {
val east = serverGroupEast.toMultiServerGroupResponse(vpc = vpcEast, subnets = listOf(subnet1East, subnet2East, subnet3East), securityGroups = listOf(sg1East, sg2East), allEnabled = true)
val west = serverGroupWest.toMultiServerGroupResponse(vpc = vpcWest, subnets = listOf(subnet1West, subnet2West, subnet3West), securityGroups = listOf(sg1West, sg2West))
before {
every { cloudDriverService.activeServerGroup(any(), "us-east-1") } returns activeServerGroupResponseEast
every { cloudDriverService.activeServerGroup(any(), "us-west-2") } returns activeServerGroupResponseWest
every { cloudDriverService.listServerGroups(any(), any(), any(), any()) } returns
ServerGroupCollection(vpcEast.account, east + west)
}
test("applying the diff creates a disable job for the oldest server group") {
val slot = slot<OrchestrationRequest>()
every { orcaService.orchestrate(resource.serviceAccount, capture(slot)) } answers { TaskRefResponse(ULID().nextULID()) }
val modified = setOf(
serverGroupEast.copy(name = activeServerGroupResponseEast.name, onlyEnabledServerGroup = false),
serverGroupWest.copy(name = activeServerGroupResponseWest.name)
)
val diff = DefaultResourceDiff(
serverGroups.byRegion(),
modified.byRegion()
)
runBlocking {
upsert(resource, diff)
}
expectThat(slot.captured.job.first()) {
get("type").isEqualTo("disableServerGroup")
get("asgName").isEqualTo(east.sortedBy { it.createdTime }.first().name)
}
}
}
context("will we take action?") {
val east = serverGroupEast.toMultiServerGroupResponse(vpc = vpcEast, subnets = listOf(subnet1East, subnet2East, subnet3East), securityGroups = listOf(sg1East, sg2East), allEnabled = true)
val west = serverGroupWest.toMultiServerGroupResponse(vpc = vpcWest, subnets = listOf(subnet1West, subnet2West, subnet3West), securityGroups = listOf(sg1West, sg2West))
before {
every { cloudDriverService.listServerGroups(any(), any(), any(), any()) } returns
ServerGroupCollection(vpcEast.account, east + west)
}
context("there is a diff in more than just enabled/disabled") {
val modified = setOf(
serverGroupEast.copy(name = activeServerGroupResponseEast.name, onlyEnabledServerGroup = false).withDoubleCapacity(),
serverGroupWest.copy(name = activeServerGroupResponseWest.name).withDoubleCapacity()
)
val diff = DefaultResourceDiff(
serverGroups.byRegion(),
modified.byRegion()
)
test("we will take action"){
val response = runBlocking { willTakeAction(resource, diff) }
expectThat(response.willAct).isTrue()
}
}
context("there is a diff only in enabled/disabled") {
val modified = setOf(
serverGroupEast.copy(name = activeServerGroupResponseEast.name, onlyEnabledServerGroup = false),
serverGroupWest.copy(name = activeServerGroupResponseWest.name)
)
val diff = DefaultResourceDiff(
serverGroups.byRegion(),
modified.byRegion()
)
context("active server group is healthy") {
before {
every { cloudDriverService.activeServerGroup(any(), "us-east-1") } returns activeServerGroupResponseEast
every { cloudDriverService.activeServerGroup(any(), "us-west-2") } returns activeServerGroupResponseWest
}
test("we will take action"){
val response = runBlocking { willTakeAction(resource, diff) }
expectThat(response.willAct).isTrue()
}
}
context("active server group is not healthy") {
before {
every { cloudDriverService.listServerGroups(any(), any(), any(), any())} returns ServerGroupCollection(
vpcEast.account,
setOf(
activeServerGroupResponseEast.toAllServerGroupsResponse(false),
activeServerGroupResponseWest.toAllServerGroupsResponse(false)
)
)
every { cloudDriverService.activeServerGroup(any(), "us-east-1") } returns serverGroupEast.toCloudDriverResponse(vpcEast, listOf(subnet1East, subnet2East, subnet3East), listOf(sg1East, sg2East), null, InstanceCounts(1,0,1,0,0,0))
every { cloudDriverService.activeServerGroup(any(), "us-west-2") } returns activeServerGroupResponseWest
}
test("we won't take action"){
val response = runBlocking { willTakeAction(resource, diff) }
expectThat(response.willAct).isFalse()
}
}
}
}
context("a diff has been detected") {
context("the diff is only in capacity") {
val modified = setOf(
serverGroupEast.copy(name = activeServerGroupResponseEast.name),
serverGroupWest.copy(name = activeServerGroupResponseWest.name).withDoubleCapacity()
)
val diff = DefaultResourceDiff(
serverGroups.byRegion(),
modified.byRegion()
)
test("annealing resizes the current server group with no stagger") {
val slot = slot<OrchestrationRequest>()
every { orcaService.orchestrate(resource.serviceAccount, capture(slot)) } answers { TaskRefResponse(ULID().nextULID()) }
runBlocking {
upsert(resource, diff)
}
expectThat(slot.captured.job.first()) {
get("type").isEqualTo("resizeServerGroup")
get("capacity").isEqualTo(
spec.resolveCapacity("us-west-2").let {
mapOf(
"min" to it.min,
"max" to it.max,
"desired" to it.desired
)
}
)
get("serverGroupName").isEqualTo(activeServerGroupResponseWest.asg.autoScalingGroupName)
}
}
}
context("the diff is only in scaling policies missing from current") {
val modified = setOf(
serverGroupEast.copy(name = activeServerGroupResponseEast.name),
serverGroupWest.copy(name = activeServerGroupResponseWest.name).withNoScalingPolicies()
)
val diff = DefaultResourceDiff(
serverGroups.byRegion(),
modified.byRegion()
)
test("annealing only upserts scaling policies on the current server group") {
val slot = slot<OrchestrationRequest>()
every { orcaService.orchestrate(resource.serviceAccount, capture(slot)) } answers { TaskRefResponse(ULID().nextULID()) }
val metricSpec = serverGroupWest.scaling.targetTrackingPolicies.first().customMetricSpec!!
runBlocking {
upsert(resource, diff)
}
expectThat(slot.captured.job.size).isEqualTo(1)
expectThat(slot.captured.job.first()) {
get("type").isEqualTo("upsertScalingPolicy")
get("targetTrackingConfiguration")
.isA<Map<String, Any?>>()
.get {
expectThat(get("targetValue"))
.isA<Double>()
.isEqualTo(560.0)
expectThat(get("disableScaleIn"))
.isA<Boolean>()
.isTrue()
expectThat(get("customizedMetricSpecification"))
.isA<CustomizedMetricSpecificationModel>()
.isEqualTo(
CustomizedMetricSpecificationModel(
metricName = metricSpec.name,
namespace = metricSpec.namespace,
statistic = metricSpec.statistic
)
)
}
}
}
}
context("the diff is only that deployed scaling policies are no longer desired") {
val modified = setOf(
serverGroupEast.copy(name = activeServerGroupResponseEast.name),
serverGroupWest.copy(name = activeServerGroupResponseWest.name).withNoScalingPolicies()
)
val diff = DefaultResourceDiff(
modified.byRegion(),
serverGroups.byRegion()
)
test("annealing only deletes policies from the current server group") {
val slot = slot<OrchestrationRequest>()
every { orcaService.orchestrate(resource.serviceAccount, capture(slot)) } answers { TaskRefResponse(ULID().nextULID()) }
runBlocking {
upsert(resource, diff)
}
expectThat(slot.captured.job.size).isEqualTo(1)
expectThat(slot.captured.job.first()) {
get("type").isEqualTo("deleteScalingPolicy")
get("policyName").isEqualTo(targetTrackingPolicyName)
}
}
}
context("only an existing scaling policy has been modified") {
val modified = setOf(
serverGroupEast.copy(name = activeServerGroupResponseEast.name),
serverGroupWest.copy(
name = activeServerGroupResponseWest.name,
scaling = serverGroupWest.scaling.copy(
targetTrackingPolicies = setOf(
serverGroupWest.scaling.targetTrackingPolicies
.first()
.copy(targetValue = 42.0)
)
)
)
)
val diff = DefaultResourceDiff(
modified.byRegion(),
serverGroups.byRegion()
)
test("the modified policy is applied in two phases via one task") {
val slot = slot<OrchestrationRequest>()
every { orcaService.orchestrate(resource.serviceAccount, capture(slot)) } answers { TaskRefResponse(ULID().nextULID()) }
runBlocking {
upsert(resource, diff)
}
expectThat(slot.captured.job.size).isEqualTo(2)
expectThat(slot.captured.job.first()) {
get("refId").isEqualTo("1")
get("requisiteStageRefIds")
.isA<List<String>>()
.isEqualTo(emptyList())
get("type").isEqualTo("deleteScalingPolicy")
get("policyName").isEqualTo(targetTrackingPolicyName)
}
expectThat(slot.captured.job[1]) {
get("refId").isEqualTo("2")
get("requisiteStageRefIds")
.isA<List<String>>()
.isEqualTo(listOf("1"))
get("type").isEqualTo("upsertScalingPolicy")
get("targetTrackingConfiguration")
.isA<Map<String, Any?>>()["targetValue"]
.isEqualTo(42.0)
}
}
}
context("the diff is only in capacity and scaling policies") {
val modified = setOf(
serverGroupEast.copy(name = activeServerGroupResponseEast.name),
serverGroupWest.copy(name = activeServerGroupResponseWest.name)
.withDoubleCapacity()
.withNoScalingPolicies()
)
val diff = DefaultResourceDiff(
serverGroups.byRegion(),
modified.byRegion()
)
test("annealing resizes and modifies scaling policies in-place on the current server group") {
val slot = slot<OrchestrationRequest>()
every { orcaService.orchestrate(resource.serviceAccount, capture(slot)) } answers { TaskRefResponse(ULID().nextULID()) }
runBlocking {
upsert(resource, diff)
}
expectThat(slot.captured.job.size).isEqualTo(2)
expectThat(slot.captured.job.first()) {
get("refId").isEqualTo("1")
get("type").isEqualTo("resizeServerGroup")
}
expectThat(slot.captured.job[1]) {
get("refId").isEqualTo("2")
get("type").isEqualTo("upsertScalingPolicy")
get("targetTrackingConfiguration")
.isA<Map<String, Any?>>()["targetValue"]
.isEqualTo(560.0)
}
}
}
context("the diff is something other than just capacity or scaling policies") {
val modified = setOf(
serverGroupEast.copy(name = activeServerGroupResponseEast.name),
serverGroupWest.copy(name = activeServerGroupResponseWest.name)
.withDoubleCapacity()
.withDifferentInstanceType()
)
val diff = DefaultResourceDiff(
serverGroups.byRegion(),
modified.byRegion()
)
test("an artifact deploying event fires when upserting the cluster") {
val slot = slot<OrchestrationRequest>()
every { orcaService.orchestrate(resource.serviceAccount, capture(slot)) } answers { TaskRefResponse(ULID().nextULID()) }
runBlocking {
upsert(resource, diff)
}
verify { publisher.publishEvent(ArtifactVersionDeploying(resource.id, "keel-0.287.0-h208.fe2e8a1")) }
}
test("annealing clones the current server group") {
val slot = slot<OrchestrationRequest>()
every { orcaService.orchestrate(resource.serviceAccount, capture(slot)) } answers { TaskRefResponse(ULID().nextULID()) }
runBlocking {
upsert(resource, diff)
}
expectThat(slot.captured.job.first()) {
get("type").isEqualTo("createServerGroup")
get("source").isEqualTo(
mapOf(
"account" to activeServerGroupResponseWest.accountName,
"region" to activeServerGroupResponseWest.region,
"asgName" to activeServerGroupResponseWest.asg.autoScalingGroupName
)
)
}
}
test("the default deploy strategy is used") {
val slot = slot<OrchestrationRequest>()
every { orcaService.orchestrate(resource.serviceAccount, capture(slot)) } answers { TaskRefResponse(ULID().nextULID()) }
val deployWith = RedBlack()
runBlocking {
upsert(resource, diff)
}
expectThat(slot.captured.job.first()) {
get("strategy").isEqualTo("redblack")
get("delayBeforeDisableSec").isEqualTo(deployWith.delayBeforeDisable?.seconds)
get("delayBeforeScaleDownSec").isEqualTo(deployWith.delayBeforeScaleDown?.seconds)
get("rollback").isA<Map<String, Any?>>().get("onFailure").isEqualTo(deployWith.rollbackOnFailure)
get("scaleDown").isEqualTo(deployWith.resizePreviousToZero)
get("maxRemainingAsgs").isEqualTo(deployWith.maxServerGroups)
}
}
test("the deploy strategy is configured") {
val slot = slot<OrchestrationRequest>()
every { orcaService.orchestrate(resource.serviceAccount, capture(slot)) } answers { TaskRefResponse(ULID().nextULID()) }
val deployWith = RedBlack(
resizePreviousToZero = true,
delayBeforeDisable = Duration.ofMinutes(1),
delayBeforeScaleDown = Duration.ofMinutes(5),
maxServerGroups = 3
)
runBlocking {
upsert(resource.copy(spec = resource.spec.copy(deployWith = deployWith)), diff)
}
expectThat(slot.captured.job.first()) {
get("strategy").isEqualTo("redblack")
get("delayBeforeDisableSec").isEqualTo(deployWith.delayBeforeDisable?.seconds)
get("delayBeforeScaleDownSec").isEqualTo(deployWith.delayBeforeScaleDown?.seconds)
get("rollback").isA<Map<String, Any?>>().get("onFailure").isEqualTo(deployWith.rollbackOnFailure)
get("scaleDown").isEqualTo(deployWith.resizePreviousToZero)
get("maxRemainingAsgs").isEqualTo(deployWith.maxServerGroups)
}
}
test("the cluster does not use discovery-based health during deployment") {
val slot = slot<OrchestrationRequest>()
every { orcaService.orchestrate(resource.serviceAccount, capture(slot)) } answers { TaskRefResponse(ULID().nextULID()) }
val deployWith = RedBlack(health = NONE)
runBlocking {
upsert(resource.copy(spec = resource.spec.copy(deployWith = deployWith)), diff)
}
expectThat(slot.captured.job.first()) {
get("strategy").isEqualTo("redblack")
get("interestingHealthProviderNames").isA<List<String>>().containsExactly("Amazon")
}
}
test("the cluster uses discovery-based health during deployment") {
val slot = slot<OrchestrationRequest>()
every { orcaService.orchestrate(resource.serviceAccount, capture(slot)) } answers { TaskRefResponse(ULID().nextULID()) }
val deployWith = RedBlack(health = AUTO)
runBlocking {
upsert(resource.copy(spec = resource.spec.copy(deployWith = deployWith)), diff)
}
expectThat(slot.captured.job.first()) {
get("strategy").isEqualTo("redblack")
get("interestingHealthProviderNames").isNull()
}
}
test("a different deploy strategy is used") {
val slot = slot<OrchestrationRequest>()
every { orcaService.orchestrate(resource.serviceAccount, capture(slot)) } answers { TaskRefResponse(ULID().nextULID()) }
runBlocking {
upsert(resource.copy(spec = resource.spec.copy(deployWith = Highlander())), diff)
}
expectThat(slot.captured.job.first()) {
get("strategy").isEqualTo("highlander")
not().containsKey("delayBeforeDisableSec")
not().containsKey("delayBeforeScaleDownSec")
not().containsKey("rollback")
not().containsKey("scaleDown")
not().containsKey("maxRemainingAsgs")
}
}
}
context("multiple server groups have a diff") {
val modified = setOf(
serverGroupEast.copy(name = activeServerGroupResponseEast.name).withDifferentInstanceType(),
serverGroupWest.copy(name = activeServerGroupResponseWest.name).withDoubleCapacity()
)
val diff = DefaultResourceDiff(
serverGroups.byRegion(),
modified.byRegion()
)
test("annealing launches one task per server group") {
val tasks = mutableListOf<OrchestrationRequest>()
every { orcaService.orchestrate(any(), capture(tasks)) } answers { TaskRefResponse(ULID().nextULID()) }
runBlocking {
upsert(resource, diff)
}
expectThat(tasks)
.hasSize(2)
.map { it.job.first()["type"] }
.containsExactlyInAnyOrder("createServerGroup", "resizeServerGroup")
}
test("each task has a distinct correlation id") {
val tasks = mutableListOf<OrchestrationRequest>()
every { orcaService.orchestrate(any(), capture(tasks)) } answers { TaskRefResponse(ULID().nextULID()) }
runBlocking {
upsert(resource, diff)
}
expectThat(tasks)
.hasSize(2)
.map { it.trigger.correlationId }
.containsDistinctElements()
}
}
context("nothing currently deployed, desired state is single region deployment") {
fun diff(instanceType: String) =
DefaultResourceDiff(
desired=clusterSpec(instanceType).resolve().filter {it.location.region == "us-west-2"}.byRegion(),
current=emptyMap()
)
test("supported instance type for setting EBS volume type") {
val slot = slot<OrchestrationRequest>()
every { orcaService.orchestrate(resource.serviceAccount, capture(slot)) } answers { TaskRefResponse(ULID().nextULID()) }
val instanceType = "m5.large"
runBlocking {
upsert(resource, diff(instanceType))
}
expectThat(slot.captured.job.first()) {
get("type").isEqualTo("createServerGroup")
get("blockDevices")
.isNotNull()
.isA<List<Map<String, Any>>>()
.hasSize(1)
.all {
get("volumeType").isEqualTo("gp2")
get("size").isEqualTo(40)
}
}
}
test("unsupported instance type for setting EBS volume type") {
val slot = slot<OrchestrationRequest>()
every { orcaService.orchestrate(resource.serviceAccount, capture(slot)) } answers { TaskRefResponse(ULID().nextULID()) }
val instanceType = "c1.medium"
runBlocking {
upsert(resource, diff(instanceType))
}
expectThat(slot.captured.job.first()) {
get("type").isEqualTo("createServerGroup")
get("blockDevices").isNull()
}
}
}
}
}
private suspend fun CloudDriverService.activeServerGroup(user: String, region: String) = activeServerGroup(
user = user,
app = spec.moniker.app,
account = spec.locations.account,
cluster = spec.moniker.toString(),
region = region,
cloudProvider = CLOUD_PROVIDER
)
}
private fun <E, T : Iterable<E>> Assertion.Builder<T>.containsDistinctElements() =
assert("contains distinct elements") { subject ->
val duplicates = subject
.associateWith { elem -> subject.count { it == elem } }
.filterValues { it > 1 }
.keys
when (duplicates.size) {
0 -> pass()
1 -> fail(duplicates.first(), "The element %s occurs more than once")
else -> fail(duplicates, "The elements %s occur more than once")
}
}
private fun ServerGroup.withDoubleCapacity(): ServerGroup =
copy(
capacity = Capacity(
min = capacity.min * 2,
max = capacity.max * 2,
desired = when (capacity.desired) {
null -> null
else -> capacity.desired!! * 2
}
)
)
private fun ServerGroup.withNoScalingPolicies(): ServerGroup =
copy(scaling = Scaling(), capacity = capacity.copy(desired = capacity.max))
private fun ServerGroup.withDifferentInstanceType(): ServerGroup =
copy(
launchConfiguration = launchConfiguration.copy(
instanceType = "r4.16xlarge"
)
)
private fun ServerGroup.withMissingAppVersion(): ServerGroup =
copy(
launchConfiguration = launchConfiguration.copy(
appVersion = null
)
)
private fun ActiveServerGroup.withOlderAppVersion(): ActiveServerGroup =
copy(
image = image.copy(
imageId = "ami-573e1b2650a5",
appVersion = "keel-0.251.0-h167.9ea0465"
),
launchConfig = launchConfig?.copy(
imageId = "ami-573e1b2650a5"
)
)
private fun ActiveServerGroup.withMissingAppVersion(): ActiveServerGroup =
copy(
image = image.copy(
imageId = "ami-573e1b2650a5",
appVersion = null
)
)
| 4 | null | 144 | 99 | 6115964c42e863cfd269616a836145b883f165f3 | 44,280 | keel | Apache License 2.0 |
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsintegrationevents/services/IntegrationEventTopicServiceTests.kt | ministryofjustice | 772,145,800 | false | {"Kotlin": 160570, "Shell": 3805, "Dockerfile": 1150, "Makefile": 154} | package uk.gov.justice.digital.hmpps.hmppsintegrationevents.services
import com.fasterxml.jackson.databind.ObjectMapper
import io.kotest.matchers.shouldBe
import net.javacrumbs.jsonunit.assertj.JsonAssertions
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.mockito.Mockito.mock
import org.mockito.kotlin.any
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.json.JsonTest
import org.springframework.test.context.ActiveProfiles
import software.amazon.awssdk.services.sns.SnsAsyncClient
import software.amazon.awssdk.services.sns.model.ListSubscriptionsByTopicRequest
import software.amazon.awssdk.services.sns.model.ListSubscriptionsByTopicResponse
import software.amazon.awssdk.services.sns.model.MessageAttributeValue
import software.amazon.awssdk.services.sns.model.PublishRequest
import software.amazon.awssdk.services.sns.model.SetSubscriptionAttributesRequest
import software.amazon.awssdk.services.sns.model.Subscription
import uk.gov.justice.digital.hmpps.hmppsintegrationevents.models.enums.EventTypeValue
import uk.gov.justice.digital.hmpps.hmppsintegrationevents.repository.model.data.EventNotification
import uk.gov.justice.hmpps.sqs.HmppsQueue
import uk.gov.justice.hmpps.sqs.HmppsQueueService
import uk.gov.justice.hmpps.sqs.HmppsTopic
import java.time.LocalDateTime
import java.util.concurrent.CompletableFuture
@ActiveProfiles("test")
@JsonTest
class IntegrationEventTopicServiceTests(@Autowired private val objectMapper: ObjectMapper) {
val hmppsQueueService: HmppsQueueService = mock()
val hmppsEventSnsClient: SnsAsyncClient = mock()
val deadLetterQueueService: DeadLetterQueueService = mock()
val mockQueue: HmppsQueue = mock()
private lateinit var service: IntegrationEventTopicService
val currentTime = LocalDateTime.now()
@BeforeEach
fun setUp() {
whenever(hmppsQueueService.findByTopicId("integrationeventtopic"))
.thenReturn(HmppsTopic("integrationeventtopic", "sometopicarn", hmppsEventSnsClient))
whenever(hmppsQueueService.findByQueueId("mockQueue")).thenReturn(mockQueue)
whenever(mockQueue.queueArn).thenReturn("mockARN")
service = IntegrationEventTopicService(hmppsQueueService, deadLetterQueueService, objectMapper)
}
@Test
fun `Publish Event `() {
val event = EventNotification(123, "hmppsId", EventTypeValue.ADDRESS_CHANGE, "mockUrl", currentTime)
service.sendEvent(event)
argumentCaptor<PublishRequest>().apply {
verify(hmppsEventSnsClient, times(1)).publish(capture())
val payload = firstValue.message()
val messageAttributes = firstValue.messageAttributes()
JsonAssertions.assertThatJson(payload).node("eventType").isEqualTo(event.eventType.name)
JsonAssertions.assertThatJson(payload).node("hmppsId").isEqualTo(event.hmppsId)
JsonAssertions.assertThatJson(payload).node("url").isEqualTo(event.url)
Assertions.assertThat(messageAttributes["eventType"])
.isEqualTo(MessageAttributeValue.builder().stringValue(event.eventType.name).dataType("String").build())
}
}
@Test
fun `Put event into dlq if failed to publish message`() {
val event = EventNotification(123, "hmppsId", EventTypeValue.ADDRESS_CHANGE, "mockUrl", currentTime)
whenever(hmppsEventSnsClient.publish(any<PublishRequest>())).thenThrow(RuntimeException("MockError"))
service.sendEvent(event)
val eventCapture = argumentCaptor<EventNotification>()
val stringCapture = argumentCaptor<String>()
verify(deadLetterQueueService, times(1)).sendEvent(eventCapture.capture(), stringCapture.capture())
val payload = eventCapture.firstValue
Assertions.assertThat(payload.eventType).isEqualTo(event.eventType)
Assertions.assertThat(payload.hmppsId).isEqualTo(event.hmppsId)
Assertions.assertThat(payload.url).isEqualTo(event.url)
Assertions.assertThat(stringCapture.firstValue).isEqualTo("MockError")
}
@Test
fun `Update Subscription Attributes`() {
val mockSubs = listOf(Subscription.builder().protocol("sqs").endpoint("mockARN").subscriptionArn("mockSubscriptionArn").build())
whenever(hmppsEventSnsClient.listSubscriptionsByTopic(any<ListSubscriptionsByTopicRequest>()))
.thenReturn(
CompletableFuture.completedFuture(
ListSubscriptionsByTopicResponse
.builder()
.subscriptions(mockSubs)
.build(),
),
)
service.updateSubscriptionAttributes("mockQueue", "AttriName", "mockValue")
argumentCaptor<SetSubscriptionAttributesRequest>().apply {
verify(hmppsEventSnsClient, times(1)).setSubscriptionAttributes(capture())
Assertions.assertThat("mockSubscriptionArn").isEqualTo(firstValue.subscriptionArn())
Assertions.assertThat("AttriName").isEqualTo(firstValue.attributeName())
Assertions.assertThat("mockValue").isEqualTo(firstValue.attributeValue())
}
}
@Test
fun`Get subscription arn for given queue name`() {
val mockSubs = listOf(Subscription.builder().protocol("sqs").endpoint("mockARN").subscriptionArn("mockSubscriptionArn").build())
whenever(hmppsEventSnsClient.listSubscriptionsByTopic(any<ListSubscriptionsByTopicRequest>()))
.thenReturn(
CompletableFuture.completedFuture(
ListSubscriptionsByTopicResponse
.builder()
.subscriptions(mockSubs)
.build(),
),
)
val result = service.getSubscriptionArnByQueueName("mockQueue")
argumentCaptor<ListSubscriptionsByTopicRequest>().apply {
verify(hmppsEventSnsClient, times(1)).listSubscriptionsByTopic(capture())
Assertions.assertThat("sometopicarn").isEqualTo(firstValue.topicArn())
}
result.shouldBe("mockSubscriptionArn")
}
}
| 1 | Kotlin | 0 | 0 | 6ee5acea4cfdda529d415d05d6073fdeac3602c5 | 5,962 | hmpps-integration-events | MIT License |
app/src/main/java/com/bridou_n/beaconscanner/models/BeaconSaved.kt | Bridouille | 69,493,556 | false | null | package com.bridou_n.beaconscanner.models
import android.text.format.DateUtils
import androidx.room.ColumnInfo
import androidx.room.Embedded
import androidx.room.Entity
import com.bridou_n.beaconscanner.Database.BeaconsDao
import com.bridou_n.beaconscanner.utils.BuildTypes
import com.bridou_n.beaconscanner.utils.RuuviParser
import com.google.gson.GsonBuilder
import com.google.gson.annotations.SerializedName
import org.altbeacon.beacon.Beacon
import org.altbeacon.beacon.utils.UrlBeaconUrlCompressor
import java.lang.IllegalStateException
import java.util.*
/**
* Created by bridou_n on 30/09/2016.
*/
@Entity(
tableName = BeaconsDao.TABLE_NAME,
primaryKeys = [
"hashcode"
]
)
data class BeaconSaved(
@SerializedName("hashcode")
@ColumnInfo(name = "hashcode")
val hashcode: Int = 0, // hashcode()
@SerializedName("beacon_type")
@ColumnInfo(name = "beacon_type")
val beaconType: String? = null, // Eddystone, altBeacon, iBeacon
@SerializedName("beacon_address")
@ColumnInfo(name = "beacon_address")
val beaconAddress: String? = null, // MAC address of the bluetooth emitter
@SerializedName("manufacturer")
@ColumnInfo(name = "manufacturer")
val manufacturer: Int = 0,
@SerializedName("tx_power")
@ColumnInfo(name = "tx_power")
val txPower: Int = 0,
@SerializedName("rssi")
@ColumnInfo(name = "rssi")
val rssi: Int = 0,
@SerializedName("distance")
@ColumnInfo(name = "distance")
val distance: Double = 0.toDouble(),
@SerializedName("last_seen")
@ColumnInfo(name = "last_seen")
val lastSeen: Long = 0,
/**
* Specialized field for every beacon type
*/
@SerializedName("ibeacon_data")
@Embedded(prefix = "ibeacon_data_")
val ibeaconData: IbeaconData? = null,
@SerializedName("eddystone_url_data")
@Embedded(prefix = "eddystone_url_data_")
val eddystoneUrlData: EddystoneUrlData? = null,
@SerializedName("eddystoneUidData")
@Embedded(prefix = "eddystone_uid_data_")
val eddystoneUidData: EddystoneUidData? = null,
@SerializedName("telemetry_data")
@Embedded(prefix = "telemetry_data_")
val telemetryData: TelemetryData? = null,
@SerializedName("ruuvi_data")
@Embedded(prefix = "ruuvi_data_")
val ruuviData: RuuviData? = null,
@ColumnInfo(name = "is_blocked")
val isBlocked: Boolean = false
) {
companion object {
const val TYPE_EDDYSTONE_UID = "eddystone_uid"
const val TYPE_EDDYSTONE_URL = "eddystone_url"
const val TYPE_ALTBEACON = "altbeacon"
const val TYPE_IBEACON = "ibeacon"
const val TYPE_RUUVITAG = "ruuvitag"
fun createFromBeacon(beacon: Beacon, isBlocked: Boolean = false) : BeaconSaved {
// Common fields to every beacons
var hashcode = beacon.hashCode()
val lastSeen = Date().time
val beaconAddress = beacon.bluetoothAddress
val manufacturer = beacon.manufacturer
val rssi = beacon.rssi
val txPower = beacon.txPower
val distance = if (beacon.distance.isInfinite()) {
(-1).toDouble()
} else {
beacon.distance
}
var beaconType: String? = null
var ibeaconData: IbeaconData? = null
var eddystoneUrlData: EddystoneUrlData? = null
var eddystoneUidData: EddystoneUidData? = null
var telemetryData: TelemetryData? = null
var ruuviData: RuuviData? = null
if (beacon.serviceUuid == 0xFEAA) { // This is an Eddystone format
// Do we have telemetry data?
if (beacon.extraDataFields.size >= 5) {
telemetryData = TelemetryData(beacon.extraDataFields[0],
beacon.extraDataFields[1],
TelemetryData.getTemperatureFromTlmField(beacon.extraDataFields[2].toFloat()),
beacon.extraDataFields[3],
beacon.extraDataFields[4])
}
when (beacon.beaconTypeCode) {
0x00 -> { // This is a Eddystone-UID frame
beaconType = TYPE_EDDYSTONE_UID
eddystoneUidData = EddystoneUidData(beacon.id1.toString(), beacon.id2.toString())
}
0x10 -> { // This is a Eddystone-URL frame
beaconType = TYPE_EDDYSTONE_URL
val url = UrlBeaconUrlCompressor.uncompress(beacon.id1.toByteArray())
eddystoneUrlData = EddystoneUrlData(url)
if (url?.startsWith("https://ruu.vi/#") == true) { // This is a RuuviTag
val hash = url.split("#").get(1)
// We manually set the hashcode of the RuuviTag so it only appears once per address
hashcode = beaconAddress?.hashCode() ?: -1
beaconType = TYPE_RUUVITAG
val ruuviParser = RuuviParser(hash)
ruuviData = RuuviData(ruuviParser.humidity, ruuviParser.airPressure, ruuviParser.temp)
}
}
}
} else { // This is an iBeacon or ALTBeacon
beaconType = if (beacon.beaconTypeCode == 0xBEAC) TYPE_ALTBEACON else TYPE_IBEACON // 0x4c000215 is iBeacon
ibeaconData = IbeaconData(beacon.id1.toString(), beacon.id2.toString(), beacon.id3.toString())
}
return BeaconSaved(
hashcode = hashcode,
lastSeen = lastSeen,
manufacturer = manufacturer,
rssi = rssi,
txPower = txPower,
distance = distance,
beaconType = beaconType,
ibeaconData = ibeaconData,
eddystoneUrlData = eddystoneUrlData,
eddystoneUidData = eddystoneUidData,
telemetryData = telemetryData,
ruuviData = ruuviData,
isBlocked = isBlocked
)
}
fun eddystoneUidSample() : BeaconSaved {
check(!BuildTypes.isRelease()) { "Only use this for debugging purposes" }
return BeaconSaved(
hashcode = UUID.randomUUID().hashCode(),
beaconType = TYPE_EDDYSTONE_UID,
beaconAddress = "74:FC:B0:45:0B:02",
manufacturer = 0xFEAA,
txPower = -63,
rssi = -38,
distance = 0.02,
lastSeen = Date().time - 40 * DateUtils.SECOND_IN_MILLIS,
eddystoneUidData = EddystoneUidData(
namespaceId = "0x00010203040506070809",
instanceId = "0xabcdefabcdef"
),
telemetryData = TelemetryData(
batteryMilliVolts = 400,
temperature = 40.7F,
pduCount = 654,
uptime = 32
)
)
}
fun eddystoneUrlSample() : BeaconSaved {
check(!BuildTypes.isRelease()) { "Only use this for debugging purposes" }
return BeaconSaved(
hashcode = UUID.randomUUID().hashCode(),
beaconType = TYPE_EDDYSTONE_URL,
beaconAddress = "74:FC:B0:45:0B:02",
manufacturer = 0xFEAA,
txPower = -63,
rssi = -38,
distance = 0.02,
lastSeen = Date().time - 40 * DateUtils.SECOND_IN_MILLIS,
eddystoneUrlData = EddystoneUrlData(
url = "http://example.com"
),
telemetryData = TelemetryData(
batteryMilliVolts = 500,
temperature = 42.5F,
pduCount = 211345,
uptime = 5234
)
)
}
fun iBeaconSample() : BeaconSaved {
check(!BuildTypes.isRelease()) { "Only use this for debugging purposes" }
return BeaconSaved(
hashcode = UUID.randomUUID().hashCode(),
beaconType = TYPE_IBEACON,
beaconAddress = "74:FC:B0:45:0B:02",
manufacturer = 0x004C,
txPower = -63,
rssi = -38,
distance = 0.02,
lastSeen = Date().time - 40 * DateUtils.SECOND_IN_MILLIS,
ibeaconData = IbeaconData(
uuid = UUID.randomUUID().toString(),
major = "1",
minor = "602"
)
)
}
fun altBeaconSample() : BeaconSaved {
check(!BuildTypes.isRelease()) { "Only use this for debugging purposes" }
return BeaconSaved(
hashcode = UUID.randomUUID().hashCode(),
beaconType = TYPE_ALTBEACON,
beaconAddress = "74:FC:B0:45:0B:02",
manufacturer = 0x0118,
txPower = -63,
rssi = -38,
distance = 0.02,
lastSeen = Date().time - 40 * DateUtils.SECOND_IN_MILLIS,
ibeaconData = IbeaconData(
uuid = UUID.randomUUID().toString(),
major = "2",
minor = "342"
)
)
}
fun ruuviTagSample() : BeaconSaved {
check(!BuildTypes.isRelease()) { "Only use this for debugging purposes" }
return BeaconSaved(
hashcode = UUID.randomUUID().hashCode(),
beaconType = TYPE_RUUVITAG,
beaconAddress = "77:CC:B7:45:0B:02",
manufacturer = 0xFEAA,
txPower = -63,
rssi = -38,
distance = 0.02,
lastSeen = Date().time - 40 * DateUtils.SECOND_IN_MILLIS,
ruuviData = RuuviData(
humidity = 66,
airPressure = 722,
temperatue = 22
)
)
}
}
fun toJson(): String {
return GsonBuilder().setPrettyPrinting().create().toJson(this)
}
}
| 9 | Kotlin | 104 | 320 | 2093c24a70b696e2d2ee7c06f4bcf210aefdeb52 | 10,452 | android-beacon-scanner | Apache License 2.0 |
app/src/main/java/com/example/noteapp/features/note/domain/usecases/AddNoteUseCase.kt | nguyencse | 611,364,219 | false | null | package com.example.noteapp.features.note.domain.usecases
import com.example.noteapp.features.note.domain.entities.InvalidNoteException
import com.example.noteapp.features.note.domain.entities.Note
import com.example.noteapp.features.note.domain.repositories.NoteRepository
class AddNoteUseCase(private val repository: NoteRepository) {
@Throws(InvalidNoteException::class)
suspend operator fun invoke(note: Note) {
if (note.title.isBlank()) {
throw InvalidNoteException("The title of the note can't be empty.")
} else if (note.content.isBlank()) {
throw InvalidNoteException("The content of the note can't be empty.")
}
repository.insertNote(note)
}
} | 0 | Kotlin | 0 | 0 | 85d467406fe889fe2edb0bbab882a18ab0710906 | 723 | NoteApp | Apache License 2.0 |
src/main/kotlin/org/jitsi/jibri/selenium/pageobjects/AbstractPageObject.kt | jitsi | 51,473,177 | false | null | /*
* Copyright @ 2018 Atlassian Pty Ltd
*
* 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.jitsi.jibri.selenium.pageobjects
import org.jitsi.utils.logging2.createLogger
import org.openqa.selenium.remote.RemoteWebDriver
import kotlin.time.measureTime
/**
* [AbstractPageObject] is a page object class containing logic common to
* all page object instances
*/
open class AbstractPageObject(protected val driver: RemoteWebDriver) {
private val logger = createLogger()
open fun visit(url: String): Boolean {
logger.info("Visiting url $url")
val totalTime = measureTime {
driver.get(url)
}
logger.info("Waited $totalTime for driver to load page")
return true
}
}
| 82 | null | 313 | 609 | bdf9fc5e676f8629708e5ccd68406ca00258e712 | 1,258 | jibri | Apache License 2.0 |
samples/app/gallery/src/main/java/com/badoo/ribs/samples/gallery/rib/other/picker/OtherPickerBuilder.kt | badoo | 170,855,556 | false | null | package com.badoo.ribs.samples.gallery.rib.other.picker
import com.badoo.ribs.builder.SimpleBuilder
import com.badoo.ribs.core.modality.BuildParams
class OtherPickerBuilder(
private val dependency: OtherPicker.Dependency
) : SimpleBuilder<OtherPicker>() {
override fun build(buildParams: BuildParams<Nothing?>): OtherPicker {
val customisation = buildParams.getOrDefault(OtherPicker.Customisation())
val interactor = interactor(buildParams)
return node(buildParams, customisation, interactor)
}
private fun interactor(
buildParams: BuildParams<*>,
) = OtherPickerInteractor(
buildParams = buildParams,
)
private fun node(
buildParams: BuildParams<Nothing?>,
customisation: OtherPicker.Customisation,
interactor: OtherPickerInteractor
) = OtherPickerNode(
buildParams = buildParams,
viewFactory = customisation.viewFactory(null),
plugins = listOf(
interactor
)
)
}
| 34 | null | 50 | 162 | cec2ca936ed17ddd7720b4b7f8fca4ce12033a89 | 1,046 | RIBs | Apache License 2.0 |
tabler-icons/src/commonMain/kotlin/compose/icons/tablericons/Polaroid.kt | DevSrSouza | 311,134,756 | false | {"Kotlin": 36719092} | package compose.icons.tablericons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
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.TablerIcons
public val TablerIcons.Polaroid: ImageVector
get() {
if (_polaroid != null) {
return _polaroid!!
}
_polaroid = Builder(name = "Polaroid", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(6.0f, 4.0f)
lineTo(18.0f, 4.0f)
arcTo(2.0f, 2.0f, 0.0f, false, true, 20.0f, 6.0f)
lineTo(20.0f, 18.0f)
arcTo(2.0f, 2.0f, 0.0f, false, true, 18.0f, 20.0f)
lineTo(6.0f, 20.0f)
arcTo(2.0f, 2.0f, 0.0f, false, true, 4.0f, 18.0f)
lineTo(4.0f, 6.0f)
arcTo(2.0f, 2.0f, 0.0f, false, true, 6.0f, 4.0f)
close()
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(4.0f, 16.0f)
lineTo(20.0f, 16.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(4.0f, 12.0f)
lineToRelative(3.0f, -3.0f)
curveToRelative(0.928f, -0.893f, 2.072f, -0.893f, 3.0f, 0.0f)
lineToRelative(4.0f, 4.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(13.0f, 12.0f)
lineToRelative(2.0f, -2.0f)
curveToRelative(0.928f, -0.893f, 2.072f, -0.893f, 3.0f, 0.0f)
lineToRelative(2.0f, 2.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(14.0f, 7.0f)
lineTo(14.01f, 7.0f)
}
}
.build()
return _polaroid!!
}
private var _polaroid: ImageVector? = null
| 17 | Kotlin | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 3,503 | compose-icons | MIT License |
bitgouel-domain/src/main/kotlin/team/msg/domain/user/repository/custom/CustomUserRepository.kt | GSM-MSG | 700,741,727 | false | {"Kotlin": 232884, "Shell": 788, "Dockerfile": 206} | package team.msg.domain.user.repository.custom
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import team.msg.domain.user.enums.Authority
import team.msg.domain.user.model.User
interface CustomUserRepository {
fun query(keyword: String, authority: Authority, pageable: Pageable): Page<User>
} | 5 | Kotlin | 0 | 11 | 620fbb7aa11c31994a314345092bcfa864792baf | 343 | Bitgouel-Server | MIT License |
app/src/androidTest/kotlin/io/github/hidroh/tldroid/CommandActivityTest.kt | hidroh | 48,721,927 | false | null | package io.github.hidroh.tldroid
import android.content.Intent
import android.support.test.InstrumentationRegistry
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.action.ViewActions.click
import android.support.test.espresso.intent.Intents.intended
import android.support.test.espresso.intent.matcher.ComponentNameMatchers.hasClassName
import android.support.test.espresso.intent.matcher.IntentMatchers.hasComponent
import android.support.test.espresso.intent.rule.IntentsTestRule
import android.support.test.espresso.matcher.ViewMatchers.withContentDescription
import android.support.test.espresso.matcher.ViewMatchers.withId
import android.support.test.espresso.web.assertion.WebViewAssertions.webContent
import android.support.test.espresso.web.matcher.DomMatchers.containingTextInBody
import android.support.test.espresso.web.sugar.Web.onWebView
import android.support.test.runner.AndroidJUnit4
import org.assertj.core.api.Assertions.assertThat
import org.junit.After
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class CommandActivityTest {
@Rule @JvmField
val intentsRule = IntentsTestRule<CommandActivity>(CommandActivity::class.java, false, false)
@Test
fun testRender() {
MarkdownProcessor.markdown = "<div>Blah</div>"
intentsRule.launchActivity(Intent().putExtra(CommandActivity.EXTRA_QUERY, "ls"))
onWebView(withId(R.id.web_view))
.forceJavascriptEnabled()
.check(webContent(containingTextInBody("Blah")))
}
@Test
fun testRunClick() {
MarkdownProcessor.markdown = "<div>Blah</div>"
intentsRule.launchActivity(Intent().putExtra(CommandActivity.EXTRA_QUERY, "ls"))
onView(withId(R.id.menu_run)).perform(click())
intended(hasComponent(hasClassName(RunActivity::class.java.name)))
}
@Test
fun testHomeClick() {
intentsRule.launchActivity(Intent().putExtra(CommandActivity.EXTRA_QUERY, "ls"))
onView(withContentDescription(InstrumentationRegistry.getTargetContext()
.getString(R.string.abc_action_bar_up_description)))
.perform(click())
assertThat(intentsRule.activity.isFinishing || intentsRule.activity.isDestroyed)
.isTrue()
}
@Test
fun testRenderNoContent() {
MarkdownProcessor.markdown = null
intentsRule.launchActivity(Intent().putExtra(CommandActivity.EXTRA_QUERY, "ls"))
onWebView(withId(R.id.web_view))
.forceJavascriptEnabled()
.check(webContent(containingTextInBody("This command is not yet available.")))
}
@Test
fun testStateRestoration() {
MarkdownProcessor.markdown = "<div>Blah</div>"
intentsRule.launchActivity(Intent().putExtra(CommandActivity.EXTRA_QUERY, "ls"))
MarkdownProcessor.markdown = ""
InstrumentationRegistry.getInstrumentation().runOnMainSync { intentsRule.activity.recreate() }
onWebView(withId(R.id.web_view))
.forceJavascriptEnabled()
.check(webContent(containingTextInBody("Blah")))
}
@After
fun tearDown() {
MarkdownProcessor.markdown = null
}
} | 6 | Kotlin | 15 | 129 | b33394e48ffcabb39d99ceb7c69fd56322ca8a68 | 3,085 | tldroid | Apache License 2.0 |
bootstrap-icons-compose/src/main/java/com/wiryadev/bootstrapiconscompose/bootstrapicons/filled/Calendar2Range.kt | wiryadev | 380,639,096 | false | null | package com.wiryadev.bootstrapiconscompose.bootstrapicons.filled
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 com.wiryadev.bootstrapiconscompose.bootstrapicons.FilledGroup
public val FilledGroup.Calendar2Range: ImageVector
get() {
if (_calendar2Range != null) {
return _calendar2Range!!
}
_calendar2Range = Builder(name = "Calendar2Range", defaultWidth = 16.0.dp, defaultHeight =
16.0.dp, viewportWidth = 16.0f, viewportHeight = 16.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(3.5f, 0.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.5f, 0.5f)
lineTo(4.0f, 1.0f)
horizontalLineToRelative(8.0f)
lineTo(12.0f, 0.5f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, 1.0f, 0.0f)
lineTo(13.0f, 1.0f)
horizontalLineToRelative(1.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, 2.0f)
verticalLineToRelative(11.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.0f, 2.0f)
lineTo(2.0f, 16.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.0f, -2.0f)
lineTo(0.0f, 3.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, -2.0f)
horizontalLineToRelative(1.0f)
lineTo(3.0f, 0.5f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.5f, -0.5f)
close()
moveTo(13.454f, 3.0f)
lineTo(2.545f, 3.0f)
curveToRelative(-0.3f, 0.0f, -0.545f, 0.224f, -0.545f, 0.5f)
verticalLineToRelative(1.0f)
curveToRelative(0.0f, 0.276f, 0.244f, 0.5f, 0.545f, 0.5f)
horizontalLineToRelative(10.91f)
curveToRelative(0.3f, 0.0f, 0.545f, -0.224f, 0.545f, -0.5f)
verticalLineToRelative(-1.0f)
curveToRelative(0.0f, -0.276f, -0.244f, -0.5f, -0.546f, -0.5f)
close()
moveTo(10.0f, 7.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.0f, 2.0f)
horizontalLineToRelative(5.0f)
lineTo(15.0f, 7.0f)
horizontalLineToRelative(-5.0f)
close()
moveTo(6.0f, 11.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, -1.0f, -1.0f)
lineTo(1.0f, 10.0f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(4.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 1.0f, -1.0f)
close()
}
}
.build()
return _calendar2Range!!
}
private var _calendar2Range: ImageVector? = null
| 0 | Kotlin | 0 | 2 | 1c199d953dc96b261aab16ac230dc7f01fb14a53 | 3,429 | bootstrap-icons-compose | MIT License |
app/src/main/java/ru/net2fox/trackerapp/data/model/Task.kt | Net2Fox | 560,577,851 | false | {"Kotlin": 26148} | package ru.net2fox.trackerapp.data.model
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.util.Date
@Entity(tableName = "tasks")
data class Task(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
var title: String,
var description: String?,
var isCompleted: Boolean = false,
var listId: Int
) | 0 | Kotlin | 0 | 0 | 728d4b50c14c05de11aaf3161be3430969815a24 | 337 | YATT | Apache License 2.0 |
app/src/main/java/ru/net2fox/trackerapp/data/model/Task.kt | Net2Fox | 560,577,851 | false | {"Kotlin": 26148} | package ru.net2fox.trackerapp.data.model
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.util.Date
@Entity(tableName = "tasks")
data class Task(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
var title: String,
var description: String?,
var isCompleted: Boolean = false,
var listId: Int
) | 0 | Kotlin | 0 | 0 | 728d4b50c14c05de11aaf3161be3430969815a24 | 337 | YATT | Apache License 2.0 |
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/kinesisanalyticsv2/CfnApplicationProps.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 149148378} | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.kinesisanalyticsv2
import io.cloudshiftdev.awscdk.CfnTag
import io.cloudshiftdev.awscdk.IResolvable
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import io.cloudshiftdev.awscdk.common.CdkObject
import kotlin.Any
import kotlin.String
import kotlin.Unit
import kotlin.collections.List
import kotlin.jvm.JvmName
/**
* Properties for defining a `CfnApplication`.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.kinesisanalyticsv2.*;
* CfnApplicationProps cfnApplicationProps = CfnApplicationProps.builder()
* .runtimeEnvironment("runtimeEnvironment")
* .serviceExecutionRole("serviceExecutionRole")
* // the properties below are optional
* .applicationConfiguration(ApplicationConfigurationProperty.builder()
* .applicationCodeConfiguration(ApplicationCodeConfigurationProperty.builder()
* .codeContent(CodeContentProperty.builder()
* .s3ContentLocation(S3ContentLocationProperty.builder()
* .bucketArn("bucketArn")
* .fileKey("fileKey")
* // the properties below are optional
* .objectVersion("objectVersion")
* .build())
* .textContent("textContent")
* .zipFileContent("zipFileContent")
* .build())
* .codeContentType("codeContentType")
* .build())
* .applicationSnapshotConfiguration(ApplicationSnapshotConfigurationProperty.builder()
* .snapshotsEnabled(false)
* .build())
* .environmentProperties(EnvironmentPropertiesProperty.builder()
* .propertyGroups(List.of(PropertyGroupProperty.builder()
* .propertyGroupId("propertyGroupId")
* .propertyMap(Map.of(
* "propertyMapKey", "propertyMap"))
* .build()))
* .build())
* .flinkApplicationConfiguration(FlinkApplicationConfigurationProperty.builder()
* .checkpointConfiguration(CheckpointConfigurationProperty.builder()
* .configurationType("configurationType")
* // the properties below are optional
* .checkpointingEnabled(false)
* .checkpointInterval(123)
* .minPauseBetweenCheckpoints(123)
* .build())
* .monitoringConfiguration(MonitoringConfigurationProperty.builder()
* .configurationType("configurationType")
* // the properties below are optional
* .logLevel("logLevel")
* .metricsLevel("metricsLevel")
* .build())
* .parallelismConfiguration(ParallelismConfigurationProperty.builder()
* .configurationType("configurationType")
* // the properties below are optional
* .autoScalingEnabled(false)
* .parallelism(123)
* .parallelismPerKpu(123)
* .build())
* .build())
* .sqlApplicationConfiguration(SqlApplicationConfigurationProperty.builder()
* .inputs(List.of(InputProperty.builder()
* .inputSchema(InputSchemaProperty.builder()
* .recordColumns(List.of(RecordColumnProperty.builder()
* .name("name")
* .sqlType("sqlType")
* // the properties below are optional
* .mapping("mapping")
* .build()))
* .recordFormat(RecordFormatProperty.builder()
* .recordFormatType("recordFormatType")
* // the properties below are optional
* .mappingParameters(MappingParametersProperty.builder()
* .csvMappingParameters(CSVMappingParametersProperty.builder()
* .recordColumnDelimiter("recordColumnDelimiter")
* .recordRowDelimiter("recordRowDelimiter")
* .build())
* .jsonMappingParameters(JSONMappingParametersProperty.builder()
* .recordRowPath("recordRowPath")
* .build())
* .build())
* .build())
* // the properties below are optional
* .recordEncoding("recordEncoding")
* .build())
* .namePrefix("namePrefix")
* // the properties below are optional
* .inputParallelism(InputParallelismProperty.builder()
* .count(123)
* .build())
* .inputProcessingConfiguration(InputProcessingConfigurationProperty.builder()
* .inputLambdaProcessor(InputLambdaProcessorProperty.builder()
* .resourceArn("resourceArn")
* .build())
* .build())
* .kinesisFirehoseInput(KinesisFirehoseInputProperty.builder()
* .resourceArn("resourceArn")
* .build())
* .kinesisStreamsInput(KinesisStreamsInputProperty.builder()
* .resourceArn("resourceArn")
* .build())
* .build()))
* .build())
* .vpcConfigurations(List.of(VpcConfigurationProperty.builder()
* .securityGroupIds(List.of("securityGroupIds"))
* .subnetIds(List.of("subnetIds"))
* .build()))
* .zeppelinApplicationConfiguration(ZeppelinApplicationConfigurationProperty.builder()
* .catalogConfiguration(CatalogConfigurationProperty.builder()
* .glueDataCatalogConfiguration(GlueDataCatalogConfigurationProperty.builder()
* .databaseArn("databaseArn")
* .build())
* .build())
* .customArtifactsConfiguration(List.of(CustomArtifactConfigurationProperty.builder()
* .artifactType("artifactType")
* // the properties below are optional
* .mavenReference(MavenReferenceProperty.builder()
* .artifactId("artifactId")
* .groupId("groupId")
* .version("version")
* .build())
* .s3ContentLocation(S3ContentLocationProperty.builder()
* .bucketArn("bucketArn")
* .fileKey("fileKey")
* // the properties below are optional
* .objectVersion("objectVersion")
* .build())
* .build()))
* .deployAsApplicationConfiguration(DeployAsApplicationConfigurationProperty.builder()
* .s3ContentLocation(S3ContentBaseLocationProperty.builder()
* .bucketArn("bucketArn")
* // the properties below are optional
* .basePath("basePath")
* .build())
* .build())
* .monitoringConfiguration(ZeppelinMonitoringConfigurationProperty.builder()
* .logLevel("logLevel")
* .build())
* .build())
* .build())
* .applicationDescription("applicationDescription")
* .applicationMaintenanceConfiguration(ApplicationMaintenanceConfigurationProperty.builder()
* .applicationMaintenanceWindowStartTime("applicationMaintenanceWindowStartTime")
* .build())
* .applicationMode("applicationMode")
* .applicationName("applicationName")
* .runConfiguration(RunConfigurationProperty.builder()
* .applicationRestoreConfiguration(ApplicationRestoreConfigurationProperty.builder()
* .applicationRestoreType("applicationRestoreType")
* // the properties below are optional
* .snapshotName("snapshotName")
* .build())
* .flinkRunConfiguration(FlinkRunConfigurationProperty.builder()
* .allowNonRestoredState(false)
* .build())
* .build())
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html)
*/
public interface CfnApplicationProps {
/**
* Use this parameter to configure the application.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-applicationconfiguration)
*/
public fun applicationConfiguration(): Any? = unwrap(this).getApplicationConfiguration()
/**
* The description of the application.
*
* Default: - ""
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-applicationdescription)
*/
public fun applicationDescription(): String? = unwrap(this).getApplicationDescription()
/**
* Describes the maintenance configuration for the application.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-applicationmaintenanceconfiguration)
*/
public fun applicationMaintenanceConfiguration(): Any? =
unwrap(this).getApplicationMaintenanceConfiguration()
/**
* To create a Kinesis Data Analytics Studio notebook, you must set the mode to `INTERACTIVE` .
*
* However, for a Kinesis Data Analytics for Apache Flink application, the mode is optional.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-applicationmode)
*/
public fun applicationMode(): String? = unwrap(this).getApplicationMode()
/**
* The name of the application.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-applicationname)
*/
public fun applicationName(): String? = unwrap(this).getApplicationName()
/**
* Describes the starting parameters for an Managed Service for Apache Flink application.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-runconfiguration)
*/
public fun runConfiguration(): Any? = unwrap(this).getRunConfiguration()
/**
* The runtime environment for the application.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-runtimeenvironment)
*/
public fun runtimeEnvironment(): String
/**
* Specifies the IAM role that the application uses to access external resources.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-serviceexecutionrole)
*/
public fun serviceExecutionRole(): String
/**
* A list of one or more tags to assign to the application.
*
* A tag is a key-value pair that identifies an application. Note that the maximum number of
* application tags includes system tags. The maximum number of user-defined application tags is 50.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-tags)
*/
public fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
/**
* A builder for [CfnApplicationProps]
*/
@CdkDslMarker
public interface Builder {
/**
* @param applicationConfiguration Use this parameter to configure the application.
*/
public fun applicationConfiguration(applicationConfiguration: IResolvable)
/**
* @param applicationConfiguration Use this parameter to configure the application.
*/
public
fun applicationConfiguration(applicationConfiguration: CfnApplication.ApplicationConfigurationProperty)
/**
* @param applicationConfiguration Use this parameter to configure the application.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("0311262f37fdea8610ef532b83f150fa088cd6b977e7d5f8506f2aec9e87187f")
public
fun applicationConfiguration(applicationConfiguration: CfnApplication.ApplicationConfigurationProperty.Builder.() -> Unit)
/**
* @param applicationDescription The description of the application.
*/
public fun applicationDescription(applicationDescription: String)
/**
* @param applicationMaintenanceConfiguration Describes the maintenance configuration for the
* application.
*/
public fun applicationMaintenanceConfiguration(applicationMaintenanceConfiguration: IResolvable)
/**
* @param applicationMaintenanceConfiguration Describes the maintenance configuration for the
* application.
*/
public
fun applicationMaintenanceConfiguration(applicationMaintenanceConfiguration: CfnApplication.ApplicationMaintenanceConfigurationProperty)
/**
* @param applicationMaintenanceConfiguration Describes the maintenance configuration for the
* application.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("f6e8d4ae0d711726a391dceb350c3c6278c0987adacf55593e14fbe3d9f6b95b")
public
fun applicationMaintenanceConfiguration(applicationMaintenanceConfiguration: CfnApplication.ApplicationMaintenanceConfigurationProperty.Builder.() -> Unit)
/**
* @param applicationMode To create a Kinesis Data Analytics Studio notebook, you must set the
* mode to `INTERACTIVE` .
* However, for a Kinesis Data Analytics for Apache Flink application, the mode is optional.
*/
public fun applicationMode(applicationMode: String)
/**
* @param applicationName The name of the application.
*/
public fun applicationName(applicationName: String)
/**
* @param runConfiguration Describes the starting parameters for an Managed Service for Apache
* Flink application.
*/
public fun runConfiguration(runConfiguration: IResolvable)
/**
* @param runConfiguration Describes the starting parameters for an Managed Service for Apache
* Flink application.
*/
public fun runConfiguration(runConfiguration: CfnApplication.RunConfigurationProperty)
/**
* @param runConfiguration Describes the starting parameters for an Managed Service for Apache
* Flink application.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("a848636436393563579e51b9e873c3e51744a04ea6909c18c9771bd03591e8fa")
public
fun runConfiguration(runConfiguration: CfnApplication.RunConfigurationProperty.Builder.() -> Unit)
/**
* @param runtimeEnvironment The runtime environment for the application.
*/
public fun runtimeEnvironment(runtimeEnvironment: String)
/**
* @param serviceExecutionRole Specifies the IAM role that the application uses to access
* external resources.
*/
public fun serviceExecutionRole(serviceExecutionRole: String)
/**
* @param tags A list of one or more tags to assign to the application.
* A tag is a key-value pair that identifies an application. Note that the maximum number of
* application tags includes system tags. The maximum number of user-defined application tags is
* 50.
*/
public fun tags(tags: List<CfnTag>)
/**
* @param tags A list of one or more tags to assign to the application.
* A tag is a key-value pair that identifies an application. Note that the maximum number of
* application tags includes system tags. The maximum number of user-defined application tags is
* 50.
*/
public fun tags(vararg tags: CfnTag)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.kinesisanalyticsv2.CfnApplicationProps.Builder =
software.amazon.awscdk.services.kinesisanalyticsv2.CfnApplicationProps.builder()
/**
* @param applicationConfiguration Use this parameter to configure the application.
*/
override fun applicationConfiguration(applicationConfiguration: IResolvable) {
cdkBuilder.applicationConfiguration(applicationConfiguration.let(IResolvable::unwrap))
}
/**
* @param applicationConfiguration Use this parameter to configure the application.
*/
override
fun applicationConfiguration(applicationConfiguration: CfnApplication.ApplicationConfigurationProperty) {
cdkBuilder.applicationConfiguration(applicationConfiguration.let(CfnApplication.ApplicationConfigurationProperty::unwrap))
}
/**
* @param applicationConfiguration Use this parameter to configure the application.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("0311262f37fdea8610ef532b83f150fa088cd6b977e7d5f8506f2aec9e87187f")
override
fun applicationConfiguration(applicationConfiguration: CfnApplication.ApplicationConfigurationProperty.Builder.() -> Unit):
Unit =
applicationConfiguration(CfnApplication.ApplicationConfigurationProperty(applicationConfiguration))
/**
* @param applicationDescription The description of the application.
*/
override fun applicationDescription(applicationDescription: String) {
cdkBuilder.applicationDescription(applicationDescription)
}
/**
* @param applicationMaintenanceConfiguration Describes the maintenance configuration for the
* application.
*/
override
fun applicationMaintenanceConfiguration(applicationMaintenanceConfiguration: IResolvable) {
cdkBuilder.applicationMaintenanceConfiguration(applicationMaintenanceConfiguration.let(IResolvable::unwrap))
}
/**
* @param applicationMaintenanceConfiguration Describes the maintenance configuration for the
* application.
*/
override
fun applicationMaintenanceConfiguration(applicationMaintenanceConfiguration: CfnApplication.ApplicationMaintenanceConfigurationProperty) {
cdkBuilder.applicationMaintenanceConfiguration(applicationMaintenanceConfiguration.let(CfnApplication.ApplicationMaintenanceConfigurationProperty::unwrap))
}
/**
* @param applicationMaintenanceConfiguration Describes the maintenance configuration for the
* application.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("f6e8d4ae0d711726a391dceb350c3c6278c0987adacf55593e14fbe3d9f6b95b")
override
fun applicationMaintenanceConfiguration(applicationMaintenanceConfiguration: CfnApplication.ApplicationMaintenanceConfigurationProperty.Builder.() -> Unit):
Unit =
applicationMaintenanceConfiguration(CfnApplication.ApplicationMaintenanceConfigurationProperty(applicationMaintenanceConfiguration))
/**
* @param applicationMode To create a Kinesis Data Analytics Studio notebook, you must set the
* mode to `INTERACTIVE` .
* However, for a Kinesis Data Analytics for Apache Flink application, the mode is optional.
*/
override fun applicationMode(applicationMode: String) {
cdkBuilder.applicationMode(applicationMode)
}
/**
* @param applicationName The name of the application.
*/
override fun applicationName(applicationName: String) {
cdkBuilder.applicationName(applicationName)
}
/**
* @param runConfiguration Describes the starting parameters for an Managed Service for Apache
* Flink application.
*/
override fun runConfiguration(runConfiguration: IResolvable) {
cdkBuilder.runConfiguration(runConfiguration.let(IResolvable::unwrap))
}
/**
* @param runConfiguration Describes the starting parameters for an Managed Service for Apache
* Flink application.
*/
override fun runConfiguration(runConfiguration: CfnApplication.RunConfigurationProperty) {
cdkBuilder.runConfiguration(runConfiguration.let(CfnApplication.RunConfigurationProperty::unwrap))
}
/**
* @param runConfiguration Describes the starting parameters for an Managed Service for Apache
* Flink application.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("a848636436393563579e51b9e873c3e51744a04ea6909c18c9771bd03591e8fa")
override
fun runConfiguration(runConfiguration: CfnApplication.RunConfigurationProperty.Builder.() -> Unit):
Unit = runConfiguration(CfnApplication.RunConfigurationProperty(runConfiguration))
/**
* @param runtimeEnvironment The runtime environment for the application.
*/
override fun runtimeEnvironment(runtimeEnvironment: String) {
cdkBuilder.runtimeEnvironment(runtimeEnvironment)
}
/**
* @param serviceExecutionRole Specifies the IAM role that the application uses to access
* external resources.
*/
override fun serviceExecutionRole(serviceExecutionRole: String) {
cdkBuilder.serviceExecutionRole(serviceExecutionRole)
}
/**
* @param tags A list of one or more tags to assign to the application.
* A tag is a key-value pair that identifies an application. Note that the maximum number of
* application tags includes system tags. The maximum number of user-defined application tags is
* 50.
*/
override fun tags(tags: List<CfnTag>) {
cdkBuilder.tags(tags.map(CfnTag::unwrap))
}
/**
* @param tags A list of one or more tags to assign to the application.
* A tag is a key-value pair that identifies an application. Note that the maximum number of
* application tags includes system tags. The maximum number of user-defined application tags is
* 50.
*/
override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList())
public fun build(): software.amazon.awscdk.services.kinesisanalyticsv2.CfnApplicationProps =
cdkBuilder.build()
}
private class Wrapper(
override val cdkObject: software.amazon.awscdk.services.kinesisanalyticsv2.CfnApplicationProps,
) : CdkObject(cdkObject), CfnApplicationProps {
/**
* Use this parameter to configure the application.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-applicationconfiguration)
*/
override fun applicationConfiguration(): Any? = unwrap(this).getApplicationConfiguration()
/**
* The description of the application.
*
* Default: - ""
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-applicationdescription)
*/
override fun applicationDescription(): String? = unwrap(this).getApplicationDescription()
/**
* Describes the maintenance configuration for the application.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-applicationmaintenanceconfiguration)
*/
override fun applicationMaintenanceConfiguration(): Any? =
unwrap(this).getApplicationMaintenanceConfiguration()
/**
* To create a Kinesis Data Analytics Studio notebook, you must set the mode to `INTERACTIVE` .
*
* However, for a Kinesis Data Analytics for Apache Flink application, the mode is optional.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-applicationmode)
*/
override fun applicationMode(): String? = unwrap(this).getApplicationMode()
/**
* The name of the application.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-applicationname)
*/
override fun applicationName(): String? = unwrap(this).getApplicationName()
/**
* Describes the starting parameters for an Managed Service for Apache Flink application.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-runconfiguration)
*/
override fun runConfiguration(): Any? = unwrap(this).getRunConfiguration()
/**
* The runtime environment for the application.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-runtimeenvironment)
*/
override fun runtimeEnvironment(): String = unwrap(this).getRuntimeEnvironment()
/**
* Specifies the IAM role that the application uses to access external resources.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-serviceexecutionrole)
*/
override fun serviceExecutionRole(): String = unwrap(this).getServiceExecutionRole()
/**
* A list of one or more tags to assign to the application.
*
* A tag is a key-value pair that identifies an application. Note that the maximum number of
* application tags includes system tags. The maximum number of user-defined application tags is
* 50.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalyticsv2-application.html#cfn-kinesisanalyticsv2-application-tags)
*/
override fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): CfnApplicationProps {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.kinesisanalyticsv2.CfnApplicationProps):
CfnApplicationProps = Wrapper(cdkObject)
internal fun unwrap(wrapped: CfnApplicationProps):
software.amazon.awscdk.services.kinesisanalyticsv2.CfnApplicationProps = (wrapped as
CdkObject).cdkObject as
software.amazon.awscdk.services.kinesisanalyticsv2.CfnApplicationProps
}
}
| 4 | Kotlin | 0 | 4 | ddf2bfd2275b50bb86a667c4298dd92f59d7e342 | 25,086 | kotlin-cdk-wrapper | Apache License 2.0 |
game-api/src/main/java/org/runestar/client/game/api/live/WidgetGroupParents.kt | ittwit | 163,532,582 | true | {"Java": 1852312, "Kotlin": 1247608} | package org.runestar.client.game.api.live
import org.runestar.client.game.api.NodeHashTable
import org.runestar.client.game.api.Widget
import org.runestar.client.game.api.WidgetId
import org.runestar.client.game.raw.CLIENT
import org.runestar.client.game.raw.access.XNodeHashTable
import org.runestar.client.game.raw.access.XWidgetGroupParent
object WidgetGroupParents : NodeHashTable<WidgetId, Int, XWidgetGroupParent>() {
override val accessor: XNodeHashTable get() = CLIENT.widgetGroupParents
override fun wrapKey(node: XWidgetGroupParent): WidgetId = WidgetId(node.key.toInt())
override fun unwrapKey(k: WidgetId): Long = k.packed.toLong()
override fun wrapValue(node: XWidgetGroupParent): Int = node.group
fun parentId(group: Int): Int {
val node = nodes.firstOrNull { it.group == group } ?: return -1
return node.key.toInt()
}
fun parent(group: Int): Widget.Layer? {
val pid = parentId(group)
if (pid == -1) return null
return Widgets[WidgetId.getGroup(pid), WidgetId.getIndex(pid)] as Widget.Layer?
}
} | 0 | Java | 0 | 0 | 7b60ec3d0c917571b7def908037dfc4a744092e0 | 1,089 | client | MIT License |
game-api/src/main/java/org/runestar/client/game/api/live/WidgetGroupParents.kt | ittwit | 163,532,582 | true | {"Java": 1852312, "Kotlin": 1247608} | package org.runestar.client.game.api.live
import org.runestar.client.game.api.NodeHashTable
import org.runestar.client.game.api.Widget
import org.runestar.client.game.api.WidgetId
import org.runestar.client.game.raw.CLIENT
import org.runestar.client.game.raw.access.XNodeHashTable
import org.runestar.client.game.raw.access.XWidgetGroupParent
object WidgetGroupParents : NodeHashTable<WidgetId, Int, XWidgetGroupParent>() {
override val accessor: XNodeHashTable get() = CLIENT.widgetGroupParents
override fun wrapKey(node: XWidgetGroupParent): WidgetId = WidgetId(node.key.toInt())
override fun unwrapKey(k: WidgetId): Long = k.packed.toLong()
override fun wrapValue(node: XWidgetGroupParent): Int = node.group
fun parentId(group: Int): Int {
val node = nodes.firstOrNull { it.group == group } ?: return -1
return node.key.toInt()
}
fun parent(group: Int): Widget.Layer? {
val pid = parentId(group)
if (pid == -1) return null
return Widgets[WidgetId.getGroup(pid), WidgetId.getIndex(pid)] as Widget.Layer?
}
} | 0 | Java | 0 | 0 | 7b60ec3d0c917571b7def908037dfc4a744092e0 | 1,089 | client | MIT License |
xesar-connect/src/main/kotlin/com/open200/xesar/connect/messages/command/CreateCodingStationMapi.kt | open200 | 684,928,079 | false | null | package com.open200.xesar.connect.messages.command
import com.open200.xesar.connect.utils.UUIDSerializer
import java.util.*
import kotlinx.serialization.Serializable
/**
* Represents a command POJO to change data of a zone.
*
* @param commandId The id of the command.
* @param name The name of the zone.
* @param description The description of the zone.
* @param id The id of the zone.
* @param token The token of the command.
*/
@Serializable
data class ChangeZoneDataMapi(
override val commandId: @Serializable(with = UUIDSerializer::class) UUID,
val name: String,
val description: String,
@Serializable(with = UUIDSerializer::class) val id: UUID,
val token: String
) : Command
| 17 | null | 1 | 9 | 2ded0fbbe8a5df74065c141f5afe1b20c72022c6 | 710 | xesar-connect | Apache License 2.0 |
src/main/kotlin/org/objectionary/ddr/transform/impl/BasicDecoratorsResolver.kt | objectionary | 518,891,717 | false | null | /*
* The MIT License (MIT)
*
* Copyright (c) 2022 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.objectionary.ddr.transform.impl
import org.objectionary.ddr.graph.base
import org.objectionary.ddr.graph.line
import org.objectionary.ddr.graph.name
import org.objectionary.ddr.graph.pos
import org.objectionary.ddr.graph.repr.Graph
import org.objectionary.ddr.graph.repr.IGraphAttr
import org.objectionary.ddr.graph.repr.IGraphNode
import org.objectionary.ddr.transform.Resolver
import org.w3c.dom.Document
import org.w3c.dom.Element
import org.w3c.dom.Node
import java.nio.file.Path
/**
* Collects all decorators and inserts desired .@ applications
*/
class BasicDecoratorsResolver(
private val graph: Graph,
documents: MutableMap<Document, Path>
) : Resolver(graph, documents) {
/**
* Aggregates process of resolving all decorators:
* collects declarations, finds references of the decorators
* and injects all needed .@ elements into the corresponding documents
*/
override fun resolve() {
collectDeclarations()
resolveRefs()
injectAttributes()
transformDocuments()
}
/**
* Traverses objects and injects phi attributes for each.
* Plus, checks if phi attribute has to be inserted before the object
*/
private fun injectAttributes() {
val objects = graph.initialObjects
for (node in objects) {
val baseObject = firstRef(node, objects)
val abstract = getIgAbstract(baseObject) ?: continue
traverseDotChain(node, abstract)
graph.igNodes.find { node.parentNode == it.body }?.let { parentNode ->
parentNode.attributes
.find { it.name == name(baseObject) }?.parentDistance
?.let { insertBefore(node, parentNode.body, it) }
}
}
}
/**
* Traverses dot chain and inserts phi attributes along the way
*/
private fun traverseDotChain(
node: Node,
abstract: IGraphNode
) {
var sibling = node.nextSibling
sibling?.attributes ?: run {
sibling = sibling?.nextSibling
}
while (base(sibling)?.startsWith(".") == true) {
val base = base(sibling)
val attr = abstract.attributes.find { it.name == base?.substring(1) }
if (attr != null && sibling != null) {
insert(sibling, attr)
}
sibling = sibling?.nextSibling
}
}
/**
* Inserts phi before the object like this: @.foo
*/
private fun insertBefore(
node: Node,
parent: Node,
dist: Int
) {
val siblings: MutableSet<Node> = mutableSetOf()
var tmpNode = node
while (tmpNode.nextSibling != null) {
siblings.add(tmpNode.nextSibling)
tmpNode = tmpNode.nextSibling
}
parent.removeChild(node)
siblings.forEach { parent.removeChild(it) }
val document = parent.ownerDocument
if (dist > 0) {
addDocumentChild(document, node, parent, "@", 0)
}
for (i in 1 until dist) {
addDocumentChild(document, node, parent, ".@", i * 2)
}
val newChild: Element = document.createElement("o")
for (i in 0 until node.attributes.length) {
val attr = node.attributes.item(i)
if (attr.nodeName == "base") {
newChild.setAttribute("base", ".${attr.textContent}")
} else {
newChild.setAttribute(attr.nodeName, attr.textContent)
}
}
parent.appendChild(newChild)
siblings.forEach { parent.appendChild(it) }
}
/**
* Inserts phi attributes in between applications like this: [email protected]
*/
private fun insert(node: Node, attr: IGraphAttr) {
val parent = node.parentNode
val siblings = removeSiblings(node)
val document = parent.ownerDocument
for (i in 0 until attr.parentDistance) {
addDocumentChild(document, node, parent, ".@", i * 2)
}
siblings.forEach { parent.appendChild(it) }
}
/**
* Constructs phi attribute node to be inserted
*/
private fun addDocumentChild(
document: Document,
node: Node,
parent: Node,
baseValue: String,
offset: Int
) {
val newChild: Element = document.createElement("o")
newChild.setAttribute("base", baseValue)
newChild.setAttribute("line", line(node))
if (baseValue == ".@") {
newChild.setAttribute("method", "")
}
newChild.setAttribute("pos", "${base(node)?.length?.plus(pos(node)?.toInt()!!)?.plus(offset)}")
parent.appendChild(newChild)
}
}
| 22 | null | 1 | 8 | e61ed93f4c7b8551e1c37929f2a0890ebb074766 | 5,861 | ddr | MIT License |
onebusaway-sdk-kotlin-core/src/main/kotlin/org/onebusaway/services/blocking/TripsForLocationServiceImpl.kt | OneBusAway | 869,113,248 | false | {"Kotlin": 1790435, "Shell": 3662, "Dockerfile": 399} | // File generated from our OpenAPI spec by Stainless.
package org.onebusaway.services.async
import org.onebusaway.core.ClientOptions
import org.onebusaway.core.RequestOptions
import org.onebusaway.core.handlers.errorHandler
import org.onebusaway.core.handlers.jsonHandler
import org.onebusaway.core.handlers.withErrorHandler
import org.onebusaway.core.http.HttpMethod
import org.onebusaway.core.http.HttpRequest
import org.onebusaway.core.http.HttpResponse.Handler
import org.onebusaway.errors.OnebusawaySdkError
import org.onebusaway.models.AgenciesWithCoverageListParams
import org.onebusaway.models.AgenciesWithCoverageListResponse
class AgenciesWithCoverageServiceAsyncImpl
constructor(
private val clientOptions: ClientOptions,
) : AgenciesWithCoverageServiceAsync {
private val errorHandler: Handler<OnebusawaySdkError> = errorHandler(clientOptions.jsonMapper)
private val listHandler: Handler<AgenciesWithCoverageListResponse> =
jsonHandler<AgenciesWithCoverageListResponse>(clientOptions.jsonMapper)
.withErrorHandler(errorHandler)
/**
* Returns a list of all transit agencies currently supported by OneBusAway along with the
* center of their coverage area.
*/
override suspend fun list(
params: AgenciesWithCoverageListParams,
requestOptions: RequestOptions
): AgenciesWithCoverageListResponse {
val request =
HttpRequest.builder()
.method(HttpMethod.GET)
.addPathSegments("api", "where", "agencies-with-coverage.json")
.putAllQueryParams(clientOptions.queryParams)
.putAllQueryParams(params.getQueryParams())
.putAllHeaders(clientOptions.headers)
.putAllHeaders(params.getHeaders())
.build()
return clientOptions.httpClient.executeAsync(request, requestOptions).let { response ->
response
.use { listHandler.handle(it) }
.apply {
if (requestOptions.responseValidation ?: clientOptions.responseValidation) {
validate()
}
}
}
}
}
| 0 | Kotlin | 1 | 1 | 81a22faf155835ea66702dd772c099cd3b5c0df4 | 2,196 | kotlin-sdk | Apache License 2.0 |
app/src/main/java/com/samridhoverseasfsm/features/orderhistory/api/LocationUpdateRepository.kt | DebashisINT | 699,836,260 | false | null | package com.paricottfsm.features.orderhistory.api
import com.paricottfsm.base.BaseResponse
import com.paricottfsm.features.orderhistory.model.LocationUpdateRequest
import io.reactivex.Observable
/**
* Created by Pratishruti on 23-11-2017.
*/
class LocationUpdateRepository(val apiService:LocationUpdateApi) {
fun sendLocationUpdate(location: LocationUpdateRequest): Observable<BaseResponse> {
return apiService.sendLocationUpdates(location)
}
} | 0 | Kotlin | 0 | 0 | d10d93027ec0adf4be3231aa211b6a433e981b12 | 464 | SwitzFood | Apache License 2.0 |
src/main/kotlin/GetFriends.kt | KilluaSSR | 846,533,751 | false | {"Kotlin": 39490} | package killua.dev
import twitter4j.v1.TwitterV1
enum class RelationshipType {
Followers,
Following,
Blocked
}
suspend fun getUserIDs(
twitterV1: TwitterV1,
relationshipType: RelationshipType,
userID: Long? = null
): MutableSet<Long> {
val idsSet = mutableSetOf<Long>()
var cursor = -1L
val friendsFollowers = twitterV1.friendsFollowers()
while (cursor != 0L) {
val ids = withRetry {
when (relationshipType) {
RelationshipType.Followers -> {
if (userID != null) {
println("Getting his/her followers.")
friendsFollowers.getFollowersIDs(userID, cursor)
} else {
println("Getting my followers.")
friendsFollowers.getFollowersIDs(cursor)
}
}
RelationshipType.Following -> {
if (userID != null) {
println("Getting his/her followings.")
friendsFollowers.getFriendsIDs(userID, cursor)
} else {
println("Getting my followings.")
friendsFollowers.getFriendsIDs(cursor)
}
}
RelationshipType.Blocked -> {
println("Getting my blocked ids.")
twitterV1.users().getBlocksIDs(cursor)
}
}
} ?: break
cursor = ids.nextCursor
rateLimitStatus = ids.rateLimitStatus ?: RateLimit.Unlimited
println("Done. (count=${ids.iDs.size}, hasMore=${cursor != 0L})\n")
idsSet.addAll(ids.iDs.toSet())
}
return idsSet
}
suspend fun getMyFollowings(twitterV1: TwitterV1): MutableSet<Long> =
getUserIDs(twitterV1, RelationshipType.Following)
suspend fun getMyFollowers(twitterV1: TwitterV1): MutableSet<Long> =
getUserIDs(twitterV1, RelationshipType.Followers)
suspend fun getOthersFollowers(twitterV1: TwitterV1, userID: Long): MutableSet<Long> =
getUserIDs(twitterV1, RelationshipType.Followers, userID)
suspend fun getOthersFollowings(twitterV1: TwitterV1, userID: Long): MutableSet<Long> =
getUserIDs(twitterV1, RelationshipType.Following, userID)
suspend fun getMyBlocked(twitterV1: TwitterV1):MutableSet<Long> =
getUserIDs(twitterV1, RelationshipType.Blocked) | 0 | Kotlin | 0 | 12 | 00fceaf8f480a45b689de34a5894cde3eb9fc7a0 | 2,423 | TwitterBanSpamFollowers | MIT License |
rulebook-codenarc/src/main/kotlin/com/hanggrian/rulebook/codenarc/AssignmentWrappingRule.kt | hanggrian | 556,969,715 | false | {"Kotlin": 266381, "Python": 72652, "Java": 18075, "Groovy": 329} | package com.hanggrian.rulebook.codenarc
import com.hanggrian.rulebook.codenarc.internals.Messages
import com.hanggrian.rulebook.codenarc.internals.isMultiline
import org.codehaus.groovy.ast.expr.BinaryExpression
import org.codehaus.groovy.syntax.Types.ASSIGN
import org.codenarc.rule.AbstractAstVisitor
/**
* [See wiki](https://github.com/hanggrian/rulebook/wiki/Rules/#assignment-wrapping)
*/
public class AssignmentWrappingRule : Rule() {
override fun getName(): String = "AssignmentWrapping"
override fun getAstVisitorClass(): Class<*> = Visitor::class.java
internal companion object {
const val MSG = "assignment.wrapping"
}
public class Visitor : AbstractAstVisitor() {
override fun visitBinaryExpression(node: BinaryExpression) {
super.visitBinaryExpression(node)
// target multiline assignment
val assign =
node.operation
.takeIf { it.type == ASSIGN && node.isMultiline() }
?: return
// checks for violation
val expression =
node.rightExpression
.takeUnless { it.lineNumber == assign.startLine + 1 }
?: return
addViolation(expression, Messages[MSG])
}
}
}
| 0 | Kotlin | 0 | 1 | 94a3a554563534ace2c06ea48f872bd096d5db82 | 1,304 | rulebook | Apache License 2.0 |
coil-base/src/main/java/coil/ImageLoader.kt | coil-kt | 201,684,760 | false | null | @file:Suppress("UNUSED_PARAMETER")
package coil
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Drawable
import androidx.annotation.DrawableRes
import androidx.annotation.FloatRange
import androidx.lifecycle.Lifecycle
import coil.decode.Decoder
import coil.disk.DiskCache
import coil.drawable.CrossfadeDrawable
import coil.fetch.Fetcher
import coil.intercept.Interceptor
import coil.memory.MemoryCache
import coil.request.CachePolicy
import coil.request.DefaultRequestOptions
import coil.request.Disposable
import coil.request.ErrorResult
import coil.request.ImageRequest
import coil.request.ImageResult
import coil.request.SuccessResult
import coil.size.Precision
import coil.target.ViewTarget
import coil.transform.Transformation
import coil.transition.CrossfadeTransition
import coil.transition.Transition
import coil.util.DEFAULT_BITMAP_CONFIG
import coil.util.DEFAULT_REQUEST_OPTIONS
import coil.util.ImageLoaderOptions
import coil.util.Logger
import coil.util.SingletonDiskCache
import coil.util.getDrawableCompat
import coil.util.unsupported
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import okhttp3.Call
import okhttp3.OkHttpClient
import java.io.File
/**
* A service class that loads images by executing [ImageRequest]s. Image loaders handle
* caching, data fetching, image decoding, request management, memory management, and more.
*
* Image loaders are designed to be shareable and work best when you create a single
* instance and share it throughout your app.
*/
interface ImageLoader {
/**
* The default options that are used to fill in unset [ImageRequest] values.
*/
val defaults: DefaultRequestOptions
/**
* The components used to fulfil image requests.
*/
val components: ComponentRegistry
/**
* An in-memory cache of previously loaded images.
*/
val memoryCache: MemoryCache?
/**
* An on-disk cache of previously loaded images.
*/
val diskCache: DiskCache?
/**
* Enqueue the [request] to be executed asynchronously.
*
* NOTE: The request will wait until [ImageRequest.lifecycle] is at least
* [Lifecycle.State.STARTED] before being executed.
*
* @param request The request to execute.
* @return A [Disposable] which can be used to cancel or check the status of the request.
*/
fun enqueue(request: ImageRequest): Disposable
/**
* Execute the [request] in the current coroutine scope.
*
* NOTE: If [ImageRequest.target] is a [ViewTarget], the job will automatically be cancelled
* if its view is detached.
*
* @param request The request to execute.
* @return A [SuccessResult] if the request completes successfully.
* Else, returns an [ErrorResult].
*/
suspend fun execute(request: ImageRequest): ImageResult
/**
* Cancel any new and in progress requests, clear the [MemoryCache], and close any open
* system resources.
*
* Shutting down an image loader is optional. It will be shut down automatically if
* dereferenced.
*/
fun shutdown()
/**
* Create an [ImageLoader.Builder] that shares the same resources and configuration as this
* image loader.
*/
fun newBuilder(): Builder
class Builder {
private val applicationContext: Context
private var defaults: DefaultRequestOptions
private var memoryCache: Lazy<MemoryCache?>?
private var diskCache: Lazy<DiskCache?>?
private var callFactory: Lazy<Call.Factory>?
private var eventListenerFactory: EventListener.Factory?
private var componentRegistry: ComponentRegistry?
private var options: ImageLoaderOptions
private var logger: Logger?
constructor(context: Context) {
applicationContext = context.applicationContext
defaults = DEFAULT_REQUEST_OPTIONS
memoryCache = null
diskCache = null
callFactory = null
eventListenerFactory = null
componentRegistry = null
options = ImageLoaderOptions()
logger = null
}
internal constructor(imageLoader: RealImageLoader) {
applicationContext = imageLoader.context.applicationContext
defaults = imageLoader.defaults
memoryCache = imageLoader.memoryCacheLazy
diskCache = imageLoader.diskCacheLazy
callFactory = imageLoader.callFactoryLazy
eventListenerFactory = imageLoader.eventListenerFactory
componentRegistry = imageLoader.componentRegistry
options = imageLoader.options
logger = imageLoader.logger
}
/**
* Set the [OkHttpClient] used for network requests.
*
* This is a convenience function for calling `callFactory(Call.Factory)`.
*/
fun okHttpClient(okHttpClient: OkHttpClient) = callFactory(okHttpClient)
/**
* Set a lazy callback to create the [OkHttpClient] used for network requests.
*
* This allows lazy creation of the [OkHttpClient] on a background thread.
* [initializer] is guaranteed to be called at most once.
*
* Prefer using this instead of `okHttpClient(OkHttpClient)`.
*
* This is a convenience function for calling `callFactory(() -> Call.Factory)`.
*/
fun okHttpClient(initializer: () -> OkHttpClient) = callFactory(initializer)
/**
* Set the [Call.Factory] used for network requests.
*/
fun callFactory(callFactory: Call.Factory) = apply {
this.callFactory = lazyOf(callFactory)
}
/**
* Set a lazy callback to create the [Call.Factory] used for network requests.
*
* This allows lazy creation of the [Call.Factory] on a background thread.
* [initializer] is guaranteed to be called at most once.
*
* Prefer using this instead of `callFactory(Call.Factory)`.
*/
fun callFactory(initializer: () -> Call.Factory) = apply {
this.callFactory = lazy(initializer)
}
/**
* Build and set the [ComponentRegistry].
*/
@JvmSynthetic
inline fun components(
builder: ComponentRegistry.Builder.() -> Unit
) = components(ComponentRegistry.Builder().apply(builder).build())
/**
* Set the [ComponentRegistry].
*/
fun components(components: ComponentRegistry) = apply {
this.componentRegistry = components
}
/**
* Set the [MemoryCache].
*/
fun memoryCache(memoryCache: MemoryCache?) = apply {
this.memoryCache = lazyOf(memoryCache)
}
/**
* Set a lazy callback to create the [MemoryCache].
*
* Prefer using this instead of `memoryCache(MemoryCache)`.
*/
fun memoryCache(initializer: () -> MemoryCache?) = apply {
this.memoryCache = lazy(initializer)
}
/**
* Set the [DiskCache].
*
* NOTE: By default, [ImageLoader]s share the same disk cache instance. This is necessary
* as having multiple disk cache instances active in the same directory at the same time
* can corrupt the disk cache.
*
* @see DiskCache.directory
*/
fun diskCache(diskCache: DiskCache?) = apply {
this.diskCache = lazyOf(diskCache)
}
/**
* Set a lazy callback to create the [DiskCache].
*
* Prefer using this instead of `diskCache(DiskCache)`.
*
* NOTE: By default, [ImageLoader]s share the same disk cache instance. This is necessary
* as having multiple disk cache instances active in the same directory at the same time
* can corrupt the disk cache.
*
* @see DiskCache.directory
*/
fun diskCache(initializer: () -> DiskCache?) = apply {
this.diskCache = lazy(initializer)
}
/**
* Allow the use of [Bitmap.Config.HARDWARE].
*
* If false, any use of [Bitmap.Config.HARDWARE] will be treated as
* [Bitmap.Config.ARGB_8888].
*
* NOTE: Setting this to false this will reduce performance on API 26 and above. Only
* disable this if necessary.
*
* Default: true
*/
fun allowHardware(enable: Boolean) = apply {
this.defaults = this.defaults.copy(allowHardware = enable)
}
/**
* Allow automatically using [Bitmap.Config.RGB_565] when an image is guaranteed to not
* have alpha.
*
* This will reduce the visual quality of the image, but will also reduce memory usage.
*
* Prefer only enabling this for low memory and resource constrained devices.
*
* Default: false
*/
fun allowRgb565(enable: Boolean) = apply {
this.defaults = this.defaults.copy(allowRgb565 = enable)
}
/**
* Enables adding [File.lastModified] to the memory cache key when loading an image from a
* [File].
*
* This allows subsequent requests that load the same file to miss the memory cache if the
* file has been updated. However, if the memory cache check occurs on the main thread
* (see [interceptorDispatcher]) calling [File.lastModified] will cause a strict mode
* violation.
*
* Default: true
*/
fun addLastModifiedToFileCacheKey(enable: Boolean) = apply {
this.options = this.options.copy(addLastModifiedToFileCacheKey = enable)
}
/**
* Enables short circuiting network requests if the device is offline.
*
* If true, reading from the network will automatically be disabled if the device is
* offline. If a cached response is unavailable the request will fail with a
* '504 Unsatisfiable Request' response.
*
* If false, the image loader will attempt a network request even if the device is offline.
*
* Default: true
*/
fun networkObserverEnabled(enable: Boolean) = apply {
this.options = this.options.copy(networkObserverEnabled = enable)
}
/**
* Enables support for network cache headers. If enabled, this image loader will respect the
* cache headers returned by network responses when deciding if an image can be stored or
* served from the disk cache. If disabled, images will always be served from the disk cache
* (if present) and will only be evicted to stay under the maximum size.
*
* Default: true
*/
fun respectCacheHeaders(enable: Boolean) = apply {
this.options = this.options.copy(respectCacheHeaders = enable)
}
/**
* Sets the maximum number of parallel [BitmapFactory] decode operations at once.
*
* Increasing this number will allow more parallel [BitmapFactory] decode operations,
* however it can result in worse UI performance.
*
* Default: 4
*/
fun bitmapFactoryMaxParallelism(maxParallelism: Int) = apply {
require(maxParallelism > 0) { "maxParallelism must be > 0." }
this.options = this.options.copy(bitmapFactoryMaxParallelism = maxParallelism)
}
/**
* Set a single [EventListener] that will receive all callbacks for requests launched by
* this image loader.
*
* @see eventListenerFactory
*/
fun eventListener(listener: EventListener) = eventListenerFactory { listener }
/**
* Set the [EventListener.Factory] to create per-request [EventListener]s.
*/
fun eventListenerFactory(factory: EventListener.Factory) = apply {
this.eventListenerFactory = factory
}
/**
* Enable a crossfade animation with duration [CrossfadeDrawable.DEFAULT_DURATION]
* milliseconds when a request completes successfully.
*
* Default: false
*/
fun crossfade(enable: Boolean) =
crossfade(if (enable) CrossfadeDrawable.DEFAULT_DURATION else 0)
/**
* Enable a crossfade animation with [durationMillis] milliseconds when a request completes
* successfully.
*
* @see `crossfade(Boolean)`
*/
fun crossfade(durationMillis: Int) = apply {
val factory = if (durationMillis > 0) {
CrossfadeTransition.Factory(durationMillis)
} else {
Transition.Factory.NONE
}
transitionFactory(factory)
}
/**
* Set the default [Transition.Factory] for each request.
*/
fun transitionFactory(factory: Transition.Factory) = apply {
this.defaults = this.defaults.copy(transitionFactory = factory)
}
/**
* Set the default precision for a request. [Precision] controls whether the size of the
* loaded image must match the request's size exactly or not.
*
* Default: [Precision.AUTOMATIC]
*/
fun precision(precision: Precision) = apply {
this.defaults = this.defaults.copy(precision = precision)
}
/**
* Set the preferred [Bitmap.Config].
*
* This is not guaranteed and a different config may be used in some situations.
*
* Default: [DEFAULT_BITMAP_CONFIG]
*/
fun bitmapConfig(bitmapConfig: Bitmap.Config) = apply {
this.defaults = this.defaults.copy(bitmapConfig = bitmapConfig)
}
/**
* A convenience function to set [fetcherDispatcher], [decoderDispatcher], and
* [transformationDispatcher] in one call.
*/
fun dispatcher(dispatcher: CoroutineDispatcher) = apply {
this.defaults = this.defaults.copy(
fetcherDispatcher = dispatcher,
decoderDispatcher = dispatcher,
transformationDispatcher = dispatcher
)
}
/**
* The [CoroutineDispatcher] that the [Interceptor] chain will be executed on.
*
* Default: `Dispatchers.Main.immediate`
*/
fun interceptorDispatcher(dispatcher: CoroutineDispatcher) = apply {
this.defaults = this.defaults.copy(interceptorDispatcher = dispatcher)
}
/**
* The [CoroutineDispatcher] that [Fetcher.fetch] will be executed on.
*
* Default: [Dispatchers.IO]
*/
fun fetcherDispatcher(dispatcher: CoroutineDispatcher) = apply {
this.defaults = this.defaults.copy(fetcherDispatcher = dispatcher)
}
/**
* The [CoroutineDispatcher] that [Decoder.decode] will be executed on.
*
* Default: [Dispatchers.IO]
*/
fun decoderDispatcher(dispatcher: CoroutineDispatcher) = apply {
this.defaults = this.defaults.copy(decoderDispatcher = dispatcher)
}
/**
* The [CoroutineDispatcher] that [Transformation.transform] will be executed on.
*
* Default: [Dispatchers.IO]
*/
fun transformationDispatcher(dispatcher: CoroutineDispatcher) = apply {
this.defaults = this.defaults.copy(transformationDispatcher = dispatcher)
}
/**
* Set the default placeholder drawable to use when a request starts.
*/
fun placeholder(@DrawableRes drawableResId: Int) =
placeholder(applicationContext.getDrawableCompat(drawableResId))
/**
* Set the default placeholder drawable to use when a request starts.
*/
fun placeholder(drawable: Drawable?) = apply {
this.defaults = this.defaults.copy(placeholder = drawable?.mutate())
}
/**
* Set the default error drawable to use when a request fails.
*/
fun error(@DrawableRes drawableResId: Int) =
error(applicationContext.getDrawableCompat(drawableResId))
/**
* Set the default error drawable to use when a request fails.
*/
fun error(drawable: Drawable?) = apply {
this.defaults = this.defaults.copy(error = drawable?.mutate())
}
/**
* Set the default fallback drawable to use if [ImageRequest.data] is null.
*/
fun fallback(@DrawableRes drawableResId: Int) =
fallback(applicationContext.getDrawableCompat(drawableResId))
/**
* Set the default fallback drawable to use if [ImageRequest.data] is null.
*/
fun fallback(drawable: Drawable?) = apply {
this.defaults = this.defaults.copy(fallback = drawable?.mutate())
}
/**
* Set the default memory cache policy.
*/
fun memoryCachePolicy(policy: CachePolicy) = apply {
this.defaults = this.defaults.copy(memoryCachePolicy = policy)
}
/**
* Set the default disk cache policy.
*/
fun diskCachePolicy(policy: CachePolicy) = apply {
this.defaults = this.defaults.copy(diskCachePolicy = policy)
}
/**
* Set the default network cache policy.
*
* NOTE: Disabling writes has no effect.
*/
fun networkCachePolicy(policy: CachePolicy) = apply {
this.defaults = this.defaults.copy(networkCachePolicy = policy)
}
/**
* Set the [Logger] to write logs to.
*
* NOTE: Setting a [Logger] can reduce performance and should be avoided in release builds.
*/
fun logger(logger: Logger?) = apply {
this.logger = logger
}
/**
* Create a new [ImageLoader] instance.
*/
fun build(): ImageLoader {
return RealImageLoader(
context = applicationContext,
defaults = defaults,
memoryCacheLazy = memoryCache ?: lazy { MemoryCache.Builder(applicationContext).build() },
diskCacheLazy = diskCache ?: lazy { SingletonDiskCache.get(applicationContext) },
callFactoryLazy = callFactory ?: lazy { OkHttpClient() },
eventListenerFactory = eventListenerFactory ?: EventListener.Factory.NONE,
componentRegistry = componentRegistry ?: ComponentRegistry(),
options = options,
logger = logger
)
}
@Deprecated(
message = "Migrate to 'memoryCache'.",
replaceWith = ReplaceWith(
expression = "memoryCache { MemoryCache.Builder(context).maxSizePercent(percent).build() }",
imports = ["coil.memory.MemoryCache"]
),
level = DeprecationLevel.ERROR // Temporary migration aid.
)
fun availableMemoryPercentage(@FloatRange(from = 0.0, to = 1.0) percent: Double): Builder = unsupported()
@Deprecated(
message = "Migrate to 'memoryCache'.",
replaceWith = ReplaceWith(
expression = "memoryCache { MemoryCache.Builder(context).weakReferencesEnabled(enable).build() }",
imports = ["coil.memory.MemoryCache"]
),
level = DeprecationLevel.ERROR // Temporary migration aid.
)
fun trackWeakReferences(enable: Boolean): Builder = unsupported()
@Deprecated(
message = "Migrate to 'interceptorDispatcher'.",
replaceWith = ReplaceWith(
expression = "interceptorDispatcher(if (enable) Dispatchers.Main.immediate else Dispatchers.IO)",
imports = ["kotlinx.coroutines.Dispatchers"]
),
level = DeprecationLevel.ERROR // Temporary migration aid.
)
fun launchInterceptorChainOnMainThread(enable: Boolean): Builder = unsupported()
@Deprecated(
message = "Replace with 'components'.",
replaceWith = ReplaceWith("components(builder)"),
level = DeprecationLevel.ERROR // Temporary migration aid.
)
@JvmSynthetic
fun componentRegistry(builder: ComponentRegistry.Builder.() -> Unit): Builder = unsupported()
@Deprecated(
message = "Replace with 'components'.",
replaceWith = ReplaceWith("components(registry)"),
level = DeprecationLevel.ERROR // Temporary migration aid.
)
fun componentRegistry(registry: ComponentRegistry): Builder = unsupported()
@Deprecated(
message = "Migrate to 'transitionFactory'.",
replaceWith = ReplaceWith("transitionFactory { _, _ -> transition }"),
level = DeprecationLevel.ERROR // Temporary migration aid.
)
fun transition(transition: Transition): Builder = unsupported()
}
}
| 43 | null | 620 | 9,812 | 051e0b20969ff695d69b06cd72a1fdc9e504bf68 | 21,397 | coil | Apache License 2.0 |
finance/src/test/kotlin/net/corda/finance/contracts/CommercialPaperTests.kt | unphon | 113,458,422 | true | {"Kotlin": 1706445, "Java": 130061, "Groovy": 16432, "Shell": 1653, "CSS": 636, "Batchfile": 84} | package net.corda.finance.contracts
import net.corda.core.contracts.*
import net.corda.core.identity.AnonymousParty
import net.corda.core.identity.Party
import net.corda.core.node.services.Vault
import net.corda.core.node.services.VaultService
import net.corda.core.transactions.SignedTransaction
import net.corda.core.transactions.TransactionBuilder
import net.corda.core.utilities.days
import net.corda.core.utilities.seconds
import net.corda.finance.DOLLARS
import net.corda.finance.`issued by`
import net.corda.finance.contracts.asset.*
import net.corda.testing.*
import net.corda.testing.contracts.fillWithSomeTestCash
import net.corda.testing.node.MockServices
import net.corda.testing.node.MockServices.Companion.makeTestDatabaseAndMockServices
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import java.time.Instant
import java.util.*
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
// TODO: The generate functions aren't tested by these tests: add them.
interface ICommercialPaperTestTemplate {
fun getPaper(): ICommercialPaperState
fun getIssueCommand(notary: Party): CommandData
fun getRedeemCommand(notary: Party): CommandData
fun getMoveCommand(): CommandData
fun getContract(): ContractClassName
}
class JavaCommercialPaperTest : ICommercialPaperTestTemplate {
override fun getPaper(): ICommercialPaperState = JavaCommercialPaper.State(
MEGA_CORP.ref(123),
MEGA_CORP,
1000.DOLLARS `issued by` MEGA_CORP.ref(123),
TEST_TX_TIME + 7.days
)
override fun getIssueCommand(notary: Party): CommandData = JavaCommercialPaper.Commands.Issue()
override fun getRedeemCommand(notary: Party): CommandData = JavaCommercialPaper.Commands.Redeem()
override fun getMoveCommand(): CommandData = JavaCommercialPaper.Commands.Move()
override fun getContract() = JavaCommercialPaper.JCP_PROGRAM_ID
}
class KotlinCommercialPaperTest : ICommercialPaperTestTemplate {
override fun getPaper(): ICommercialPaperState = CommercialPaper.State(
issuance = MEGA_CORP.ref(123),
owner = MEGA_CORP,
faceValue = 1000.DOLLARS `issued by` MEGA_CORP.ref(123),
maturityDate = TEST_TX_TIME + 7.days
)
override fun getIssueCommand(notary: Party): CommandData = CommercialPaper.Commands.Issue()
override fun getRedeemCommand(notary: Party): CommandData = CommercialPaper.Commands.Redeem()
override fun getMoveCommand(): CommandData = CommercialPaper.Commands.Move()
override fun getContract() = CommercialPaper.CP_PROGRAM_ID
}
class KotlinCommercialPaperLegacyTest : ICommercialPaperTestTemplate {
override fun getPaper(): ICommercialPaperState = CommercialPaper.State(
issuance = MEGA_CORP.ref(123),
owner = MEGA_CORP,
faceValue = 1000.DOLLARS `issued by` MEGA_CORP.ref(123),
maturityDate = TEST_TX_TIME + 7.days
)
override fun getIssueCommand(notary: Party): CommandData = CommercialPaper.Commands.Issue()
override fun getRedeemCommand(notary: Party): CommandData = CommercialPaper.Commands.Redeem()
override fun getMoveCommand(): CommandData = CommercialPaper.Commands.Move()
override fun getContract() = CommercialPaper.CP_PROGRAM_ID
}
@RunWith(Parameterized::class)
class CommercialPaperTestsGeneric {
companion object {
@Parameterized.Parameters @JvmStatic
fun data() = listOf(JavaCommercialPaperTest(), KotlinCommercialPaperTest(), KotlinCommercialPaperLegacyTest())
}
@Parameterized.Parameter
lateinit var thisTest: ICommercialPaperTestTemplate
val issuer = MEGA_CORP.ref(123)
@Test
fun `trade lifecycle test`() {
val someProfits = 1200.DOLLARS `issued by` issuer
ledger {
unverifiedTransaction {
output(CASH_PROGRAM_ID, "alice's $900", 900.DOLLARS.CASH `issued by` issuer `owned by` ALICE)
output(CASH_PROGRAM_ID, "some profits", someProfits.STATE `owned by` MEGA_CORP)
}
// Some CP is issued onto the ledger by MegaCorp.
transaction("Issuance") {
output(thisTest.getContract(), "paper") { thisTest.getPaper() }
command(MEGA_CORP_PUBKEY) { thisTest.getIssueCommand(DUMMY_NOTARY) }
timeWindow(TEST_TX_TIME)
this.verifies()
}
// The CP is sold to alice for her $900, $100 less than the face value. At 10% interest after only 7 days,
// that sounds a bit too good to be true!
transaction("Trade") {
input("paper")
input("alice's $900")
output(CASH_PROGRAM_ID, "borrowed $900") { 900.DOLLARS.CASH `issued by` issuer `owned by` MEGA_CORP }
output(thisTest.getContract(), "alice's paper") { "paper".output<ICommercialPaperState>().withOwner(ALICE) }
command(ALICE_PUBKEY) { Cash.Commands.Move() }
command(MEGA_CORP_PUBKEY) { thisTest.getMoveCommand() }
this.verifies()
}
// Time passes, and Alice redeem's her CP for $1000, netting a $100 profit. MegaCorp has received $1200
// as a single payment from somewhere and uses it to pay Alice off, keeping the remaining $200 as change.
transaction("Redemption") {
input("alice's paper")
input("some profits")
fun TransactionDSL<TransactionDSLInterpreter>.outputs(aliceGetsBack: Amount<Issued<Currency>>) {
output(CASH_PROGRAM_ID, "Alice's profit") { aliceGetsBack.STATE `owned by` ALICE }
output(CASH_PROGRAM_ID, "Change") { (someProfits - aliceGetsBack).STATE `owned by` MEGA_CORP }
}
command(MEGA_CORP_PUBKEY) { Cash.Commands.Move() }
command(ALICE_PUBKEY) { thisTest.getRedeemCommand(DUMMY_NOTARY) }
tweak {
outputs(700.DOLLARS `issued by` issuer)
timeWindow(TEST_TX_TIME + 8.days)
this `fails with` "received amount equals the face value"
}
outputs(1000.DOLLARS `issued by` issuer)
tweak {
timeWindow(TEST_TX_TIME + 2.days)
this `fails with` "must have matured"
}
timeWindow(TEST_TX_TIME + 8.days)
tweak {
output(thisTest.getContract()) { "paper".output<ICommercialPaperState>() }
this `fails with` "must be destroyed"
}
this.verifies()
}
}
}
@Test
fun `key mismatch at issue`() {
transaction {
output(thisTest.getContract()) { thisTest.getPaper() }
command(MINI_CORP_PUBKEY) { thisTest.getIssueCommand(DUMMY_NOTARY) }
timeWindow(TEST_TX_TIME)
this `fails with` "output states are issued by a command signer"
}
}
@Test
fun `face value is not zero`() {
transaction {
output(thisTest.getContract()) { thisTest.getPaper().withFaceValue(0.DOLLARS `issued by` issuer) }
command(MEGA_CORP_PUBKEY) { thisTest.getIssueCommand(DUMMY_NOTARY) }
timeWindow(TEST_TX_TIME)
this `fails with` "output values sum to more than the inputs"
}
}
@Test
fun `maturity date not in the past`() {
transaction {
output(thisTest.getContract()) { thisTest.getPaper().withMaturityDate(TEST_TX_TIME - 10.days) }
command(MEGA_CORP_PUBKEY) { thisTest.getIssueCommand(DUMMY_NOTARY) }
timeWindow(TEST_TX_TIME)
this `fails with` "maturity date is not in the past"
}
}
@Test
fun `issue cannot replace an existing state`() {
transaction {
input(thisTest.getContract(), thisTest.getPaper())
output(thisTest.getContract()) { thisTest.getPaper() }
command(MEGA_CORP_PUBKEY) { thisTest.getIssueCommand(DUMMY_NOTARY) }
timeWindow(TEST_TX_TIME)
this `fails with` "output values sum to more than the inputs"
}
}
/**
* Unit test requires two separate Database instances to represent each of the two
* transaction participants (enforces uniqueness of vault content in lieu of partipant identity)
*/
private lateinit var bigCorpServices: MockServices
private lateinit var bigCorpVault: Vault<ContractState>
private lateinit var bigCorpVaultService: VaultService
private lateinit var aliceServices: MockServices
private lateinit var aliceVaultService: VaultService
private lateinit var alicesVault: Vault<ContractState>
private val notaryServices = MockServices(DUMMY_NOTARY_KEY)
private val issuerServices = MockServices(DUMMY_CASH_ISSUER_KEY)
private lateinit var moveTX: SignedTransaction
@Test
fun `issue move and then redeem`() {
initialiseTestSerialization()
val aliceDatabaseAndServices = makeTestDatabaseAndMockServices(keys = listOf(ALICE_KEY))
val databaseAlice = aliceDatabaseAndServices.first
aliceServices = aliceDatabaseAndServices.second
aliceVaultService = aliceServices.vaultService
databaseAlice.transaction {
alicesVault = aliceServices.fillWithSomeTestCash(9000.DOLLARS, issuerServices, atLeastThisManyStates = 1, atMostThisManyStates = 1, issuedBy = DUMMY_CASH_ISSUER)
aliceVaultService = aliceServices.vaultService
}
val bigCorpDatabaseAndServices = makeTestDatabaseAndMockServices(keys = listOf(BIG_CORP_KEY))
val databaseBigCorp = bigCorpDatabaseAndServices.first
bigCorpServices = bigCorpDatabaseAndServices.second
bigCorpVaultService = bigCorpServices.vaultService
databaseBigCorp.transaction {
bigCorpVault = bigCorpServices.fillWithSomeTestCash(13000.DOLLARS, issuerServices, atLeastThisManyStates = 1, atMostThisManyStates = 1, issuedBy = DUMMY_CASH_ISSUER)
bigCorpVaultService = bigCorpServices.vaultService
}
// Propagate the cash transactions to each side.
aliceServices.recordTransactions(bigCorpVault.states.map { bigCorpServices.validatedTransactions.getTransaction(it.ref.txhash)!! })
bigCorpServices.recordTransactions(alicesVault.states.map { aliceServices.validatedTransactions.getTransaction(it.ref.txhash)!! })
// BigCorp™ issues $10,000 of commercial paper, to mature in 30 days, owned initially by itself.
val faceValue = 10000.DOLLARS `issued by` DUMMY_CASH_ISSUER
val issuance = bigCorpServices.myInfo.legalIdentity.ref(1)
val issueBuilder = CommercialPaper().generateIssue(issuance, faceValue, TEST_TX_TIME + 30.days, DUMMY_NOTARY)
issueBuilder.setTimeWindow(TEST_TX_TIME, 30.seconds)
val issuePtx = bigCorpServices.signInitialTransaction(issueBuilder)
val issueTx = notaryServices.addSignature(issuePtx)
databaseAlice.transaction {
// Alice pays $9000 to BigCorp to own some of their debt.
moveTX = run {
val builder = TransactionBuilder(DUMMY_NOTARY)
Cash.generateSpend(aliceServices, builder, 9000.DOLLARS, AnonymousParty(bigCorpServices.key.public))
CommercialPaper().generateMove(builder, issueTx.tx.outRef(0), AnonymousParty(aliceServices.key.public))
val ptx = aliceServices.signInitialTransaction(builder)
val ptx2 = bigCorpServices.addSignature(ptx)
val stx = notaryServices.addSignature(ptx2)
stx
}
}
databaseBigCorp.transaction {
// Verify the txns are valid and insert into both sides.
listOf(issueTx, moveTX).forEach {
it.toLedgerTransaction(aliceServices).verify()
aliceServices.recordTransactions(it)
bigCorpServices.recordTransactions(it)
}
}
databaseBigCorp.transaction {
fun makeRedeemTX(time: Instant): Pair<SignedTransaction, UUID> {
val builder = TransactionBuilder(DUMMY_NOTARY)
builder.setTimeWindow(time, 30.seconds)
CommercialPaper().generateRedeem(builder, moveTX.tx.outRef(1), bigCorpServices)
val ptx = aliceServices.signInitialTransaction(builder)
val ptx2 = bigCorpServices.addSignature(ptx)
val stx = notaryServices.addSignature(ptx2)
return Pair(stx, builder.lockId)
}
val redeemTX = makeRedeemTX(TEST_TX_TIME + 10.days)
val tooEarlyRedemption = redeemTX.first
val tooEarlyRedemptionLockId = redeemTX.second
val e = assertFailsWith(TransactionVerificationException::class) {
tooEarlyRedemption.toLedgerTransaction(aliceServices).verify()
}
// manually release locks held by this failing transaction
aliceServices.vaultService.softLockRelease(tooEarlyRedemptionLockId)
assertTrue(e.cause!!.message!!.contains("paper must have matured"))
val validRedemption = makeRedeemTX(TEST_TX_TIME + 31.days).first
validRedemption.toLedgerTransaction(aliceServices).verify()
// soft lock not released after success either!!! (as transaction not recorded)
}
resetTestSerialization()
}
}
| 4 | Kotlin | 1 | 1 | c36bea3af521be69f7702d7b7abbbfac0258de1f | 13,612 | corda | Apache License 2.0 |
buildSrc/src/main/kotlin/tasks/ReportGenerateTask.kt | sokoobo | 869,785,019 | false | {"Kotlin": 163808, "HTML": 4051} | package tasks
import korlibs.template.Template
import kotlinx.coroutines.runBlocking
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
import org.simpleframework.xml.Serializer
import org.simpleframework.xml.core.Persister
import tasks.model.TestCase
import tasks.model.TestSuite
import java.io.File
import kotlin.math.roundToInt
open class ReportGenerateTask : DefaultTask() {
@TaskAction
fun execute() {
val reportsRoot = File(project.rootDir, "build/test-results/test")
val outputRoot = File(project.rootDir, "build/test-results-html")
outputRoot.deleteRecursively()
outputRoot.mkdir()
for (file in checkNotNull(reportsRoot.listFiles()) {
"No files found in $reportsRoot"
}) {
if (file.isDirectory) {
continue
}
val report = makeReport(file)
val output = File(outputRoot, file.nameWithoutExtension + ".htm")
output.writeText(report)
println("Report generated: ${output.absolutePath}")
}
}
private fun makeReport(file: File): String {
val serializer: Serializer = Persister()
val testSuite = serializer.read(TestSuite::class.java, file)
val templateText = javaClass.classLoader.getResourceAsStream("report.html")?.use {
it.bufferedReader().readText()
}
val results = LinkedHashMap<String, LinkedHashMap<String, TestCase>>()
val tests = LinkedHashSet<String>()
for (case in testSuite.testCases) {
if (!case.isValid()) {
continue
}
tests.add(case.testName)
val map = results.getOrPut(case.source) { LinkedHashMap() }
val oldValue = map.put(case.testName, case)
check(oldValue == null) { "Check failed: $oldValue" }
}
val failPercent = (testSuite.failures.toDouble() / testSuite.tests * 100.0).roundToInt()
val errorPercent = (testSuite.errors.toDouble() / testSuite.tests * 100.0).roundToInt()
return runBlocking {
val template = Template(requireNotNull(templateText))
template(
mapOf(
"testSuite" to testSuite,
"tests" to tests,
"results" to results,
"success_percent" to 100 - (failPercent + errorPercent),
"error_percent" to errorPercent,
"fail_percent" to failPercent,
"success" to testSuite.tests - (testSuite.failures + testSuite.errors),
),
)
}
}
}
| 0 | Kotlin | 0 | 0 | 535e638059205ac87e77615cdc436b2500574f7d | 2,230 | damzel-parsers | MIT License |
src/main/kotlin/com/github/ninz9/aicommentator/llm/modelsImpl/openAI/data/post/Choice.kt | Ninz9 | 857,720,577 | false | {"Kotlin": 135585} | package com.github.ninz9.aicommentator.llm.modelsImpl.openAI.data.post
data class Choice(
val finish_reason: String,
val index: Int,
val logprobs: Any,
val message: Message
)
| 7 | Kotlin | 0 | 0 | 08e242ed26d8c6962e5e405725c64140f672afa9 | 192 | AiCommentator | MIT License |
simple-icons/src/commonMain/kotlin/compose/icons/simpleicons/Quora.kt | DevSrSouza | 311,134,756 | false | null | package compose.icons.simpleicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Butt
import androidx.compose.ui.graphics.StrokeJoin.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.SimpleIcons
public val SimpleIcons.Quora: ImageVector
get() {
if (_quora != null) {
return _quora!!
}
_quora = Builder(name = "Quora", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(12.738f, 18.701f)
curveToRelative(-0.831f, -1.635f, -1.805f, -3.287f, -3.708f, -3.287f)
curveToRelative(-0.362f, 0.0f, -0.727f, 0.061f, -1.059f, 0.209f)
lineToRelative(-0.646f, -1.289f)
curveToRelative(0.786f, -0.678f, 2.058f, -1.214f, 3.693f, -1.214f)
curveToRelative(2.544f, 0.0f, 3.851f, 1.229f, 4.888f, 2.792f)
curveToRelative(0.613f, -1.335f, 0.904f, -3.14f, 0.904f, -5.375f)
curveToRelative(0.0f, -5.582f, -1.744f, -8.447f, -5.822f, -8.447f)
curveToRelative(-4.018f, 0.0f, -5.757f, 2.865f, -5.757f, 8.447f)
curveToRelative(0.0f, 5.553f, 1.739f, 8.389f, 5.757f, 8.389f)
curveToRelative(0.64f, 0.0f, 1.22f, -0.069f, 1.75f, -0.225f)
close()
moveTo(13.734f, 20.648f)
curveToRelative(-0.881f, 0.237f, -1.817f, 0.366f, -2.743f, 0.366f)
curveToRelative(-5.352f, 0.0f, -10.59f, -4.269f, -10.59f, -10.478f)
curveTo(0.402f, 4.271f, 5.639f, 0.0f, 10.991f, 0.0f)
curveToRelative(5.441f, 0.0f, 10.628f, 4.238f, 10.628f, 10.537f)
curveToRelative(0.0f, 3.504f, -1.635f, 6.351f, -4.01f, 8.191f)
curveToRelative(0.764f, 1.148f, 1.543f, 1.914f, 2.652f, 1.914f)
curveToRelative(1.199f, 0.0f, 1.68f, -0.915f, 1.77f, -1.649f)
horizontalLineToRelative(1.557f)
curveToRelative(0.092f, 0.974f, -0.402f, 5.007f, -4.766f, 5.007f)
curveToRelative(-2.652f, 0.0f, -4.047f, -1.528f, -5.096f, -3.328f)
lineToRelative(0.008f, -0.024f)
close()
}
}
.build()
return _quora!!
}
private var _quora: ImageVector? = null
| 17 | null | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 2,869 | compose-icons | MIT License |
app/src/main/java/knf/kuma/animeinfo/AnimeViewModel.kt | jordyamc | 119,774,950 | false | null | package knf.kuma.animeinfo
import android.content.Context
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import knf.kuma.commons.doOnUI
import knf.kuma.commons.jsoupCookies
import knf.kuma.commons.noCrashLet
import knf.kuma.database.CacheDB
import knf.kuma.pojos.AnimeObject
import knf.kuma.retrofit.Repository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jetbrains.anko.doAsync
class AnimeViewModel : ViewModel() {
private val repository = Repository()
val liveData: MutableLiveData<AnimeObject?> = MutableLiveData()
fun init(context: Context, link: String?, persist: Boolean) {
link?.let {
if (it.contains("/ver/")) {
GlobalScope.launch(Dispatchers.Main) {
val nLink = withContext(Dispatchers.IO) { "https://animeflv.net" + noCrashLet { jsoupCookies(it).get().select("a[href~=/anime/]").attr("href") } }
repository.getAnime(context, nLink, persist, liveData)
}
} else
repository.getAnime(context, link, persist, liveData)
}
}
fun init(aid: String?) {
doAsync {
aid?.let {
val animeObject = CacheDB.INSTANCE.animeDAO().getAnimeByAid(aid)
doOnUI { liveData.value = animeObject }
} ?: doOnUI { liveData.value = null }
}
}
fun reload(context: Context, link: String?, persist: Boolean) {
init(context, link, persist)
}
}
| 24 | null | 40 | 159 | 99d8108ca5a9c32b89952aeb217319693df57688 | 1,607 | UKIKU | MIT License |
app/src/main/java/com/jonnemakinen/audiorecorder/recorder/RecordingState.kt | jonnemakinen | 575,529,060 | false | null | package com.jonnemakinen.audiorecorder.recorder
enum class RecordingState {
Idle,
Recording,
Saving
} | 0 | Kotlin | 0 | 0 | 3b573e78999ff1000c05bf4ae20846ae99d5a211 | 114 | audio-recorder | MIT License |
mmdownloader/src/main/java/pl/kwiatekmichal/mkdownloader/MMDownloaderException.kt | kwiatekM | 196,874,772 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Proguard": 2, "Kotlin": 15, "XML": 19, "Java": 2} | package pl.kwiatekmichal.mkdownloader
abstract class MMDownloaderException(override val message: String) : RuntimeException()
class MMDownloaderUriException(message: String) : MMDownloaderException(message = message)
class MMDownloaderEmptyRequestException(message: String) : MMDownloaderException(message = message) | 1 | null | 1 | 1 | c5e1e032e939c4b4b2940f772b0924c83e3196fd | 318 | MMDownloader | MIT License |
compiler/testData/debug/stepping/lambdaStepInlineWithDefaults.kt | JetBrains | 3,432,266 | false | null |
// FILE: test.kt
inline fun foo(stringMaker: () -> String = { "OK" }): String {
return stringMaker()
}
inline fun foo2(stringMaker: () -> String = {
"OK"
// Comment
}): String {
return stringMaker()
}
fun box(): String {
foo()
foo2()
return "OK"
}
// EXPECTATIONS JVM_IR
// test.kt:15 box
// test.kt:3 box
// test.kt:4 box
// test.kt:3 box
// test.kt:4 box
// test.kt:16 box
// test.kt:7 box
// test.kt:11 box
// test.kt:8 box
// test.kt:11 box
// test.kt:17 box
// EXPECTATIONS JS_IR
// test.kt:17 box
// EXPECTATIONS WASM
// test.kt:15 $box
// test.kt:4 $box (11, 4)
// test.kt:3 $box (45, 45, 45, 45, 49)
// test.kt:16 $box
// test.kt:11 $box (11, 4)
// test.kt:8 $box (4, 4, 4, 4, 8)
// test.kt:17 $box (11, 11, 11, 11, 4)
| 184 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 761 | kotlin | Apache License 2.0 |
feature/search/src/main/kotlin/com/merxury/blocker/feature/search/navigation/SearchNavigation.kt | lihenggui | 115,417,337 | false | null | /*
* Copyright 2023 Blocker
*
* 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.merxury.blocker.feature.search.navigation
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavOptions
import androidx.navigation.compose.composable
import com.merxury.blocker.core.ui.AppDetailTabs
import com.merxury.blocker.feature.search.SearchRoute
const val searchRoute = "search_route"
fun NavController.navigateToSearch(navOptions: NavOptions? = null) {
this.navigate(searchRoute, navOptions)
}
fun NavGraphBuilder.searchScreen(
navigateToAppDetail: (String, AppDetailTabs, List<String>) -> Unit = { _, _, _ -> },
navigateToRuleDetail: (Int) -> Unit = {},
) {
composable(route = searchRoute) {
SearchRoute(
navigateToAppDetail = navigateToAppDetail,
navigateToRuleDetail = navigateToRuleDetail,
)
}
}
| 25 | null | 54 | 988 | 9696c391c64d1aa4a74384d22b4433fb7c67c890 | 1,437 | blocker | Apache License 2.0 |
samples/kaspresso-compose-support-sample/src/main/kotlin/com/kaspersky/kaspresso/composesupport/sample/resources/C.kt | KasperskyLab | 208,070,025 | false | null | package com.kaspersky.kaspresso.composesupport.sample.resources
// Like R, but C
object C {
object Tag {
const val main_screen_container = "main_screen_container"
const val main_screen_simple_flaky_button = "main_screen_simple_flaky_button"
const val main_screen_scroll_button = "main_screen_scroll_button"
const val main_screen_sanity_flaky_button = "main_screen_sanity_flaky_button"
const val simple_flaky_screen_container = "simple_flaky_screen_container"
const val simple_flaky_screen_simple_first_button = "simple_flaky_screen_simple_first_button"
const val simple_flaky_screen_simple_second_button = "simple_flaky_screen_simple_second_button"
const val simple_flaky_screen_simple_edittext = "simple_flaky_screen_simple_edittext"
const val sanity_flaky_screen_container = "sanity_flaky_screen_container"
const val sanity_flaky_screen_simple_first_button = "sanity_flaky_screen_simple_first_button"
const val sanity_flaky_screen_simple_second_button = "sanity_flaky_screen_simple_second_button"
const val scroll_screen_container = "scroll_screen_container"
val scroll_screen_buttons = MutableList(30) {
"button_${it}"
}
}
object Screen {
const val main_screen = "main_screen"
const val simple_flaky_screen = "simple_flaky_screen"
const val sanity_flaky_screen = "sanity_flaky_screen"
const val scroll_screen = "scroll_screen"
}
}
| 55 | null | 150 | 1,784 | 9c94128c744d640dcd646b86de711d2a1b9c3aa1 | 1,511 | Kaspresso | Apache License 2.0 |
compose-mds/src/main/java/ch/sbb/compose_mds/sbbicons/large/FaceDisagreeLarge.kt | SchweizerischeBundesbahnen | 853,290,161 | false | {"Kotlin": 6728512} | package ch.sbb.compose_mds.sbbicons.large
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
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 ch.sbb.compose_mds.sbbicons.LargeGroup
public val LargeGroup.FaceDisagreeLarge: ImageVector
get() {
if (_faceDisagreeLarge != null) {
return _faceDisagreeLarge!!
}
_faceDisagreeLarge = Builder(name = "FaceDisagreeLarge", defaultWidth = 48.0.dp,
defaultHeight = 48.0.dp, viewportWidth = 48.0f, viewportHeight = 48.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd) {
moveTo(7.0f, 23.5f)
curveTo(7.0f, 13.835f, 14.835f, 6.0f, 24.5f, 6.0f)
reflectiveCurveTo(42.0f, 13.835f, 42.0f, 23.5f)
reflectiveCurveTo(34.165f, 41.0f, 24.5f, 41.0f)
reflectiveCurveTo(7.0f, 33.165f, 7.0f, 23.5f)
moveTo(24.5f, 5.0f)
curveTo(14.283f, 5.0f, 6.0f, 13.283f, 6.0f, 23.5f)
reflectiveCurveTo(14.283f, 42.0f, 24.5f, 42.0f)
reflectiveCurveTo(43.0f, 33.717f, 43.0f, 23.5f)
reflectiveCurveTo(34.717f, 5.0f, 24.5f, 5.0f)
moveToRelative(0.0f, 22.0f)
curveToRelative(-3.929f, 0.0f, -7.385f, 1.825f, -9.568f, 4.698f)
lineToRelative(0.796f, 0.605f)
curveTo(17.725f, 29.675f, 20.89f, 28.0f, 24.5f, 28.0f)
reflectiveCurveToRelative(6.775f, 1.675f, 8.772f, 4.303f)
lineToRelative(0.796f, -0.605f)
curveTo(31.885f, 28.825f, 28.43f, 27.0f, 24.5f, 27.0f)
moveToRelative(-6.0f, -7.793f)
lineToRelative(-2.646f, 2.647f)
lineToRelative(-0.708f, -0.708f)
lineToRelative(2.647f, -2.646f)
lineToRelative(-2.647f, -2.646f)
lineToRelative(0.708f, -0.708f)
lineToRelative(2.646f, 2.647f)
lineToRelative(2.646f, -2.647f)
lineToRelative(0.708f, 0.708f)
lineToRelative(-2.647f, 2.646f)
lineToRelative(2.647f, 2.646f)
lineToRelative(-0.708f, 0.708f)
close()
moveTo(30.5f, 19.207f)
lineTo(27.854f, 21.854f)
lineTo(27.146f, 21.146f)
lineTo(29.793f, 18.5f)
lineTo(27.146f, 15.854f)
lineTo(27.854f, 15.146f)
lineTo(30.5f, 17.793f)
lineTo(33.146f, 15.146f)
lineTo(33.854f, 15.854f)
lineTo(31.207f, 18.5f)
lineTo(33.854f, 21.146f)
lineTo(33.146f, 21.854f)
close()
}
}
.build()
return _faceDisagreeLarge!!
}
private var _faceDisagreeLarge: ImageVector? = null
| 0 | Kotlin | 0 | 1 | 090a66a40e1e5a44d4da6209659287a68cae835d | 3,407 | mds-android-compose | MIT License |
kt/entry-generation/godot-kotlin-symbol-processor/src/main/kotlin/godot/annotation/processor/compiler/KtCallExpressionExtractor.kt | utopia-rise | 289,462,532 | false | null | package godot.entrygenerator.generator.property.defaultvalue.extractor
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.MemberName
import org.jetbrains.kotlin.backend.common.serialization.findPackage
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.ClassConstructorDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.impl.ClassConstructorDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.FunctionDescriptorImpl
import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtConstructor
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.referenceExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getReferenceTargets
import org.jetbrains.kotlin.resolve.calls.callUtil.getType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassConstructorDescriptor
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedSimpleFunctionDescriptor
object KtCallExpressionExtractor {
fun extract(
bindingContext: BindingContext,
expression: KtCallExpression,
getDefaultValueTemplateStringWithTemplateArguments: (KtExpression) -> Pair<String, Array<out Any>>?
): Pair<String, Array<out Any>> {
val ref = expression
.referenceExpression()
?.getReferenceTargets(bindingContext)
?.firstOrNull()
if (ref != null) {
val psi = ref.findPsi()
val transformedArgs = expression
.valueArguments
.mapNotNull { it.getArgumentExpression() }
.map { getDefaultValueTemplateStringWithTemplateArguments(it) }
// if an arg is null, then it means that it contained a non static reference
var hasNullArg = false
for (arg in transformedArgs) {
if (arg == null) {
hasNullArg = true
break
}
}
when {
//constructor
psi is KtConstructor<*> && !hasNullArg -> {
val fqName = psi.containingClassOrObject!!.fqName
require(fqName != null)
val pkg = fqName.parent().asString()
val className = fqName.shortName().asString()
val params = mutableListOf<Any>()
params.add(ClassName(pkg, className))
transformedArgs.forEach { params.addAll(it!!.second) }
return "%T(${transformedArgs.joinToString { it!!.first }})" to params.toTypedArray()
}
//constructor
ref is ClassConstructorDescriptor && !hasNullArg -> {
val fqName = ref.constructedClass.fqNameSafe
val pkg = fqName.parent().asString()
val className = fqName.shortName().asString()
val params = mutableListOf<Any>()
params.add(ClassName(pkg, className))
transformedArgs.forEach { params.addAll(it!!.second) }
return "%T(${transformedArgs.joinToString { it!!.first }})" to params.toTypedArray()
}
//godot arrays and kotlin collections
//Note: kotlin collections only as constructor arguments or function params. TypeToVariantAsClassNameMapper already enshures that they are not registered as property types
ref is FunctionDescriptor && (
ref.fqNameSafe.asString().matches(Regex("^godot\\.core\\..*(ArrayOf|Array)\$"))
|| ref.fqNameSafe.asString().matches(Regex("^godot\\.core\\..*(dictionaryOf|Dictionary)\$"))
|| ref.findPackage().fqName.asString() == "kotlin.collections"
) -> {
val fqName = ref.fqNameSafe
val pkg = fqName.parent().asString()
val functionName = fqName.shortName().asString()
val params = mutableListOf<Any>()
params.add(MemberName(pkg, functionName))
transformedArgs.forEach { params.addAll(it!!.second) }
return "%M(${transformedArgs.joinToString { it!!.first }})" to params.toTypedArray()
}
//set's for enum flag registration
expression.getType(bindingContext)?.let(KotlinBuiltIns::isSetOrNullableSet) == true -> {
//setOf -> ref is null in this case
val params = mutableListOf<Any>()
params.add(expression.children.first().text)
transformedArgs.forEach { params.addAll(it!!.second) }
return "%L(${transformedArgs.joinToString { it!!.first }})" to params.toTypedArray()
}
}
}
throw IllegalStateException("KtCallExpressionExtractor could not handle expression: $expression")
}
}
| 50 | null | 25 | 301 | 0d33ac361b354b26c31bb36c7f434e6455583738 | 5,362 | godot-kotlin-jvm | MIT License |
android/src/main/java/com/jpiasecki/spatialsdk/BoxViewManager.kt | j-piasecki | 868,164,718 | false | {"Kotlin": 44340, "TypeScript": 15591, "Ruby": 3166, "Objective-C": 2527, "JavaScript": 1429, "Objective-C++": 1204, "C": 103, "Swift": 62} | package com.jpiasecki.spatialsdk
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.module.annotations.ReactModule
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.ViewGroupManager
import com.facebook.react.viewmanagers.RNSpatialBoxViewManagerDelegate
import com.facebook.react.viewmanagers.RNSpatialBoxViewManagerInterface
@ReactModule(name = PanelViewManager.NAME)
class BoxViewManager :
ViewGroupManager<BoxView>(),
RNSpatialBoxViewManagerInterface<BoxView> {
private val delegate = RNSpatialBoxViewManagerDelegate(this)
override fun getDelegate() = delegate
override fun getName() = NAME
override fun createViewInstance(reactContext: ThemedReactContext): BoxView = BoxView(reactContext)
override fun setPosition(view: BoxView, value: ReadableArray?) {
if (value != null) {
view.setPosition(
value.getDouble(0).toFloat(),
value.getDouble(1).toFloat(),
value.getDouble(2).toFloat(),
)
}
}
override fun setOrientation(view: BoxView, value: ReadableArray?) {
if (value != null) {
view.setOrientation(
value.getDouble(0).toFloat(),
value.getDouble(1).toFloat(),
value.getDouble(2).toFloat(),
)
}
}
override fun setWidth(view: BoxView, value: Double) {
view.setWidth(value.toFloat())
}
override fun setHeight(view: BoxView, value: Double) {
view.setHeight(value.toFloat())
}
override fun setDepth(view: BoxView, value: Double) {
view.setDepth(value.toFloat())
}
override fun setPositionRelativeToParent(view: BoxView, value: Boolean) {
view.setPositionRelativeToParent(value)
}
override fun getExportedCustomDirectEventTypeConstants(): MutableMap<String, Any> =
mutableMapOf(
PositionChangeEvent.NAME to mapOf("registrationName" to "onPositionChange"),
OrientationChangeEvent.NAME to mapOf("registrationName" to "onOrientationChange"),
)
companion object {
const val NAME = "RNSpatialBoxView"
}
}
| 0 | Kotlin | 0 | 6 | b1b15e35935e24f1b70a790beca04710285860ee | 2,041 | react-native-spatial-sdk | MIT License |
java/com/example/minecrafttamagotchiapp/MainActivity3.kt | Amongubishh | 796,691,130 | false | {"Kotlin": 6765} | package com.example.minecrafttamagotchiapp
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
class MainActivity3 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main3)
var returntopets = findViewById<Button>(R.id.returntopets)
returntopets.setOnClickListener {
val intent = Intent(this, MainActivity2::class.java)
startActivity(intent)
}
var feedbtn = findViewById<Button>(R.id.feed)
val editText: EditText = findViewById(R.id.et1)
val imageView: ImageView = findViewById(R.id.imageView4)
var counter = 0
feedbtn.setOnClickListener {
counter += 10
editText.setText(counter.toString())
imageView.setImageResource(R.drawable.iron_golem_eating)
var cleanbtn = findViewById<Button>(R.id.clean)
val editText: EditText = findViewById(R.id.et2)
var counter = 0
cleanbtn.setOnClickListener {
counter += 10
editText.setText(counter.toString())
imageView.setImageResource(R.drawable.cleangolem)
var playbtn = findViewById<Button>(R.id.play)
val editText: EditText = findViewById(R.id.et3)
var counter = 0
playbtn.setOnClickListener {
counter += 10
editText.setText(counter.toString())
imageView.setImageResource(R.drawable.iron_fun)
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 8dd50b0c8a1d7316318f7b4271679dacd71e2a82 | 2,051 | Assignment-2 | MIT License |
apps/mobile/src/main/kotlin/dev/marlonlom/cappajv/features/catalog_list/screens/DefaultPortraitCatalogListScreen.kt | marlonlom | 766,685,767 | false | {"Kotlin": 192163} | /*
* Copyright 2024 Marlonlom
* SPDX-License-Identifier: Apache-2.0
*/
package dev.marlonlom.cappajv.features.catalog_list.screens
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.safeContentPadding
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import dev.marlonlom.cappajv.core.database.entities.CatalogItemTuple
import dev.marlonlom.cappajv.features.catalog_list.parts.CatalogListHeadline
import dev.marlonlom.cappajv.features.catalog_list.slots.CatalogCategoriesChipGroup
import dev.marlonlom.cappajv.features.catalog_list.slots.CatalogListBanner
import dev.marlonlom.cappajv.features.catalog_list.slots.CatalogListTuplesSlot
import dev.marlonlom.cappajv.ui.main.CappajvAppState
/**
* Default portrait catalog list screen composable ui.
*
* @author marlonlom
*
* @param appState Application ui state.
* @param isRouting True/False if should navigate through routing.
* @param catalogItemsListState Catalog items lazy list state.
* @param catalogItems Catalog items list.
* @param categories Categories list.
* @param selectedCategory Selected category name.
* @param onSelectedCategoryChanged Action for category selected.
* @param onCatalogItemSelected Action for catalog item selected.
* @param modifier Modifier for this composable.
*/
@ExperimentalLayoutApi
@ExperimentalFoundationApi
@Composable
fun DefaultPortraitCatalogListScreen(
appState: CappajvAppState,
isRouting: Boolean,
catalogItemsListState: LazyListState,
catalogItems: List<CatalogItemTuple>,
categories: List<String>,
selectedCategory: String,
onSelectedCategoryChanged: (String) -> Unit,
onCatalogItemSelected: (Long, Boolean) -> Unit,
modifier: Modifier = Modifier,
) {
Column(
modifier = modifier
.fillMaxWidth()
.safeContentPadding(),
horizontalAlignment = Alignment.CenterHorizontally
) {
CatalogListHeadline(appState)
CatalogListBanner(appState)
CatalogCategoriesChipGroup(
categories = categories,
selectedCategory = selectedCategory,
onCategoryChipSelected = { onSelectedCategoryChanged(it) },
)
CatalogListTuplesSlot(
appState = appState,
catalogItemsListState = catalogItemsListState,
catalogTuples = catalogItems,
onCatalogItemTupleClicked = { onCatalogItemSelected(it, isRouting) },
)
}
}
| 5 | Kotlin | 0 | 0 | fc5aa21c0ae0a1bd5c1ea3176e0b0279882ac30d | 2,650 | cappajv | Apache License 2.0 |
app/src/main/java/com/codepath/articlesearch/DetailActivity.kt | FrenzyExists | 779,540,345 | false | null | package com.codepath.articlesearch
import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
private const val TAG = "DetailActivity"
class DetailActivity : AppCompatActivity() {
private lateinit var mediaImageView: ImageView
private lateinit var titleTextView: TextView
private lateinit var bylineTextView: TextView
private lateinit var abstractTextView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detail)
mediaImageView = findViewById(R.id.mediaImage)
titleTextView = findViewById(R.id.mediaTitle)
bylineTextView = findViewById(R.id.mediaByline)
abstractTextView = findViewById(R.id.mediaAbstract)
val article = intent.getSerializableExtra(ARTICLE_EXTRA) as DisplayArticle
// Set title and abstract information for the article
titleTextView.text = article.headline
bylineTextView.text = article.byline
abstractTextView.text = article.abstract
// I'm cooking
// Load the media image
Glide.with(this)
.load(article.mediaImageUrl)
.into(mediaImageView)
}
} | 1 | Kotlin | 1 | 0 | ef0115da3ed35f15d8e0e90215ec377e8de0320c | 1,322 | UpComingMovies | Apache License 2.0 |
app/src/main/java/com/kcteam/features/reimbursement/presentation/ReimbursementExpenseAdapter.kt | DebashisINT | 558,234,039 | false | null | package com.santebreezefsm.features.reimbursement.presentation
import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.santebreezefsm.R
import com.santebreezefsm.features.reimbursement.model.reimbursementlist.ReimbursementListDataModel
import kotlinx.android.synthetic.main.inflate_reimbursement_expense_item.view.*
/**
* Created by Saikat on 23-01-2019.
*/
class ReimbursementExpenseAdapter(context: Context, private val list: ArrayList<ReimbursementListDataModel>?, val listener: OnItemClickListener) : RecyclerView.Adapter<ReimbursementExpenseAdapter.MyViewHolder>() {
private val layoutInflater: LayoutInflater
private var context: Context
//private var list = arrayOfNulls<String>(10)
init {
layoutInflater = LayoutInflater.from(context)
this.context = context
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bindItems(context, list, listener)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val v = layoutInflater.inflate(R.layout.inflate_reimbursement_expense_item, parent, false)
return MyViewHolder(v)
}
override fun getItemCount(): Int {
return list?.size!!
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindItems(context: Context, list: ArrayList<ReimbursementListDataModel>?, listener: OnItemClickListener) {
//Picasso.with(context).load(list[adapterPosition].shopImageLocalPath).into(itemView.shop_image_IV)
try {
itemView.tv_food_amount.text = list?.get(adapterPosition)?.total_amount
itemView.tv_expense_type.text = list?.get(adapterPosition)?.expense_type
itemView.cv_food_price.isSelected = list?.get(adapterPosition)?.isSelected!!
itemView.iv_food_rupee.isSelected = list[adapterPosition].isSelected
itemView.tv_food_amount.isSelected = list[adapterPosition].isSelected
if (!TextUtils.isEmpty(list[adapterPosition].expense_type_image)) {
Glide.with(context)
.load(list[adapterPosition].expense_type_image)
.apply(RequestOptions.placeholderOf(R.drawable.ic_food_icon).error(R.drawable.ic_food_icon))
.into(itemView.iv_expense_icon)
}
itemView.setOnClickListener({
//if (adapterPosition==list[adapterPosition])
/*itemView.cv_food_price.isSelected = true
itemView.iv_food_rupee.isSelected = true
itemView.tv_food_amount.isSelected = true*/
listener.onItemClick(adapterPosition)
})
} catch (e: Exception) {
e.printStackTrace()
}
}
}
interface OnItemClickListener {
fun onItemClick(adapterPosition: Int)
}
} | 0 | null | 1 | 1 | e6114824d91cba2e70623631db7cbd9b4d9690ed | 3,221 | NationalPlastic | Apache License 2.0 |
goProControllerAndroid/src/main/java/com/bortxapps/goprocontrollerandroid/infrastructure/ble/data/BleNetworkMessage.kt | neoBortx | 692,337,190 | false | {"Kotlin": 340760, "Java": 572} | package com.bortxapps.goprocontrollerandroid.infrastructure.ble.data
@OptIn(ExperimentalUnsignedTypes::class)
data class BleNetworkMessage(val id: Int, val status: Int, val data: UByteArray) | 0 | Kotlin | 0 | 0 | b79c87b5a8d1f7bccf9918460c4024e1bcf02388 | 191 | goProController | Apache License 2.0 |
wire-grpc-server-generator/src/main/java/com/squareup/wire/kotlin/grpcserver/StubGenerator.kt | square | 12,274,147 | false | {"Kotlin": 4614764, "Java": 2161563, "Swift": 580805, "Ruby": 3972, "Shell": 1059, "JavaScript": 210} | /*
* Copyright (C) 2021 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire.kotlin.grpcserver
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.MemberName
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.wire.kotlin.grpcserver.ImplBaseGenerator.addImplBaseRpcSignature
import com.squareup.wire.schema.Rpc
import com.squareup.wire.schema.Service
object StubGenerator {
internal fun addStub(
generator: ClassNameGenerator,
builder: TypeSpec.Builder,
service: Service,
options: KotlinGrpcGenerator.Companion.Options
): TypeSpec.Builder {
return if (options.suspendingCalls) {
suspendedStubs(generator, service, builder, options)
} else {
asyncStubs(generator, service, builder, options)
}
}
private fun suspendedStubs(
generator: ClassNameGenerator,
service: Service,
builder: TypeSpec.Builder,
options: KotlinGrpcGenerator.Companion.Options
): TypeSpec.Builder {
val serviceClassName = generator.classNameFor(service.type)
val stubClassName = ClassName(
packageName = serviceClassName.packageName,
"${serviceClassName.simpleName}WireGrpc", "${serviceClassName.simpleName}Stub"
)
return builder
.addFunction(
FunSpec.builder("newStub")
.addParameter("channel", ClassName("io.grpc", "Channel"))
.returns(stubClassName)
.addCode("return %T(channel)", stubClassName)
.build()
)
.addType(
TypeSpec.classBuilder(stubClassName)
.apply {
addAbstractStubConstructor(generator, this, service,
ClassName("io.grpc.kotlin", "AbstractCoroutineStub"))
addSuspendedStubRpcCalls(generator, this, service, options)
}
.build()
)
}
private fun asyncStubs(
generator: ClassNameGenerator,
service: Service,
builder: TypeSpec.Builder,
options: KotlinGrpcGenerator.Companion.Options
): TypeSpec.Builder {
val serviceClassName = generator.classNameFor(service.type)
val stubClassName = ClassName(
packageName = serviceClassName.packageName,
"${serviceClassName.simpleName}WireGrpc", "${serviceClassName.simpleName}Stub"
)
return builder
.addFunction(
FunSpec.builder("newStub")
.addParameter("channel", ClassName("io.grpc", "Channel"))
.returns(stubClassName)
.addCode("return %T(channel)", stubClassName)
.build()
)
.addType(
TypeSpec.classBuilder(stubClassName)
.apply {
addAbstractStubConstructor(generator, this, service, ClassName("io.grpc.stub", "AbstractStub"))
addStubRpcCalls(generator, this, service, options)
}
.build()
)
}
internal fun addAbstractStubConstructor(
generator: ClassNameGenerator,
builder: TypeSpec.Builder,
service: Service,
superClass: ClassName
): TypeSpec.Builder {
val serviceClassName = generator.classNameFor(service.type)
val stubClassName = ClassName(
packageName = serviceClassName.packageName,
"${serviceClassName.simpleName}WireGrpc", "${serviceClassName.simpleName}Stub"
)
return builder
// Really this is a superclass, just want to add secondary constructors.
.addSuperinterface(superClass.parameterizedBy(stubClassName))
.addFunction(
FunSpec.constructorBuilder()
.addModifiers(KModifier.INTERNAL)
.addParameter("channel", ClassName("io.grpc", "Channel"))
.callSuperConstructor("channel")
.build()
)
.addFunction(
FunSpec.constructorBuilder()
.addModifiers(KModifier.INTERNAL)
.addParameter("channel", ClassName("io.grpc", "Channel"))
.addParameter("callOptions", ClassName("io.grpc", "CallOptions"))
.callSuperConstructor("channel", "callOptions")
.build()
)
.addFunction(
FunSpec.builder("build")
.addModifiers(KModifier.OVERRIDE)
.addParameter("channel", ClassName("io.grpc", "Channel"))
.addParameter("callOptions", ClassName("io.grpc", "CallOptions"))
.addStatement("return ${service.name}Stub(channel, callOptions)")
.build()
)
}
private fun addStubRpcCalls(
generator: ClassNameGenerator,
builder: TypeSpec.Builder,
service: Service,
options: KotlinGrpcGenerator.Companion.Options
): TypeSpec.Builder {
service.rpcs.forEach { rpc ->
val codeBlock = when {
rpc.requestStreaming ->
CodeBlock.of(
"return %M(channel.newCall(get${rpc.name}Method(), callOptions), response)",
MemberName(ClassName("io.grpc.stub", "ClientCalls"), clientCallType(rpc))
)
else ->
CodeBlock.of(
"%M(channel.newCall(get${rpc.name}Method(), callOptions), request, response)",
MemberName(ClassName("io.grpc.stub", "ClientCalls"), clientCallType(rpc))
)
}
builder.addFunction(
FunSpec.builder(rpc.name)
.apply { addImplBaseRpcSignature(generator, this, rpc, options) }
.addCode(codeBlock)
.build()
)
}
return builder
}
private fun addSuspendedStubRpcCalls(
generator: ClassNameGenerator,
builder: TypeSpec.Builder,
service: Service,
options: KotlinGrpcGenerator.Companion.Options
): TypeSpec.Builder {
service.rpcs.forEach { rpc ->
val codeBlock = CodeBlock.of(
"return %M(channel, get${rpc.name}Method(), request, callOptions)",
MemberName(ClassName("io.grpc.kotlin", "ClientCalls"), suspendedClientCallType(rpc))
)
builder.addFunction(
FunSpec.builder(rpc.name)
.apply { addImplBaseRpcSignature(generator, this, rpc, options) }
.addModifiers(KModifier.SUSPEND)
.addCode(codeBlock)
.build()
)
}
return builder
}
private fun suspendedClientCallType(rpc: Rpc): String = when {
rpc.requestStreaming && rpc.responseStreaming -> "bidiStreamingRpc"
rpc.requestStreaming -> "clientStreamingRpc"
rpc.responseStreaming -> "serverStreamingRpc"
else -> "unaryRpc"
}
private fun clientCallType(rpc: Rpc): String = when {
rpc.requestStreaming && rpc.responseStreaming -> "asyncBidiStreamingCall"
rpc.requestStreaming -> "asyncClientStreamingCall"
rpc.responseStreaming -> "asyncServerStreamingCall"
else -> "asyncUnaryCall"
}
}
| 163 | Kotlin | 621 | 4,142 | 9df9f57a4b7a771a7a3baf7600cc75b64d4a64f5 | 7,247 | wire | Apache License 2.0 |
app/src/main/java/com/sztorm/notecalendar/DayNoteFragment.kt | Sztorm | 342,018,745 | false | null | package com.sztorm.notecalendar
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.sztorm.notecalendar.databinding.FragmentDayNoteBinding
import com.sztorm.notecalendar.helpers.ViewHelper.Companion.hideKeyboard
import com.sztorm.notecalendar.helpers.ViewHelper.Companion.showKeyboard
import com.sztorm.notecalendar.repositories.NoteRepository
import timber.log.Timber
import java.time.LocalDate
class DayNoteFragment(
private val dayFragment: DayFragment, private var note: NoteData?
) : Fragment() {
private lateinit var binding: FragmentDayNoteBinding
private lateinit var mainActivity: MainActivity
override fun onAttach(context: Context) {
super.onAttach(context)
mainActivity = activity as MainActivity
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
binding = FragmentDayNoteBinding.inflate(inflater, container, false)
binding.lblNote.text = note?.text
setTheme()
setBtnNoteEditTextClickListener()
setBtnNoteEditSaveClickListener()
setBtnNoteEditCancelClickListener()
setBtnNoteDeleteTextClickListener()
return binding.root
}
private fun setEditUI() {
binding.btnNoteEditSave.visibility = View.VISIBLE
binding.btnNoteEditCancel.visibility = View.VISIBLE
binding.btnNoteEditText.visibility = View.GONE
binding.btnNoteDeleteText.visibility = View.GONE
binding.spacerCenter.visibility = View.GONE
binding.spacerEnd.visibility = View.GONE
binding.layoutNoteEditBottom.visibility = View.VISIBLE
binding.layoutNoteBottom.visibility = View.GONE
}
private fun setViewUI() {
binding.btnNoteEditSave.visibility = View.GONE
binding.btnNoteEditCancel.visibility = View.GONE
binding.btnNoteEditText.visibility = View.VISIBLE
binding.btnNoteDeleteText.visibility = View.VISIBLE
binding.spacerCenter.visibility = View.VISIBLE
binding.spacerEnd.visibility = View.VISIBLE
binding.layoutNoteEditBottom.visibility = View.GONE
binding.layoutNoteBottom.visibility = View.VISIBLE
}
private fun setBtnNoteEditTextClickListener() = binding.btnNoteEditText.setOnClickListener {
binding.txtNoteEdit.text.clear()
if (note !== null) {
binding.txtNoteEdit.text.append(note?.text)
}
setEditUI()
binding.txtNoteEdit.requestFocus()
binding.txtNoteEdit.showKeyboard()
}
private fun setBtnNoteEditSaveClickListener() = binding.btnNoteEditSave.setOnClickListener {
val editedText: String = binding.txtNoteEdit.text.toString()
val editedNote: NoteData? = NoteRepository.getByDate(mainActivity.viewedDate)
if (editedNote != null) {
editedNote.date = mainActivity.viewedDate.toString()
editedNote.text = editedText
editedNote.save()
note = editedNote
if (mainActivity.tryScheduleNoteNotification(
ScheduleNoteNotificationArguments(note = note)
)
) {
Timber.i("${LogTags.NOTIFICATIONS} Scheduled notification after note edit")
}
}
binding.lblNote.text = editedText
setViewUI()
binding.root.hideKeyboard()
}
private fun setBtnNoteEditCancelClickListener() = binding.btnNoteEditCancel.setOnClickListener {
setViewUI()
binding.txtNoteEdit.text.clear()
binding.root.hideKeyboard()
}
private fun setBtnNoteDeleteTextClickListener() = binding.btnNoteDeleteText.setOnClickListener {
val possibleNote: NoteData? = note
if (possibleNote !== null) {
NoteRepository.delete(possibleNote)
if (mainActivity.tryCancelScheduledNotification(LocalDate.parse(possibleNote.date))) {
Timber.i("${LogTags.NOTIFICATIONS} Canceled notification after note deletion")
}
}
dayFragment.setFragment(DayNoteEmptyFragment(dayFragment))
}
private fun setTheme() {
val themePainter: ThemePainter = mainActivity.themePainter
val noteColor: Int = themePainter.values.noteColor
binding.layoutNoteEditBottom.setBackgroundColor(noteColor)
binding.layoutNoteBottom.setBackgroundColor(noteColor)
binding.lblNote.setTextColor(themePainter.values.noteTextColor)
themePainter.paintNote(binding.layoutNoteUpper)
themePainter.paintOutlinedButton(binding.btnNoteEditText)
themePainter.paintOutlinedButton(binding.btnNoteDeleteText)
themePainter.paintButton(binding.btnNoteEditSave)
themePainter.paintButton(binding.btnNoteEditCancel)
themePainter.paintEditText(binding.txtNoteEdit)
}
} | 5 | null | 4 | 9 | 6d48535839826811dc5755ee6f5c02f73dc05132 | 4,988 | NoteCalendar | MIT License |
core/src/main/java/jmp0/apk/ManifestAnalyse.kt | asmjmp0 | 466,534,924 | false | null | package jmp0.apk
import org.apache.log4j.Logger
import org.dom4j.io.SAXReader
import org.dom4j.tree.DefaultElement
import java.io.File
import java.util.jar.Manifest
class ManifestAnalyse(private val manifestFile: File) {
private val logger = Logger.getLogger(manifestFile::class.java)
lateinit var packaeName:String
init {
analyse()
}
private fun analyseApplication(node:DefaultElement){
}
private fun analyseManifest(element: DefaultElement){
element.attributes().forEach { attribute->
if(attribute.qName.name == "package"){
packaeName = attribute.value
}
}
}
private fun analyse(){
val f = SAXReader().read(manifestFile)
f.content().forEach {
if(it is DefaultElement){
if(it.qName.name == "manifest"){
analyseManifest(it)
}
}
}
}
} | 0 | Kotlin | 42 | 189 | 468a37a87e5b87a8ee3623de8853f09b732e832b | 943 | appdbg | Apache License 2.0 |
modules/log/impl/src/commonMain/kotlin/com/hadilq/mastan/log/RealLogLogicIo.kt | hadilq | 715,823,678 | false | {"Kotlin": 689784, "Nix": 4671} | package com.hadilq.mastan.log
class RealLogLogicIo(
private val debugAllowed: Boolean,
private val warningAllowed: Boolean,
): LogLogicIo {
override fun logDebug(message: String) {
if (debugAllowed) {
println("QQQ d: $message")
}
}
override fun logDebug(message: () -> String) {
if (debugAllowed) {
logDebug(message())
}
}
override fun logWarning(message: String) {
if (warningAllowed) {
println("QQQ w: $message")
}
}
override fun logWarning(message: () -> String) {
if (warningAllowed) {
logWarning(message())
}
}
override fun wrongState(message: () -> String) {
if (debugAllowed) {
TODO("wrong state: ${message()}")
}
}
} | 0 | Kotlin | 0 | 3 | f17caa73c487d927d651e788215aa30b8b9cf842 | 817 | Mastan | Apache License 2.0 |
app/src/main/java/com/gbsys/card_reader_util/ui/main/MainFragment.kt | JulianSalinas | 246,587,829 | false | {"Java": 171863, "Kotlin": 38316} | package com.gbsys.card_reader_util.ui.main
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.gbsys.card_reader_util.R
class MainFragment : Fragment() {
companion object {
fun newInstance() = MainFragment()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
return inflater.inflate(R.layout.main_fragment, container, false)
}
}
| 1 | Java | 1 | 1 | aaa93985fda0e61b973ec9c3495562f910a943ca | 571 | card-reader-util | Apache License 2.0 |
src/main/kotlin/id/walt/vclib/credentials/gaiax/KybCredential.kt | walt-id | 392,421,433 | false | null | package id.walt.vclib.credentials.gaiax
import com.beust.klaxon.Json
import id.walt.vclib.model.*
import id.walt.vclib.registry.VerifiableCredentialMetadata
import id.walt.vclib.schema.SchemaService.PropertyName
import id.walt.vclib.schema.SchemaService.Required
data class KybCredential(
@Json(name = "@context") @field:PropertyName(name = "@context") @field:Required
var context: List<String> = listOf("https://www.w3.org/2018/credentials/v1"),
override var id: String?,
override var issuer: String?,
@Json(serializeNull = false) override var issuanceDate: String? = null,
@Json(serializeNull = false) override var validFrom: String? = null,
@Json(serializeNull = false) override var expirationDate: String? = null,
@Json(serializeNull = false) override var credentialSubject: KybCredentialSubject?,
@Json(serializeNull = false) override var credentialSchema: CredentialSchema? = null,
@Json(serializeNull = false) override var proof: Proof? = null,
) : AbstractVerifiableCredential<KybCredential.KybCredentialSubject>(type) {
data class KybCredentialSubject(
override var id: String?, // did:key
var legallyBindingName: String, // deltaDAO AG
var brandName: String, // deltaDAO
var legallyBindingAddress: LegallyBindingAddress,
var webAddress: String,
var corporateEmailAddress: String, // <EMAIL>
var individualContactLegal: String, // <EMAIL>
var individualContactTechnical: String, // <EMAIL>
var legalForm: String, // Stock Company
var jurisdiction: String, // Germany
var commercialRegister: CommercialRegister,
var legalRegistrationNumber: String // HRB 170364
) : CredentialSubject() {
data class LegallyBindingAddress(
var streetAddress: String, // Geibelstr. 46B
var postalCode: String, // 22303
var locality: String, // Hamburg
var countryName: String // Germany
)
data class CommercialRegister(
var organizationName: String, // Amtsgericht Hamburg (-Mitte)
var organizationUnit: String, // Registergericht
var streetAddress: String, // Caffamacherreihe 20
var postalCode: String, // 20355
var locality: String, // Hamburg
var countryName: String // Germany
)
}
companion object : VerifiableCredentialMetadata(
type = listOf("VerifiableCredential", "VerifiableAttestation", "KybCredential"),
template = {
KybCredential(
id = "did:ebsi-eth:00000001/credentials/1872",
issuer = "did:example:456",
issuanceDate = "2020-08-24T14:13:44Z",
credentialSubject = KybCredentialSubject(
id = "did:key:dummy",
legallyBindingName = "deltaDAO AG",
brandName = "deltaDAO",
webAddress = "https://www.delta-dao.com/",
legallyBindingAddress = KybCredentialSubject.LegallyBindingAddress(
streetAddress = "Geibelstr. 46B",
postalCode = "22303",
locality = "Hamburg",
countryName = "Germany"
),
corporateEmailAddress = "<EMAIL>",
individualContactLegal = "<EMAIL>",
individualContactTechnical = "<EMAIL>",
legalForm = "Stock Company",
jurisdiction = "Germany",
commercialRegister = KybCredentialSubject.CommercialRegister(
organizationName = "Amtsgericht Hamburg (-Mitte)",
organizationUnit = "Registergericht",
streetAddress = "Caffamacherreihe 20",
postalCode = "20355",
locality = "Hamburg",
countryName = "Germany"
),
legalRegistrationNumber = "HRB 170364"
)
)
}
)
}
| 5 | Kotlin | 6 | 9 | 87d79bfb29b307c717b2c3db54f787244be0878d | 4,123 | waltid-ssikit-vclib | Apache License 2.0 |
logic-auth-server/src/main/kotlin/io/lonmstalker/springkube/enums/TokenType.kt | lonmstalker | 634,331,522 | false | null | package io.lonmstalker.springkube.enums
enum class TokenType {
ACCESS,
REFRESH
} | 0 | Kotlin | 0 | 0 | d94bd56bf4d4ce5e5163840f369eba993431a10a | 89 | spring-kube | Apache License 2.0 |
sample/src/main/java/ru/volkdown/sample/base/LifeCycleEvent.kt | volkdown | 237,741,034 | false | null | package ru.volkdown.sample.base
enum class LifeCycleEvent {
ATTACH,
CREATE,
CREATE_VIEW,
START,
RESUME,
PAUSE,
STOP,
DESTROY_VIEW,
DESTROY,
DETACH
} | 0 | Kotlin | 0 | 6 | 090509a0fba784a6a109c7944a012515a20c0d75 | 189 | octopus | MIT License |
src/main/kotlin/dev/entao/kava/json/YsonValue.kt | yangentao | 181,521,846 | false | null | @file:Suppress("unused", "MemberVisibilityCanBePrivate")
package dev.entao.kan.json
abstract class YsonValue {
abstract fun yson(buf: StringBuilder)
open fun yson(): String {
val sb = StringBuilder(preferBufferSize())
yson(sb)
return sb.toString()
}
open fun preferBufferSize(): Int {
return 64
}
override fun toString(): String {
return yson()
}
val isCollection: Boolean get() = this is YsonObject || this is YsonArray
companion object {
fun from(value: Any?): YsonValue {
return when (value) {
null -> YsonNull.inst
is YsonValue -> value
is String -> YsonString(value)
is Boolean -> YsonBool(value)
is Number -> YsonNum(value)
is ByteArray -> YsonBlob(value)
else -> YsonString(value.toString())
}
}
}
} | 0 | Kotlin | 0 | 0 | a860d75281ccf39906c69599096ff20ff88a0279 | 772 | kavajson | MIT License |
src/main/kotlin/dev/entao/kava/json/YsonValue.kt | yangentao | 181,521,846 | false | null | @file:Suppress("unused", "MemberVisibilityCanBePrivate")
package dev.entao.kan.json
abstract class YsonValue {
abstract fun yson(buf: StringBuilder)
open fun yson(): String {
val sb = StringBuilder(preferBufferSize())
yson(sb)
return sb.toString()
}
open fun preferBufferSize(): Int {
return 64
}
override fun toString(): String {
return yson()
}
val isCollection: Boolean get() = this is YsonObject || this is YsonArray
companion object {
fun from(value: Any?): YsonValue {
return when (value) {
null -> YsonNull.inst
is YsonValue -> value
is String -> YsonString(value)
is Boolean -> YsonBool(value)
is Number -> YsonNum(value)
is ByteArray -> YsonBlob(value)
else -> YsonString(value.toString())
}
}
}
} | 0 | Kotlin | 0 | 0 | a860d75281ccf39906c69599096ff20ff88a0279 | 772 | kavajson | MIT License |
app/src/androidTest/java/com/ultraviolince/mykitchen/recipes/presentation/recipes/SmokeTest.kt | violinyanev | 714,727,270 | false | {"Kotlin": 95524} | package com.ultraviolince.mykitchen.recipes.presentation.recipes
import android.util.Log
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.hasContentDescription
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performTextInput
import androidx.test.platform.app.InstrumentationRegistry
import androidx.work.Configuration
import androidx.work.testing.SynchronousExecutor
import androidx.work.testing.WorkManagerTestInitHelper
import com.ultraviolince.mykitchen.recipes.presentation.MainActivity
import org.junit.Before
import org.junit.Rule
import org.junit.Test
@OptIn(ExperimentalTestApi::class)
class SmokeTest {
@get:Rule
val composeTestRule = createAndroidComposeRule<MainActivity>()
@Before
fun setup() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
val config = Configuration.Builder()
.setMinimumLoggingLevel(Log.DEBUG)
.setExecutor(SynchronousExecutor())
.build()
WorkManagerTestInitHelper.initializeTestWorkManager(context, config)
}
private fun createRecipe(title: String, content: String) {
// When the "New Recipe" button is clicked
with(composeTestRule.onNodeWithContentDescription("New recipe")) {
assertExists()
assertIsDisplayed()
performClick()
}
composeTestRule.waitForIdle()
// Type recipe details
with(composeTestRule.onNodeWithContentDescription("Enter recipe title")) {
assertExists()
assertIsDisplayed()
performTextInput(title)
}
with(composeTestRule.onNodeWithContentDescription("Enter recipe content")) {
assertExists()
assertIsDisplayed()
performTextInput(content)
}
// Click "save"
with(composeTestRule.onNodeWithContentDescription("Save recipe")) {
assertExists()
assertIsDisplayed()
performClick()
}
composeTestRule.waitForIdle()
// Recipe is in the overview
with(composeTestRule.onNodeWithText(title)) {
assertExists()
assertIsDisplayed()
}
with(composeTestRule.onNodeWithText(content)) {
assertExists()
assertIsDisplayed()
}
}
@Test fun createRecipe_WithoutLogin() {
// By default, no cloud sync
with(composeTestRule.onNodeWithContentDescription("Synchronisation with the backend is disabled")) {
assertExists()
assertIsDisplayed()
}
createRecipe("recipe1", "content1")
}
// TODO Fix the test
@Test fun loginToBackend_ThenCreateRecipe() {
// By default, no cloud sync
with(composeTestRule.onNodeWithContentDescription("Synchronisation with the backend is disabled")) {
assertExists()
assertIsDisplayed()
performClick()
}
// Enter server and credentials
with(composeTestRule.onNodeWithContentDescription("Server URI")) {
assertExists()
assertIsDisplayed()
performTextInput("https://ultraviolince.com:8019")
}
with(composeTestRule.onNodeWithContentDescription("User name")) {
assertExists()
assertIsDisplayed()
performTextInput("[email protected]")
}
with(composeTestRule.onNodeWithContentDescription("Password")) {
assertExists()
assertIsDisplayed()
performTextInput("TestPassword")
}
// Login
with(composeTestRule.onNodeWithContentDescription("Login")) {
assertExists()
assertIsDisplayed()
performClick()
}
// Create a new recipe, with backend now
composeTestRule.waitUntilExactlyOneExists(hasContentDescription("New recipe"), 5000)
createRecipe("recipe2", "content2")
}
}
| 8 | Kotlin | 0 | 0 | f814c155b820c65103ce50f47d4f90b3f5aa9a76 | 4,236 | my-kitchen | Apache License 2.0 |
src/main/java/net/eduard/api/lib/command/BukkitCommand.kt | EduardMaster | 103,982,025 | false | null | package net.eduard.api.lib.command
import net.eduard.api.lib.hybrid.Hybrid
import net.eduard.api.lib.manager.CommandManager
import net.eduard.api.lib.modules.Extra
import net.eduard.api.lib.modules.Mine
import net.eduard.api.lib.plugin.IPluginInstance
import org.bukkit.Bukkit
import org.bukkit.command.*
import org.bukkit.command.Command
import org.bukkit.entity.Player
import org.bukkit.plugin.java.JavaPlugin
class BukkitCommand(val command: net.eduard.api.lib.command.Command)
: Command(command.name),
CommandExecutor,
TabCompleter, HybridCommand {
override fun register(plugin: IPluginInstance) {
register(plugin.plugin as JavaPlugin)
}
override fun unregister(plugin: IPluginInstance){
unregister(plugin.plugin as JavaPlugin)
}
fun unregister(plugin: JavaPlugin){
try {
val commandMap = Extra.getFieldValue(Bukkit.getServer().pluginManager, "commandMap") as CommandMap
unregister(commandMap)
//commandMap.getCommand("cmd").unregister(commandMap)
val currentCommands = Extra.getFieldValue(commandMap, "knownCommands") as MutableMap<String, Command>
val cmdName = name.toLowerCase()
val pluginName = plugin.name.toLowerCase()
for (aliase in aliases) {
//log("Removendo aliase §a$aliase§f do comando §b$cmdName")
currentCommands.remove(aliase.toLowerCase())
currentCommands.remove(pluginName.toLowerCase() + ":" + aliase.toLowerCase())
}
try {
currentCommands.remove(cmdName)
currentCommands.remove(pluginName.toLowerCase() + ":" + cmdName)
} catch (ex: Exception) {
ex.printStackTrace()
}
} catch (ex: java.lang.Exception) {
ex.printStackTrace()
}
}
fun register(plugin: JavaPlugin) {
var cmd: Command? = plugin.getCommand(command.name)
var registred = false
if ((cmd != null)) {
registred = true
(cmd as PluginCommand).executor = this
cmd.tabCompleter = this
} else cmd = this
cmd.permission = command.permission
cmd.permissionMessage = command.permissionMessage
cmd.aliases = command.aliases
cmd.usage = command.usage
cmd.description = command.description
if (!registred) {
Bukkit.getScheduler().runTask(plugin) {
val serverClass = Extra.getClassFrom(Bukkit.getServer())
val field = serverClass.getDeclaredField("commandMap")
field.isAccessible = true
val map = field[Bukkit.getServer()] as CommandMap
map.register(plugin.name, cmd)
}
}
}
override fun onCommand(sender: CommandSender, cmd: Command, label: String, args: Array<String>): Boolean {
if (sender is Player) {
command.processCommand(
Hybrid.instance.getPlayer(sender.name, sender.uniqueId),
args.toList()
)
} else {
command.processCommand(Hybrid.instance.console, args.toList())
}
return true
}
override fun execute(sender: CommandSender, label: String, args: Array<String>): Boolean {
try {
if (sender.hasPermission(permission)) {
return onCommand(sender, this, label, args)
} else {
sender.sendMessage(permissionMessage)
}
} catch (ex: Exception) {
ex.printStackTrace()
}
return false
}
@Throws(IllegalArgumentException::class)
override fun tabComplete(sender: CommandSender, alias: String, args: Array<String>): List<String>? {
return onTabComplete(sender, this, alias, args)
}
override fun onTabComplete(
sender: CommandSender, cmd: Command,
label: String,
args: Array<String>
): List<String>? {
val result = command.processTabComplete(
if (sender is Player)
Hybrid.instance.getPlayer(sender.name, sender.uniqueId)
else Hybrid.instance.console, args.toList()
)
return result.ifEmpty { null }
}
} | 0 | null | 5 | 7 | bb778365ce76fabbdbc516b918b4feedee7edf12 | 4,287 | MineToolkit | MIT License |
sample/src/main/java/com/cookpad/android/license_tools_plugin/ui/send/SendViewModel.kt | k4zy | 234,051,686 | false | null | package com.minapp.android.test.ui.send
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class SendViewModel : ViewModel() {
private val _text = MutableLiveData<String>().apply {
value = "This is send Fragment"
}
val text: LiveData<String> = _text
} | 95 | null | 88 | 4 | 5985018f4dfa38f89133c7960df3630283b3600a | 336 | LicenseToolsPlugin | Apache License 2.0 |
src/main/kotlin/team/kun/minecraftwars/rx/Observable.kt | TeamKun | 377,053,216 | false | null | package net.kunmc.lab.theworld.rx
import org.bukkit.plugin.java.JavaPlugin
import org.bukkit.scheduler.BukkitRunnable
class Observable private constructor(private val tick: Long) {
companion object {
fun interval(tick: Long): Observable {
return Observable(tick)
}
}
private var limit: Long? = null
private var doOnNextFunction: ((data: Long) -> Unit)? = null
private var doOnCompleteFunction: ((data: Long) -> Unit)? = null
private var doOnCompleteConditionFunction: ((data: Long) -> Boolean)? = null
private var doOnErrorFunction: ((data: Long) -> Unit)? = null
private var doOnErrorConditionFunction: ((data: Long) -> Boolean)? = null
fun take(data: Long): Observable {
limit = data
return this
}
fun doOnNext(function: (data: Long) -> Unit): Observable {
doOnNextFunction = function
return this
}
fun doOnCompleteCondition(function: (data: Long) -> Boolean): Observable {
doOnCompleteConditionFunction = function
return this
}
fun doOnComplete(function: (data: Long) -> Unit): Observable {
doOnCompleteFunction = function
return this
}
fun doOnErrorCondition(function: (data: Long) -> Boolean): Observable {
doOnErrorConditionFunction = function
return this
}
fun doOnError(function: (data: Long) -> Unit): Observable {
doOnErrorFunction = function
return this
}
fun subscribe(plugin: JavaPlugin) {
object : BukkitRunnable() {
var data: Long = 0L
override fun run() {
val isComplete = doOnCompleteConditionFunction?.invoke(data) ?: false
if (isComplete || isLimit(data)) {
doOnCompleteFunction?.invoke(data)
plugin.server.scheduler.cancelTask(taskId)
}
val isError = doOnErrorConditionFunction?.invoke(data) ?: false
if (isError) {
doOnErrorFunction?.invoke(data)
plugin.server.scheduler.cancelTask(taskId)
}
doOnNextFunction?.invoke(data)
data += 1
}
}.runTaskTimerAsynchronously(plugin, 0, tick)
}
private fun isLimit(data: Long): Boolean {
val currentLimit = limit ?: return false
return data >= currentLimit
}
}
| 0 | null | 1 | 1 | 9070a48f550ce90ad75934c52ff501ce11f451af | 2,428 | SpigotTemplate | Apache License 2.0 |
compiler/fir/fir2ir/jvm-backend/src/org/jetbrains/kotlin/fir/backend/jvm/JvmFir2IrExtensions.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.backend.jvm
import org.jetbrains.kotlin.backend.common.serialization.signature.PublicIdSignatureComputer
import org.jetbrains.kotlin.backend.jvm.*
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.JVMConfigurationKeys
import org.jetbrains.kotlin.config.JvmSerializeIrMode
import org.jetbrains.kotlin.config.languageVersionSettings
import org.jetbrains.kotlin.fir.backend.Fir2IrComponents
import org.jetbrains.kotlin.fir.backend.Fir2IrConversionScope
import org.jetbrains.kotlin.fir.backend.Fir2IrExtensions
import org.jetbrains.kotlin.fir.backend.InjectedValue
import org.jetbrains.kotlin.fir.references.FirReference
import org.jetbrains.kotlin.ir.IrBuiltIns
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrExternalPackageFragmentImpl
import org.jetbrains.kotlin.ir.declarations.impl.IrFactoryImpl
import org.jetbrains.kotlin.ir.overrides.IrExternalOverridabilityCondition
import org.jetbrains.kotlin.ir.symbols.impl.DescriptorlessExternalPackageFragmentSymbol
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.load.java.JvmAnnotationNames
import org.jetbrains.kotlin.load.kotlin.FacadeClassSource
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
class JvmFir2IrExtensions(
configuration: CompilerConfiguration,
private val irDeserializer: JvmIrDeserializer,
private val mangler: KotlinMangler.IrMangler,
) : Fir2IrExtensions, JvmGeneratorExtensions {
override val externalOverridabilityConditions: List<IrExternalOverridabilityCondition> = emptyList() // TODO: KT-61370, KT-61804
override val classNameOverride: MutableMap<IrClass, JvmClassName> = mutableMapOf()
override val cachedFields = CachedFieldsForObjectInstances(IrFactoryImpl, configuration.languageVersionSettings)
private val kotlinIrInternalPackage =
IrExternalPackageFragmentImpl(DescriptorlessExternalPackageFragmentSymbol(), IrBuiltIns.KOTLIN_INTERNAL_IR_FQN)
private val kotlinJvmInternalPackage =
IrExternalPackageFragmentImpl(DescriptorlessExternalPackageFragmentSymbol(), JvmAnnotationNames.KOTLIN_JVM_INTERNAL)
private val specialAnnotationConstructors = mutableListOf<IrConstructor>()
private val rawTypeAnnotationClass =
createSpecialAnnotationClass(JvmSymbols.RAW_TYPE_ANNOTATION_FQ_NAME, kotlinIrInternalPackage)
override val rawTypeAnnotationConstructor: IrConstructor =
rawTypeAnnotationClass.constructors.single()
init {
createSpecialAnnotationClass(JvmAnnotationNames.ENHANCED_NULLABILITY_ANNOTATION, kotlinJvmInternalPackage)
createSpecialAnnotationClass(JvmSymbols.FLEXIBLE_NULLABILITY_ANNOTATION_FQ_NAME, kotlinIrInternalPackage)
createSpecialAnnotationClass(JvmSymbols.FLEXIBLE_MUTABILITY_ANNOTATION_FQ_NAME, kotlinIrInternalPackage)
}
private fun createSpecialAnnotationClass(fqn: FqName, parent: IrPackageFragment) =
IrFactoryImpl.createSpecialAnnotationClass(fqn, parent).apply {
specialAnnotationConstructors.add(constructors.single())
}
override fun registerDeclarations(symbolTable: SymbolTable) {
val signatureComputer = PublicIdSignatureComputer(mangler)
specialAnnotationConstructors.forEach { constructor ->
symbolTable.declareConstructorWithSignature(signatureComputer.composePublicIdSignature(constructor, false), constructor.symbol)
}
}
override fun findInjectedValue(calleeReference: FirReference, conversionScope: Fir2IrConversionScope): InjectedValue? {
return null
}
override val irNeedsDeserialization: Boolean =
configuration.get(JVMConfigurationKeys.SERIALIZE_IR, JvmSerializeIrMode.NONE) != JvmSerializeIrMode.NONE
override fun generateOrGetFacadeClass(declaration: IrMemberWithContainerSource, components: Fir2IrComponents): IrClass? {
val deserializedSource = declaration.containerSource ?: return null
if (deserializedSource !is FacadeClassSource) return null
val facadeName = deserializedSource.facadeClassName ?: deserializedSource.className
return JvmFileFacadeClass(
if (deserializedSource.facadeClassName != null) IrDeclarationOrigin.JVM_MULTIFILE_CLASS else IrDeclarationOrigin.FILE_CLASS,
facadeName.fqNameForTopLevelClassMaybeWithDollars.shortName(),
deserializedSource,
deserializeIr = { irClass -> deserializeToplevelClass(irClass, components) }
).also {
it.createParameterDeclarations()
classNameOverride[it] = facadeName
}
}
override fun deserializeToplevelClass(irClass: IrClass, components: Fir2IrComponents): Boolean =
irDeserializer.deserializeTopLevelClass(
irClass, components.irBuiltIns, components.symbolTable, components.irProviders, this
)
}
| 182 | null | 5771 | 47,637 | d257153a50bdaa761d54bbc9fd1c5d78a3769f0f | 5,152 | kotlin | Apache License 2.0 |
app/src/main/java/org/footstep/activities/AddFootstepActivity.kt | yuantao-yin | 255,526,268 | false | null | package org.footstep.activities
import android.Manifest
import android.app.Activity
import android.app.DatePickerDialog
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.provider.Settings
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.google.android.libraries.places.api.Places
import com.google.android.libraries.places.api.model.Place
import com.google.android.libraries.places.widget.Autocomplete
import com.google.android.libraries.places.widget.model.AutocompleteActivityMode
import com.karumi.dexter.Dexter
import com.karumi.dexter.MultiplePermissionsReport
import com.karumi.dexter.PermissionToken
import com.karumi.dexter.listener.PermissionRequest
import com.karumi.dexter.listener.multi.MultiplePermissionsListener
import kotlinx.android.synthetic.main.activity_add_footstep.*
import org.footstep.R
import org.footstep.database.DatabaseHandler
import org.footstep.models.FootstepModel
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
class AddFootstepActivity : AppCompatActivity(), View.OnClickListener{
private var cal = Calendar.getInstance()
private lateinit var dataSetListener: DatePickerDialog.OnDateSetListener
private var savedImagePath: Uri? = null
private var mLatitude: Double = 0.0
private var mLongitude: Double = 0.0
private var mFootstepDetails: FootstepModel? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_footstep)
setSupportActionBar(toolbar_add_place)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
toolbar_add_place.setNavigationOnClickListener {
onBackPressed()
}
if (!Places.isInitialized()) {
Places.initialize(this@AddFootstepActivity, resources.getString(R.string.google_maps_api_key))
}
dataSetListener = DatePickerDialog.OnDateSetListener{
view, year, month, dayOfMonth ->
cal.set(Calendar.YEAR, year)
cal.set(Calendar.MONTH, month)
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
updateDateInView()
}
updateDateInView()
if (intent.hasExtra(MainActivity.EXTRA_DETAILS)) {
mFootstepDetails = intent.getParcelableExtra(MainActivity.EXTRA_DETAILS) as FootstepModel
}
if(mFootstepDetails != null) {
supportActionBar?.title = "Edit Happy Place"
et_title.setText(mFootstepDetails!!.title)
et_description.setText(mFootstepDetails!!.description)
et_date.setText(mFootstepDetails!!.date)
et_location.setText(mFootstepDetails!!.location)
mLatitude = mFootstepDetails!!.latitude
mLongitude = mFootstepDetails!!.longitude
savedImagePath = Uri.parse(mFootstepDetails!!.image)
iv_place_image.setImageURI(savedImagePath)
btn_save.text = "UPDATE"
}
et_date.setOnClickListener(this)
tv_add_image.setOnClickListener(this)
btn_save.setOnClickListener(this)
et_location.setOnClickListener(this)
}
private fun updateDateInView() {
val myFormat = "yyyy-MM-dd"
val sdf = SimpleDateFormat(myFormat, Locale.getDefault())
et_date.setText(sdf.format(cal.time).toString())
}
override fun onClick(v: View?) {
when(v!!.id) {
R.id.et_date -> {
DatePickerDialog(
this@AddFootstepActivity,
dataSetListener,
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH)
).show()
}
R.id.tv_add_image -> {
val pictureDialog = AlertDialog.Builder(this)
pictureDialog.setTitle("Select Action")
val pictureDialogItems = arrayOf("Select photo from Gallery",
"Capture photo from camera")
pictureDialog.setItems(pictureDialogItems) {
dialog, which ->
when(which) {
0 -> choosePhotoFromGallery()
1 -> takePhotoFromCamera()
}
}
pictureDialog.show()
}
R.id.btn_save -> {
when {
et_title.text.isNullOrEmpty() -> {
Toast.makeText(this, "Please enter title", Toast.LENGTH_SHORT).show()
}
et_description.text.isNullOrEmpty() -> {
Toast.makeText(this, "Please enter description", Toast.LENGTH_SHORT)
.show()
}
// et_location.text.isNullOrEmpty() -> {
// Toast.makeText(this, "Please select location", Toast.LENGTH_SHORT)
// .show()
// }
savedImagePath == null -> {
Toast.makeText(this, "Please add image", Toast.LENGTH_SHORT).show()
}
else -> {
val footstepModel = FootstepModel(
if (mFootstepDetails == null) 0 else mFootstepDetails!!.id,
et_title.text.toString(),
savedImagePath.toString(),
et_description.text.toString(),
et_date.text.toString(),
et_location.text.toString(),
mLatitude,
mLongitude
)
val dbHandler = DatabaseHandler(this)
if (mFootstepDetails == null) {
val addHappyPlace = dbHandler.addRow(footstepModel)
if (addHappyPlace > 0) {
setResult(Activity.RESULT_OK);
finish()//finishing activity
}
} else {
val updateHappyPlace = dbHandler.updateRow(footstepModel)
if (updateHappyPlace > 0) {
setResult(Activity.RESULT_OK);
finish()//finishing activity
}
}
}
}
}
R.id.et_location -> {
try {
// These are the list of fields which we required is passed
val fields = listOf(
Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG,
Place.Field.ADDRESS
)
// Start the autocomplete intent with a unique request code.
val intent =
Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, fields)
.build(this@AddFootstepActivity)
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
private fun takePhotoFromCamera() {
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA
)
.withListener(object : MultiplePermissionsListener {
override fun onPermissionsChecked(report: MultiplePermissionsReport?) {
// Here after all the permission are granted launch the CAMERA to capture an image.
if (report!!.areAllPermissionsGranted()) {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(intent,
CAMERA
)
}
}
override fun onPermissionRationaleShouldBeShown(
permissions: MutableList<PermissionRequest>?,
token: PermissionToken?
) {
showRationalDialogForPermissions()
}
}).onSameThread()
.check()
}
private fun choosePhotoFromGallery() {
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
).withListener(object : MultiplePermissionsListener {
override fun onPermissionsChecked(report: MultiplePermissionsReport) {
if(report.areAllPermissionsGranted()) {
val galleryIntent = Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
)
startActivityForResult(galleryIntent,
GALLERY
)
}
}
override fun onPermissionRationaleShouldBeShown(
permissions: List<PermissionRequest?>?,
token: PermissionToken?
) {
showRationalDialogForPermissions()
}
}).onSameThread().check()
}
/**
* A function used to show the alert dialog when the permissions are denied and need to allow it from settings app info.
*/
private fun showRationalDialogForPermissions() {
AlertDialog.Builder(this)
.setMessage("It Looks like you have turned off permissions required for this feature. It can be enabled under Application Settings")
.setPositiveButton(
"GO TO SETTINGS"
) { _, _ ->
try {
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
val uri = Uri.fromParts("package", packageName, null)
intent.data = uri
startActivity(intent)
} catch (e: ActivityNotFoundException) {
e.printStackTrace()
}
}
.setNegativeButton("Cancel") { dialog, _ -> dialog.dismiss()
}.show()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
if (requestCode == GALLERY) {
if (data != null) {
val contentURI = data.data
try {
// iv_place_image.visibility = View.VISIBLE
// iv_place_image.setImageURI(data.data)
@Suppress("DEPRECATION")
val selectedImageBitmap =
MediaStore.Images.Media.getBitmap(this.contentResolver, contentURI)
iv_place_image.setImageBitmap(selectedImageBitmap)
savedImagePath = saveImageToInternalStorage(selectedImageBitmap)
Log.i("Saved Image : ", "Path :: $savedImagePath")
} catch (e: Exception) {
e.printStackTrace()
Toast.makeText(this@AddFootstepActivity, "Failed!", Toast.LENGTH_SHORT)
.show()
}
}
} else if (requestCode == CAMERA) {
val thumbnail: Bitmap = data!!.extras!!.get("data") as Bitmap
iv_place_image.setImageBitmap(thumbnail)
savedImagePath = saveImageToInternalStorage(thumbnail)
Log.i("Saved Camera Image : ", "Path :: $savedImagePath")
} else if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
val place: Place = Autocomplete.getPlaceFromIntent(data!!)
et_location.setText(place.address)
mLatitude = place.latLng!!.latitude
mLongitude = place.latLng!!.longitude
}
}
}
private fun saveImageToInternalStorage(bitmap: Bitmap): Uri {
val wrapper = ContextWrapper(applicationContext)
var path = wrapper.getDir(IMAGE_DIRECTORY, Context.MODE_PRIVATE)
var file = File(path, "${UUID.randomUUID()}.jpg")
file.outputStream()
.use {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, it)
}
return Uri.parse(file.absolutePath)
}
companion object {
private const val GALLERY = 1
private const val CAMERA = 2
private const val IMAGE_DIRECTORY = "FootstepImages"
// A constant variable for place picker
private const val PLACE_AUTOCOMPLETE_REQUEST_CODE = 3
}
}
| 0 | Kotlin | 0 | 0 | 6b411321724d2846c65152917737cdca760f9925 | 13,445 | Footstep | MIT License |
libraries/core/src/main/kotlin/io/plastique/core/work/WorkManagerInitializer.kt | plastiqueapp | 150,879,887 | false | null | package io.plastique.core.work
import android.content.Context
import androidx.work.Configuration
import androidx.work.WorkManager
import androidx.work.WorkerFactory
import io.plastique.core.init.Initializer
import javax.inject.Inject
class WorkManagerInitializer @Inject constructor(
private val context: Context,
private val workerFactory: WorkerFactory
) : Initializer() {
override fun initialize() {
WorkManager.initialize(context, Configuration.Builder()
.setWorkerFactory(workerFactory)
.build())
}
}
| 0 | Kotlin | 2 | 9 | 9271853f3741add18822858cbad9d4f8e8104f54 | 557 | plastique | Apache License 2.0 |
compose_material3/src/main/java/dev/vengateshm/compose_material3/other_concepts/upload_file/UploadFileSample.kt | vengateshm | 670,054,614 | false | {"Kotlin": 2030949, "Java": 55066} | package dev.vengateshm.compose_material3.other_concepts.upload_file
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
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.material3.Button
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlin.math.roundToInt
@Composable
fun UploadFileSample() {
val context = LocalContext.current
val fileReader = remember { FileReader(context) }
val repository = remember { UploadFileRepository(UploadFileClient.client, fileReader) }
val viewModel = viewModel<UploadFileViewModel>(
factory = UploadFileViewModelFactory(repository),
)
val state = viewModel.state
val filePicker = rememberLauncherForActivityResult(
contract = ActivityResultContracts.GetContent(),
) { contentUri ->
contentUri?.let {
viewModel.uploadFile(contentUri)
}
}
LaunchedEffect(state.errorMessage) {
if (!state.errorMessage.isNullOrEmpty()) {
Toast.makeText(context, state.errorMessage, Toast.LENGTH_SHORT).show()
}
}
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
Box(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding),
contentAlignment = Alignment.Center,
) {
when {
!state.isUploading -> {
Button(
onClick = {
filePicker.launch("*/*")
},
) {
Text(text = "Pick a file")
}
}
else -> {
val progress by animateFloatAsState(
targetValue = state.progress,
label = "progress animation",
animationSpec = tween(durationMillis = 500),
)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
) {
LinearProgressIndicator(
progress = { progress },
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
.height(16.dp),
)
Text(text = "${(state.progress * 100).roundToInt()}%")
Button(
onClick = {
viewModel.cancelUpload()
},
) {
Text(text = "Cancel upload")
}
}
}
}
}
}
}
@Preview
@Composable
private fun UploadFileSamplePreview() {
MaterialTheme {
Surface {
UploadFileSample()
}
}
} | 0 | Kotlin | 0 | 1 | 2f5a7710bcbd4d04b443e77459e7fb8a43a5e6ab | 4,020 | Android-Kotlin-Jetpack-Compose-Practice | Apache License 2.0 |
lib/src/main/java/io/ashkay/crashgrabber/internal/utils/getDeviceMetaAsJson.kt | Ash-Kay | 678,936,244 | false | {"Kotlin": 37783} | package io.ashkay.crashgrabber.internal.utils
import android.os.Build
import com.google.gson.Gson
internal fun getDeviceMetaAsJson(): String? {
val os = System.getProperty("os.version") // OS version
val apiLevel = Build.VERSION.SDK_INT // API Level
val device = Build.DEVICE // Device
val model = Build.MODEL // Model
val product = Build.PRODUCT // Product
val map = HashMap<String, String>()
map["OS"] = os.orEmpty()
map["API_LEVEL"] = apiLevel.toString()
map["DEVICE"] = device.orEmpty()
map["MODEL"] = model.orEmpty()
map["PRODUCT"] = product.orEmpty()
return runCatching {
Gson().toJson(map)
}.getOrNull()
}
| 0 | Kotlin | 1 | 2 | 6557457455eb46966c8f1cae2f583e72bdc179c1 | 712 | CrashGrabber | MIT License |
src/main/kotlin/com/pashmi/achievements/CopperOreBreakCounter.kt | paasshme | 835,235,594 | false | {"Kotlin": 69688, "Java": 8826} | package com.pashmi.achievements
import com.pashmi.CopperGodMod.toModId
import net.fabricmc.fabric.api.event.player.PlayerBlockBreakEvents
import net.fabricmc.fabric.api.networking.v1.PacketByteBufs
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking
import net.minecraft.block.Blocks
import net.minecraft.network.PacketByteBuf
class CopperOreBreakCounter {
companion object {
val INITIAL_SYNC = "initial_sync".toModId()
val OPEN_CUSTOM_BOOK_SCREEN = "copper_book".toModId()
val ID = "copper_ore_break_counter".toModId()
fun initializeCopperOreCounter() {
ServerPlayConnectionEvents.JOIN.register { handler, sender, server ->
val data = PacketByteBufs.create().apply {
writeMap(
StateSaverAndLoader.getPlayerCopper(server).mapValues { (_, value) -> value.copperOreBroken },
PacketByteBuf::writeUuid,
PacketByteBuf::writeInt
)
}
server.execute { ServerPlayNetworking.send(handler.player, INITIAL_SYNC, data) }
}
PlayerBlockBreakEvents.AFTER.register { world, player, _, state, _ ->
if (state.block == Blocks.COPPER_ORE) {
world.server?.let { server ->
val playerState = StateSaverAndLoader.getPlayerState(player)
playerState.copperOreBroken += 1
val data = PacketByteBufs.create().apply {
writeUuid(player.uuid)
writeInt(playerState.copperOreBroken)
}
server.execute {
server.playerManager.playerList.forEach { ServerPlayNetworking.send(it, ID, data) }
}
}
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 5dd6c93c8c84442b45a2d5128981cab9083a326d | 2,018 | copper-addict-mod | Creative Commons Zero v1.0 Universal |
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/LayoutBottombarCollapse.kt | walter-juan | 868,046,028 | false | {"Kotlin": 20416825} | package com.woowla.compose.icon.collections.tabler.tabler.outline
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.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup
import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound
import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound
public val OutlineGroup.LayoutBottombarCollapse: ImageVector
get() {
if (_layoutBottombarCollapse != null) {
return _layoutBottombarCollapse!!
}
_layoutBottombarCollapse = Builder(name = "LayoutBottombarCollapse", defaultWidth = 24.0.dp,
defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(20.0f, 6.0f)
verticalLineToRelative(12.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.0f, 2.0f)
horizontalLineToRelative(-12.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.0f, -2.0f)
verticalLineToRelative(-12.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, -2.0f)
horizontalLineToRelative(12.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, 2.0f)
close()
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(20.0f, 15.0f)
horizontalLineToRelative(-16.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(14.0f, 8.0f)
lineToRelative(-2.0f, 2.0f)
lineToRelative(-2.0f, -2.0f)
}
}
.build()
return _layoutBottombarCollapse!!
}
private var _layoutBottombarCollapse: ImageVector? = null
| 0 | Kotlin | 0 | 1 | b037895588c2f62d069c724abe624b67c0889bf9 | 2,789 | compose-icon-collections | MIT License |
libraries/tools/kotlin-gradle-plugin-api/src/common/kotlin/org/jetbrains/kotlin/gradle/plugin/KotlinPlatformType.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | /*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.gradle.plugin
import org.gradle.api.Named
import org.gradle.api.attributes.*
import org.gradle.util.GradleVersion
import java.io.Serializable
/**
* @suppress TODO: KT-58858 add documentation
*/
enum class KotlinPlatformType : Named, Serializable {
common, jvm, js, androidJvm, native, wasm;
override fun toString(): String = name
override fun getName(): String = name
class CompatibilityRule : AttributeCompatibilityRule<KotlinPlatformType> {
override fun execute(details: CompatibilityCheckDetails<KotlinPlatformType>) = with(details) {
if (producerValue == jvm && consumerValue == androidJvm)
compatible()
// Allow the input metadata configuration consume platform-specific artifacts if no metadata is available, KT-26834
if (consumerValue == common)
compatible()
}
}
class DisambiguationRule : AttributeDisambiguationRule<KotlinPlatformType> {
override fun execute(details: MultipleCandidatesDetails<KotlinPlatformType?>) = with(details) {
if (consumerValue in candidateValues) {
closestMatch(checkNotNull(consumerValue))
return@with
}
/**
* If the consumer doesn't request anything specific and matches both JVM and Android,
* then assume that it's an ordinary pure-Java consumer. If it's a pure-Android consumer, it will have
* other means of disambiguation that will take precedence
* (the buildType attribute, the target JVM environment = android)
*/
if (consumerValue == null && androidJvm in candidateValues && jvm in candidateValues) {
closestMatch(jvm)
return@with
}
if (common in candidateValues && jvm !in candidateValues && androidJvm !in candidateValues) {
// then the consumer requests common or requests no platform-specific artifacts,
// so common is the best match, KT-26834; apply this rule only when no JVM variant is available,
// as doing otherwise would conflict with Gradle java's disambiguation rules and lead to KT-32239
closestMatch(common)
return@with
}
}
}
companion object {
val attribute = Attribute.of(
"org.jetbrains.kotlin.platform.type",
KotlinPlatformType::class.java
)
fun setupAttributesMatchingStrategy(attributesSchema: AttributesSchema) {
attributesSchema.attribute(KotlinPlatformType.attribute).run {
compatibilityRules.add(CompatibilityRule::class.java)
disambiguationRules.add(DisambiguationRule::class.java)
}
}
}
}
| 34 | Kotlin | 5771 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 3,054 | kotlin | Apache License 2.0 |
user-management/keycloak-gateway/src/main/kotlin/co/nilin/opex/auth/gateway/data/KycRequest.kt | opexdev | 370,411,517 | false | null | package co.nilin.opex.auth.gateway.data
class KycRequest {
var selfiePath: String? = null
var idCardPath: String? = null
var acceptFormPath: String? = null
constructor()
constructor(selfiePath: String?, idCardPath: String?, acceptFormPath: String?) {
this.selfiePath = selfiePath
this.idCardPath = idCardPath
this.acceptFormPath = acceptFormPath
}
} | 29 | null | 22 | 51 | fedf3be46ee7fb85ca7177ae91b13dbc6f2e8a73 | 402 | core | MIT License |
presentation/src/main/kotlin/com/reactions/deathlines/presentation/ui/features/goals/GoalsViewModel.kt | dreinoso | 263,789,868 | false | {"Gradle": 7, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 5, "Batchfile": 1, "Markdown": 1, "Kotlin": 70, "Proguard": 3, "Java": 2, "XML": 44} | package com.reactions.deathlines.presentation.ui.features.goals
import com.reactions.deathlines.domain.usecase.album.GetAlbumsUseCase
import com.reactions.deathlines.presentation.ui.base.BaseViewModel
import javax.inject.Inject
class GoalsViewModel @Inject constructor(private val getAlbumsUseCase: GetAlbumsUseCase) : BaseViewModel() {
} | 1 | null | 1 | 1 | 47fc9ce0e26d7a725488f510c152c825dba2a25d | 341 | deathlines | Apache License 2.0 |
buildSrc/src/main/java/com/androix/buildsrc/JUnit.kt | aliahmedbd | 625,302,209 | false | null | object JUnit {
private const val version = "4.13.2"
const val junit4 = "junit:junit:$version"
private const val extVersion = "1.1.3"
const val ext = "androidx.test.ext:junit:$extVersion"
private const val mockkVersion = "1.12.3"
const val mockk = "io.mockk:mockk:$mockkVersion"
} | 0 | Kotlin | 0 | 8 | 498963b616a0c92d5682dec7b227b1a72db3162f | 305 | WeatherApp-Android-Clean-Architecture-Jetpack-Compose-Kotlin-Hilt-Flow | Apache License 2.0 |
app/src/test/kotlin/team/ommaya/wequiz/android/dummy/dummy.kt | mash-up-kr | 628,190,373 | false | null | /*
* Designed and developed by "옴마야" Team 2023.
*
* Licensed under the MIT.
* Please see full license: https://github.com/mash-up-kr/WeQuiz-Android/blob/main/LICENSE
*/
package team.ommaya.wequiz.android.dummy
import kotlinx.collections.immutable.toImmutableList
import kotlinx.collections.immutable.toPersistentList
import team.ommaya.wequiz.android.home.quizlist.QuizNameAndIsWritingPair
import team.ommaya.wequiz.android.home.friends.NicknameUuidScoreTriple
val DummyFriendsRanking =
List(30) { index ->
@Suppress("NAME_SHADOWING")
val index = index + 1
NicknameUuidScoreTriple(
/*nickname = */ "${index}번_친구${if (index >= 10) "_친" else ""}".take(8),
/*uuid = */ index * 1_000,
/*score = */ index * 100,
)
}.toImmutableList()
val DummyQuizs =
List(30) { index ->
@Suppress("NAME_SHADOWING")
val index = index + 1
val boolean = index % 2 == 0
QuizNameAndIsWritingPair(
/*QuizName = */ "${index}번${"_시험지".repeat(10)}".take(if (!boolean) 10 else 38),
/*isWip = */ boolean,
)
}.toPersistentList()
| 14 | null | 0 | 6 | c7f20fd3a09561f312df5c5b54e3e35cec387dc7 | 1,153 | WeQuiz-Android | MIT License |
tl/src/main/kotlin/com/github/badoualy/telegram/tl/api/messages/TLAbsRecentStickers.kt | Miha-x64 | 436,587,061 | true | {"Kotlin": 3919807, "Java": 75352} | package com.github.badoualy.telegram.tl.api.messages
import com.github.badoualy.telegram.tl.core.TLObject
/**
* Abstraction level for the following constructors:
* * [messages.recentStickers#88d37c56][TLRecentStickers]
* * [messages.recentStickersNotModified#b17f890][TLRecentStickersNotModified]
*
* @author <NAME> <EMAIL>
* @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a>
*/
abstract class TLAbsRecentStickers : TLObject()
| 1 | Kotlin | 2 | 3 | 1a8963dce921c1e9ef05b9d1e56d8fbcb1ea1c4b | 479 | kotlogram-resurrected | MIT License |
common_parser/src/main/kotlin/ru/alfabank/ecomm/dcreator/parser/line/BoundsLineParser.kt | alfa-laboratory | 121,268,190 | false | null | package ru.alfabank.ecomm.dcreator.parser.line
abstract class BoundsLineParser(private val openCloseSymbols: String) : LineParser {
override fun openSymbolsSuited(startSymbols: String): BoundSymbolsSuiteResult {
val partySuiteStatus = startSymbols.first() == openCloseSymbols.first()
val fullySuitedStatus = partySuiteStatus && startSymbols == openCloseSymbols
return BoundSymbolsSuiteResult(partySuiteStatus, fullySuitedStatus)
}
override fun endSymbolsSuited(endSymbols: String): BoundSymbolsSuiteResult = openSymbolsSuited(endSymbols)
override fun endSymbolsLength(): Int = openCloseSymbols.length
override fun openSymbolsLength(): Int = openCloseSymbols.length
} | 0 | Kotlin | 0 | 7 | 1f1425c2c020baca91d02b5d3567cdf28e3a95bd | 715 | kgen-doc-tools | MIT License |
wallet-common/src/main/kotlin/com/wallet/biz/service/DepositService.kt | GalaxySciTech | 339,935,435 | false | {"Kotlin": 273747, "CSS": 210000, "HTML": 94074, "PLpgSQL": 76509, "Java": 56269, "JavaScript": 47624, "SCSS": 25514, "Dockerfile": 1104, "Shell": 1071} | package com.wallet.biz.service
import com.wallet.biz.domain.PageEntity
import com.wallet.entity.domain.Deposit
import org.springframework.data.domain.Page
interface DepositService {
fun getById(id:Long): Deposit?
fun save(deposit:Deposit): Deposit
fun getByHash(hash: String, address: String): Deposit?
fun findByEntity(find: PageEntity<Deposit>): Page<Deposit>
fun getByHash(hash: String): Deposit?
fun getByIsUpload(isUpload: Int): List<Deposit>
fun saveAll(list: List<Deposit>): List<Deposit>
fun findAll(): List<Deposit>
}
| 5 | Kotlin | 40 | 99 | d52e8f7f4b151676be9b98dc2c85b912b06cf536 | 562 | java-wallet | MIT License |
src/main/kotlin/com/tylerthrailkill/helpers/prettyprint/PrettyPrint.kt | snowe2010 | 165,758,520 | false | null | package com.tylerthrailkill.helpers.prettyprint
import com.ibm.icu.text.BreakIterator
import mu.KLogging
import java.math.BigDecimal
import java.math.BigInteger
import java.util.*
/**
* Pretty print function.
*
* Prints any object in a pretty format for easy debugging/reading
*
* @param [obj] the object to pretty print
* @param [indent] optional param that specifies the number of spaces to use to indent. Defaults to 2.
* @param [writeTo] optional param that specifies the [Appendable] to output the pretty print to. Defaults appending to `System.out`.
* @param [wrappedLineWidth] optional param that specifies how many characters of a string should be on a line.
*/
@JvmOverloads
fun pp(obj: Any?, indent: Int = 2, writeTo: Appendable = System.out, wrappedLineWidth: Int = 80) =
PrettyPrinter(indent, writeTo, wrappedLineWidth).pp(obj)
/**
* Inline helper method for printing withing method chains. Simply delegates to [pp]
*
* Example:
* val foo = op2(op1(bar).pp())
*
* @param [T] the object to pretty print
* @param [indent] optional param that specifies the number of spaces to use to indent. Defaults to 2.
* @param [writeTo] optional param that specifies the [Appendable] to output the pretty print to. Defaults appending to `System.out`
* @param [wrappedLineWidth] optional param that specifies how many characters of a string should be on a line.
*/
@JvmOverloads
fun <T> T.pp(
indent: Int = 2,
writeTo: Appendable = System.out,
wrappedLineWidth: Int = 80
): T = this.also { pp(it, indent, writeTo, wrappedLineWidth) }
/**
* Class for performing pretty print operations on any object with customized indentation, target output, and line wrapping
* width for long strings.
*
* @param [tabSize] How much more to indent each level of nesting.
* @param [writeTo] Where to write a pretty printed object.
* @param [wrappedLineWidth] How long a String needs to be before it gets transformed into a multiline String.
*/
private class PrettyPrinter(val tabSize: Int, val writeTo: Appendable, val wrappedLineWidth: Int) {
private val lineInstance = BreakIterator.getLineInstance()
// private val logger = KotlinLogging.logger {}
private val visited = mutableSetOf<Int>()
private val revisited = mutableSetOf<Int>()
companion object: KLogging()
/**
* Pretty prints the given object with this printer.
*
* @param [obj] The object to pretty print.
*/
fun pp(obj: Any?) {
ppAny(obj)
writeLine()
}
/**
* The core pretty print method. Delegates to the appropriate pretty print method based on the object's type. Handles
* cyclic references. `collectionElementPad` and `objectFieldPad` are generally the same. A specific case in which they
* differ is to handle the difference in alignment of different types of fields in an object, as seen in `ppPlainObject(...)`.
*
* @param [obj] The object to pretty print.
* @param [collectionElementPad] How much to indent the elements of a collection.
* @param [objectFieldPad] How much to indent the field of an object.
*/
private fun ppAny(
obj: Any?,
collectionElementPad: String = "",
objectFieldPad: String = collectionElementPad
) {
val id = System.identityHashCode(obj)
if (!obj.isAtomic() && visited[id]) {
write("cyclic reference detected for $id")
revisited.add(id)
return
}
visited.add(id)
when {
obj is Iterable<*> -> ppIterable(obj, collectionElementPad)
obj is Map<*, *> -> ppMap(obj, collectionElementPad)
obj is String -> ppString(obj, collectionElementPad)
obj is Enum<*> -> ppEnum(obj)
obj.isAtomic() -> ppAtomic(obj)
obj is Any -> ppPlainObject(obj, objectFieldPad)
}
visited.remove(id)
if (revisited[id]) {
write("[\$id=$id]")
revisited -= id
}
}
/**
* Pretty prints the contents of the Iterable receiver. The given function is applied to each element. The result
* of an application to each element is on its own line, separated by a separator. `currentDepth` specifies the
* indentation level of any closing bracket.
*/
private fun <T> Iterable<T>.ppContents(currentDepth: String, separator: String = "", f: (T) -> Unit) {
val list = this.toList()
if (!list.isEmpty()) {
f(list.first())
list.drop(1).forEach {
writeLine(separator)
f(it)
}
writeLine()
}
write(currentDepth)
}
private fun ppPlainObject(obj: Any, currentDepth: String) {
val increasedDepth = deepen(currentDepth)
val className = obj.javaClass.simpleName
writeLine("$className(")
obj.javaClass.declaredFields
.filterNot { it.isSynthetic }
.ppContents(currentDepth) {
it.isAccessible = true
write("$increasedDepth${it.name} = ")
val extraIncreasedDepth = deepen(increasedDepth, it.name.length + 3) // 3 is " = ".length in prev line
val fieldValue = it.get(obj)
logger.debug { "field value is ${fieldValue.javaClass}" }
ppAny(fieldValue, extraIncreasedDepth, increasedDepth)
}
write(')')
}
private fun ppIterable(obj: Iterable<*>, currentDepth: String) {
val increasedDepth = deepen(currentDepth)
writeLine('[')
obj.ppContents(currentDepth, ",") {
write(increasedDepth)
ppAny(it, increasedDepth)
}
write(']')
}
private fun ppMap(obj: Map<*, *>, currentDepth: String) {
val increasedDepth = deepen(currentDepth)
writeLine('{')
obj.entries.ppContents(currentDepth, ",") {
write(increasedDepth)
ppAny(it.key, increasedDepth)
write(" -> ")
ppAny(it.value, increasedDepth)
}
write('}')
}
private fun ppString(s: String, currentDepth: String) {
if (s.length > wrappedLineWidth) {
val tripleDoubleQuotes = "\"\"\""
writeLine(tripleDoubleQuotes)
writeLine(wordWrap(s, currentDepth))
write("$currentDepth$tripleDoubleQuotes")
} else {
write("\"$s\"")
}
}
private fun ppEnum(enum: Enum<*>) {
write("${enum.javaClass.simpleName}.${enum.toString()}")
}
private fun ppAtomic(obj: Any?) {
write(obj.toString())
}
/**
* Writes to the writeTo with a new line and adds logging
*/
private fun writeLine(str: Any? = "") {
logger.debug { "writing $str" }
writeTo.append(str.toString()).appendln()
}
/**
* Writes to the writeTo and adds logging
*/
private fun write(str: Any?) {
logger.debug { "writing $str" }
writeTo.append(str.toString())
}
private fun wordWrap(text: String, padding: String): String {
lineInstance.setText(text)
var start = lineInstance.first()
var end = lineInstance.next()
val breakableLocations = mutableListOf<String>()
while (end != BreakIterator.DONE) {
val substring = text.substring(start, end)
breakableLocations.add(substring)
start = end
end = lineInstance.next()
}
val arr = mutableListOf(mutableListOf<String>())
var index = 0
arr[index].add(breakableLocations[0])
breakableLocations.drop(1).forEach {
val currentSize = arr[index].joinToString(separator = "").length
if (currentSize + it.length <= wrappedLineWidth) {
arr[index].add(it)
} else {
arr.add(mutableListOf(it))
index += 1
}
}
return arr.flatMap { listOf("$padding${it.joinToString(separator = "")}") }.joinToString("\n")
}
private fun deepen(currentDepth: String, size: Int = tabSize): String = " ".repeat(size) + currentDepth
}
/**
* Determines if this object should not be broken down further for pretty printing.
*/
private fun Any?.isAtomic(): Boolean =
this == null
|| this is Char || this is Number || this is Boolean || this is BigInteger || this is BigDecimal || this is UUID
// For syntactic sugar
operator fun <T> Set<T>.get(x: T): Boolean = this.contains(x)
| 10 | null | 2 | 80 | 8f3aa28a49c55318752d3e560e06b4c56aeb447e | 8,555 | pretty-print | MIT License |
app/src/main/java/com/hashim/instagram/ui/main/MainViewModel.kt | hashimshafiq | 244,229,633 | false | null | package com.hashim.instagram.ui.main
import androidx.lifecycle.MutableLiveData
import com.hashim.instagram.data.repository.UserRepository
import com.hashim.instagram.ui.base.BaseViewModel
import com.hashim.instagram.utils.common.Event
import com.hashim.instagram.utils.network.NetworkHelper
import com.hashim.instagram.utils.rx.CoroutineDispatchers
class MainViewModel(
coroutineDispatchers: CoroutineDispatchers,
networkHelper: NetworkHelper,
private val userRepository: UserRepository
) : BaseViewModel(coroutineDispatchers, networkHelper) {
private val profileNavigation = MutableLiveData<Event<Boolean>>()
private val homeNavigation = MutableLiveData<Event<Boolean>>()
override fun onCreate() {
if (!userRepository.isThemeChange()) {
homeNavigation.postValue(Event(true))
}else{
profileNavigation.postValue(Event(true))
}
userRepository.saveThemeChange(false)
//homeNavigation.postValue(Event(true))
}
} | 1 | Kotlin | 10 | 21 | e13d04ef515e93ae52fca5a04dc987226adc750a | 1,008 | Instagram | MIT License |
app/src/main/java/com/concordium/wallet/ui/common/identity/IdentityUpdater.kt | Concordium | 358,250,608 | false | null | package com.concordium.wallet.ui.common.identity
import android.app.Application
import androidx.room.withTransaction
import com.concordium.wallet.App
import com.concordium.wallet.BuildConfig
import com.concordium.wallet.data.AccountRepository
import com.concordium.wallet.data.IdentityRepository
import com.concordium.wallet.data.RecipientRepository
import com.concordium.wallet.data.model.IdentityStatus
import com.concordium.wallet.data.model.IdentityTokenContainer
import com.concordium.wallet.data.model.TransactionStatus
import com.concordium.wallet.data.room.Account
import com.concordium.wallet.data.room.Identity
import com.concordium.wallet.data.room.Recipient
import com.concordium.wallet.data.room.WalletDatabase
import com.concordium.wallet.util.Log
import kotlinx.coroutines.*
import java.io.FileNotFoundException
import java.net.URL
class IdentityUpdater(val application: Application, private val viewModelScope: CoroutineScope) {
private val gson = App.appCore.gson
private val identityRepository: IdentityRepository
private val accountRepository: AccountRepository
private val recipientRepository: RecipientRepository
private val database: WalletDatabase
private var updateListener: UpdateListener? = null
private var run = true
init {
database = WalletDatabase.getDatabase(application)
val identityDao = database.identityDao()
identityRepository = IdentityRepository(identityDao)
val accountDao = database.accountDao()
accountRepository = AccountRepository(accountDao)
val recipientDao = database.recipientDao()
recipientRepository = RecipientRepository(recipientDao)
}
interface UpdateListener {
fun onError(identity: Identity, account: Account?)
fun onDone()
fun onNewAccountFinalized(accountName: String)
}
fun setUpdateListener(updateListener: UpdateListener) {
this.updateListener = updateListener
}
fun dispose() {
// Coroutines is disposed/cancelled when in viewModelScope
}
fun stop() {
run = false
updateListener = null
Log.d("Poll for identity status stopped")
}
fun checkPendingIdentities(updateListener: UpdateListener) {
Log.d("Poll for identity status started")
this.updateListener = updateListener
run = true
viewModelScope.launch(Dispatchers.Default) {
var hasMorePending = true
while (isActive && hasMorePending && run) {
hasMorePending = pollForIdentityStatus()
delay(5000)
}
withContext(Dispatchers.Main) {
updateListener.onDone()
}
Log.d("Poll for identity status done")
}
}
private suspend fun pollForIdentityStatus(): Boolean {
var hasMorePending = false
Log.d("Poll for identity status")
for (identity in identityRepository.getAll()) {
if (identity.status == IdentityStatus.PENDING) {
try {
val resp = URL(identity.codeUri).readText()
Log.d("Identity poll response: $resp")
val identityTokenContainer = gson.fromJson<IdentityTokenContainer>(resp, IdentityTokenContainer::class.java)
val newStatus = if(BuildConfig.FAIL_IDENTITY_CREATION) IdentityStatus.ERROR else identityTokenContainer.status
if (newStatus != IdentityStatus.PENDING) {
identity.status = identityTokenContainer.status
identity.detail = identityTokenContainer.detail
if (newStatus == IdentityStatus.DONE && identityTokenContainer.token != null) {
val token = identityTokenContainer.token
val identityContainer = token.identityObject
val accountCredentialWrapper = token.credential
val accountAddress = token.accountAddress
identity.identityObject = identityContainer.value
val account = accountRepository.getAllByIdentityId(identity.id).firstOrNull()
account?.let {
if (it.address == accountAddress) {
it.credential = accountCredentialWrapper
if (identityTokenContainer.status == IdentityStatus.DONE) {
if(account.transactionStatus != TransactionStatus.FINALIZED){
updateListener?.onNewAccountFinalized(account.name)
recipientRepository.insert(Recipient(0, account.name, account.address))
}
account.transactionStatus = TransactionStatus.FINALIZED
} else if (identityTokenContainer.status == IdentityStatus.ERROR) {
account.transactionStatus = TransactionStatus.ABSENT
}
database.withTransaction {
accountRepository.update(account)
identityRepository.update(identity)
}
}
}
} else if (newStatus == IdentityStatus.ERROR) {
identityRepository.update(identity)
val account = accountRepository.getAllByIdentityId(identity.id).firstOrNull()
account?.let { accountRepository.delete(it) }
withContext(Dispatchers.Main) {
updateListener?.onError(identity, account)
}
}
} else {
hasMorePending = true
}
} catch (e: FileNotFoundException) {
Log.e("Identity backend request failed", e)
hasMorePending = true
} catch (e: Exception) {
Log.e("Identity backend failure", e)
e.printStackTrace()
hasMorePending = true
}
}
}
return hasMorePending
}
} | 77 | null | 1 | 6 | cf482234db350007bdfef2540e16b07bfa174d03 | 6,534 | concordium-reference-wallet-android | Apache License 2.0 |
placeholder/src/jvmTest/kotlin/com/eygraber/compose/placeholder/DesktopPlaceholderTest.kt | eygraber | 708,597,627 | false | null | /*
* Copyright 2021 The Android Open Source Project
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.eygraber.compose.placeholder
import androidx.compose.animation.core.InfiniteRepeatableSpec
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.platform.InspectableValue
import androidx.compose.ui.platform.ValueElement
import androidx.compose.ui.platform.isDebugInspectorInfoEnabled
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.assertHeightIsEqualTo
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertWidthIsEqualTo
import androidx.compose.ui.test.captureToImage
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.unit.dp
import io.kotest.matchers.sequences.shouldContainExactly
import io.kotest.matchers.shouldBe
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class DesktopPlaceholderTest {
@get:Rule
val composeTestRule = createComposeRule()
private val contentTag = "Content"
@Before
fun before() {
isDebugInspectorInfoEnabled = true
}
@After
fun after() {
isDebugInspectorInfoEnabled = false
}
@Test
fun placeholder_switchVisible1() {
var visible by mutableStateOf(true)
composeTestRule.setContent {
Box(
Modifier
.size(128.dp)
.background(color = Color.Black)
.placeholder(visible = visible, color = Color.Red)
.testTag(contentTag)
)
}
composeTestRule.onNodeWithTag(contentTag)
.assertIsDisplayed()
.assertWidthIsEqualTo(128.dp)
.assertHeightIsEqualTo(128.dp)
.captureToImage()
.assertPixels(Color.Red)
visible = false
composeTestRule.onNodeWithTag(contentTag)
.assertIsDisplayed()
.assertWidthIsEqualTo(128.dp)
.assertHeightIsEqualTo(128.dp)
.captureToImage()
.assertPixels(Color.Black)
}
@Test
fun placeholder_switchVisible2() {
var visible by mutableStateOf(true)
composeTestRule.setContent {
Box(
Modifier
.size(128.dp)
.background(color = Color.Black)
.placeholder(
visible = visible,
color = Color.Gray,
highlight = Solid(Color.Red)
)
.testTag(contentTag)
)
}
composeTestRule.onNodeWithTag(contentTag)
.assertIsDisplayed()
.assertWidthIsEqualTo(128.dp)
.assertHeightIsEqualTo(128.dp)
.captureToImage()
.assertPixels(Color.Red)
visible = false
composeTestRule.onNodeWithTag(contentTag)
.assertIsDisplayed()
.assertWidthIsEqualTo(128.dp)
.assertHeightIsEqualTo(128.dp)
.captureToImage()
.assertPixels(Color.Black)
}
@Test
fun placeholder_switchColor() {
var color by mutableStateOf(Color.Red)
composeTestRule.setContent {
Box(
Modifier
.size(128.dp)
.background(color = Color.Black)
.placeholder(visible = true, color = color)
.testTag(contentTag)
)
}
composeTestRule.onNodeWithTag(contentTag)
.assertIsDisplayed()
.assertWidthIsEqualTo(128.dp)
.assertHeightIsEqualTo(128.dp)
.captureToImage()
.assertPixels(Color.Red)
color = Color.Blue
composeTestRule.onNodeWithTag(contentTag)
.assertIsDisplayed()
.assertWidthIsEqualTo(128.dp)
.assertHeightIsEqualTo(128.dp)
.captureToImage()
.assertPixels(Color.Blue)
}
@Test
fun placeholder_switchAnimatedBrush() {
var animatedBrush by mutableStateOf(Solid(Color.Red))
composeTestRule.setContent {
Box(
Modifier
.size(128.dp)
.background(color = Color.Black)
.placeholder(
visible = true,
color = Color.Gray,
highlight = animatedBrush
)
.testTag(contentTag)
)
}
composeTestRule.onNodeWithTag(contentTag)
.assertIsDisplayed()
.assertWidthIsEqualTo(128.dp)
.assertHeightIsEqualTo(128.dp)
.captureToImage()
.assertPixels(Color.Red)
animatedBrush = Solid(Color.Blue)
composeTestRule.onNodeWithTag(contentTag)
.assertIsDisplayed()
.assertWidthIsEqualTo(128.dp)
.assertHeightIsEqualTo(128.dp)
.captureToImage()
.assertPixels(Color.Blue)
}
@Test
fun placeholder_switchShape1() {
var shape by mutableStateOf(RectangleShape)
composeTestRule.setContent {
Box(
Modifier
.size(20.dp)
.background(color = Color.Black)
.placeholder(
visible = true,
color = Color.Red,
shape = shape
)
.testTag(contentTag)
)
}
composeTestRule.onNodeWithTag(contentTag)
.assertIsDisplayed()
.assertWidthIsEqualTo(20.dp)
.assertHeightIsEqualTo(20.dp)
.captureToImage()
.assertPixels(Color.Red)
shape = CircleShape
composeTestRule.onNodeWithTag(contentTag)
.assertIsDisplayed()
.assertWidthIsEqualTo(20.dp)
.assertHeightIsEqualTo(20.dp)
.captureToImage()
// There is no stable API to assert the shape.
// So check the color of the vertices simply.
.assertPixelsOfVertices(Color.Black)
}
@Test
fun placeholder_switchShape2() {
var shape by mutableStateOf(RectangleShape)
composeTestRule.setContent {
Box(
Modifier
.size(20.dp)
.background(color = Color.Black)
.placeholder(
visible = true,
color = Color.Gray,
highlight = Solid(Color.Red),
shape = shape
)
.testTag(contentTag)
)
}
composeTestRule.onNodeWithTag(contentTag)
.assertIsDisplayed()
.assertWidthIsEqualTo(20.dp)
.assertHeightIsEqualTo(20.dp)
.captureToImage()
.assertPixels(Color.Red)
shape = CircleShape
composeTestRule.onNodeWithTag(contentTag)
.assertIsDisplayed()
.assertWidthIsEqualTo(20.dp)
.assertHeightIsEqualTo(20.dp)
.captureToImage()
// There is no stable API to assert the shape.
// So check the color of the vertices simply.
.assertPixelsOfVertices(Color.Black)
}
@Test
fun placeholder_inspectableParameter1() {
val highlight = PlaceholderHighlight.shimmer(Color.Red)
val modifier = Modifier.placeholder(
visible = true,
color = Color.Blue,
highlight = highlight,
) as InspectableValue
modifier.nameFallback shouldBe "placeholder"
modifier.valueOverride shouldBe true
modifier.inspectableElements shouldContainExactly sequenceOf(
ValueElement("visible", true),
ValueElement("color", Color.Blue),
ValueElement("highlight", highlight),
ValueElement("shape", RectangleShape)
)
}
@Test
fun placeholder_inspectableParameter2() {
val highlight = PlaceholderHighlight.fade(Color.Red)
val modifier = Modifier.placeholder(
visible = true,
color = Color.Blue,
highlight = highlight,
) as InspectableValue
modifier.nameFallback shouldBe "placeholder"
modifier.valueOverride shouldBe true
modifier.inspectableElements shouldContainExactly sequenceOf(
ValueElement("visible", true),
ValueElement("color", Color.Blue),
ValueElement("highlight", highlight),
ValueElement("shape", RectangleShape)
)
}
}
internal class Solid(
private val color: Color,
override val animationSpec: InfiniteRepeatableSpec<Float> = infiniteRepeatable(
animation = tween(delayMillis = 0, durationMillis = 500),
repeatMode = RepeatMode.Restart
)
) : PlaceholderHighlight {
override fun alpha(progress: Float): Float = 1f
override fun brush(progress: Float, size: Size): Brush = SolidColor(color)
}
| 46 | null | 596 | 96 | f38efc430ef6b32634370820d5ef61ca5fdf52e5 | 9,155 | compose-placeholder | Apache License 2.0 |
mccoroutine-sponge-api/src/main/java/com/github/shynixn/mccoroutine/sponge/SuspendingCommandExecutor.kt | Shynixn | 156,845,738 | false | null | package com.github.shynixn.mccoroutine.sponge
import org.spongepowered.api.command.CommandResult
import org.spongepowered.api.command.CommandSource
import org.spongepowered.api.command.args.CommandContext
/**
* Interface containing the method directing how a certain command will
* be executed.
*/
@FunctionalInterface
interface SuspendingCommandExecutor {
/**
* Callback for the execution of a command.
*
* @param src The commander who is executing this command
* @param args The parsed command arguments for this command
* @return the result of executing this command.
*/
suspend fun execute(src: CommandSource, args: CommandContext): CommandResult
}
| 0 | null | 19 | 205 | 67662b0c239010ff2765599685f8edf37dd6ad8d | 697 | MCCoroutine | MIT License |
compiler/testData/loadJava/compiledKotlin/prop/ExtVarl.kt | JakeWharton | 99,388,807 | true | null | package test
var Int.junk: Short
get() = throw Exception()
set(p: Short) = throw Exception()
val String.junk: Int
get() = throw Exception()
| 179 | Kotlin | 5640 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 154 | kotlin | Apache License 2.0 |
js/js.tests/test/org/jetbrains/kotlin/incremental/FirAbstractInvalidationTest.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.incremental
import org.jetbrains.kotlin.cli.common.messages.MessageRenderer
import org.jetbrains.kotlin.cli.common.messages.PrintingMessageCollector
import org.jetbrains.kotlin.cli.js.klib.compileModuleToAnalyzedFirWithPsi
import org.jetbrains.kotlin.cli.js.klib.serializeFirKlib
import org.jetbrains.kotlin.cli.js.klib.transformFirToIr
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.diagnostics.DiagnosticReporterFactory
import org.jetbrains.kotlin.ir.backend.js.MainModule
import org.jetbrains.kotlin.ir.backend.js.ModulesStructure
import org.jetbrains.kotlin.test.TargetBackend
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.PrintStream
import java.nio.charset.Charset
abstract class AbstractJsFirInvalidationTest : FirAbstractInvalidationTest(TargetBackend.JS_IR, "incrementalOut/invalidationFir")
abstract class FirAbstractInvalidationTest(
targetBackend: TargetBackend,
workingDirPath: String
) : AbstractInvalidationTest(targetBackend, workingDirPath) {
private fun getFirInfoFile(defaultInfoFile: File): File {
val firInfoFileName = "${defaultInfoFile.nameWithoutExtension}.fir.${defaultInfoFile.extension}"
val firInfoFile = defaultInfoFile.parentFile.resolve(firInfoFileName)
return firInfoFile.takeIf { it.exists() } ?: defaultInfoFile
}
override fun getModuleInfoFile(directory: File): File {
return getFirInfoFile(super.getModuleInfoFile(directory))
}
override fun getProjectInfoFile(directory: File): File {
return getFirInfoFile(super.getProjectInfoFile(directory))
}
override fun buildKlib(
configuration: CompilerConfiguration,
moduleName: String,
sourceDir: File,
dependencies: Collection<File>,
friends: Collection<File>,
outputKlibFile: File
) {
val outputStream = ByteArrayOutputStream()
val messageCollector = PrintingMessageCollector(PrintStream(outputStream), MessageRenderer.PLAIN_FULL_PATHS, true)
val diagnosticsReporter = DiagnosticReporterFactory.createPendingReporter()
val libraries = dependencies.map { it.absolutePath }
val friendLibraries = friends.map { it.absolutePath }
val sourceFiles = sourceDir.filteredKtFiles().map { environment.createPsiFile(it) }
val moduleStructure = ModulesStructure(
project = environment.project,
mainModule = MainModule.SourceFiles(sourceFiles),
compilerConfiguration = configuration,
dependencies = libraries,
friendDependenciesPaths = friendLibraries
)
val analyzedOutput = compileModuleToAnalyzedFirWithPsi(
moduleStructure = moduleStructure,
ktFiles = sourceFiles,
libraries = libraries,
friendLibraries = friendLibraries,
diagnosticsReporter = diagnosticsReporter,
incrementalDataProvider = null,
lookupTracker = null,
)
val fir2IrActualizedResult = transformFirToIr(moduleStructure, analyzedOutput.output, diagnosticsReporter)
if (analyzedOutput.reportCompilationErrors(moduleStructure, diagnosticsReporter, messageCollector)) {
val messages = outputStream.toByteArray().toString(Charset.forName("UTF-8"))
throw AssertionError("The following errors occurred compiling test:\n$messages")
}
serializeFirKlib(
moduleStructure = moduleStructure,
firOutputs = analyzedOutput.output,
fir2IrActualizedResult = fir2IrActualizedResult,
outputKlibPath = outputKlibFile.absolutePath,
messageCollector = messageCollector,
diagnosticsReporter = diagnosticsReporter,
jsOutputName = moduleName
)
if (messageCollector.hasErrors()) {
val messages = outputStream.toByteArray().toString(Charset.forName("UTF-8"))
throw AssertionError("The following errors occurred serializing test klib:\n$messages")
}
}
}
| 184 | null | 5771 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 4,318 | kotlin | Apache License 2.0 |
Chapter13/HelloKotlin/app/src/main/java/com/goobar/hellokotlin/SampleFragment.kt | PacktPublishing | 164,067,642 | false | null | package com.example.navigationdemo1
import android.content.Context
import android.net.Uri
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Activities that contain this fragment must implement the
* [FirstFragment.OnFragmentInteractionListener] interface
* to handle interaction events.
* Use the [FirstFragment.newInstance] factory method to
* create an instance of this fragment.
*
*/
class FirstFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private var listener: OnFragmentInteractionListener? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false)
}
// TODO: Rename method, update argument and hook method into UI event
fun onButtonPressed(uri: Uri) {
listener?.onFragmentInteraction(uri)
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is OnFragmentInteractionListener) {
listener = context
} else {
throw RuntimeException(context.toString() + " must implement OnFragmentInteractionListener")
}
}
override fun onDetach() {
super.onDetach()
listener = null
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
*
*
* See the Android Training lesson [Communicating with Other Fragments]
* (http://developer.android.com/training/basics/fragments/communicating.html)
* for more information.
*/
interface OnFragmentInteractionListener {
// TODO: Update argument type and name
fun onFragmentInteraction(uri: Uri)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment FirstFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
FirstFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
}
| 4 | null | 5748 | 51 | 9fd893de74c2546e2059606f4f87e2ddaa9644ea | 3,309 | Mastering-Kotlin | MIT License |
app/src/main/java/com/a10miaomiao/bilimiao/adapter/UpperChannelAdapter.kt | 10miaomiao | 115,510,569 | false | null | package com.a10miaomiao.bilimiao.adapter
import com.a10miaomiao.bilimiao.R
import com.a10miaomiao.bilimiao.entity.UpperChannelInfo
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
/**
* Created by 10喵喵 on 2017/10/29.
*/
class UpperChannelAdapter(list : List<UpperChannelInfo.UperChannelData>) :
BaseQuickAdapter<UpperChannelInfo.UperChannelData, BaseViewHolder>(R.layout.item_uper_channel,list){
override fun convert(helper: BaseViewHolder?, item: UpperChannelInfo.UperChannelData?) {
helper?.setText(R.id.item_title,item!!.name)
helper?.setText(R.id.item_count,"${item!!.count}个投稿")
Glide.with(mContext)
.load(item!!.cover)
.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(R.drawable.bili_default_image_tv)
.dontAnimate()
.into(helper?.getView(R.id.item_img))
}
} | 1 | null | 1 | 20 | dfd78b56b5c41eb49454836ee2bce5cefc667db7 | 1,066 | bilimiao | Apache License 2.0 |
src/main/kotlin/no/nav/syfo/util/CredentialUtil.kt | navikt | 290,982,864 | false | null | package no.nav.syfo.util
import java.util.*
fun basicHeader(
credentialUsername: String,
credentialPassword: String,
) = "Basic " + Base64.getEncoder().encodeToString(java.lang.String.format("%s:%s", credentialUsername, credentialPassword).toByteArray())
fun bearerHeader(token: String): String {
return "Bearer $token"
}
| 0 | Kotlin | 0 | 0 | b103750661526e06e2a6a531ef63e1004f137e06 | 337 | syfooversikthendelsetilfelle | MIT License |
service/src/main/kotlin/com/r3/corda/finance/cash/issuer/service/flows/IssueCash.kt | joshtharakan | 218,566,108 | true | {"Kotlin": 159237} | package com.allianz.t2i.issuer.workflows.flows
import co.paralleluniverse.fibers.Suspendable
import com.r3.corda.lib.tokens.contracts.utilities.heldBy
import com.r3.corda.lib.tokens.contracts.utilities.issuedBy
import com.r3.corda.lib.tokens.contracts.utilities.of
import com.r3.corda.lib.tokens.workflows.flows.rpc.ConfidentialIssueTokens
import com.allianz.t2i.common.contracts.NodeTransactionContract
import com.allianz.t2i.common.contracts.states.NodeTransactionState
import com.allianz.t2i.common.contracts.types.NodeTransactionStatus
import net.corda.core.flows.*
import net.corda.core.transactions.SignedTransaction
import net.corda.core.transactions.TransactionBuilder
import net.corda.core.utilities.ProgressTracker
// TODO: Denominations? E.g. 100 split between 10 issuances of 10.
// TODO: Ask the counterparty for a random key and issue to that key.
// TODO: Move all tx generation stuff to the common library.
// TODO: Add the option for issuing to anonymous public keys.
@InitiatingFlow
@StartableByService
class IssueCash(val stx: SignedTransaction) : FlowLogic<Pair<SignedTransaction, SignedTransaction>>() {
companion object {
object GENERATING_TX : ProgressTracker.Step("Generating node transaction")
object SIGNING_TX : ProgressTracker.Step("Signing node transaction")
object FINALISING_TX : ProgressTracker.Step("Obtaining notary signature and recording node transaction") {
override fun childProgressTracker() = FinalityFlow.tracker()
}
@JvmStatic
fun tracker() = ProgressTracker(GENERATING_TX, SIGNING_TX, FINALISING_TX)
}
override val progressTracker = tracker()
@Suspendable
override fun call(): Pair<SignedTransaction, SignedTransaction> {
// Our chosen notary.
val notary = serviceHub.networkMapCache.notaryIdentities.first()
val nodeTransactionStateAndRef = stx.tx.outRefsOfType<NodeTransactionState>().single()
val nodeTransactionState = nodeTransactionStateAndRef.state.data
progressTracker.currentStep = GENERATING_TX
// TODO: Check that the bank account states are verified.
val internalBuilder = TransactionBuilder(notary = notary).apply {
addCommand(NodeTransactionContract.Update(), listOf(ourIdentity.owningKey))
addInputState(nodeTransactionStateAndRef)
addOutputState(nodeTransactionState.copy(status = NodeTransactionStatus.COMPLETE), NodeTransactionContract.CONTRACT_ID)
}
progressTracker.currentStep = SIGNING_TX
val signedTransaction = serviceHub.signInitialTransaction(internalBuilder)
progressTracker.currentStep = FINALISING_TX
val internalFtx = subFlow(FinalityFlow(signedTransaction, emptySet<FlowSession>(), Companion.FINALISING_TX.childProgressTracker()))
/** Commit the cash issuance transaction. */
val recipient = nodeTransactionState.amountTransfer.destination
val quantity = nodeTransactionState.amountTransfer.quantityDelta
val tokenType = nodeTransactionState.amountTransfer.token
val tokenToIssue = quantity of tokenType issuedBy ourIdentity heldBy recipient
val issueTx = subFlow(ConfidentialIssueTokens(tokensToIssue = listOf(tokenToIssue), observers = emptyList()))
// Return the internal tx and the external tx.
return Pair(internalFtx, issueTx)
}
} | 0 | null | 0 | 0 | 34c4f213e5bb67757a7ae022c96e323c6afc1913 | 3,400 | cash-issuer | Apache License 2.0 |
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsinterventionsservice/reporting/BatchUtilsTest.kt | ministryofjustice | 312,544,431 | false | {"Kotlin": 1714963, "Mustache": 3350, "Shell": 2684, "PLpgSQL": 2362, "Dockerfile": 1980} | package uk.gov.justice.digital.hmpps.hmppsinterventionsservice.reporting
import com.nhaarman.mockitokotlin2.mock
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.springframework.batch.item.ExecutionContext
import org.springframework.core.io.FileSystemResource
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.reporting.ndmis.performance.NdmisDateTime
import java.io.File
import java.time.Instant
import java.time.LocalDate
import java.time.Month
import java.time.OffsetDateTime
import java.time.ZoneOffset
import java.util.Date
import java.util.UUID
import kotlin.io.path.createTempFile
internal class BatchUtilsTest {
private val batchUtils = BatchUtils()
@Test
fun `parseLocalDateToDate converts LocalDate objects to Date at start of day`() {
var localDate = LocalDate.of(2024, Month.FEBRUARY, 29)
val date = batchUtils.parseLocalDateToDate(localDate)
assertThat(date.toInstant()).isEqualTo(Instant.parse("2024-02-29T00:00:00.00Z"))
}
@Test
fun `parseDateToOffsetDateTime converts Dates to OffsetDateTimes in UTC`() {
// it doesn't really matter how we format these dates, they are all equivalent
// (OffsetDateTime is just a more modern representation)
var date = Date.from(Instant.parse("1999-12-31T23:59:59.99Z"))
var offsetDateTime = batchUtils.parseDateToOffsetDateTime(date)
assertThat(offsetDateTime).isEqualTo(OffsetDateTime.parse("2000-01-01T00:59:59.99+01:00"))
date = Date.from(Instant.parse("1989-02-10T10:00:00.00Z"))
offsetDateTime = batchUtils.parseDateToOffsetDateTime(date)
assertThat(offsetDateTime).isEqualTo(OffsetDateTime.parse("1989-02-10T10:00:00.00Z"))
}
@Test
fun `csvFileWriter writes valid csv`() {
data class Data(
val stringVal: String,
val uuidVal: UUID,
)
val tmpFile = File(createTempFile().toString())
try {
val writer = batchUtils.csvFileWriter<Data>(
"dataWriter",
FileSystemResource(tmpFile),
headers = listOf("string value", "uuid value"),
fields = listOf("stringVal", "uuidVal"),
)
writer.open(mock<ExecutionContext>())
writer.write(
listOf(
Data("tom", UUID.fromString("5863b32b-bb60-4bad-aeee-a15ff61abf3a")),
Data("andrew", UUID.fromString("cec6b55f-b32f-43af-828b-c72a4c1aade7"))
)
)
assertThat(tmpFile.readText()).isEqualTo(
"""
string value,uuid value
tom,5863b32b-bb60-4bad-aeee-a15ff61abf3a
andrew,cec6b55f-b32f-43af-828b-c72a4c1aade7
""".trimIndent()
)
} finally {
tmpFile.delete()
}
}
@Nested
inner class CsvLineAggregatorTest {
private inner class Item(
val intVal: Int,
val stringVal: String,
val nullableListVal: List<String>?,
val dateTimeVal: NdmisDateTime?,
)
private val aggregator = CsvLineAggregator<Item>(
listOf("intVal", "stringVal", "nullableListVal", "dateTimeVal"),
)
@Test
fun `aggregates null fields`() {
val item = Item(10, "tom", null, null)
val result = aggregator.aggregate(item)
assertThat(result).isEqualTo("10,tom,,")
}
@Test
fun `aggregates NdmisDateTime fields using custom format`() {
val datetime = OffsetDateTime.of(2020, 11, 17, 13, 30, 0, 0, ZoneOffset.ofHours(8))
val item = Item(10, "tom", null, NdmisDateTime(datetime))
val result = aggregator.aggregate(item)
assertThat(result).isEqualTo("10,tom,,2020-11-17 05:30:00.000000+00")
}
@Test
fun `aggregates all fields correctly, even lists or strings with commas in`() {
val item = Item(10, "tom, tom, tom", listOf("a", "b", "c"), null)
val result = aggregator.aggregate(item)
assertThat(result).isEqualTo("10,\"tom, tom, tom\",\"[a, b, c]\",")
}
@Test
fun `aggregates fields containing quotes`() {
val item = Item(10, "something \"quoted\"", null, null)
val result = aggregator.aggregate(item)
assertThat(result).isEqualTo("10,\"something \"\"quoted\"\"\",,")
}
@Test
fun `aggregates fields containing newlines and tabs`() {
val item = Item(10, "all types\nof\r\nnewline\tand tab", null, null)
val result = aggregator.aggregate(item)
assertThat(result).isEqualTo("10,\"all types\nof\r\nnewline\tand tab\",,")
}
}
}
| 8 | Kotlin | 1 | 2 | bca6f4f269753425f1e5df434e08e4e941cb7075 | 4,424 | hmpps-interventions-service | MIT License |
Core/src/commonMain/kotlin/io/nacular/doodle/core/Display.kt | nacular | 108,631,782 | false | {"Kotlin": 3150677} | package io.nacular.doodle.core
import io.nacular.doodle.core.ContentDirection.RightLeft
import io.nacular.doodle.drawing.AffineTransform
import io.nacular.doodle.drawing.AffineTransform.Companion.Identity
import io.nacular.doodle.drawing.Color
import io.nacular.doodle.drawing.Paint
import io.nacular.doodle.drawing.paint
import io.nacular.doodle.focus.FocusTraversalPolicy
import io.nacular.doodle.geometry.Point
import io.nacular.doodle.geometry.Size
import io.nacular.doodle.layout.Insets
import io.nacular.doodle.system.Cursor
import io.nacular.doodle.utils.ChangeObservers
import io.nacular.doodle.utils.ObservableList
import io.nacular.doodle.utils.Pool
import io.nacular.doodle.utils.PropertyObservers
/**
* The top-level surface for presenting [View]s. An item must be added to the Display (either directly, or
* as a descendant of the Display) before it can be rendered or interact with the user.
*
* @author Nicholas Eddy
*/
public interface Display: Iterable<View> {
override fun iterator(): MutableIterator<View> = children.iterator()
/**
* The top-level cursor. This will be the cursor used for [View] hierarchies that do not have one set.
*/
public var cursor: Cursor?
/** The current size of the Display. This may be smaller than the client's screen in situations where the application is hosted within a window. */
public val size: Size
/** The layout applied */
public var layout: Layout?
/** Insets if any */
public var insets: Insets
/**
* Affine transform applied to the View. This transform does not affect the Display's [size] or how it is handled by [Layout].
* Hit-detection is handled correctly such that the pointer intersects with the Display as expected after transformation.
* So no additional handling is necessary in general. The default is [Identity]
*/
public var transform: AffineTransform
/** The list of top-level items added to the Display */
public val children: ObservableList<View>
/**
* Notifies changes to [children]
*/
public val childrenChanged: Pool<ChildObserver<Display>>
/** Fires when the display cursor changes */
public val cursorChanged: PropertyObservers<Display, Cursor?>
/** Fires when the display re-sizes */
public val sizeChanged: PropertyObservers<Display, Size>
public var focusTraversalPolicy: FocusTraversalPolicy?
/** Fires when [contentDirection] changes. */
public val contentDirectionChanged: ChangeObservers<Display>
/**
* Indicates the direction of content within the Display. This is used to support right-to-left locales.
* Top-level Views without a [View.localContentDirection] specified will inherit this value and pass it on to their
* descendants that have no explicit value.
*/
public var contentDirection: ContentDirection
/**
* Indicates whether the Display should be mirrored (as though transformed using [AffineTransform.flipHorizontally]),
* when the [contentDirection] is [RightLeft].
*
* Apps should set this to `false` if they want more control over how top-level Views are displayed.
*
* Defaults to `true`
*/
public var mirrorWhenRightLeft: Boolean
/** Fires when [mirrored] changes. */
public val mirroringChanged: ChangeObservers<Display>
/**
* `true` if [contentDirection] == [RightLeft] && [mirrorWhenRightLeft]
*/
public val mirrored: Boolean get() = contentDirection == RightLeft && mirrorWhenRightLeft
/**
* Maps a [Point] within the Display to absolute coordinate-space.
*
* @param point to be mapped
* @returns a Point relative to the un-transformed [Display]
*/
public fun toAbsolute(point: Point): Point
/**
* Maps a [Point] from absolute coordinate-space un-transformed [Display], into this Display's coordinate-space.
* The result is different form the input if the Display's [transform] is not [Identity].
*
* @param point to be mapped
* @returns a Point relative to this Display
*/
public fun fromAbsolute(point: Point): Point
/** Fills the Display's background with the given fill */
public fun fill(fill: Paint)
/**
* @param at the x,y within the Display's coordinate-space
* @return a View if one is found to contain the given point
*/
public fun child(at: Point): View?
/**
* @param at the x,y within the Display's coordinate-space
* @return a View if one is found to contain the given point and match [predicate]
*/
public fun child(at: Point, predicate: (View) -> Boolean): View?
/**
* Adds [view] to the Display.
*
* @param view to be added
*/
public operator fun plusAssign(view: View): Unit = children.plusAssign(view)
/**
* Adds the given [views] to the Display.
*
* @param views to be added
*/
public operator fun plusAssign(views: Collection<View>): Unit = children.plusAssign(views)
/**
* Removes [view] from the Display.
*
* @param view to be removed
*/
public operator fun minusAssign(view: View): Unit = children.minusAssign(view)
/**
* Removes the given [views] from the Display.
*
* @param views to be removed
*/
public operator fun minusAssign(views: Collection<View>): Unit = children.minusAssign(views)
/**
* @param view in question
* @return `true` IFF [view] is a descendant of the Display
*/
public infix fun ancestorOf(view: View): Boolean
/** Prompts the Display to layout its children if it has a Layout installed. */
public fun relayout()
}
/**
* The width of the Display
* @see Display.size
*/
public inline val Display.width: Double get() = size.width
/**
* The height of the Display
* @see Display.size
*/
public inline val Display.height: Double get() = size.height
/**
* Fills the Display with [color].paint
* @see Display.fill
*/
public fun Display.fill(color: Color): Unit = fill(color.paint)
/** @suppress */
@Internal
public interface InternalDisplay: Display {
public val popups: List<View>
public fun repaint()
public fun showPopup(view: View)
public fun hidePopup(view: View)
}
/**
* The Display's center point in its coordinate system.
*/
public val Display.center: Point get() = Point(width/2, height/2)
| 5 | Kotlin | 26 | 613 | f7414d4c30cdd7632992071234223653e52b978c | 6,411 | doodle | MIT License |
zettai_step1_http/src/main/kotlin/com/ubertob/fotf/zettai/ui/HtmlPage.kt | uberto | 654,026,766 | false | null | package com.ubertob.fotf.zettai.ui
import com.ubertob.fotf.zettai.domain.ToDoItem
import com.ubertob.fotf.zettai.domain.ToDoList
data class HtmlPage(val raw: String)
fun renderHtml(todoList: ToDoList): HtmlPage =
HtmlPage(
"""
<html>
<body>
<h1>Zettai</h1>
<h2>${todoList.listName.name}</h2>
<table>
<tbody>${renderItems(todoList.items)}</tbody>
</table>
</body>
</html>
""".trimIndent()
)
private fun renderItems(items: List<ToDoItem>) =
items.map {
"""<tr><td>${it.description}</td></tr>""".trimIndent()
}.joinToString("")
| 0 | Kotlin | 0 | 2 | 2f80b8f4022cacbf6d7a92919224f98d37453a4d | 655 | fotf | MIT License |
buildSrc/src/main/kotlin/MavenUtil.kt | kepocnhh | 349,158,555 | false | null | object MavenUtil {
private const val MAVEN_APACHE_URL = "http://maven.apache.org"
private fun mavenApacheUrlPom(modelVersion: String): String {
return "$MAVEN_APACHE_URL/POM/$modelVersion"
}
fun pom(
modelVersion: String,
groupId: String,
artifactId: String,
version: String,
packaging: String,
scmUrl: String,
licenses: Set<Pair<String, String>>,
developers: Set<String>,
name: String,
description: String,
url: String
): String {
val mavenApacheUrlPom = mavenApacheUrlPom(modelVersion = modelVersion)
val project = setOf(
"xsi:schemaLocation" to "$mavenApacheUrlPom $MAVEN_APACHE_URL/xsd/maven-$modelVersion.xsd",
"xmlns" to mavenApacheUrlPom,
"xmlns:xsi" to "http://www.w3.org/2001/XMLSchema-instance"
).joinToString(separator = " ") { (key, value) ->
"$key=\"$value\""
}
val scm = "<scm><url>$scmUrl</url></scm>"
val l = licenses.joinToString(
prefix = "<licenses>",
separator = "",
postfix = "</licenses>"
) { (name, url) ->
"<license><name>$name</name><url>$url</url></license>"
}
val d = developers.joinToString(
prefix = "<developers>",
separator = "",
postfix = "</developers>"
) { "<developer><name>$it</name></developer>" }
return mapOf(
"modelVersion" to modelVersion,
"groupId" to groupId,
"artifactId" to artifactId,
"version" to version,
"packaging" to packaging,
"name" to name,
"description" to description,
"url" to url
).toList().joinToString(
prefix = "<project $project>",
separator = "",
postfix = "$scm$l$d</project>"
) { (key, value) ->
"<$key>$value</$key>"
}
}
}
| 2 | null | 1 | 1 | a6c81acc88e4beffb4453d2cd00a7719b5d2887c | 1,995 | GitHubPackagesSample | Apache License 2.0 |
app/src/main/java/com/isscroberto/powernap/util/AlarmService.kt | robertoissc | 129,319,747 | false | null | package com.isscroberto.powernap.util
import android.app.Service
import android.content.Context
import android.content.Intent
import android.media.Ringtone
import android.media.RingtoneManager
import android.os.IBinder
class AlarmService : Service() {
private lateinit var ringtone: Ringtone
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
playAlarm()
return super.onStartCommand(intent, flags, startId)
}
override fun onDestroy() {
super.onDestroy()
ringtone.stop()
}
fun playAlarm() {
val notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)
ringtone = RingtoneManager.getRingtone(this, notification)
if(!ringtone.isPlaying()) {
ringtone.play()
}
}
} | 2 | Kotlin | 0 | 1 | e829d7deda80be73233cfd556d114dd10db986c4 | 891 | power-nap-android | MIT License |
compiler/testData/codegen/script/topLevelLocalDelegatedProperty.kts | JakeWharton | 99,388,807 | false | null | import kotlin.reflect.KProperty
class Delegate {
operator fun getValue(t: Any?, p: KProperty<*>): Int = 3
}
val prop: Int by Delegate()
val x = prop
// expected: x: 3
| 181 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 177 | kotlin | Apache License 2.0 |
strings-core/src/commonMain/kotlin/com/chrynan/strings/core/StringArrayResourceID.kt | chRyNaN | 177,022,027 | false | null | package com.chrynan.strings.core
inline class StringArrayResourceID(override val name: String) : ResourceID | 0 | Kotlin | 0 | 4 | 4319ab4ee3585213a0295cb79b850b5b771e21fd | 108 | strings | Apache License 2.0 |
src/main/kotlin/com/ecwid/apiclient/v3/dto/common/ExtendedOrderTax.kt | Ecwid | 160,232,759 | false | {"Kotlin": 1019261} | package com.ecwid.apiclient.v3.dto.common
interface ExtendedOrderTax : BaseOrderTax {
val includeInPrice: Boolean?
}
| 11 | Kotlin | 13 | 17 | 2f94bfea3ad2073b89b8ea2b38dacdaa5f443a47 | 119 | ecwid-java-api-client | Apache License 2.0 |
app/src/main/java/com/kcteam/features/photoReg/model/UserPhotoRegModel.kt | DebashisINT | 558,234,039 | false | null | package com.breezefieldsalesashavarifoods.features.photoReg.model
class UserPhotoRegModel {
var user_id: String? = null
var session_token: String? = null
var registration_date_time: String? = null
} | 0 | null | 1 | 1 | a9aabcf48662c76db18bcece75cae9ac961da1ed | 211 | NationalPlastic | Apache License 2.0 |
src/commonMain/kotlin/org/angproj/crypt/shake/Shake256Hash.kt | angelos-project | 677,062,617 | false | {"Kotlin": 17587776} | /**
* Copyright (c) 2023 by <NAME> <<EMAIL>>.
*
* This software is available under the terms of the MIT license. Parts are licensed
* under different terms if stated. The legal terms are attached to the LICENSE file
* and are made available on:
*
* https://opensource.org/licenses/MIT
*
* SPDX-License-Identifier: MIT
*
* Contributors:
* <NAME> - initial implementation
*/
package org.angproj.crypt.sha
import org.angproj.aux.util.readLongAt
import org.angproj.aux.util.writeLongAt
import org.angproj.crypt.Hash
import org.angproj.crypt.keccak.AbstractKeccakHashEngine
import org.angproj.crypt.keccak.KeccakHashEngine
internal class Sha3256Hash : AbstractKeccakHashEngine() {
private val state = Array<Long>(25) { 0 }
private val w = ByteArray(permutationSize)
protected var lasting: ByteArray = byteArrayOf()
protected var count: Int = 0
protected fun ioLoop(breakAt: Int, block: (i: Int) -> Unit) {
for (i in 0 until permutationSize step wordSize) {
block(i)
if (i >= breakAt) break
}
}
protected fun i5Loop(block: (i: Int) -> Unit) {
for (i in 0 until 5) block(i)
}
protected fun pad(size: Int): ByteArray = when (size) {
1 -> byteArrayOf(-122)
else -> ByteArray(size).also {
it[0] = 6
it[size - 1] = -128
}
}
private fun stepTheta(a: Array<Long>) {
val c = arrayOf<Long>(0, 0, 0, 0, 0)
val d = arrayOf<Long>(0, 0, 0, 0, 0)
i5Loop { i ->
c[i] = a[i + 0] xor a[i + 5] xor a[i + 10] xor a[i + 15] xor a[i + 20]
}
i5Loop { i ->
d[i] = c[(i + 4).mod(5)] xor c[(i + 1).mod(5)].rotateLeft(1)
}
a.indices.forEach { i ->
a[i] = a[i] xor d[i.mod(5)]
}
}
private fun stepPiAndRho(a: Array<Long>) {
val tmp: Long = a[10].rotateLeft(3)
prTo.indices.forEach { i -> a[prTo[i]] = a[prFrom[i]].rotateLeft(prLeft[i]) }
a[7] = tmp
}
private fun stepChi(a: Array<Long>) {
val y = arrayOf<Long>(0, 0, 0, 0, 0)
(a.indices step 5).forEach { i ->
a.copyInto(y, 0, i, i + 5)
i5Loop { j ->
a[i + j] = y[j] xor (y[(j + 1).mod(5)].inv() and y[(j + 2).mod(5)])
}
}
}
private fun stepIota(a: Array<Long>, i: Int) {
a[0] = a[0] xor roundConstants[i]
}
fun keccak(): Unit = (0 until rounds).forEach { i ->
stepTheta(state)
stepPiAndRho(state)
stepChi(state)
stepIota(state, i)
}
fun absorb(): Unit = ioLoop(blockSize) { i ->
state[i / 8] = state[i / 8] xor w.readLongAt(i).asLittle()
}
fun squeeze(): ByteArray {
w.fill(0)
ioLoop(messageDigestSize) { i ->
w.writeLongAt(i, state[i / 8].asLittle())
}
return w.copyOfRange(0, messageDigestSize)
}
private fun push(chunk: ByteArray) {
chunk.copyInto(w)
absorb()
}
private fun transform() {
keccak()
}
override fun update(messagePart: ByteArray) {
val buffer = lasting + messagePart
lasting = byteArrayOf(0) // Setting an empty array
(0..buffer.size step blockSize).forEach { i ->
// Slicing the buffer in ranges of 64, if too small it's lasting.
val chunk = try {
messagePart.copyOfRange(i, i + blockSize)
} catch (_: IndexOutOfBoundsException) {
lasting = buffer.copyOfRange(i, buffer.size)
return
}
push(chunk)
transform()
count += blockSize
}
}
override fun final(): ByteArray {
when (lasting.size != blockSize) {
true -> {
push(lasting + pad(blockSize - lasting.size))
transform()
}
else -> {
push(lasting)
transform()
push(pad(blockSize))
transform()
}
}
return squeeze()
}
override val type: String
get() = "SHA3 Under developlment"
companion object : Hash {
override val name: String = "${KeccakHashEngine.TYPE}3-256"
override val blockSize: Int = 1088.inByteSize
override val wordSize: Int = 64.inByteSize
override val messageDigestSize: Int = 256.inByteSize
val permutationSize: Int = 1600.inByteSize
val rounds: Int = 24
override fun create(): Sha3256Hash = Sha3256Hash()
protected val prTo = intArrayOf(
10, 1, 6, 9, 22, 14, 20, 2, 12, 13, 19, 23, 15, 4, 24, 21, 8, 16, 5, 3, 18, 17, 11
)
protected val prFrom = intArrayOf(
1, 6, 9, 22, 14, 20, 2, 12, 13, 19, 23, 15, 4, 24, 21, 8, 16, 5, 3, 18, 17, 11, 7
)
protected val prLeft = intArrayOf(
1, 44, 20, 61, 39, 18, 62, 43, 25, 8, 56, 41, 27, 14, 2, 55, 45, 36, 28, 21, 15, 10, 6
)
protected val roundConstants = longArrayOf(
1L,
32898L,
-9223372036854742902L,
-9223372034707259392L,
32907L,
2147483649L,
-9223372034707259263L,
-9223372036854743031L,
138L,
136L,
2147516425L,
2147483658L,
2147516555L,
-9223372036854775669L,
-9223372036854742903L,
-9223372036854743037L,
-9223372036854743038L,
-9223372036854775680L,
32778L,
-9223372034707292150L,
-9223372034707259263L,
-9223372036854742912L,
2147483649L,
-9223372034707259384L
)
}
} | 0 | Kotlin | 0 | 0 | ed191fa0bc60aa5ed01fe8ef63a86c742890d243 | 5,809 | angelos-project-crypt | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.