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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/androidTest/java/com/pechuro/bsuirschedule/util/Utils.kt
|
Ilyshka991
| 147,244,674
| false
| null |
package com.pechuro.bsuirschedule.util
import android.os.SystemClock
inline fun waitFor(delay: Long) {
SystemClock.sleep(delay)
}
| 1
|
Kotlin
|
1
| 8
|
0112f76ff117b99505bc1b013643f4116d5ec379
| 135
|
BsuirSchedule
|
Apache License 2.0
|
shared/feature/geminio-sdk/src/main/kotlin/ru/hh/plugins/geminio/sdk/models/GeminioTemplateParametersIds.kt
|
hhru
| 159,637,875
| false
| null |
package ru.hh.plugins.geminio.sdk.models
data class GeminioTemplateParametersIds(
val newModuleNameParameterId: String,
val newModulePackageNameParameterId: String,
val newModuleLibrariesModulesParameterId: String,
val newApplicationModulesParameterId: String,
)
| 17
| null |
11
| 97
|
2d6c02fc814eff3934c17de77ef7ade91d3116f5
| 280
|
android-multimodule-plugin
|
MIT License
|
compiler/fir/tree/src/org/jetbrains/kotlin/fir/declarations/FirResolvePhase.kt
|
JetBrains
| 3,432,266
| false
| null |
/*
* Copyright 2010-2019 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.declarations
enum class FirResolvePhase {
RAW_FIR,
ANNOTATIONS_FOR_PLUGINS, // run only if some extensions are registered
FIRST_PLUGIN_GENERATION, // plugin phase
IMPORTS,
SUPER_TYPES,
SEALED_CLASS_INHERITORS,
TYPES,
STATUS,
CONTRACTS,
IMPLICIT_TYPES_BODY_RESOLVE,
BODY_RESOLVE;
val requiredToLaunch: FirResolvePhase
get() = when (this) {
RAW_FIR -> RAW_FIR
IMPORTS -> RAW_FIR
IMPLICIT_TYPES_BODY_RESOLVE, BODY_RESOLVE -> STATUS
else -> values()[ordinal - 1]
}
val next: FirResolvePhase get() = values()[ordinal + 1]
companion object {
// Short-cut
val DECLARATIONS = STATUS
val ANALYZED_DEPENDENCIES = BODY_RESOLVE
}
}
| 34
| null |
5771
| 46,772
|
bef0946ab7e5acd5b24b971eca532c43c8eba750
| 1,015
|
kotlin
|
Apache License 2.0
|
runtime/src/main/java/io/novafoundation/nova/runtime/multiNetwork/chain/model/Chain.kt
|
nova-wallet
| 496,649,319
| false
| null |
package io.novafoundation.nova.runtime.multiNetwork.chain.model
import io.novafoundation.nova.common.utils.Identifiable
import java.math.BigInteger
typealias ChainId = String
typealias ChainAssetId = Int
typealias StringTemplate = String
typealias ExplorerTemplateExtractor = (Chain.Explorer) -> StringTemplate?
typealias BuyProviderId = String
typealias BuyProviderArguments = Map<String, Any?>
data class FullChainAssetId(val chainId: ChainId, val assetId: ChainAssetId)
data class Chain(
val id: ChainId,
val name: String,
val assets: List<Asset>,
val nodes: List<Node>,
val explorers: List<Explorer>,
val externalApi: ExternalApi?,
val icon: String,
val addressPrefix: Int,
val types: Types?,
val isEthereumBased: Boolean,
val isTestNet: Boolean,
val hasCrowdloans: Boolean,
val governance: List<Governance>,
val parentId: String?,
val additional: Additional?
) : Identifiable {
companion object // extensions
val assetsBySymbol = assets.associateBy(Asset::symbol)
val assetsById = assets.associateBy(Asset::id)
data class Additional(
val defaultTip: BigInteger?,
)
data class Types(
val url: String,
val overridesCommon: Boolean,
)
data class Asset(
val iconUrl: String?,
val id: ChainAssetId,
val priceId: String?,
val chainId: ChainId,
val symbol: String,
val precision: Int,
val buyProviders: Map<BuyProviderId, BuyProviderArguments>,
val staking: StakingType,
val type: Type,
val name: String,
) : Identifiable {
sealed class Type {
object Native : Type()
data class Statemine(
val id: BigInteger,
val palletName: String?
) : Type()
data class Orml(
val currencyIdScale: String,
val currencyIdType: String,
val existentialDeposit: BigInteger,
val transfersEnabled: Boolean,
) : Type()
object Unsupported : Type()
}
enum class StakingType {
UNSUPPORTED,
RELAYCHAIN, RELAYCHAIN_AURA, ALEPH_ZERO, // relaychain like
PARACHAIN, TURING // parachain-staking like
}
override val identifier = "$chainId:$id"
}
data class Node(
val chainId: ChainId,
val url: String,
val name: String,
val orderId: Int,
) : Identifiable {
override val identifier: String = "$chainId:$url"
}
data class Explorer(
val chainId: ChainId,
val name: String,
val account: StringTemplate?,
val extrinsic: StringTemplate?,
val event: StringTemplate?
) : Identifiable {
override val identifier = "$chainId:$name"
}
data class ExternalApi(
val staking: Section?,
val history: Section?,
val crowdloans: Section?,
val governance: Section?
) {
data class Section(val type: Type, val url: String) {
enum class Type {
SUBQUERY, GITHUB, UNKNOWN, POLKASSEMBLY
}
}
}
enum class Governance {
V1, V2
}
override val identifier: String = id
}
enum class TypesUsage {
BASE, OWN, BOTH,
}
| 4
|
Kotlin
|
8
| 24
|
69c3ee9eb9986ea092e4dd354d4c6df65642e608
| 3,355
|
nova-android-app
|
Apache License 2.0
|
src/main/kotlin/world/seoraw/core/Webhook.kt
|
SeorawWorld
| 446,886,909
| false
|
{"Kotlin": 17079}
|
package world.seoraw.core
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.cio.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import kotlinx.coroutines.runBlocking
import net.kyori.adventure.text.Component
import org.bukkit.Bukkit
import java.io.File
import java.util.*
open class Payload(source: String) {
val payload = JsonParser.parseString(source).asJsonObject!!
fun getWorkflow(): Workflow? {
if (payload.has("repository") && payload.has("action") && payload.get("action").asString == "completed") {
return Workflow(payload.getAsJsonObject("workflow_run") ?: return null)
}
return null
}
}
open class Workflow(payload: JsonObject) {
companion object {
var firstTask = true
}
val headBranch = payload.get("head_branch").asString!!
val repositoryName = payload.getAsJsonObject("repository").get("name").asString!!
val repositoryOwner = payload.getAsJsonObject("repository").getAsJsonObject("owner").get("login").asString!!
val event = payload.get("event").asString!!
val status = payload.get("status").asString!!
val conclusion = payload.get("conclusion").asString!!
val artifactsUrl = payload.get("artifacts_url").asString!!
val headCommitMessage = payload.getAsJsonObject("head_commit").get("message").asString!!
val headCommitAuthorName = payload.getAsJsonObject("head_commit").getAsJsonObject("author").get("name").asString!!
open fun isMainBranch(): Boolean {
return headBranch == "main" || headBranch == "master"
}
open fun isConclusionSuccess(): Boolean {
return status == "completed" && conclusion == "success"
}
open fun checkUpdate() {
if (repositoryOwner == "SeorawWorld" && (repositoryName == "SeorawPlugin" || repositoryName == "SeorawCore")) {
SeorawCore.instance.logger.info("§c核心插件 $repositoryName 收到新的提交,正在获取详细信息。")
Bukkit.getScheduler().runTaskAsynchronously(SeorawCore.instance, Runnable {
runBlocking {
HttpClient(CIO).use { client ->
var response: HttpResponse = client.get(artifactsUrl) {
headers["Authorization"] = "token ${SeorawCore.instance.conf.getString("github-token")}"
}
val artifacts = JsonParser.parseString(response.receive<ByteArray>().decodeToString()).asJsonObject
val artifact = artifacts.getAsJsonArray("artifacts")[0].asJsonObject
val archiveDownloadUrl = artifact.get("archive_download_url").asString
if (!archiveDownloadUrl.startsWith("https://api.github.com/repos/SeorawWorld")) {
SeorawCore.instance.logger.info("§c未经允许的来源: $archiveDownloadUrl")
return@use
}
SeorawCore.instance.logger.info("§c正在下载...")
response = client.get(archiveDownloadUrl) {
headers["Authorization"] = "token ${SeorawCore.instance.conf.getString("github-token")}"
}
val file = newFile("plugins/update/${UUID.randomUUID()}.zip")
try {
file.writeBytes(response.readBytes())
SeorawCore.instance.logger.info("§c下载完成,开始部署。")
val unzipFile = newFile("plugins/update/${UUID.randomUUID()}", folder = true)
file.unzip(unzipFile)
val listFiles = unzipFile.listFiles()
if (listFiles != null && listFiles.isNotEmpty()) {
val newFile = File("plugins/update/$repositoryName.jar")
newFile.delete()
listFiles[0].copyTo(newFile)
if (newFile.exists()) {
Bukkit.broadcast(Component.text("§e核心插件 §7$repositoryName §e收到新的有效提交, 服务器即将重新启动。"))
Bukkit.broadcast(Component.text("§e来自: §7$headCommitAuthorName"))
Bukkit.broadcast(Component.text("§e更新内容:"))
headCommitMessage.lines().forEach { message ->
Bukkit.broadcast(Component.text("§7 - $message"))
}
if (Bukkit.getOnlinePlayers().isEmpty()) {
Bukkit.shutdown()
} else if (firstTask) {
firstTask = false
SafelyShutdown.shutdown(60)
}
}
}
unzipFile.deepDelete()
} catch (ex: Throwable) {
ex.printStackTrace()
}
file.delete()
}
}
})
}
}
}
| 0
|
Kotlin
|
0
| 0
|
fca482e36bd964789c39d45b03fd4744f8598a34
| 5,318
|
SeorawCore
|
MIT License
|
clients/android/NewsBlur/app/src/main/java/com/newsblur/util/FeedExt.kt
|
samuelclay
| 101,248
| false
| null |
package com.newsblur.util
import com.newsblur.domain.Feed
object FeedExt {
fun Feed.isNotifyEmail(): Boolean = isNotify(NOTIFY_EMAIL)
fun Feed.isNotifyWeb(): Boolean = isNotify(NOTIFY_WEB)
fun Feed.isNotifyIOS(): Boolean = isNotify(NOTIFY_IOS)
fun Feed.isNotifyAndroid(): Boolean = isNotify(NOTIFY_ANDROID)
fun Feed.enableNotificationType(type: String) {
if (notificationTypes == null) notificationTypes = mutableListOf()
if (!notificationTypes.contains(type)) notificationTypes.add(type)
}
fun Feed.disableNotificationType(type: String) {
notificationTypes?.remove(type)
}
fun Feed.disableNotification() {
notificationFilter = null
}
@JvmStatic
fun Feed.isAndroidNotifyUnread(): Boolean = isNotifyUnread() && isNotifyAndroid()
@JvmStatic
fun Feed.isAndroidNotifyFocus(): Boolean = isNotifyFocus() && isNotifyAndroid()
@JvmStatic
fun Feed.isNotifyUnread(): Boolean = notificationFilter == Feed.NOTIFY_FILTER_UNREAD
@JvmStatic
fun Feed.isNotifyFocus(): Boolean = notificationFilter == Feed.NOTIFY_FILTER_FOCUS
fun Feed.setNotifyFocus() {
notificationFilter = Feed.NOTIFY_FILTER_FOCUS
}
fun Feed.setNotifyUnread() {
notificationFilter = Feed.NOTIFY_FILTER_UNREAD
}
private fun Feed.isNotify(type: String): Boolean = notificationTypes?.contains(type) ?: false
const val NOTIFY_EMAIL = "email"
const val NOTIFY_WEB = "web"
const val NOTIFY_IOS = "ios"
const val NOTIFY_ANDROID = "android"
}
| 163
| null |
997
| 6,853
|
cf9f0d9ef3403990f641f336f09009f791407e3b
| 1,559
|
NewsBlur
|
MIT License
|
nj2k/tests/org/jetbrains/kotlin/nj2k/AbstractNewJavaToKotlinConverterSingleFileTest.kt
|
svitalsky
| 181,867,437
| true
|
{"Markdown": 58, "Gradle": 502, "Gradle Kotlin DSL": 227, "Java Properties": 13, "Shell": 11, "Ignore List": 10, "Batchfile": 9, "Git Attributes": 1, "Protocol Buffer": 13, "Java": 6006, "Kotlin": 45173, "Proguard": 8, "XML": 1628, "Text": 9955, "JavaScript": 241, "JAR Manifest": 2, "Roff": 210, "Roff Manpage": 34, "INI": 97, "AsciiDoc": 1, "SVG": 32, "HTML": 468, "Groovy": 31, "JSON": 18, "JFlex": 3, "Maven POM": 94, "CSS": 1, "Ant Build System": 50, "C": 1, "ANTLR": 1, "YAML": 1, "JSON with Comments": 1, "Scala": 1}
|
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* 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.jetbrains.kotlin.nj2k
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.j2k.IdeaJavaToKotlinServices
import org.jetbrains.kotlin.j2k.AbstractJavaToKotlinConverterSingleFileTest
import org.jetbrains.kotlin.j2k.ConverterSettings
import org.jetbrains.kotlin.test.KotlinTestUtils
import org.junit.AfterClass
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import kotlin.test.AfterTest
abstract class AbstractNewJavaToKotlinConverterSingleFileTest : AbstractJavaToKotlinConverterSingleFileTest() {
override fun compareResults(expectedFile: File, actual: String) {
KotlinTestUtils.assertEqualsToFile(expectedFile, actual) {
val file = createKotlinFile(it)
file.dumpStructureText()
}
}
override fun fileToKotlin(text: String, settings: ConverterSettings, project: Project): String {
val file = createJavaFile(text)
return NewJavaToKotlinConverter(project, settings, IdeaJavaToKotlinServices)
.filesToKotlin(listOf(file), NewJ2kPostProcessor(true, settings)).results.single()
}
override fun provideExpectedFile(javaPath: String): File =
File(javaPath.replace(".java", ".new.kt")).takeIf { it.exists() }
?: super.provideExpectedFile(javaPath)
}
| 0
|
Kotlin
|
0
| 0
|
bcc88020140c4e01fcf24730dced3594d2147390
| 1,913
|
kotlin
|
Apache License 2.0
|
wear/src/main/java/hibernate/v2/testyourwear/model/MainItem.kt
|
himphen
| 369,255,395
| false
| null |
package hibernate.v2.testyourwear.model
/**
* Created by himphen on 24/5/16.
*/
class MainItem(val mainText: String, val mainImageId: Int, val intentClass: Class<*>)
| 0
|
Kotlin
|
0
| 0
|
dd4030596c7ed469617ecc5bd11d2d94d2a90ad2
| 168
|
TestYourAndroid
|
Apache License 2.0
|
androidApp/src/main/java/com/mongodb/mongoize/android/screens/registration/RegistrationViewModel.kt
|
mongodb-developer
| 543,055,392
| false
|
{"Kotlin": 56591, "Swift": 3797, "Ruby": 1722}
|
package com.mongodb.mongoize.android.screens.registration
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mongodb.mongoize.RealmRepo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class RegistrationViewModel : ViewModel() {
private val repo = RealmRepo()
val registrationSuccess = MutableLiveData<Boolean>()
fun register(email: String, password: String) {
viewModelScope.launch(Dispatchers.IO) {
try {
repo.registration(password = <PASSWORD>, email = email).run {
withContext(Dispatchers.Main) {
registrationSuccess.value = true
}
}
} catch (e: Exception) {
withContext(Dispatchers.Main) {
registrationSuccess.value = false
}
}
}
}
}
| 0
|
Kotlin
|
6
| 5
|
f4959f739d49478d2f20aab56403508e993cc48d
| 998
|
mongo-conference
|
Apache License 2.0
|
itemplotter/src/main/kotlin/com/ijoic/item_plotter/source/PlotterSource.kt
|
VerstSiu
| 118,207,494
| false
|
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 3, "Proguard": 2, "Java": 2, "XML": 17, "Kotlin": 58}
|
/*
*
* Copyright(c) 2018 VerstSiu
*
* 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.ijoic.item_plotter.source
/**
* Plotter source.
*
* @author xiao.yl on 2018/1/25.
* @version 1.0
*/
interface PlotterSource
| 0
|
Kotlin
|
0
| 0
|
06eed56719e62da9efaf7b4f3e3d341e02ad1b63
| 748
|
item_plotter
|
Apache License 2.0
|
compiler/ir/backend.wasm/src/org/jetbrains/kotlin/backend/wasm/WasmSymbols.kt
|
BradOselo
| 367,097,840
| false
| null |
/*
* Copyright 2010-2019 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.backend.wasm
import org.jetbrains.kotlin.backend.common.ir.Symbols
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.PackageViewDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.ir.builders.declarations.addFunction
import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
import org.jetbrains.kotlin.ir.symbols.IrClassSymbol
import org.jetbrains.kotlin.ir.symbols.IrClassifierSymbol
import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol
import org.jetbrains.kotlin.ir.types.defaultType
import org.jetbrains.kotlin.ir.util.SymbolTable
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.util.OperatorNameConventions
class WasmSymbols(
context: WasmBackendContext,
private val symbolTable: SymbolTable
) : Symbols<WasmBackendContext>(context, context.irBuiltIns, symbolTable) {
private val wasmInternalPackage: PackageViewDescriptor =
context.module.getPackage(FqName("kotlin.wasm.internal"))
private val collectionsPackage: PackageViewDescriptor =
context.module.getPackage(StandardNames.COLLECTIONS_PACKAGE_FQ_NAME)
private val builtInsPackage: PackageViewDescriptor =
context.module.getPackage(StandardNames.BUILT_INS_PACKAGE_FQ_NAME)
override val throwNullPointerException = getInternalFunction("THROW_NPE")
override val throwISE = getInternalFunction("THROW_ISE")
override val throwTypeCastException = getInternalFunction("THROW_CCE")
override val throwUninitializedPropertyAccessException =
getInternalFunction("throwUninitializedPropertyAccessException")
override val defaultConstructorMarker =
getIrClass(FqName("kotlin.wasm.internal.DefaultConstructorMarker"))
override val throwKotlinNothingValueException: IrSimpleFunctionSymbol
get() = TODO()
override val stringBuilder
get() = TODO()
override val coroutineImpl
get() = TODO()
override val coroutineSuspendedGetter
get() = TODO()
override val getContinuation
get() = TODO()
override val coroutineContextGetter by lazy {
context.irFactory.addFunction(context.getExcludedPackageFragment(FqName("kotlin.excluded"))) {
name = Name.identifier("coroutineContextGetter\$Stub")
}.symbol
}
override val suspendCoroutineUninterceptedOrReturn
get() = TODO()
override val coroutineGetContext
get() = TODO()
override val returnIfSuspended
get() = TODO()
override val functionAdapter: IrClassSymbol
get() = TODO()
val wasmUnreachable = getInternalFunction("wasm_unreachable")
val consumeAnyIntoVoid = getInternalFunction("consumeAnyIntoVoid")
val voidClass = getIrClass(FqName("kotlin.wasm.internal.Void"))
val voidType by lazy { voidClass.defaultType }
val equalityFunctions = mapOf(
context.irBuiltIns.booleanType to getInternalFunction("wasm_i32_eq"),
context.irBuiltIns.byteType to getInternalFunction("wasm_i32_eq"),
context.irBuiltIns.shortType to getInternalFunction("wasm_i32_eq"),
context.irBuiltIns.charType to getInternalFunction("wasm_i32_eq"),
context.irBuiltIns.intType to getInternalFunction("wasm_i32_eq"),
context.irBuiltIns.longType to getInternalFunction("wasm_i64_eq")
)
val floatEqualityFunctions = mapOf(
context.irBuiltIns.floatType to getInternalFunction("wasm_f32_eq"),
context.irBuiltIns.doubleType to getInternalFunction("wasm_f64_eq")
)
private fun wasmPrimitiveTypeName(classifier: IrClassifierSymbol): String = with(context.irBuiltIns) {
when (classifier) {
booleanClass, byteClass, shortClass, charClass, intClass -> "i32"
floatClass -> "f32"
doubleClass -> "f64"
longClass -> "i64"
else -> error("Unknown primitive type")
}
}
val comparisonBuiltInsToWasmIntrinsics = context.irBuiltIns.run {
listOf(
lessFunByOperandType to "lt",
lessOrEqualFunByOperandType to "le",
greaterOrEqualFunByOperandType to "ge",
greaterFunByOperandType to "gt"
).map { (typeToBuiltIn, wasmOp) ->
typeToBuiltIn.map { (type, builtin) ->
val wasmType = wasmPrimitiveTypeName(type)
val markSign = if (wasmType == "i32" || wasmType == "i64") "_s" else ""
builtin to getInternalFunction("wasm_${wasmType}_$wasmOp$markSign")
}
}.flatten().toMap()
}
val booleanAnd = getInternalFunction("wasm_i32_and")
val refEq = getInternalFunction("wasm_ref_eq")
val refIsNull = getInternalFunction("wasm_ref_is_null")
val refTest = getInternalFunction("wasm_ref_test")
val intToLong = getInternalFunction("wasm_i64_extend_i32_s")
val wasmRefCast = getInternalFunction("wasm_ref_cast")
val boxIntrinsic: IrSimpleFunctionSymbol = getInternalFunction("boxIntrinsic")
val unboxIntrinsic: IrSimpleFunctionSymbol = getInternalFunction("unboxIntrinsic")
val stringGetLiteral = getFunction("stringLiteral", builtInsPackage)
val wasmClassId = getInternalFunction("wasmClassId")
val wasmInterfaceId = getInternalFunction("wasmInterfaceId")
val getVirtualMethodId = getInternalFunction("getVirtualMethodId")
val getInterfaceImplId = getInternalFunction("getInterfaceImplId")
val isInterface = getInternalFunction("isInterface")
val nullableEquals = getInternalFunction("nullableEquals")
val ensureNotNull = getInternalFunction("ensureNotNull")
val anyNtoString = getInternalFunction("anyNtoString")
val nullableFloatIeee754Equals = getInternalFunction("nullableFloatIeee754Equals")
val nullableDoubleIeee754Equals = getInternalFunction("nullableDoubleIeee754Equals")
val exportString = getInternalFunction("exportString")
val unsafeGetScratchRawMemory = getInternalFunction("unsafeGetScratchRawMemory")
private val functionNInterfaces = (0..22).map { arity ->
getIrClass(FqName("kotlin.wasm.internal.Function$arity"))
}
val functionNInvokeMethods by lazy {
functionNInterfaces.map { interfaceSymbol ->
interfaceSymbol.owner.declarations.filterIsInstance<IrSimpleFunction>().single { method ->
method.name == OperatorNameConventions.INVOKE
}.symbol
}
}
val arraysCopyInto = findFunctions(collectionsPackage.memberScope, Name.identifier("copyInto"))
.map { symbolTable.referenceSimpleFunction(it) }
override fun functionN(n: Int): IrClassSymbol =
functionNInterfaces[n]
private fun findClass(memberScope: MemberScope, name: Name): ClassDescriptor =
memberScope.getContributedClassifier(name, NoLookupLocation.FROM_BACKEND) as ClassDescriptor
private fun findFunctions(memberScope: MemberScope, name: Name): List<SimpleFunctionDescriptor> =
memberScope.getContributedFunctions(name, NoLookupLocation.FROM_BACKEND).toList()
private fun findProperty(memberScope: MemberScope, name: Name): List<PropertyDescriptor> =
memberScope.getContributedVariables(name, NoLookupLocation.FROM_BACKEND).toList()
internal fun getClass(fqName: FqName): ClassDescriptor =
findClass(context.module.getPackage(fqName.parent()).memberScope, fqName.shortName())
internal fun getProperty(fqName: FqName): PropertyDescriptor =
findProperty(context.module.getPackage(fqName.parent()).memberScope, fqName.shortName()).single()
private fun getFunction(name: String, ownerPackage: PackageViewDescriptor): IrSimpleFunctionSymbol {
val tmp = findFunctions(ownerPackage.memberScope, Name.identifier(name)).single()
return symbolTable.referenceSimpleFunction(tmp)
}
private fun getInternalFunction(name: String) = getFunction(name, wasmInternalPackage)
private fun getIrClass(fqName: FqName): IrClassSymbol = symbolTable.referenceClass(getClass(fqName))
}
| 34
| null |
2
| 3
|
58c7aa9937334b7f3a70acca84a9ce59c35ab9d1
| 8,553
|
kotlin
|
Apache License 2.0
|
src/main/kotlin/de/menkalian/pisces/command/impl/audio/playlist/CreatePlaylistCommand.kt
|
Menkalian
| 471,663,267
| false
| null |
package de.menkalian.pisces.command.impl.audio.playlist
import de.menkalian.pisces.OnConfigValueCondition
import de.menkalian.pisces.RequiresKey
import de.menkalian.pisces.audio.IAudioHandler
import de.menkalian.pisces.command.CommonCommandBase
import de.menkalian.pisces.command.ICommandHandler
import de.menkalian.pisces.command.data.CommandParameter
import de.menkalian.pisces.command.data.ECommandSource
import de.menkalian.pisces.database.IDatabaseHandler
import de.menkalian.pisces.message.IMessageHandler
import de.menkalian.pisces.util.FixedVariables
import org.springframework.context.annotation.Conditional
import org.springframework.stereotype.Component
/**
* Implementierung eines Befehls zum Erstellen einer Playlist
*/
@Component
@Conditional(OnConfigValueCondition::class)
@RequiresKey(["pisces.command.impl.audio.playlist.CreatePlaylist"])
class CreatePlaylistCommand(
override val databaseHandler: IDatabaseHandler,
val messageHandler: IMessageHandler,
val audioHandler: IAudioHandler
) : CommonCommandBase() {
override fun initialize() {
innerCategory = "Playlist"
aliases.add("createpl")
aliases.add("mkpl")
aliases.add("makepl")
aliases.add("makeplaylist")
supportedContexts.addAll(ALL_GUILD_CONTEXTS)
supportedSources.addAll(ALL_SOURCES)
addStringParameter(description = "Name der Playlist, die erstellt werden soll.")
super.initialize()
}
override val name: String
get() = "createPlaylist"
override val description: String
get() = "Erstellt eine neue Playlist."
override fun execute(
commandHandler: ICommandHandler,
source: ECommandSource,
parameters: List<CommandParameter>,
guildId: Long,
channelId: Long,
authorId: Long,
sourceInformation: FixedVariables
) {
val playlistName: String = parameters.getTextArg()
if (!PlaylistHelper.ensurePlaylistValid(playlistName, guildId, channelId, messageHandler)) {
return
}
val plExists = databaseHandler.getPlaylistIfExists(guildId, playlistName) != null
if (!plExists) {
databaseHandler.getOrCreatePlaylist(guildId, playlistName)
}
messageHandler
.createMessage(guildId, channelId)
.withTitle(
if (plExists)
"Die Playlist \"$playlistName\" existiert bereits."
else
"Die neue Playlist \"$playlistName\" wurde angelegt."
)
.build()
}
private fun List<CommandParameter>.getTextArg(): String {
return getDefaultArg()
?.asString() ?: ""
}
}
| 0
|
Kotlin
|
0
| 1
|
efc7818da5419ce720cd04878c8aa30809fc35c0
| 2,726
|
pisces
|
Apache License 2.0
|
app/src/main/java/com/alex/injector/libServer/PointerAngel.kt
|
ALEX5402
| 641,489,295
| false
|
{"Kotlin": 61345, "C": 17580, "C++": 11686, "Java": 3970, "Makefile": 1669}
|
package com.alex.injector.libServer
import android.annotation.SuppressLint
import android.os.AsyncTask
import android.util.Log
import com.alex.injector.MainActivity
import com.alex.injector.objects.global.Companion.TAG
import com.topjohnwu.superuser.Shell.*
import java.io.*
import java.lang.ref.WeakReference
import java.net.URL
@Suppress("DEPRECATION")
class PointerAngel(mainActivity: MainActivity ) : AsyncTask <String, Void, String>(){
lateinit var outputfile : File
private val mainactivityy = WeakReference(mainActivity)
var verify : Boolean = false
@SuppressLint("SetWorldReadable", "SetWorldWritable")
@Deprecated("Deprecated in Java")
override fun doInBackground(vararg params: String?): String? {
val downloadlink = params[ 0 ]
val tempDir = System.getProperty("java.io.tmpdir")
val timestamp = System.currentTimeMillis()
outputfile = File(tempDir, "$timestamp.zip")
val url = downloadlink.let {
URL(it)
}
var inputStream: InputStream? = null
var outputStream: OutputStream? = null
try {
inputStream = url.openStream()
outputStream = FileOutputStream(outputfile)
val buff = ByteArray(1024)
var byteread = inputStream.read(buff)
while (byteread != -1) {
outputStream.write(buff, 0, byteread)
byteread = inputStream.read(buff)
}
verify = true
File(outputfile.absolutePath).setExecutable(true)
File(outputfile.absolutePath).setWritable(true)
return outputfile.absolutePath
}catch (E : java.lang.Exception)
{
E.printStackTrace()
verify = false
}
finally {
inputStream?.close()
outputStream?.close()
}
return null
}
@Deprecated("Deprecated in Java")
override fun onPostExecute(result: String?) {
if (verify)
{
result?.let {
mainactivityy.get()?.alldone(it)
}
result?.let { Log.d(TAG, it) }
// Log.i( TAG , "done")
}else {
mainactivityy.get()?.somethingwrong()
}
}
}
| 0
|
Kotlin
|
8
| 22
|
6a49d33a228bdbf714aaa5321a4ac147a266d7d7
| 2,264
|
Reinject
|
MIT License
|
src/test/kotlin/no/nav/familie/ef/sak/vilkår/VurderingServiceTest.kt
|
navikt
| 206,805,010
| false
|
{"Kotlin": 3747804, "Gherkin": 163948, "Dockerfile": 180}
|
package no.nav.familie.ef.sak.service
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.runs
import io.mockk.slot
import io.mockk.verify
import no.nav.familie.ef.sak.barn.BarnService
import no.nav.familie.ef.sak.behandling.BehandlingService
import no.nav.familie.ef.sak.behandling.domain.BehandlingStatus
import no.nav.familie.ef.sak.blankett.BlankettRepository
import no.nav.familie.ef.sak.opplysninger.personopplysninger.GrunnlagsdataService
import no.nav.familie.ef.sak.opplysninger.personopplysninger.PersonopplysningerIntegrasjonerClient
import no.nav.familie.ef.sak.opplysninger.personopplysninger.dto.Sivilstandstype
import no.nav.familie.ef.sak.opplysninger.søknad.SøknadService
import no.nav.familie.ef.sak.opplysninger.søknad.domain.tilSøknadsverdier
import no.nav.familie.ef.sak.opplysninger.søknad.mapper.SøknadsskjemaMapper
import no.nav.familie.ef.sak.repository.behandling
import no.nav.familie.ef.sak.repository.fagsak
import no.nav.familie.ef.sak.repository.vilkårsvurdering
import no.nav.familie.ef.sak.testutil.søknadsBarnTilBehandlingBarn
import no.nav.familie.ef.sak.vilkår.DelvilkårsvurderingWrapper
import no.nav.familie.ef.sak.vilkår.VilkårGrunnlagService
import no.nav.familie.ef.sak.vilkår.VilkårType
import no.nav.familie.ef.sak.vilkår.Vilkårsresultat
import no.nav.familie.ef.sak.vilkår.Vilkårsresultat.OPPFYLT
import no.nav.familie.ef.sak.vilkår.Vilkårsresultat.SKAL_IKKE_VURDERES
import no.nav.familie.ef.sak.vilkår.Vilkårsvurdering
import no.nav.familie.ef.sak.vilkår.VilkårsvurderingRepository
import no.nav.familie.ef.sak.vilkår.VurderingService
import no.nav.familie.ef.sak.vilkår.dto.SivilstandInngangsvilkårDto
import no.nav.familie.ef.sak.vilkår.dto.SivilstandRegistergrunnlagDto
import no.nav.familie.ef.sak.vilkår.dto.VilkårGrunnlagDto
import no.nav.familie.ef.sak.vilkår.regler.HovedregelMetadata
import no.nav.familie.ef.sak.vilkår.regler.vilkår.SivilstandRegel
import no.nav.familie.kontrakter.ef.søknad.TestsøknadBuilder
import no.nav.familie.kontrakter.felles.medlemskap.Medlemskapsinfo
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import java.util.UUID
internal class VurderingServiceTest {
private val behandlingService = mockk<BehandlingService>()
private val søknadService = mockk<SøknadService>()
private val vilkårsvurderingRepository = mockk<VilkårsvurderingRepository>()
private val personopplysningerIntegrasjonerClient = mockk<PersonopplysningerIntegrasjonerClient>()
private val blankettRepository = mockk<BlankettRepository>()
private val barnService = mockk<BarnService>()
private val vilkårGrunnlagService = mockk<VilkårGrunnlagService>()
private val grunnlagsdataService = mockk<GrunnlagsdataService>()
private val vurderingService = VurderingService(behandlingService = behandlingService,
søknadService = søknadService,
vilkårsvurderingRepository = vilkårsvurderingRepository,
vilkårGrunnlagService = vilkårGrunnlagService,
grunnlagsdataService = grunnlagsdataService,
barnService = barnService)
private val søknad = SøknadsskjemaMapper.tilDomene(TestsøknadBuilder.Builder().setBarn(listOf(
TestsøknadBuilder.Builder().defaultBarn("Navn navnesen", "14041385481"),
TestsøknadBuilder.Builder().defaultBarn("Navn navnesen", "01012067050")
)).build().søknadOvergangsstønad).tilSøknadsverdier()
private val barn = søknadsBarnTilBehandlingBarn(søknad.barn)
private val behandling = behandling(fagsak(), BehandlingStatus.OPPRETTET)
private val behandlingId = UUID.randomUUID()
@BeforeEach
fun setUp() {
every { behandlingService.hentAktivIdent(behandlingId) } returns søknad.fødselsnummer
every { behandlingService.hentBehandling(behandlingId) } returns behandling
every { søknadService.hentSøknadsgrunnlag(any()) }.returns(søknad)
every { blankettRepository.deleteById(any()) } just runs
every { personopplysningerIntegrasjonerClient.hentMedlemskapsinfo(any()) }
.returns(Medlemskapsinfo(personIdent = søknad.fødselsnummer,
gyldigePerioder = emptyList(),
uavklartePerioder = emptyList(),
avvistePerioder = emptyList()))
every { vilkårsvurderingRepository.insertAll(any()) } answers { firstArg() }
every { barnService.finnBarnPåBehandling(behandlingId) } returns barn
val sivilstand = SivilstandInngangsvilkårDto(mockk(relaxed = true),
SivilstandRegistergrunnlagDto(Sivilstandstype.GIFT, "Navn", null))
every { vilkårGrunnlagService.hentGrunnlag(any(), any(), any(), any()) } returns VilkårGrunnlagDto(mockk(relaxed = true),
mockk(relaxed = true),
sivilstand,
mockk(relaxed = true),
mockk(relaxed = true),
mockk(relaxed = true),
mockk(relaxed = true),
mockk(relaxed = true),
false,
mockk(relaxed = true))
}
@Test
fun `skal opprette nye Vilkårsvurdering for alle vilkår dersom ingen vurderinger finnes`() {
every { vilkårsvurderingRepository.findByBehandlingId(behandlingId) } returns emptyList()
val nyeVilkårsvurderinger = slot<List<Vilkårsvurdering>>()
every { vilkårsvurderingRepository.insertAll(capture(nyeVilkårsvurderinger)) } answers
{ it.invocation.args.first() as List<Vilkårsvurdering> }
val vilkår = VilkårType.hentVilkår()
vurderingService.hentEllerOpprettVurderinger(behandlingId)
assertThat(nyeVilkårsvurderinger.captured).hasSize(vilkår.size + 1) // 2 barn
assertThat(nyeVilkårsvurderinger.captured.map { it.type }.distinct()).containsExactlyInAnyOrderElementsOf(vilkår)
assertThat(nyeVilkårsvurderinger.captured.filter { it.type == VilkårType.ALENEOMSORG }).hasSize(2)
assertThat(nyeVilkårsvurderinger.captured.filter { it.barnId != null }).hasSize(2)
assertThat(nyeVilkårsvurderinger.captured.map { it.resultat }
.toSet()).containsOnly(Vilkårsresultat.IKKE_TATT_STILLING_TIL)
assertThat(nyeVilkårsvurderinger.captured.map { it.behandlingId }.toSet()).containsOnly(behandlingId)
}
@Test
fun `skal ikke opprette nye Vilkårsvurderinger for behandlinger som allerede har vurderinger`() {
every { vilkårsvurderingRepository.findByBehandlingId(behandlingId) } returns
listOf(vilkårsvurdering(resultat = OPPFYLT,
type = VilkårType.FORUTGÅENDE_MEDLEMSKAP,
behandlingId = behandlingId))
vurderingService.hentEllerOpprettVurderinger(behandlingId)
verify(exactly = 0) { vilkårsvurderingRepository.updateAll(any()) }
verify(exactly = 0) { vilkårsvurderingRepository.insertAll(any()) }
}
@Test
internal fun `skal ikke returnere delvilkår som er ikke aktuelle til frontend`() {
val delvilkårsvurdering =
SivilstandRegel().initereDelvilkårsvurdering(HovedregelMetadata(mockk(),
Sivilstandstype.ENKE_ELLER_ENKEMANN,
barn = emptyList()))
every { vilkårsvurderingRepository.findByBehandlingId(behandlingId) } returns
listOf(Vilkårsvurdering(behandlingId = behandlingId,
type = VilkårType.SIVILSTAND,
delvilkårsvurdering = DelvilkårsvurderingWrapper(delvilkårsvurdering)))
val vilkår = vurderingService.hentEllerOpprettVurderinger(behandlingId)
assertThat(delvilkårsvurdering).hasSize(5)
assertThat(delvilkårsvurdering.filter { it.resultat == Vilkårsresultat.IKKE_AKTUELL }).hasSize(4)
assertThat(delvilkårsvurdering.filter { it.resultat == Vilkårsresultat.IKKE_TATT_STILLING_TIL }).hasSize(1)
assertThat(vilkår.vurderinger).hasSize(1)
val delvilkårsvurderinger = vilkår.vurderinger.first().delvilkårsvurderinger
assertThat(delvilkårsvurderinger).hasSize(1)
assertThat(delvilkårsvurderinger.first().resultat).isEqualTo(Vilkårsresultat.IKKE_TATT_STILLING_TIL)
assertThat(delvilkårsvurderinger.first().vurderinger).hasSize(1)
}
@Test
internal fun `skal ikke opprette vilkårsvurderinger hvis behandling er låst for videre vurdering`() {
val vilkårsvurderinger = listOf(vilkårsvurdering(resultat = OPPFYLT,
type = VilkårType.FORUTGÅENDE_MEDLEMSKAP,
behandlingId = behandlingId))
every { vilkårsvurderingRepository.findByBehandlingId(behandlingId) } returns vilkårsvurderinger
val alleVilkårsvurderinger = vurderingService.hentEllerOpprettVurderinger(behandlingId).vurderinger
assertThat(alleVilkårsvurderinger).hasSize(1)
verify(exactly = 0) { vilkårsvurderingRepository.insertAll(any()) }
assertThat(alleVilkårsvurderinger.map { it.id }).isEqualTo(vilkårsvurderinger.map { it.id })
}
@Test
internal fun `Skal returnere ikke oppfylt hvis vilkårsvurderinger ikke inneholder alle vilkår`() {
val vilkårsvurderinger = listOf(vilkårsvurdering(resultat = OPPFYLT,
type = VilkårType.FORUTGÅENDE_MEDLEMSKAP,
behandlingId = behandlingId))
every { vilkårsvurderingRepository.findByBehandlingId(behandlingId) } returns vilkårsvurderinger
val erAlleVilkårOppfylt = vurderingService.erAlleVilkårOppfylt(behandlingId)
assertThat(erAlleVilkårOppfylt).isFalse
}
@Test
internal fun `Skal returnere oppfylt hvis alle vilkårsvurderinger er oppfylt`() {
val vilkårsvurderinger = lagVilkårsvurderinger(behandlingId, OPPFYLT)
every { vilkårsvurderingRepository.findByBehandlingId(behandlingId) } returns vilkårsvurderinger
val erAlleVilkårOppfylt = vurderingService.erAlleVilkårOppfylt(behandlingId)
assertThat(erAlleVilkårOppfylt).isTrue
}
@Test
internal fun `Skal returnere ikke oppfylt hvis noen vurderinger er SKAL_IKKE_VURDERES`() {
val vilkårsvurderinger = lagVilkårsvurderingerMedResultat()
// Guard
assertThat((vilkårsvurderinger.map { it.type }.containsAll(VilkårType.hentVilkår()))).isTrue()
every { vilkårsvurderingRepository.findByBehandlingId(behandlingId) } returns vilkårsvurderinger
val erAlleVilkårOppfylt = vurderingService.erAlleVilkårOppfylt(behandlingId)
assertThat(erAlleVilkårOppfylt).isFalse
}
private fun lagVilkårsvurderingerMedResultat(resultat1: Vilkårsresultat = OPPFYLT,
resultat2: Vilkårsresultat = SKAL_IKKE_VURDERES) =
lagVilkårsvurderinger(behandlingId, resultat1).subList(fromIndex = 0, toIndex = 3) +
lagVilkårsvurderinger(behandlingId, resultat2).subList(fromIndex = 3, toIndex = 10)
private fun lagVilkårsvurderinger(behandlingId: UUID,
resultat: Vilkårsresultat = OPPFYLT): List<Vilkårsvurdering> {
return VilkårType.hentVilkår().map {
vilkårsvurdering(behandlingId = behandlingId,
resultat = resultat,
type = it,
delvilkårsvurdering = listOf())
}
}
}
| 8
|
Kotlin
|
2
| 0
|
d1d8385ead500c4d24739b970940af854fa5fe2c
| 12,738
|
familie-ef-sak
|
MIT License
|
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/combat/specialattack/weapons/melee/vestas_longsword.plugin.kts
|
pitchblac23
| 201,185,078
| true
|
{"Kotlin": 3718848, "Dockerfile": 1354}
|
package gg.rsmod.plugins.content.combat.specialattack.weapons.melee
import gg.rsmod.plugins.content.combat.dealExactHit
import gg.rsmod.plugins.content.combat.formula.MeleeCombatFormula
import gg.rsmod.plugins.content.combat.specialattack.ExecutionType
import gg.rsmod.plugins.content.combat.specialattack.SpecialAttacks
import kotlin.math.floor
val SPECIAL_REQUIREMENT = 25
SpecialAttacks.register(intArrayOf(Items.VESTAS_LONGSWORD), SPECIAL_REQUIREMENT, ExecutionType.EXECUTE_ON_ATTACK) {
player.animate(id = 7515)
//TODO FIND GFX for vesta sword spec?
for (i in 0 until 1) {
val maxHit = MeleeCombatFormula.getMaxHit(player, target, specialAttackMultiplier = 1.5)
val accuracy = MeleeCombatFormula.getAccuracy(player, target, specialAttackMultiplier = 4.0)
var hitDamage = ((maxHit*1/5)..(maxHit*6/5)).random()
val landHit = accuracy >= world.randomDouble()
val delay = if (target.entityType.isNpc) i + 1 else 1
if(landHit && hitDamage > 0)
(target as Player).getSkills().alterCurrentLevel(skill = Skills.DEFENCE, value = -floor((target as Player).getSkills().getMaxLevel(Skills.DEFENCE) * 30.0/100.0).toInt() , capValue = 0)
player.dealExactHit(target = target, exactHit = hitDamage, landHit = landHit, delay = delay)
}
}
| 0
|
Kotlin
|
2
| 1
|
ade69da919ba62ec3ac37fccab9068f2820c774d
| 1,313
|
rsmod
|
Apache License 2.0
|
android/src/main/kotlin/com/klarna/inapp/sdk/flutter_klarna_inapp_sdk/hybrid/KlarnaHybridSDKMethod.kt
|
klarna
| 263,862,690
| false
| null |
package com.klarna.inapp.sdk.flutter_klarna_inapp_sdk.hybrid
import com.klarna.inapp.sdk.flutter_klarna_inapp_sdk.core.method.MethodParser
import com.klarna.inapp.sdk.flutter_klarna_inapp_sdk.core.util.requireArgument
import io.flutter.plugin.common.MethodCall
internal sealed class KlarnaHybridSDKMethod {
class Initialize(val returnUrl: String) : KlarnaHybridSDKMethod()
class RegisterEventListener : KlarnaHybridSDKMethod()
internal object Parser : MethodParser<KlarnaHybridSDKMethod> {
override fun parse(call: MethodCall): KlarnaHybridSDKMethod? {
return when (call.method) {
"initialize" -> Initialize(call.requireArgument("returnUrl"))
"registerEventListener" -> RegisterEventListener()
else -> null
}
}
}
}
| 1
|
Kotlin
|
9
| 8
|
f2b955ecad2846c09e4d8b5fc466d016423b2ddc
| 821
|
flutter-klarna-inapp-sdk
|
Apache License 2.0
|
pie-lsp/src/main/kotlin/com/virtlink/pie/lsp/PieLspModule.kt
|
Virtlink
| 90,153,785
| false
| null |
package com.virtlink.pie.lsp
import com.google.inject.AbstractModule
import com.virtlink.editorservices.lsp.AesiLspModule
import com.virtlink.pie.PieModule
class PieLspModule : AbstractModule() {
override fun configure() {
install(AesiLspModule())
install(PieModule())
}
}
| 1
| null |
1
| 1
|
f7af2531913d9809f3429c0d8e3a82fb695d5ba4
| 299
|
aesi
|
Apache License 2.0
|
app/shared/f8e-client/public/src/commonMain/kotlin/build/wallet/f8e/socrec/RetrieveTrustedContactInvitationService.kt
|
proto-at-block
| 761,306,853
| false
|
{"C": 10551861, "Kotlin": 6455657, "Rust": 1874547, "Swift": 629125, "Python": 329146, "HCL": 257498, "Shell": 97542, "TypeScript": 81148, "C++": 64770, "Meson": 64252, "JavaScript": 36229, "Just": 26345, "Ruby": 9265, "Dockerfile": 5755, "Makefile": 3839, "Open Policy Agent": 1456, "Procfile": 80}
|
package build.wallet.f8e.socrec
import build.wallet.bitkey.account.Account
import build.wallet.bitkey.socrec.Invitation
import build.wallet.f8e.error.F8eError
import build.wallet.f8e.error.code.RetrieveTrustedContactInvitationErrorCode
import com.github.michaelbull.result.Result
interface RetrieveTrustedContactInvitationService {
/**
* Retrieves invitation data for a potential Trusted Contact given a code.
* Note: [Account] can be for either a Full or Lite Customer
*/
suspend fun retrieveInvitation(
account: Account,
invitationCode: String,
): Result<Invitation, F8eError<RetrieveTrustedContactInvitationErrorCode>>
}
| 0
|
C
|
6
| 74
|
b7401e0b96f9378cbd96eb01914a4f888e0a9303
| 649
|
bitkey
|
MIT License
|
composeApp/src/commonMain/kotlin/ChordInterpretationHelper.kt
|
joshuaschori
| 833,395,858
| false
|
{"Kotlin": 60960, "Swift": 594, "HTML": 336, "CSS": 102}
|
// TODO @Serializable
// TODO contain pitches in chord interpretation helper??? get rid of inUpperOctave? or not?
class ChordInterpretationHelper() {
var inChord: Boolean = false
var inUpperOctave: Boolean = false
var lowestPitchIndex: Int = 0
var duplicatePitchIndexes: MutableList<Int> = mutableListOf()
var letterInterval: Int = 0
}
| 0
|
Kotlin
|
0
| 1
|
ec1cdeb01c9307f7dc1be01e2d29d95782b5a8df
| 355
|
MagnumOpus
|
MIT License
|
Raycasting/app/src/main/java/com/carlospinan/raycasting/RaycastingView.kt
|
cpinan
| 299,141,818
| false
| null |
package com.carlospinan.raycasting
import android.content.Context
import android.content.res.Resources
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.view.MotionEvent
import com.carlospinan.raycasting.common.GameView
import com.carlospinan.raycasting.common.Vector
import com.carlospinan.raycasting.common.degreesToRadians
import kotlin.math.*
private val map = arrayOf(
intArrayOf(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
intArrayOf(1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1),
intArrayOf(1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1),
intArrayOf(1, 0, 0, 1, 0, 0, 0, 0, 2, 2, 2, 0, 0, 0, 1),
intArrayOf(1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 2, 0, 0, 0, 1),
intArrayOf(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 1),
intArrayOf(1, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 1),
intArrayOf(1, 0, 3, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 1),
intArrayOf(1, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 3, 3, 1),
intArrayOf(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1),
intArrayOf(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
)
private const val MINI_MAP_FACTOR = 0.2F
private const val TILE_SIZE = 64
private const val FOV = 60F
private const val HALF_FOV = FOV / 2
private val mapWidth = map[0].size
private val mapHeight = map.size
private val virtualScreenWidth = TILE_SIZE * mapWidth
private val virtualScreenHeight = TILE_SIZE * mapHeight
fun normalizeAngle(angle: Float): Float {
var rotation = angle
if (rotation < 0F)
rotation += 360F
rotation %= 360F
return rotation
}
fun distanceBetweenPoints(x1: Float, y1: Float, x2: Float, y2: Float): Float {
val dX = x1 - x2
val dY = y1 - y2
return sqrt(dX * dX + dY * dY)
}
fun facingDirections(rotation: Float): BooleanArray {
val rotation = normalizeAngle(rotation)
val isFacingUp = rotation > 180 && rotation < 360
val isFacingDown = !isFacingUp
val isFacingRight = rotation > 270 || rotation < 90
val isFacingLeft = !isFacingRight
return booleanArrayOf(
isFacingUp, // 0
isFacingDown, // 1
isFacingLeft, // 2
isFacingRight // 3
)
}
fun collides(x: Float, y: Float): Boolean {
val tile = tile(x, y)
return tile >= 1
}
fun tile(x: Float, y: Float): Int {
val tiles = toMapCoordinates(x, y)
if (isSafe(tiles)) {
return map[tiles.second][tiles.first]
}
return -1
}
fun isSafe(tiles: Pair<Int, Int>): Boolean {
return (tiles.first in 0 until mapWidth) &&
(tiles.second in 0 until mapHeight)
}
fun toMapCoordinates(x: Float, y: Float): Pair<Int, Int> {
return Pair(
floor(x / TILE_SIZE).toInt(),
floor(y / TILE_SIZE).toInt()
)
}
class Ray(rotation: Float) {
private val rayPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
color = 0x22D6893A
strokeWidth = 2F
}
val angle = normalizeAngle(rotation)
private val radians = degreesToRadians(angle)
private val facingDirections = facingDirections(angle)
private val isFacingUp = facingDirections[0]
private val isFacingDown = facingDirections[1]
private val isFacingLeft = facingDirections[2]
private val isFacingRight = facingDirections[3]
private var wallHitX: Float = -1F
private var wallHitY: Float = -1F
var distance: Float = -1F
private set
var hitWallColor: Float = -1F
private set
var wasVerticalHit: Boolean = false
private set
fun cast(player: Player) {
var xIntercept: Float
var yIntercept: Float
var xStep = 0F
var yStep = 0F
// HORIZONTAL RAY-GRID INTERSECTION CODE
var foundHorizontalWallHit = false
var horizontalWallHitX = -1F
var horizontalWallHitY = -1F
var horizontalWallColor = 0F
val mapCoords = toMapCoordinates(player.x, player.y)
// Find the y-coordinate of the closest horizontal grid intersection
yIntercept = mapCoords.second * TILE_SIZE.toFloat()
yIntercept += if (isFacingDown) TILE_SIZE else 0
// Find the x-coordinate of the closest horizontal grid intersection
xIntercept = player.x + (yIntercept - player.y) / tan(radians)
yStep = TILE_SIZE.toFloat()
yStep *= if (isFacingUp) -1F else 1F
xStep = TILE_SIZE / tan(radians)
xStep *= if (isFacingLeft && xStep > 0) -1F else 1F
xStep *= if (isFacingRight && xStep < 0) -1F else 1F
var nextHorizontalTouchX = xIntercept
var nextHorizontalTouchY = yIntercept
// Increment xstep and ystep until we find a wall
while (nextHorizontalTouchX >= 0 &&
nextHorizontalTouchX <= virtualScreenWidth &&
nextHorizontalTouchY >= 0 &&
nextHorizontalTouchY <= virtualScreenHeight
) {
val evalX = nextHorizontalTouchX
val evalY = nextHorizontalTouchY + if (isFacingUp) -1 else 0
val tile = tile(evalX, evalY)
if (tile >= 1) {
foundHorizontalWallHit = true
horizontalWallHitX = nextHorizontalTouchX
horizontalWallHitY = nextHorizontalTouchY
horizontalWallColor = tile.toFloat()
break
} else {
nextHorizontalTouchX += xStep
nextHorizontalTouchY += yStep
}
}
// VERTICAL RAY-GRID INTERSECTION CODE
var foundVerticalWallHit = false
var verticalWallHitX = -1F
var verticalWallHitY = -1F
var verticalWallColor = 0F
// Find the x-coordinate of the closest vertical grid intersection
xIntercept = mapCoords.first * TILE_SIZE.toFloat()
xIntercept += if (isFacingRight) TILE_SIZE else 0
// Find the y-coordinate of the closest vertical grid intersection
yIntercept = player.y + (xIntercept - player.x) * tan(radians)
// Calculate the increment xstep and ystep
xStep = TILE_SIZE.toFloat()
xStep *= if (isFacingLeft) -1 else 1
yStep = TILE_SIZE * tan(radians)
yStep *= if (isFacingUp && yStep > 0) -1 else 1
yStep *= if (isFacingDown && yStep < 0) -1 else 1
var nextVerticalTouchX = xIntercept
var nextVerticalTouchY = yIntercept
// Increment xstep and ystep until we find a wall
while (nextVerticalTouchX >= 0 &&
nextVerticalTouchX <= virtualScreenWidth &&
nextVerticalTouchY >= 0 &&
nextVerticalTouchY <= virtualScreenHeight
) {
val evalX = nextVerticalTouchX + if (isFacingLeft) -1 else 0
val evalY = nextVerticalTouchY
val tile = tile(evalX, evalY)
if (tile >= 1) {
foundVerticalWallHit = true
verticalWallHitX = nextVerticalTouchX
verticalWallHitY = nextVerticalTouchY
verticalWallColor = tile.toFloat()
break
} else {
nextVerticalTouchX += xStep
nextVerticalTouchY += yStep
}
}
// Calculate both horizontal and vertical distances and choose the smallest value
val horizontalHitDistance = if (foundHorizontalWallHit)
distanceBetweenPoints(player.x, player.y, horizontalWallHitX, horizontalWallHitY)
else
Float.MAX_VALUE
val verticalHitDistance = if (foundVerticalWallHit)
distanceBetweenPoints(player.x, player.y, verticalWallHitX, verticalWallHitY)
else
Float.MAX_VALUE
// only store the smallest distance
if (verticalHitDistance < horizontalHitDistance) {
wallHitX = verticalWallHitX
wallHitY = verticalWallHitY
distance = verticalHitDistance
hitWallColor = verticalWallColor
wasVerticalHit = true
} else {
wallHitX = horizontalWallHitX
wallHitY = horizontalWallHitY
distance = horizontalHitDistance
hitWallColor = horizontalWallColor
wasVerticalHit = false
}
}
fun render(canvas: Canvas, startX: Float, startY: Float) {
canvas.drawLine(
startX * MINI_MAP_FACTOR,
startY * MINI_MAP_FACTOR,
wallHitX * MINI_MAP_FACTOR,
wallHitY * MINI_MAP_FACTOR,
rayPaint
)
}
}
data class Player(
var x: Float = 5 * TILE_SIZE.toFloat(),
var y: Float = 6 * TILE_SIZE.toFloat(),
val radius: Float = 4F,
var rotation: Float = 0F,
val rotationSpeed: Float = 3F,
val speed: Float = 40F,
var move: Boolean = false
) {
private val lineSize = 50F
private val playerPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL
color = 0xFFFF0000.toInt()
}
private val directionPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
color = 0xFF0000FF.toInt()
strokeWidth = 2F
}
fun renderMinimap(canvas: Canvas) {
val mapX = x
val mapY = y
// Draw Player Rect
val rect = RectF(
mapX * MINI_MAP_FACTOR,
mapY * MINI_MAP_FACTOR,
(mapX + radius) * MINI_MAP_FACTOR,
(mapY + radius) * MINI_MAP_FACTOR,
)
canvas.drawRect(rect, playerPaint)
val startX = mapX + radius / 2
val startY = mapY + radius / 2
val radianDirectionAngle = degreesToRadians(rotation)
val endX = startX + cos(radianDirectionAngle) * lineSize
val endY = startY + sin(radianDirectionAngle) * lineSize
// Draw Player Direction
canvas.drawLine(
startX * MINI_MAP_FACTOR,
startY * MINI_MAP_FACTOR,
endX * MINI_MAP_FACTOR,
endY * MINI_MAP_FACTOR,
directionPaint
)
}
fun update(dt: Float) {
if (move) {
val radianDirectionAngle = degreesToRadians(rotation)
val newX = x + cos(radianDirectionAngle) * speed * dt
val newY = y + sin(radianDirectionAngle) * speed * dt
if (!collides(newX + 0, newY + 0)) {
x = newX
y = newY
}
}
}
fun updateDirectionAngle(delta: Float) {
rotation += (delta * rotationSpeed)
rotation = normalizeAngle(rotation)
}
}
/**
* @author <NAME>
*/
class RaycastingView(context: Context) : GameView(context, 30L) {
private var currentTouch = Pair(MotionEvent.ACTION_CANCEL, Vector(0F, 0F))
private val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
color = 0xFF000000.toInt()
}
private val wallPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL
color = Color.argb(255, 128, 128, 128)
}
private val walkPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL
color = 0xFFFFFFFF.toInt()
}
private val wallPaintFullColor = arrayOf(
Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL
color = Color.argb(255, 255, 0, 0)
},
Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL
color = Color.argb(255, 0, 255, 0)
},
Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL
color = Color.argb(255, 0, 0, 255)
}
)
private val wallPaintHalfColor = arrayOf(
Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL
color = Color.argb(255, 200, 0, 0)
},
Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL
color = Color.argb(255, 0, 200, 0)
},
Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL
color = Color.argb(255, 0, 0, 200)
}
)
private val screenWidth = Resources.getSystem().displayMetrics.widthPixels
private val screenHeight = Resources.getSystem().displayMetrics.heightPixels
private val heightRatio = (screenHeight.toFloat() / virtualScreenHeight.toFloat())
private val tX = ((screenWidth - virtualScreenWidth) / heightRatio) / 4
private val tY = 0F//(screenHeight - virtualScreenHeight) / 2
private val player = Player()
private val raycastList = arrayOfNulls<Ray>(virtualScreenWidth)
override fun gameRender(canvas: Canvas) {
canvas.drawColor(0xFF000000.toInt())
canvas.save()
canvas.translate(tX, tY)
canvas.scale(heightRatio, heightRatio)
render3DProjectedWalls(canvas)
drawMinimap(canvas)
canvas.restore()
}
override fun gameUpdate(dt: Float) {
// Player direction increase clockwise
player.move = false
if (currentTouch.first == MotionEvent.ACTION_DOWN) {
val touchArea = currentTouch.second
if (touchArea.x <= -0.5F) {
player.updateDirectionAngle(-1F)
} else if (touchArea.x >= 0.5F) {
player.updateDirectionAngle(1F)
}
player.move = touchArea.y <= 0F
}
player.update(dt)
var angle = player.rotation - HALF_FOV
val angleIncrease = FOV / virtualScreenWidth
for (i in 0 until virtualScreenWidth) {
val ray = Ray(angle)
ray.cast(player)
raycastList[i] = ray
angle += angleIncrease
}
}
private fun drawMinimap(canvas: Canvas) {
for (row in 0 until mapHeight) {
for (col in 0 until mapWidth) {
val rowTile = (row * TILE_SIZE) * MINI_MAP_FACTOR
val colTile = (col * TILE_SIZE) * MINI_MAP_FACTOR
val rect = RectF(
colTile,
rowTile,
colTile + TILE_SIZE * MINI_MAP_FACTOR,
rowTile + TILE_SIZE * MINI_MAP_FACTOR
)
val tile = map[row][col]
val paintToUse = if (tile >= 1) wallPaint else walkPaint
// canvas.drawRect(rect, borderPaint)
canvas.drawRect(rect, paintToUse)
}
}
for (ray in raycastList) {
ray?.render(canvas, player.x + player.radius / 2, player.y + player.radius / 2)
}
player.renderMinimap(canvas)
}
private fun render3DProjectedWalls(canvas: Canvas) {
for (col in 0 until virtualScreenWidth) {
raycastList[col]?.let { ray ->
// get the perpendicular distance to the wall to fix fishbowl distortion
val correctedAngle = degreesToRadians(ray.angle - player.rotation)
val correctedWallDistance = ray.distance * cos(correctedAngle)
// calculate the distance to the projection plane
val distanceProjectionPlane = (virtualScreenWidth / 2) /
tan(
degreesToRadians(
HALF_FOV
)
)
// projected wall height
val wallStripHeight = (TILE_SIZE / correctedWallDistance) * distanceProjectionPlane
val left = col.toFloat()
val top = (virtualScreenHeight / 2) - (wallStripHeight / 2)
val right = left + 1F
val bottom = top + wallStripHeight
val rect = RectF(
left, top, right, bottom
)
val index = ray.hitWallColor.toInt() - 1
if (ray.wasVerticalHit) {
canvas.drawRect(rect, wallPaintHalfColor[index])
} else {
canvas.drawRect(rect, wallPaintFullColor[index])
}
}
}
}
override fun onTouchEvent(event: MotionEvent): Boolean {
val x = event.x
val y = event.y
val unitX = 2 * (x / screenWidth) - 1F
val unitY = 2 * (y / screenHeight) - 1F
currentTouch = Pair(event.action, Vector(unitX, unitY))
return true
}
}
| 0
|
Kotlin
|
0
| 4
|
f8f47d55f34d213157e6187b4e3f3713f89581a8
| 16,358
|
Raycasting-Android-Kotlin
|
Apache License 2.0
|
kotlin-typescript/src/main/generated/typescript/CreateProgramOptions.kt
|
JetBrains
| 93,250,841
| false
| null |
// Automatically generated - do not modify!
package typescript
import js.array.ReadonlyArray
sealed external interface CreateProgramOptions {
var rootNames: ReadonlyArray<String>
var options: CompilerOptions
var projectReferences: ReadonlyArray<ProjectReference>?
var host: CompilerHost?
var oldProgram: Program?
var configFileParsingDiagnostics: ReadonlyArray<Diagnostic>?
}
| 10
| null |
7
| 983
|
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
| 403
|
kotlin-wrappers
|
Apache License 2.0
|
src/main/kotlin/io/github/gaming32/mckt/packet/play/s2c/ChunkAndLightDataPacket.kt
|
mckt-Minecraft
| 532,076,162
| false
| null |
package io.github.gaming32.mckt.packet.play.s2c
import io.github.gaming32.mckt.blocks.entities.BlockEntities.getMetadata
import io.github.gaming32.mckt.blocks.entities.BlockEntity
import io.github.gaming32.mckt.data.*
import io.github.gaming32.mckt.nbt.buildNbtCompound
import io.github.gaming32.mckt.nbt.put
import io.github.gaming32.mckt.objects.BlockPosition
import io.github.gaming32.mckt.packet.Packet
import java.io.OutputStream
import java.util.*
data class ChunkAndLightDataPacket(
val x: Int, val z: Int,
val blockEntities: Map<BlockPosition, BlockEntity<*>>,
val chunk: ByteArray
) : Packet(TYPE) {
companion object {
const val TYPE = 0x21
private val EMPTY_BIT_SET = BitSet(256)
private val FULL_BIT_SET = BitSet.valueOf(LongArray(4) { -1L })
private val HEIGHTMAP = LongArray(52)
}
override fun write(out: OutputStream) {
out.writeInt(x)
out.writeInt(z)
out.writeNbt(buildNbtCompound {
put("MOTION_BLOCKING", HEIGHTMAP)
})
out.writeVarInt(chunk.size)
out.write(chunk)
out.writeArray(blockEntities) { pos, entity ->
writeByte(pos.x shl 4 or pos.z)
writeShort(pos.y)
writeVarInt(entity.type.getMetadata()?.networkId
?: throw IllegalStateException("Unknown block entity ${entity.javaClass.simpleName}"))
writeNbt(entity.initialNetworkSerialize())
}
out.writeBoolean(true) // Lighting: Trust edges
out.writeBitSet(EMPTY_BIT_SET) // Skylight mask
out.writeBitSet(EMPTY_BIT_SET) // Block light mask
out.writeBitSet(FULL_BIT_SET) // Empty skylight mask
out.writeBitSet(FULL_BIT_SET) // Empty block light mask
out.writeVarInt(0) // Skylight data count
out.writeVarInt(0) // Block light data count
}
override fun toString() = "ChunkAndLightDataPacket(x=$x, z=$z, chunk=...)"
}
| 0
|
Kotlin
|
0
| 2
|
98e88af4f54a12faeea2543c4bbdc950dd744092
| 1,944
|
mckt
|
MIT License
|
kotlin-mui-icons/src/main/generated/mui/icons/material/PermDeviceInformationSharp.kt
|
JetBrains
| 93,250,841
| false
| null |
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/PermDeviceInformationSharp")
@file:JsNonModule
package mui.icons.material
@JsName("default")
external val PermDeviceInformationSharp: SvgIconComponent
| 10
|
Kotlin
|
5
| 983
|
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
| 234
|
kotlin-wrappers
|
Apache License 2.0
|
app/src/main/java/com/android/shelfLife/model/recipe/Recipe.kt
|
commit-crimes
| 867,523,622
| false
|
{"Kotlin": 301247, "Shell": 1272}
|
package com.android.shelfLife.model.recipe
import com.google.firebase.Timestamp
data class Recipe(
val name: String, // name of recipe
// val ingredients : List<FoodItem>, // ingredients in recipe todo check with Alex about this
val instructions: String, // instructions of recipes
val servings: Int, // total number of servings
val time: Timestamp // time it take to cook
)
| 18
|
Kotlin
|
0
| 1
|
9c88d8eb66e379c0e2d0480e7547f7d72f75c102
| 397
|
shelf-life
|
No Limit Public License
|
cotta-core/src/main/kotlin/com/mgtriffid/games/cotta/core/effects/impl/EffectBusImpl.kt
|
mgtriffid
| 524,701,185
| false
|
{"Kotlin": 478306, "Java": 9323}
|
package com.mgtriffid.games.cotta.core.effects.impl
import com.mgtriffid.games.cotta.core.effects.CottaEffect
import com.mgtriffid.games.cotta.core.effects.EffectBus
import com.mgtriffid.games.cotta.core.effects.EffectPublisher
class EffectBusImpl : EffectBus {
val effects = ArrayList<CottaEffect>()
override fun effects(): Collection<CottaEffect> {
return ArrayList(effects)
}
override fun clear() {
effects.clear()
}
override fun publisher() = object : EffectPublisher {
override fun fire(effect: CottaEffect) {
effects.add(effect)
}
}
}
| 2
|
Kotlin
|
0
| 6
|
ee0bd897c67451b31f68a3a31a6ee8de756b2b52
| 618
|
cotta
|
MIT License
|
node/src/integration-test/kotlin/net/corda/services/messaging/SimpleMQClient.kt
|
corda
| 70,137,417
| false
| null |
package net.corda.services.messaging
import net.corda.core.identity.CordaX500Name
import net.corda.core.serialization.internal.nodeSerializationEnv
import net.corda.core.utilities.NetworkHostAndPort
import net.corda.nodeapi.internal.ArtemisTcpTransport.Companion.p2pConnectorTcpTransport
import net.corda.nodeapi.internal.config.MutualSslConfiguration
import net.corda.testing.internal.configureTestSSL
import org.apache.activemq.artemis.api.core.client.*
/**
* As the name suggests this is a simple client for connecting to MQ brokers.
*/
class SimpleMQClient(val target: NetworkHostAndPort,
private val config: MutualSslConfiguration? = configureTestSSL(DEFAULT_MQ_LEGAL_NAME)) {
companion object {
val DEFAULT_MQ_LEGAL_NAME = CordaX500Name(organisation = "SimpleMQClient", locality = "London", country = "GB")
}
lateinit var sessionFactory: ClientSessionFactory
lateinit var session: ClientSession
lateinit var producer: ClientProducer
fun start(username: String? = null, password: String? = null, enableSSL: Boolean = true) {
val tcpTransport = p2pConnectorTcpTransport(target, config, enableSSL = enableSSL)
val locator = ActiveMQClient.createServerLocatorWithoutHA(tcpTransport).apply {
isBlockOnNonDurableSend = true
threadPoolMaxSize = 1
isUseGlobalPools = nodeSerializationEnv != null
}
sessionFactory = locator.createSessionFactory()
session = sessionFactory.createSession(username, password, false, true, true, locator.isPreAcknowledge, locator.ackBatchSize)
session.start()
producer = session.createProducer()
}
fun createMessage(): ClientMessage = session.createMessage(false)
fun stop() {
try {
sessionFactory.close()
} catch (e: Exception) {
// sessionFactory might not have initialised.
}
}
}
| 62
| null |
1087
| 3,989
|
d27aa0e6850d3804d0982024054376d452e7073a
| 1,926
|
corda
|
Apache License 2.0
|
tmp/arrays/kotlinAndJava/70.kt
|
mandelshtamd
| 346,008,310
| false
|
{"Markdown": 122, "Gradle": 762, "Gradle Kotlin DSL": 649, "Java Properties": 23, "Shell": 49, "Ignore List": 20, "Batchfile": 26, "Git Attributes": 8, "Kotlin": 82508, "Protocol Buffer": 12, "Java": 6674, "Proguard": 12, "XML": 1698, "Text": 13298, "INI": 221, "JavaScript": 294, "JAR Manifest": 2, "Roff": 217, "Roff Manpage": 38, "JSON": 199, "HTML": 2429, "AsciiDoc": 1, "YAML": 21, "EditorConfig": 1, "OpenStep Property List": 19, "C": 79, "Objective-C": 68, "C++": 169, "Swift": 68, "Pascal": 1, "Python": 4, "CMake": 2, "Objective-C++": 12, "Groovy": 45, "Dockerfile": 3, "Diff": 1, "EJS": 1, "CSS": 6, "Ruby": 6, "SVG": 50, "JFlex": 3, "Maven POM": 107, "JSON with Comments": 9, "Ant Build System": 53, "Graphviz (DOT)": 78, "Scala": 1}
|
//File CLong.java
import kotlin.Metadata;
public final class CLong {
private final long value;
public final long getValue() {
return this.value;
}
public CLong(long value) {
this.value = value;
}
}
//File Main.kt
val nCInt3: CInt? = CInt(3)
val nCLong3: CLong? = CLong(3)
var subjectEvaluated: Int = 0
fun <T> subject(x: T): T {
subjectEvaluated++
return x
}
fun doTestInt(i: Int?) =
when (subject(i)) {
null -> "null"
0 -> "zero"
nCInt3?.value -> "three"
42 -> "magic"
else -> "other"
}
fun doTestLong(i: Long?) =
when (subject(i)) {
null -> "null"
0L -> "zero"
nCLong3?.value -> "three"
42L -> "magic"
else -> "other"
}
fun testInt(i: Int?): String {
subjectEvaluated = 0
val result = doTestInt(i)
if (subjectEvaluated != 1) throw AssertionError("Subject evaluated $subjectEvaluated")
return result
}
fun testLong(i: Long?): String {
subjectEvaluated = 0
val result = doTestLong(i)
if (subjectEvaluated != 1) throw AssertionError("Subject evaluated $subjectEvaluated")
return result
}
fun box(): String {
return when {
testInt(null) != "null" -> "Fail testInt null"
testInt(0) != "zero" -> "Fail testInt 0"
testInt(1) != "other" -> "Fail testInt 1"
testInt(3) != "three" -> "Fail testInt 3"
testInt(42) != "magic" -> "Fail testInt 42"
testLong(null) != "null" -> "Fail testLong null"
testLong(0L) != "zero" -> "Fail testLong 0"
testLong(1L) != "other" -> "Fail testLong 1"
testLong(3L) != "three" -> "Fail testLong 3"
testLong(42L) != "magic" -> "Fail testLong 42"
else -> "OK"
}
}
//File CInt.java
import kotlin.Metadata;
public final class CInt {
private final int value;
public final int getValue() {
return this.value;
}
public CInt(int value) {
this.value = value;
}
}
| 1
| null |
1
| 1
|
e772ef1f8f951873ebe7d8f6d73cf19aead480fa
| 2,048
|
kotlinWithFuzzer
|
Apache License 2.0
|
acornui-core/src/commonMain/kotlin/com/acornui/core/io/file/Files.kt
|
fuzzyweapon
| 130,889,917
| true
|
{"Kotlin": 2963922, "JavaScript": 15366, "HTML": 5956, "Java": 4507}
|
/*
* Copyright 2015 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.acornui.core.io.file
import com.acornui.collection.poll
import com.acornui.collection.pop
import com.acornui.collection.stringMapOf
import com.acornui.core.di.DKey
import com.acornui.core.replace2
import com.acornui.core.split2
import com.acornui.io.file.FilesManifest
interface Files {
fun getFile(path: String): FileEntry?
fun getDir(path: String): Directory?
companion object : DKey<Files>
}
/**
* Files allows you to check if a file or directory exists without making a request.
* Files depends on manifest data provided in the application bootstrap. This data should be auto-generated
* by the AcornAssets task.
*/
class FilesImpl(manifest: FilesManifest) : Files {
private val map = stringMapOf<FileEntry>()
private val rootDir = Directory("", null, HashMap(), HashMap())
init {
for (file in manifest.files) {
// Create all directories leading up to the new file entry.
val path = file.path
val pathSplit = path.split("/")
var p = rootDir
for (i in 0..pathSplit.lastIndex - 1) {
val part = pathSplit[i]
var dir = p.directories[part]
if (dir == null) {
val newPath = if (p == rootDir) part else p.path + "/" + part
dir = Directory(newPath, p, HashMap(), HashMap())
(p.directories as MutableMap).put(part, dir)
}
p = dir
}
val fileEntry = FileEntry(file.path, file.modified, file.size, file.mimeType, p)
map[fileEntry.path] = fileEntry
// Add the file entry to the directory.
(p.files as MutableMap)[pathSplit.last()] = fileEntry
}
}
override fun getFile(path: String): FileEntry? {
return map[path.replace2('\\', '/')]
}
override fun getDir(path: String): Directory? {
if (path == "") return rootDir
var p: Directory? = rootDir
val pathSplit = path.replace2('\\', '/').split2('/')
for (part in pathSplit) {
if (p == null) return null
p = p.getDir(part)
}
return p
}
}
class FileEntry(
val path: String,
val modified: Long,
val size: Long,
val mimeType: String?,
val parent: Directory?
) : Comparable<FileEntry> {
fun siblingFile(name: String): FileEntry? {
return parent?.getFile(name)
}
fun siblingDir(name: String): Directory? {
return parent?.getDir(name)
}
val name: String
get() {
return path.substringAfterLast('/')
}
val nameNoExtension: String
get() {
return path.substringAfterLast('/').substringBeforeLast('.')
}
val extension: String
get() {
return path.substringAfterLast('.')
}
fun hasExtension(extension: String): Boolean {
return this.extension.equals(extension, ignoreCase = true)
}
/**
* Calculates the number of directories deep this file entry is.
*/
val depth: Int by lazy {
var count = -1
var index = -1
do {
count++
index = path.indexOf('/', index + 1)
} while (index != -1)
count
}
/**
* Note, files are sorted case-sensitively. This is to ensure consistent order when two files have names
* that differ only in case.
*/
override fun compareTo(other: FileEntry): Int {
return if (depth == other.depth) {
path.compareTo(other.path)
} else {
depth.compareTo(other.depth)
}
}
}
class Directory(
val path: String,
val parent: Directory?,
val directories: Map<String, Directory>,
val files: Map<String, FileEntry>
) : Comparable<Directory> {
val name: String
get() {
return path.substringAfterLast('/')
}
val depth: Int by lazy {
if (parent == null) 0 else parent.depth + 1
}
/**
* Returns the total number of files in this directory (recursive).
*/
val totalFiles: Int by lazy {
var c = files.size
for (directory in directories.values) {
c += directory.totalFiles
}
c
}
fun getFile(name: String): FileEntry? {
return files[name]
}
fun getDir(name: String): Directory? {
return directories[name]
}
fun walkFilesTopDown(maxDepth: Int = 100): Sequence<FileEntry> {
return FilesTopDownSequence(this, maxDepth)
}
fun walkDirectoriesTopDown(maxDepth: Int = 100): Sequence<Directory> {
return DirectoriesTopDownSequence(this, maxDepth)
}
/**
* Recursively invokes a callback on all descendant files in this directory.
* @param callback Invoked once for each file. If the callback returns false, the iteration will immediately stop.
* @param maxDepth The maximum depth to traverse. A maxDepth of 0 will not follow any subdirectories of this directory.
*/
@Deprecated("use walkTopDown")
fun mapFiles(callback: (FileEntry) -> Boolean, maxDepth: Int = 100) {
val openList = ArrayList<Directory>()
val depths = ArrayList<Int>()
openList.add(this)
depths.add(0)
while (openList.isNotEmpty()) {
val next = openList.pop()
val depth = depths.pop()
for (file in next.files.values.sorted()) {
val shouldContinue = callback(file)
if (!shouldContinue) return
}
if (depth < maxDepth) {
for (i in next.directories.values.sorted()) {
openList.add(i)
depths.add(depth + 1)
}
}
}
}
/**
* Recursively invokes a callback on all descendant directories in this directory.
* @param callback Invoked once for each directory (Not including this directory). If the callback returns false, the iteration will immediately stop.
* @param maxDepth The maximum depth to traverse. A maxDepth of 0 will not follow any subdirectories of this directory.
*/
@Deprecated("use walkTopDown")
fun mapDirectories(callback: (Directory) -> Boolean, maxDepth: Int = 100) {
val openList = ArrayList<Directory>()
val depths = ArrayList<Int>()
openList.add(this)
depths.add(0)
while (openList.isNotEmpty()) {
val next = openList.pop()
val depth = depths.pop()
for (dir in next.directories.values.sorted()) {
val shouldContinue = callback(dir)
if (!shouldContinue) return
if (depth < maxDepth) {
openList.add(dir)
depths.add(depth + 1)
}
}
}
}
override fun compareTo(other: Directory): Int {
return if (depth == other.depth) {
path.compareTo(other.path)
} else {
depth.compareTo(other.depth)
}
}
fun relativePath(file: FileEntry): String {
return file.path.substringAfter("$path/", path)
}
}
private class FilesTopDownSequence(private val root: Directory, private val maxDepth: Int) : Sequence<FileEntry> {
override fun iterator(): Iterator<FileEntry> = object : Iterator<FileEntry> {
private val openList = ArrayList<Directory>()
private val files = ArrayList<FileEntry>()
private var fileIndex = 0
init {
if (root.totalFiles > 0) {
openList.add(root)
step()
}
}
override fun next(): FileEntry {
val current = files[fileIndex]
step()
return current
}
private fun step() {
if (fileIndex < files.lastIndex) {
fileIndex++
} else {
fileIndex = 0
files.clear()
while (openList.isNotEmpty()) {
val newParent = openList.poll()
if (newParent.depth <= maxDepth && newParent.totalFiles > 0) {
openList.addAll(newParent.directories.values.sorted())
}
if (newParent.files.isNotEmpty()) {
files.addAll(newParent.files.values.sorted())
break
}
}
}
}
override fun hasNext(): Boolean {
return fileIndex < files.size
}
}
}
private class DirectoriesTopDownSequence(private val root: Directory, private val maxDepth: Int) : Sequence<Directory> {
override fun iterator(): Iterator<Directory> = object : Iterator<Directory> {
private val openList = arrayListOf(root)
override fun next(): Directory {
val next = openList.pop()
if (next.depth <= maxDepth) {
openList.addAll(next.directories.values.sorted())
}
return next
}
override fun hasNext(): Boolean {
return openList.isNotEmpty()
}
}
}
| 0
|
Kotlin
|
1
| 0
|
a57100f894721ee342d23fe8cacb3fcbcedbe6dc
| 8,240
|
acornui
|
Apache License 2.0
|
infobip-rtc-ui/src/main/java/com/infobip/webrtc/ui/model/RtcUiCallVideoTrackType.kt
|
infobip
| 56,227,769
| false
| null |
package com.infobip.webrtc.ui.model
enum class RtcUiCallVideoTrackType {
CAMERA,
SCREEN_SHARE,
ANY_AVAILABLE
}
| 3
|
Java
|
14
| 42
|
f7da49229bad640663017d6519c2a330a5e7d4da
| 123
|
mobile-messaging-sdk-android
|
Apache License 2.0
|
app/src/main/java/com/mti/component/master/view/example/FlowComponentActivity.kt
|
jingzhanwu
| 276,342,601
| false
|
{"Java": 873329, "Kotlin": 149397, "HTML": 60590, "CSS": 2189}
|
package com.mti.component.master.view.example
import android.os.Bundle
import com.mti.component.common.entry.TagEntry
import com.mti.component.master.R
import com.mti.component.master.base.BaseActivity
import com.mti.component.master.util.toast
import kotlinx.android.synthetic.main.activity_flow_component.*
/**
* @company 上海道枢信息科技-->
* @anthor created by 薛兵
* @date 2020/5/21
* @change
* @describe 标签组件
**/
class FlowComponentActivity : BaseActivity() {
override fun initViews(savedInstanceState: Bundle?) {
setToolbarTitle("FlowComponent")
showToolbarBackView()
val interests = listOf<String>("唱歌", "看书", "划船", "饲养宠物",
"保龄球", "登山", "摄影", "下各种棋", "吃美食",
"书法", "看新闻", "做饭")
val interestData = interests.map { TagEntry("$it") }.toList()
val plants = listOf<String>("马尾松", "南天竹", "日本五针松", "马醉木",
"天目琼花", "珊瑚树", "杜鹃", "旱柳", "万年青",
"苦楝", "黄连木", "凌霄")
val plantsData = plants.map { TagEntry("$it") }.toList()
interestFlowComponent?.run {
isShowingDelete = false
isOptional=true
isMultiple=true
backgroundSelectorRes=R.drawable.label_test_selector
}
interestFlowComponent.initAddListener(interestData) {
position,_ -> toast("点击了${interestData[position].tagName}") }
plantFlowComponent.isShowingDelete = false
plantFlowComponent.initAddListener(plantsData) {
position,_ -> toast("点击了${plantsData[position].tagName}") }
setMarkdownData("FlowComponent.html", webView)
}
override fun getLayoutId(): Int = R.layout.activity_flow_component
}
| 0
|
Java
|
1
| 2
|
cf3f18b2b6249c3818ef417722297789399664a9
| 1,695
|
AnComponents
|
Apache License 2.0
|
src/main/kotlin/matt/exec/app/app.kt
|
mgroth0
| 365,615,593
| false
|
{"Kotlin": 9726}
|
package matt.exec.app
import matt.async.thread.TheThreadProvider
import matt.exec.app.initvalidator.startInitValidator
import matt.exec.exception.AppUncaughtExceptionHandler
import matt.lang.model.file.FsFile
import matt.file.commons.DATA_FOLDER
import matt.file.commons.LogContext
import matt.file.commons.hasFullFileAccess
import matt.file.commons.mattLogContext
import matt.lang.go
import matt.lang.shutdown.ShutdownContext
import matt.lang.shutdown.ShutdownExecutorImpl
import matt.lang.shutdown.preaper.ProcessReaper
import matt.lang.shutdown.preaper.ProcessReaperImpl
import matt.log.logger.Logger
import matt.log.profile.err.ExceptionResponse
import matt.model.code.report.Reporter
import matt.model.code.vals.portreg.PortRegistry
import matt.model.data.release.Version
import matt.rstruct.modID
import matt.shell.context.DefaultMacExecutionContext
import matt.shell.context.withReaper
import matt.shell.shell
import matt.socket.port.Port
import kotlin.reflect.KClass
context(ProcessReaper)
fun bluetoothIsOn() = "State: On" in shell("/usr/sbin/system_profiler", "SPBluetoothDataType")
val myVersion: Version by lazy {
/*Version(extractMdValue(mdText = resourceTxt(CHANGELIST_MD)!!, key = "VERSION")!!)*/
modID.version
}
fun contextForMainOnly() =
DefaultMacExecutionContext.withReaper(ProcessReaperImpl(TheThreadProvider, ShutdownExecutorImpl()))
val myDataFolder by lazy { DATA_FOLDER[modID.appName] }
context(ShutdownContext)
open class App<A : App<A>>(
val requiresBluetooth: Boolean = false,
) {
val processReaper = ProcessReaperImpl(TheThreadProvider, this@ShutdownContext)
companion object {
protected var flowApp: App<*>? = null
}
init {
flowApp = this
}
fun requireAccessToDownloadsAndDesktopFolders() {
require(hasFullFileAccess()) {
"file access issue"
}
}
open fun extraShutdownHook(
t: Thread,
e: Throwable,
shutdown: (App<*>.() -> Unit)? = null,
st: String,
exceptionFile: FsFile
): ExceptionResponse {
println("in extraShutdownHook")
return ExceptionResponse.EXIT
}
protected fun main(
shutdown: (App<*>.() -> Unit)? = null,
preFX: (App<*>.() -> Unit)? = null,
cfg: (() -> Unit)? = null,
logContext: LogContext = mattLogContext,
t: Reporter? = null,
enableExceptionAndShutdownHandlers: Boolean = true
) {
with(processReaper) {
(t as? Logger)?.info("Kotlin Version = ${KotlinVersion.CURRENT}")
if (requiresBluetooth) {
require(bluetoothIsOn()) { "please turn on bluetooth" }
}
cfg?.go { it.invoke() }
startInitValidator()
if (enableExceptionAndShutdownHandlers) {
shutdown?.go {
duringShutdown {
it.invoke(this@App)
}
}
val exceptionHandler = AppUncaughtExceptionHandler(
logContext = logContext,
extraShutdownHook = { thr, e, sd, st, ef ->
this@App.extraShutdownHook(
t = thr, e = e, shutdown = {
sd?.invoke()
}, st = st, exceptionFile = ef
)
},
shutdown = {
shutdown?.invoke(this@App)
},
)
Thread.setDefaultUncaughtExceptionHandler(exceptionHandler)
}
/*Thread.getAllStackTraces()
Thread.getAllStackTraces().keys.forEach {
val previous = it.uncaughtExceptionHandler
if (previous == null || previous is ThreadGroup) {
it.uncaughtExceptionHandler = exceptionHandler
}
}*/
preFX?.invoke(this@App)
}
}
val port by lazy {
val p = when (modID.appName) {
"task" -> PortRegistry.task
"top" -> PortRegistry.top
"notify" -> PortRegistry.notify
"launch" -> PortRegistry.launch
"brainstorm" -> PortRegistry.brainstorm
"kjg" -> PortRegistry.kjg
"pdf" -> PortRegistry.pdf
"spotify" -> PortRegistry.spotify
"fxgui" -> PortRegistry.omniFxGui
else -> error("need to configure port for ${modID.appName}")
}
Port(p)
}
}
interface InitValidator {
fun validate(): Boolean
}
annotation class ValidatedOnInit(val by: KClass<out InitValidator>)
| 0
|
Kotlin
|
0
| 0
|
474c1faef84d2619cb7d3dbf4ba38bcb07d28300
| 4,730
|
exec
|
MIT License
|
keep_screen_on/android/src/main/kotlin/dev/craftsoft/keepscreenon/KeepScreenOnPlugin.kt
|
craftsoft-dev
| 296,578,724
| false
|
{"Dart": 25844, "Kotlin": 5497, "Ruby": 2214, "Swift": 1928, "Objective-C": 723}
|
package dev.craftsoft.keepscreenon
import android.app.Activity
import android.util.Log
import android.view.WindowManager
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
/** KeepScreenOnPlugin */
public class KeepScreenOnPlugin: FlutterPlugin, MethodCallHandler, ActivityAware {
/// The MethodChannel that will the communication between Flutter and native Android
///
/// This local reference serves to register the plugin with the Flutter Engine and unregister it
/// when the Flutter Engine is detached from the Activity
private lateinit var channel : MethodChannel
private var activity: Activity? = null
override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(flutterPluginBinding.binaryMessenger, CHANNEL_NAME)
channel.setMethodCallHandler(this);
}
override fun onMethodCall(call: MethodCall, result: Result) {
when (call.method) {
"isOn" -> onMethodCallIsOn(call, result)
"turnOn" -> onMethodCallTurnOn(call, result)
"isAllowLockWhileScreenOn" -> onMethodCallIsAllowLockWhileScreenOn(call, result)
"addAllowLockWhileScreenOn" -> onMethodCallAddAllowLockWhileScreenOn(call, result)
else -> {
result.notImplemented();
}
}
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
//
// Implement ActivityAware
//
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
activity = binding.activity
}
override fun onDetachedFromActivityForConfigChanges() {
activity = null
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
activity = binding.activity
}
override fun onDetachedFromActivity() {
activity = null
}
//
// Implement a private method called from onMethodCall
//
private fun onMethodCallIsOn(@Suppress("UNUSED_PARAMETER") call: MethodCall, result: Result) {
val window = activity?.window
if (window == null) {
result.error("not-found-activity", "Not found 'activity'.", null)
return
}
val hasKeepScreenOn = (window.attributes.flags and WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) != 0;
result.success(hasKeepScreenOn);
}
private fun onMethodCallTurnOn(call: MethodCall, result: Result) {
val window = activity?.window
if (window == null) {
result.error("not-found-activity", "Not found 'activity'.", null)
return
}
val on = call.argument<Boolean>("on");
val withAllowLockWhileScreenOn = call.argument<Boolean>("withAllowLockWhileScreenOn")
val flag = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or
if(withAllowLockWhileScreenOn == true)
WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
else
0
Log.d(TAG, "flag=$flag")
if (on == true) {
window.addFlags(flag)
} else {
window.clearFlags(flag);
}
result.success(true);
}
private fun onMethodCallIsAllowLockWhileScreenOn(call: MethodCall, result: Result) {
val window = activity?.window
if (window == null) {
result.error("not-found-activity", "Not found 'activity'.", null)
return
}
val hasAllowLockWhileScreenOn = (window.attributes.flags and WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) != 0;
result.success(hasAllowLockWhileScreenOn);
}
private fun onMethodCallAddAllowLockWhileScreenOn(call: MethodCall, result: Result) {
val window = activity?.window
if (window == null) {
result.error("not-found-activity", "Not found 'activity'.", null)
return
}
val on = call.argument<Boolean>("on");
val flag = WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
if (on == true) {
window.addFlags(flag)
} else {
window.clearFlags(flag);
}
result.success(true);
}
// This static function is optional and equivalent to onAttachedToEngine. It supports the old
// pre-Flutter-1.12 Android projects. You are encouraged to continue supporting
// plugin registration via this function while apps migrate to use the new Android APIs
// post-flutter-1.12 via https://flutter.dev/go/android-project-migration.
//
// It is encouraged to share logic between onAttachedToEngine and registerWith to keep
// them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called
// depending on the user's project. onAttachedToEngine or registerWith must both be defined
// in the same class.
companion object {
const val TAG = "KeepScreenOnPlugin";
const val CHANNEL_NAME = "dev.craftsoft/keep_screen_on";
@Suppress("DEPRECATION")
@JvmStatic
fun registerWith(registrar: io.flutter.plugin.common.PluginRegistry.Registrar) {
val channel = MethodChannel(registrar.messenger(), CHANNEL_NAME)
channel.setMethodCallHandler(KeepScreenOnPlugin())
}
}
}
| 2
|
Dart
|
2
| 3
|
aa477814b87a17ad7df5988cb6936ac8fc631825
| 5,356
|
flutter_keep_screen_on
|
MIT License
|
icons/src/androidMain/kotlin/kiwi/orbit/compose/icons/Icons.kt
|
kiwicom
| 289,355,053
| false
| null |
package kiwi.orbit.compose.icons
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.res.painterResource
import kotlin.Suppress
@Suppress("unused")
public object Icons {
public val Accommodation: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_accommodation)
public val AccountCircle: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_account_circle)
public val Admin: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_admin)
public val Ai: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_ai)
public val AirConditioning: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_air_conditioning)
public val Airplane: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_airplane)
public val AirplaneDown: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_airplane_down)
public val AirplaneLanding: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_airplane_landing)
public val AirplaneReturn: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_airplane_return)
public val AirplaneTakeoff: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_airplane_takeoff)
public val AirplaneUp: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_airplane_up)
public val AirplaneUpOff: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_airplane_up_off)
public val AirportSecurity: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_airport_security)
public val Alert: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_alert)
public val AlertCircle: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_alert_circle)
public val AlertOctagon: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_alert_octagon)
public val All: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_all)
public val Android: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_android)
public val Anywhere: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_anywhere)
public val AppNotification: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_app_notification)
public val Apple: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_apple)
public val ArrowDown: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_arrow_down)
public val ArrowUp: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_arrow_up)
public val Atm: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_atm)
public val Attachment: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_attachment)
public val BaggageCabin: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_baggage_cabin)
public val BaggageCabinNone: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_baggage_cabin_none)
public val BaggageChecked10: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_baggage_checked_10)
public val BaggageChecked20: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_baggage_checked_20)
public val BaggageChecked30: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_baggage_checked_30)
public val BaggageCheckedNone: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_baggage_checked_none)
public val BaggagePersonal: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_baggage_personal)
public val BaggagePersonalNone: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_baggage_personal_none)
public val BaggageRecheck: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_baggage_recheck)
public val BaggageSet: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_baggage_set)
public val BaggageStorage: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_baggage_storage)
public val Bank: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_bank)
public val BillingDetails: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_billing_details)
public val BoardingGate: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_boarding_gate)
public val Boat: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_boat)
public val Bookmark: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_bookmark)
public val Bug: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_bug)
public val Bus: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_bus)
public val Cake: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_cake)
public val Calendar: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_calendar)
public val CalendarAnytime: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_calendar_anytime)
public val CalendarDuration: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_calendar_duration)
public val CalendarRange: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_calendar_range)
public val CalendarTripLength: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_calendar_trip_length)
public val Camera: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_camera)
public val Car: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_car)
public val CarDoor: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_car_door)
public val CarRental: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_car_rental)
public val Chart: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_chart)
public val Chat: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_chat)
public val Check: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_check)
public val CheckCircle: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_check_circle)
public val ChevronBackward: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_chevron_backward)
public val ChevronDoubleBackward: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_chevron_double_backward)
public val ChevronDoubleForward: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_chevron_double_forward)
public val ChevronDown: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_chevron_down)
public val ChevronForward: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_chevron_forward)
public val ChevronUp: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_chevron_up)
public val Child: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_child)
public val ChildFriendly: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_child_friendly)
public val Circle: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_circle)
public val CircleEmpty: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_circle_empty)
public val CircleFilled: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_circle_filled)
public val CircleSmall: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_circle_small)
public val CircleSmallEmpty: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_circle_small_empty)
public val City: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_city)
public val Clock: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_clock)
public val Close: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_close)
public val CloseCircle: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_close_circle)
public val Cocktail: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_cocktail)
public val Code: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_code)
public val CodeKiwi: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_code_kiwi)
public val Coffee: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_coffee)
public val ColorPicker: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_color_picker)
public val Compare: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_compare)
public val Compass: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_compass)
public val ContactEmail: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_contact_email)
public val Copy: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_copy)
public val CreditCard: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_credit_card)
public val CustomerSupport: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_customer_support)
public val Dashboard: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_dashboard)
public val Deals: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_deals)
public val DealsV2: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_deals_v2)
public val DeviceDesktop: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_device_desktop)
public val DeviceMobile: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_device_mobile)
public val Diamond: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_diamond)
public val Document: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_document)
public val Download: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_download)
public val Duplicate: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_duplicate)
public val Edit: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_edit)
public val EditOff: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_edit_off)
public val Email: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_email)
public val Entertainment: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_entertainment)
public val Exchange: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_exchange)
public val Facebook: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_facebook)
public val FamilyAll: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_family_all)
public val FamilyHalf: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_family_half)
public val Feedback: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_feedback)
public val Filters: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_filters)
public val Flash: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_flash)
public val FlightDirect: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_flight_direct)
public val FlightMulticity: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_flight_multicity)
public val FlightNomad: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_flight_nomad)
public val FlightReturn: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_flight_return)
public val FlightServices: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_flight_services)
public val Fuel: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_fuel)
public val FullScreen: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_full_screen)
public val FullScreenOff: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_full_screen_off)
public val Gallery: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_gallery)
public val GenderMan: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_gender_man)
public val GenderWoman: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_gender_woman)
public val Github: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_github)
public val GooglePlay: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_google_play)
public val GpsFixed: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_gps_fixed)
public val GpsIos: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_gps_ios)
public val GpsNotFixed: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_gps_not_fixed)
public val GpsOff: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_gps_off)
public val Grid: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_grid)
public val Gym: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_gym)
public val Heart: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_heart)
public val HeartOutline: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_heart_outline)
public val History: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_history)
public val Inbox: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_inbox)
public val Infant: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_infant)
public val InformationCircle: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_information_circle)
public val Instagram: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_instagram)
public val Insurance: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_insurance)
public val InsuranceConfirmed: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_insurance_confirmed)
public val InsuranceOff: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_insurance_off)
public val Invoice: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_invoice)
public val ItemCompleted: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_item_completed)
public val Kiwicom: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_kiwicom)
public val KiwicomCare: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_kiwicom_care)
public val KiwicomGuarantee: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_kiwicom_guarantee)
public val KiwicomNoGuarantee: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_kiwicom_no_guarantee)
public val Leisure: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_leisure)
public val Link: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_link)
public val Linkedin: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_linkedin)
public val List: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_list)
public val Location: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_location)
public val LocationA: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_location_a)
public val LocationAdd: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_location_add)
public val LocationB: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_location_b)
public val LocationC: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_location_c)
public val LocationD: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_location_d)
public val LocationE: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_location_e)
public val LocationF: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_location_f)
public val LocationG: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_location_g)
public val LocationH: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_location_h)
public val LocationI: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_location_i)
public val LocationJ: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_location_j)
public val Lock: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_lock)
public val LockOpen: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_lock_open)
public val Logout: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_logout)
public val Lounge: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_lounge)
public val Map: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_map)
public val Markdown: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_markdown)
public val Meal: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_meal)
public val MenuHamburger: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_menu_hamburger)
public val MenuKebab: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_menu_kebab)
public val MenuMeatballs: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_menu_meatballs)
public val Messages: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_messages)
public val MessagesOutline: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_messages_outline)
public val Minus: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_minus)
public val MinusCircle: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_minus_circle)
public val Money: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_money)
public val MoneyTransferIn: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_money_transfer_in)
public val MoneyTransferOut: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_money_transfer_out)
public val Moon: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_moon)
public val MusicalInstruments: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_musical_instruments)
public val NewWindow: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_new_window)
public val NoFlash: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_no_flash)
public val NoRefund: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_no_refund)
public val NoRescheduling: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_no_rescheduling)
public val Nonstop: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_nonstop)
public val Notification: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_notification)
public val NotificationAdd: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_notification_add)
public val NotificationOff: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_notification_off)
public val NotificationOn: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_notification_on)
public val OnlineCheckIn: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_online_checkin)
public val OnlineCheckInOff: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_online_checkin_off)
public val Outlook: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_outlook)
public val Paid: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_paid)
public val Parking: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_parking)
public val Partners: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_partners)
public val Passenger: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_passenger)
public val PassengerAdd: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_passenger_add)
public val PassengerOutline: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_passenger_outline)
public val PassengerRemove: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_passenger_remove)
public val Passengers: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_passengers)
public val Passport: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_passport)
public val Pet: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_pet)
public val Pharmacy: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_pharmacy)
public val Phone: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_phone)
public val Pin: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_pin)
public val PinOutline: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_pin_outline)
public val Placeholder: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_placeholder)
public val Play: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_play)
public val Playground: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_playground)
public val Plus: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_plus)
public val PlusCircle: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_plus_circle)
public val PlusMinus: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_plus_minus)
public val Pool: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_pool)
public val PowerPlug: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_power_plug)
public val PowerPlugOff: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_power_plug_off)
public val PriorityBoarding: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_priority_boarding)
public val Profit: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_profit)
public val PromoCode: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_promo_code)
public val QrCode: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_qr_code)
public val QuestionCircle: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_question_circle)
public val Radar: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_radar)
public val RadiusSearch: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_radius_search)
public val Refund: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_refund)
public val Relax: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_relax)
public val Reload: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_reload)
public val Remove: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_remove)
public val Replace: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_replace)
public val Restaurant: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_restaurant)
public val RouteNoStops: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_route_no_stops)
public val RouteOneStop: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_route_one_stop)
public val RouteTwoStops: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_route_two_stops)
public val Search: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_search)
public val Seat: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_seat)
public val SeatAisle: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_seat_aisle)
public val SeatExtraLegroom: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_seat_extra_legroom)
public val SeatWindow: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_seat_window)
public val Security: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_security)
public val SelfTransfer: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_self_transfer)
public val Send: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_send)
public val Settings: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_settings)
public val Share: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_share)
public val ShareAndroid: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_share_android)
public val ShareIos: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_share_ios)
public val Shopping: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_shopping)
public val ShowLess: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_show_less)
public val ShowMore: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_show_more)
public val Sightseeing: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_sightseeing)
public val Sign: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_sign)
public val Smoking: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_smoking)
public val SmokingOff: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_smoking_off)
public val Sms: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_sms)
public val Sort: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_sort)
public val Spa: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_spa)
public val SportEquipment: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_sport_equipment)
public val Sports: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_sports)
public val Stackoverflow: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_stackoverflow)
public val StarEmpty: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_star_empty)
public val StarFull: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_star_full)
public val Subway: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_subway)
public val Suitcase: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_suitcase)
public val Sun: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_sun)
public val Sunrise: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_sunrise)
public val Taxi: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_taxi)
public val Terminal: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_terminal)
public val TermsAndConditions: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_terms_and_conditions)
public val ThumbDown: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_thumb_down)
public val ThumbUp: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_thumb_up)
public val Ticket: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_ticket)
public val TicketOutline: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_ticket_outline)
public val Tiktok: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_tiktok)
public val Timelapse: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_timelapse)
public val Timer: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_timer)
public val Tips: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_tips)
public val Toilets: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_toilets)
public val Train: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_train)
public val Transmission: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_transmission)
public val Trip: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_trip)
public val Twitter: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_twitter)
public val Uber: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_uber)
public val Upload: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_upload)
public val UserGroup: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_user_group)
public val Visa: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_visa)
public val Visibility: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_visibility)
public val VisibilityOff: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_visibility_off)
public val Walk: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_walk)
public val Wallet: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_wallet)
public val Wheelchair: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_wheelchair)
public val Wifi: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_wifi)
public val WifiOff: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_wifi_off)
public val Youtube: Painter
@Composable
get() = painterResource(R.drawable.ic_orbit_youtube)
}
| 3
| null |
9
| 97
|
6d4026eef9fa059388c50cd9e9760d593c3ad6ac
| 34,101
|
orbit-compose
|
MIT License
|
packages/native_pdf_renderer/android/src/main/kotlin/io/scer/pdf/renderer/document/Page.kt
|
steffenhaak
| 251,211,166
| false
|
{"YAML": 17, "Text": 6, "Ignore List": 9, "EditorConfig": 2, "Markdown": 23, "Dart": 50, "Gradle": 19, "INI": 11, "Java Properties": 6, "XML": 67, "Java": 2, "OpenStep Property List": 14, "Objective-C": 9, "JSON": 16, "Kotlin": 12, "Swift": 11, "Shell": 6, "Batchfile": 1, "Ruby": 4, "Dockerfile": 1}
|
package io.scer.pdf.renderer.document
import android.annotation.TargetApi
import android.graphics.Bitmap
import android.graphics.pdf.PdfRenderer
import android.os.Build
import io.scer.pdf.renderer.utils.toByteArray
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
class Page (
private val id: String,
private val documentId: String,
private val pageRenderer: PdfRenderer.Page
) {
/** Page number in document */
private val number: Int get() = pageRenderer.index
private val width: Int get() = pageRenderer.width
private val height: Int get() = pageRenderer.height
val infoMap: Map<String, Any> get() =
mapOf(
"documentId" to documentId,
"id" to id,
"pageNumber" to number,
"width" to width,
"height" to height
)
fun close() {
pageRenderer.close()
}
fun render(width: Int, height: Int, background: Int, format: Int, crop: Boolean, cropX: Int, cropY: Int, cropW: Int, cropH: Int): Data {
val bitmap = Bitmap.createBitmap(
width,
height,
Bitmap.Config.ARGB_8888)
bitmap.eraseColor(background)
pageRenderer.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
if (crop && (cropW != width || cropH != height)){
val cropped = Bitmap.createBitmap(bitmap, cropX, cropY, cropW, cropH)
return Data(
cropW,
cropH,
data = cropped.toByteArray(format)
)
} else {
return Data(
width,
height,
data = bitmap.toByteArray(format)
)
}
}
data class Data(
val width: Int,
val height: Int,
val data: ByteArray
) {
val toMap: Map<String, Any> get() =
mapOf(
"width" to width,
"height" to height,
"data" to data
)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Data
if (!data.contentEquals(other.data)) return false
return true
}
override fun hashCode(): Int = data.contentHashCode()
}
}
| 1
| null |
1
| 1
|
4ef22d6d4431f822a14a43cd34a6fec5b4433ee1
| 2,397
|
packages.flutter
|
MIT License
|
TreeDragScroll/src/main/kotlin/example/App.kt
|
aterai
| 158,348,575
| false
| null |
package example
import java.awt.*
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.*
import javax.swing.tree.DefaultMutableTreeNode
import javax.swing.tree.TreePath
fun makeUI(): Component {
val tree1 = JTree()
val tree2 = JTree()
expandTree(tree1)
expandTree(tree2)
val ma = DragScrollListener()
tree2.addMouseMotionListener(ma)
tree2.addMouseListener(ma)
return JPanel(GridLayout(2, 1)).also {
it.add(makeTitledPanel("Default", tree1))
it.add(makeTitledPanel("Drag scroll", tree2))
it.preferredSize = Dimension(320, 240)
}
}
private fun expandTree(tree: JTree) {
val root = tree.model.root as? DefaultMutableTreeNode ?: return
root
.preorderEnumeration()
.toList()
.filterIsInstance<DefaultMutableTreeNode>()
.map { TreePath(it.path) }
.forEach { tree.expandRow(tree.getRowForPath(it)) }
}
private fun makeTitledPanel(
title: String,
c: Component,
): Component {
val scroll = JScrollPane(c)
scroll.border = BorderFactory.createTitledBorder(title)
return scroll
}
private class DragScrollListener : MouseAdapter() {
private val defCursor = Cursor.getDefaultCursor()
private val hndCursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
private val pp = Point()
override fun mouseDragged(e: MouseEvent) {
val c = e.component
(SwingUtilities.getUnwrappedParent(c) as? JViewport)?.also {
val cp = SwingUtilities.convertPoint(c, e.point, it)
val vp = it.viewPosition
vp.translate(pp.x - cp.x, pp.y - cp.y)
(c as? JComponent)?.scrollRectToVisible(Rectangle(vp, it.size))
pp.location = cp
}
}
override fun mousePressed(e: MouseEvent) {
val c = e.component
c.cursor = hndCursor
(SwingUtilities.getUnwrappedParent(c) as? JViewport)?.also {
pp.location = SwingUtilities.convertPoint(c, e.point, it)
}
}
override fun mouseReleased(e: MouseEvent) {
e.component.cursor = defCursor
}
}
fun main() {
EventQueue.invokeLater {
runCatching {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
}.onFailure {
it.printStackTrace()
Toolkit.getDefaultToolkit().beep()
}
JFrame().apply {
defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
contentPane.add(makeUI())
pack()
setLocationRelativeTo(null)
isVisible = true
}
}
}
| 0
| null |
6
| 9
|
47a0c684f64c3db2c8b631b2c20c6c7f9205bcab
| 2,393
|
kotlin-swing-tips
|
MIT License
|
app/src/main/java/com/king/app/workhelper/kotlin/Customer.kt
|
thinkerzhangyan
| 254,020,897
| true
|
{"Java": 2112378, "Kotlin": 60108, "HTML": 7709}
|
package com.king.app.workhelper.kotlin
/**
*创建 DTOs(POJOs/POCOs)
* 1. 所有属性的 getters (对于 var 定义的还有 setters)
* 2. equals()、hashCode()、toString()
* 3. copy()
* 4. 所有属性的 component1()、 component2()
*
* https://www.kotlincn.net/docs/reference/data-classes.html
* @author VanceKing
* @since 2019/4/15.
*/
data class Customer(val name: String = "unknown", val age: Int = 18) {
}
internal object SingleInstance {
}
data class Msg(val txt: String = "Hello", val from: Int = 0)
fun main() {
testCopy()
}
fun test() {
val (txt, from) = Msg("Name", 1)
print("$txt and $from")
}
fun testCopy() {
val aaa = Customer(name = "Vance", age = 18)
val bbb = aaa.copy(age = 20)
println(aaa.toString())
println(bbb.toString())
}
| 0
| null |
0
| 0
|
e81531e026bbac93711954a799d47b59600ad818
| 755
|
WorkHelperApp
|
Apache License 2.0
|
core-data/src/main/java/com/javnez/core_data/core/Result.kt
|
JaviSFH
| 312,879,107
| false
| null |
package com.javnez.core_data.core
sealed class Result<out Data> {
class Success<out Data>(val data: Data) : Result<Data>()
class Error(val failure: Failure) : Result<Nothing>()
}
| 0
|
Kotlin
|
0
| 0
|
5c0b5e1debd506291efa737ab11a02be18ace88d
| 188
|
android-marvel
|
Apache License 2.0
|
src/main/kotlin/Day10.kt
|
maldoinc
| 726,264,110
| false
|
{"Kotlin": 14472}
|
import java.util.*
import kotlin.io.path.Path
import kotlin.io.path.readLines
data class Coordinate(val y: Int, val x: Int)
typealias Maze = List<String>
fun Maze.isValidCoordinate(coordinate: Coordinate): Boolean =
coordinate.y in this.indices && coordinate.x in this[coordinate.y].indices
fun getStartingCoordinates(maze: Maze): Pair<Int, Int> =
maze
.withIndex()
.filter { it.value.contains('S') }
.map { it.index to it.value.indexOf('S') }
.first()
fun getPart1(start: Coordinate, maze: Maze): Int {
val up = Coordinate(-1, 0)
val down = Coordinate(1, 0)
val left = Coordinate(0, -1)
val right = Coordinate(0, 1)
val navigation = mapOf(
'|' to setOf(up, down),
'-' to setOf(left, right),
'F' to setOf(down, right),
'7' to setOf(down, left),
'J' to setOf(up, left),
'L' to setOf(up, right),
// getStartCoordNeighbors
// Manually updated for current input. It's 23:55 and I want to sleep
'S' to setOf(left, down)
).withDefault { setOf() }
val costs: MutableMap<Coordinate, Int> = mutableMapOf()
val queue: Queue<Pair<Coordinate, Int>> = PriorityQueue(compareBy { it.second })
queue.add(start to 0)
while (queue.isNotEmpty()) {
val current = queue.poll()
val currentCoords = current.first
val steps = current.second
maze[currentCoords.y][currentCoords.x].let { char ->
navigation.getValue(char).let { offsets ->
offsets.forEach { offset ->
val nextCoord = Coordinate(currentCoords.y + offset.y, currentCoords.x + offset.x)
val newSteps = steps + 1
if (maze.isValidCoordinate(nextCoord) && costs.getOrDefault(nextCoord, Int.MAX_VALUE) > newSteps) {
queue.add(Pair(nextCoord, newSteps))
costs[nextCoord] = newSteps
}
}
}
}
}
return costs.values.max()
}
fun main(args: Array<String>) {
val maze = Path(args.first()).readLines()
val startingCoords = getStartingCoordinates(maze)
println(getPart1(Coordinate(startingCoords.first, startingCoords.second), maze))
}
| 0
|
Kotlin
|
0
| 1
|
47a1ab8185eb6cf16bc012f20af28a4a3fef2f47
| 2,268
|
advent-2023
|
MIT License
|
samples/server/petstore/kotlin-springboot-3/src/main/kotlin/org/openapitools/model/Tag.kt
|
dweinstein
| 603,900,824
| true
|
{"YAML": 857, "Ruby": 543, "Shell": 461, "XML": 307, "Dockerfile": 32, "Maven POM": 316, "Batchfile": 112, "Markdown": 7443, "Git Attributes": 2, "JSON with Comments": 64, "JSON": 307, "Text": 166, "Ignore List": 317, "SQL": 71, "Gradle": 219, "Kotlin": 1508, "INI": 247, "Java": 8990, "Mustache": 3597, "Python": 3824, "Scala": 284, "OASv3-yaml": 368, "Microsoft Visual Studio Solution": 30, "C#": 3015, "Option List": 11, "Nim": 12, "Makefile": 16, "Groovy": 89, "OCaml": 17, "TOML": 15, "Rust": 188, "Erlang": 43, "R": 225, "JavaScript": 462, "HTML": 116, "OpenStep Property List": 39, "Swift": 963, "Clojure": 14, "Perl": 149, "Gradle Kotlin DSL": 19, "Java Properties": 13, "CMake": 26, "C++": 417, "PowerShell": 186, "Apex": 29, "HTTP": 3, "Julia": 22, "EditorConfig": 4, "Browserslist": 2, "CSS": 21, "Lua": 24, "Haskell": 53, "Cabal Config": 4, "Go": 270, "Go Checksums": 7, "Go Module": 10, "PHP": 695, "Ada": 8, "Crystal": 30, "Proguard": 3, "Gemfile.lock": 2, "Objective-C": 134, "MATLAB": 1, "Eiffel": 77, "QMake": 2, "Elixir": 65, "C": 41, "AsciiDoc": 13, "PlantUML": 1, "Elm": 19, "Dart": 475, "GraphQL": 21, "Protocol Buffer": 13, "F#": 49, "Gherkin": 1, "Emacs Lisp": 2, "ApacheConf": 10, "robots.txt": 4, "HTML+ERB": 4, "Dotenv": 3, "SCSS": 2, "Blade": 2, "OASv2-yaml": 39, "OASv3-json": 9, "OASv2-json": 22, "Handlebars": 84, "CODEOWNERS": 1, "SVG": 25}
|
package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import jakarta.validation.constraints.*
import jakarta.validation.Valid
/**
* A tag for a pet
* @param id
* @param name
*/
data class Tag(
@get:JsonProperty("id") val id: kotlin.Long? = null,
@get:JsonProperty("name") val name: kotlin.String? = null
) {
}
| 2
|
Java
|
2
| 1
|
c8fab3f40a1b00db75d61716016ed0846de65c42
| 385
|
openapi-generator
|
Apache License 2.0
|
samples/server/petstore/kotlin-springboot-3/src/main/kotlin/org/openapitools/model/Tag.kt
|
dweinstein
| 603,900,824
| true
|
{"YAML": 857, "Ruby": 543, "Shell": 461, "XML": 307, "Dockerfile": 32, "Maven POM": 316, "Batchfile": 112, "Markdown": 7443, "Git Attributes": 2, "JSON with Comments": 64, "JSON": 307, "Text": 166, "Ignore List": 317, "SQL": 71, "Gradle": 219, "Kotlin": 1508, "INI": 247, "Java": 8990, "Mustache": 3597, "Python": 3824, "Scala": 284, "OASv3-yaml": 368, "Microsoft Visual Studio Solution": 30, "C#": 3015, "Option List": 11, "Nim": 12, "Makefile": 16, "Groovy": 89, "OCaml": 17, "TOML": 15, "Rust": 188, "Erlang": 43, "R": 225, "JavaScript": 462, "HTML": 116, "OpenStep Property List": 39, "Swift": 963, "Clojure": 14, "Perl": 149, "Gradle Kotlin DSL": 19, "Java Properties": 13, "CMake": 26, "C++": 417, "PowerShell": 186, "Apex": 29, "HTTP": 3, "Julia": 22, "EditorConfig": 4, "Browserslist": 2, "CSS": 21, "Lua": 24, "Haskell": 53, "Cabal Config": 4, "Go": 270, "Go Checksums": 7, "Go Module": 10, "PHP": 695, "Ada": 8, "Crystal": 30, "Proguard": 3, "Gemfile.lock": 2, "Objective-C": 134, "MATLAB": 1, "Eiffel": 77, "QMake": 2, "Elixir": 65, "C": 41, "AsciiDoc": 13, "PlantUML": 1, "Elm": 19, "Dart": 475, "GraphQL": 21, "Protocol Buffer": 13, "F#": 49, "Gherkin": 1, "Emacs Lisp": 2, "ApacheConf": 10, "robots.txt": 4, "HTML+ERB": 4, "Dotenv": 3, "SCSS": 2, "Blade": 2, "OASv2-yaml": 39, "OASv3-json": 9, "OASv2-json": 22, "Handlebars": 84, "CODEOWNERS": 1, "SVG": 25}
|
package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import jakarta.validation.constraints.*
import jakarta.validation.Valid
/**
* A tag for a pet
* @param id
* @param name
*/
data class Tag(
@get:JsonProperty("id") val id: kotlin.Long? = null,
@get:JsonProperty("name") val name: kotlin.String? = null
) {
}
| 2
|
Java
|
2
| 1
|
c8fab3f40a1b00db75d61716016ed0846de65c42
| 385
|
openapi-generator
|
Apache License 2.0
|
threejs_kt/src/main/kotlin/three/Clock.module_three.kt
|
mihbor
| 525,856,941
| false
| null |
@file:JsModule("three")
@file:JsNonModule
@file:Suppress("ABSTRACT_MEMBER_NOT_IMPLEMENTED", "VAR_TYPE_MISMATCH_ON_OVERRIDE", "INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION", "PackageDirectoryMismatch")
package three.js
import kotlin.js.*
open external class Clock(autoStart: Boolean = definedExternally) {
open var autoStart: Boolean
open var startTime: Number
open var oldTime: Number
open var elapsedTime: Number
open var running: Boolean
open fun start()
open fun stop()
open fun getElapsedTime(): Number
open fun getDelta(): Number
}
| 0
|
Kotlin
|
0
| 0
|
bc6b136ed2627b04019427eced632d542c3d54ea
| 666
|
miniverse
|
MIT License
|
src/test/kotlin/EndianTest.kt
|
mvysny
| 627,762,363
| false
| null |
package com.github.mvysny.unsigned
import com.github.mvysny.dynatest.DynaTest
import kotlin.test.expect
private fun expect4(expectedHex: String, block: (ByteArray) -> Unit) {
val bytes = ByteArray(4)
block(bytes)
expect(expectedHex) { bytes.toHex() }
}
private fun expect6(expectedHex: String, block: (ByteArray) -> Unit) {
val bytes = ByteArray(6)
block(bytes)
expect(expectedHex) { bytes.toHex() }
}
private fun expect10(expectedHex: String, block: (ByteArray) -> Unit) {
val bytes = ByteArray(10)
block(bytes)
expect(expectedHex) { bytes.toHex() }
}
class EndianTest : DynaTest({
group("Big") {
val e = Endian.Big
group("getShort()") {
test("0") {
expect(0) { e.getShort("00000000".fromHex(), 1) }
}
test("0x0102") {
expect(0x0102.toShort()) { e.getShort("00010200".fromHex(), 1) }
}
test("0xdead") {
expect(0xdead.toShort()) { e.getShort("00dead00".fromHex(), 1) }
}
}
group("setShort(Int)") {
test("0") {
expect4("00000000") { e.setShort(it, 1, 0) }
}
test("0x0102") {
expect4("00010200") { e.setShort(it, 1, 0x0102) }
}
test("0xdead") {
expect4("00dead00") { e.setShort(it, 1, 0xdead) }
}
test("0xdeadbeef") {
expect4("00beef00") { e.setShort(it, 1, 0xdeadbeef.toInt()) }
}
}
group("setShort(Short)") {
test("0") {
expect4("00000000") { e.setShort(it, 1, 0.toShort()) }
}
test("0x0102") {
expect4("00010200") { e.setShort(it, 1, 0x0102.toShort()) }
}
test("0xdead") {
expect4("00dead00") { e.setShort(it, 1, 0xdead.toShort()) }
}
}
group("getUShort()") {
test("0") {
expect(0.toUShort()) { e.getUShort("00000000".fromHex(), 1) }
}
test("0x0102") {
expect(0x0102.toUShort()) { e.getUShort("00010200".fromHex(), 1) }
}
test("0xdead") {
expect(0xdead.toUShort()) { e.getUShort("00dead00".fromHex(), 1) }
}
}
group("setUShort(UInt)") {
test("0") {
expect4("00000000") { e.setUShort(it, 1, 0.toUInt()) }
}
test("0x0102") {
expect4("00010200") { e.setUShort(it, 1, 0x0102.toUInt()) }
}
test("0xdead") {
expect4("00dead00") { e.setUShort(it, 1, 0xdead.toUInt()) }
}
test("0xdeadbeef") {
expect4("00beef00") { e.setUShort(it, 1, 0xdeadbeef.toUInt()) }
}
}
group("setUShort(UShort)") {
test("0") {
expect4("00000000") { e.setUShort(it, 1, 0.toUShort()) }
}
test("0x0102") {
expect4("00010200") { e.setUShort(it, 1, 0x0102.toUShort()) }
}
test("0xdead") {
expect4("00dead00") { e.setUShort(it, 1, 0xdead.toUShort()) }
}
}
group("getInt()") {
test("0") {
expect(0) { e.getInt("000000000000".fromHex(), 1) }
}
test("0x01020304") {
expect(0x01020304) { e.getInt("000102030400".fromHex(), 1) }
}
test("0xdeadbeef") {
expect(0xdeadbeef.toInt()) { e.getInt("00deadbeef".fromHex(), 1) }
}
}
group("setInt()") {
test("0") {
expect6("000000000000") { e.setInt(it, 1, 0) }
}
test("0x01020304") {
expect6("000102030400") { e.setInt(it, 1, 0x01020304) }
}
test("0xdeadbeef") {
expect6("00deadbeef00") { e.setInt(it, 1, 0xdeadbeef.toInt()) }
}
}
group("getUInt()") {
test("0") {
expect(0.toUInt()) { e.getUInt("000000000000".fromHex(), 1) }
}
test("0x01020304") {
expect(0x01020304.toUInt()) { e.getUInt("000102030400".fromHex(), 1) }
}
test("0xdeadbeef") {
expect(0xdeadbeef.toUInt()) { e.getUInt("00deadbeef".fromHex(), 1) }
}
}
group("setUInt()") {
test("0") {
expect6("000000000000") { e.setUInt(it, 1, 0.toUInt()) }
}
test("0x01020304") {
expect6("000102030400") { e.setUInt(it, 1, 0x01020304.toUInt()) }
}
test("0xdeadbeef") {
expect6("00deadbeef00") { e.setUInt(it, 1, 0xdeadbeef.toUInt()) }
}
}
group("getLong()") {
test("0") {
expect(0) { e.getLong("00000000000000000000".fromHex(), 1) }
}
test("0x0102030405060708") {
expect(0x0102030405060708) { e.getLong("00010203040506070800".fromHex(), 1) }
}
test("0xdeadbeefaabbccdd") {
expect(deadbeefaabbccdd.toLong()) { e.getLong("00deadbeefaabbccdd".fromHex(), 1) }
}
}
group("setLong()") {
test("0") {
expect10("00000000000000000000") { e.setLong(it, 1, 0) }
}
test("0x0102030405060708") {
expect10("00010203040506070800") { e.setLong(it, 1, 0x0102030405060708L) }
}
test("0xdeadbeefaabbccdd") {
expect10("00deadbeefaabbccdd00") { e.setLong(it, 1, deadbeefaabbccdd.toLong()) }
}
}
group("getULong()") {
test("0") {
expect(0.toULong()) { e.getULong("00000000000000000000".fromHex(), 1) }
}
test("0x0102030405060708") {
expect(0x0102030405060708.toULong()) { e.getULong("00010203040506070800".fromHex(), 1) }
}
test("0xdeadbeefaabbccdd") {
expect(deadbeefaabbccdd) { e.getULong("00deadbeefaabbccdd".fromHex(), 1) }
}
}
group("setULong()") {
test("0") {
expect10("00000000000000000000") { e.setULong(it, 1, 0.toULong()) }
}
test("0x0102030405060708") {
expect10("00010203040506070800") { e.setULong(it, 1, 0x0102030405060708L.toULong()) }
}
test("0xdeadbeefaabbccdd") {
expect10("00deadbeefaabbccdd00") { e.setULong(it, 1, deadbeefaabbccdd) }
}
}
}
group("Little") {
val e = Endian.Little
group("getShort()") {
test("0") {
expect(0) { e.getShort("00000000".fromHex(), 1) }
}
test("0x0102") {
expect(0x0201.toShort()) { e.getShort("00010200".fromHex(), 1) }
}
test("0xdead") {
expect(0xadde.toShort()) { e.getShort("00dead00".fromHex(), 1) }
}
}
group("setShort(Int)") {
test("0") {
expect4("00000000") { e.setShort(it, 1, 0) }
}
test("0x0102") {
expect4("00020100") { e.setShort(it, 1, 0x0102) }
}
test("0xdead") {
expect4("00adde00") { e.setShort(it, 1, 0xdead) }
}
test("0xdeadbeef") {
expect4("00efbe00") { e.setShort(it, 1, 0xdeadbeef.toInt()) }
}
}
group("setShort(Short)") {
test("0") {
expect4("00000000") { e.setShort(it, 1, 0.toShort()) }
}
test("0x0102") {
expect4("00020100") { e.setShort(it, 1, 0x0102.toShort()) }
}
test("0xdead") {
expect4("00adde00") { e.setShort(it, 1, 0xdead.toShort()) }
}
}
group("getUShort()") {
test("0") {
expect(0.toUShort()) { e.getUShort("00000000".fromHex(), 1) }
}
test("0x0102") {
expect(0x0201.toUShort()) { e.getUShort("00010200".fromHex(), 1) }
}
test("0xdead") {
expect(0xadde.toUShort()) { e.getUShort("00dead00".fromHex(), 1) }
}
}
group("setUShort(UInt)") {
test("0") {
expect4("00000000") { e.setUShort(it, 1, 0.toUInt()) }
}
test("0x0102") {
expect4("00020100") { e.setUShort(it, 1, 0x0102.toUInt()) }
}
test("0xdead") {
expect4("00adde00") { e.setUShort(it, 1, 0xdead.toUInt()) }
}
test("0xdeadbeef") {
expect4("00efbe00") { e.setUShort(it, 1, 0xdeadbeef.toUInt()) }
}
}
group("setUShort(UShort)") {
test("0") {
expect4("00000000") { e.setUShort(it, 1, 0.toUShort()) }
}
test("0x0102") {
expect4("00020100") { e.setUShort(it, 1, 0x0102.toUShort()) }
}
test("0xdead") {
expect4("00adde00") { e.setUShort(it, 1, 0xdead.toUShort()) }
}
}
group("getInt()") {
test("0") {
expect(0) { e.getInt("000000000000".fromHex(), 1) }
}
test("0x01020304") {
expect(0x04030201) { e.getInt("000102030400".fromHex(), 1) }
}
test("0xdeadbeef") {
expect(0xefbeadde.toInt()) { e.getInt("00deadbeef".fromHex(), 1) }
}
}
group("setInt()") {
test("0") {
expect6("000000000000") { e.setInt(it, 1, 0) }
}
test("0x01020304") {
expect6("000403020100") { e.setInt(it, 1, 0x01020304) }
}
test("0xdeadbeef") {
expect6("00efbeadde00") { e.setInt(it, 1, 0xdeadbeef.toInt()) }
}
}
group("getUInt()") {
test("0") {
expect(0.toUInt()) { e.getUInt("000000000000".fromHex(), 1) }
}
test("0x01020304") {
expect(0x04030201.toUInt()) { e.getUInt("000102030400".fromHex(), 1) }
}
test("0xdeadbeef") {
expect(0xefbeadde.toUInt()) { e.getUInt("00deadbeef".fromHex(), 1) }
}
}
group("setUInt()") {
test("0") {
expect6("000000000000") { e.setUInt(it, 1, 0.toUInt()) }
}
test("0x01020304") {
expect6("000403020100") { e.setUInt(it, 1, 0x01020304.toUInt()) }
}
test("0xdeadbeef") {
expect6("00efbeadde00") { e.setUInt(it, 1, 0xdeadbeef.toUInt()) }
}
}
group("getLong()") {
test("0") {
expect(0) { e.getLong("00000000000000000000".fromHex(), 1) }
}
test("0x0102030405060708") {
expect(0x0807060504030201) { e.getLong("00010203040506070800".fromHex(), 1) }
}
test("0xdeadbeefaabbccdd") {
expect(ddccbbaaefbeadde.toLong()) { e.getLong("00deadbeefaabbccdd".fromHex(), 1) }
}
}
group("setLong()") {
test("0") {
expect10("00000000000000000000") { e.setLong(it, 1, 0) }
}
test("0x0102030405060708") {
expect10("00080706050403020100") { e.setLong(it, 1, 0x0102030405060708L) }
}
test("0xdeadbeefaabbccdd") {
expect10("00ddccbbaaefbeadde00") { e.setLong(it, 1, deadbeefaabbccdd.toLong()) }
}
}
group("getULong()") {
test("0") {
expect(0.toULong()) { e.getULong("00000000000000000000".fromHex(), 1) }
}
test("0x0102030405060708") {
expect(0x0807060504030201.toULong()) { e.getULong("00010203040506070800".fromHex(), 1) }
}
test("0xdeadbeefaabbccdd") {
expect(ddccbbaaefbeadde) { e.getULong("00deadbeefaabbccdd".fromHex(), 1) }
}
}
group("setULong()") {
test("0") {
expect10("00000000000000000000") { e.setULong(it, 1, 0.toULong()) }
}
test("0x0102030405060708") {
expect10("00080706050403020100") { e.setULong(it, 1, 0x0102030405060708L.toULong()) }
}
test("0xdeadbeefaabbccdd") {
expect10("00ddccbbaaefbeadde00") { e.setULong(it, 1, deadbeefaabbccdd) }
}
}
}
})
// workaround for https://youtrack.jetbrains.com/issue/KT-4749
private val deadbeefaabbccdd = "deadbeefaabbccdd".toULong(16)
private val ddccbbaaefbeadde = "ddccbbaaefbeadde".toULong(16)
| 0
|
Kotlin
|
0
| 3
|
b834aaf5235d81d99a338188e506c50eddbb7dae
| 13,023
|
kotlin-unsigned-jvm
|
MIT License
|
src/main/kotlin/io/DataInput.kt
|
Geek202
| 333,961,120
| false
|
{"Gradle": 2, "Markdown": 1, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "INI": 1, "Java": 2, "JSON": 2, "PHP": 1, "Kotlin": 11}
|
package me.geek.tom.slimeforfabric.io
import me.geek.tom.slimeforfabric.util.Bitset
import net.minecraft.nbt.CompoundTag
import okio.Buffer
@ExperimentalUnsignedTypes
interface DataInput {
fun checkSlimeHeader(): Boolean {
val header = readHeader()
return header.first == (0xB1).toUByte() && header.second == (0x0C).toUByte()
}
fun readHeader(): Pair<UByte, UByte>
fun readUByte(): UByte
fun readUShort(): UShort
fun readShort(): Short
fun readInt(): Int
fun readBitset(length: UInt, bytesLength: Int): Bitset
fun readBytes(length: Int): ByteArray
fun decompressAndReadBuffer(): Buffer
fun readCompressedNbt(): CompoundTag
}
| 1
| null |
1
| 1
|
6e446528360a3a9853b72475659348940a46ed8b
| 688
|
slime-for-fabric
|
MIT License
|
app/src/main/java/com/raul/macias/wikiheroes/view/adapter/CreatorsAdapter.kt
|
xR4ULx
| 313,670,556
| false
|
{"Gradle": 3, "Java Properties": 4, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "INI": 7, "Proguard": 1, "Kotlin": 119, "XML": 222, "Java": 5}
|
package com.raul.macias.wikiheroes.view.adapter
import android.view.View
import com.raul.macias.wikiheroes.R
import com.raul.macias.wikiheroes.models.Item
import com.raul.macias.wikiheroes.view.viewholder.BaseViewHolder
import com.raul.macias.wikiheroes.view.viewholder.CreatorViewHolder
class CreatorsAdapter (val delegate : CreatorViewHolder.Delegate, private val creators : List<Item>) : BaseAdapter() {
init {
addItems(creators)
}
override fun layout(item: Any?): Int {
return R.layout.creator_item
}
override fun viewHolder(layout: Int, view: View): BaseViewHolder {
return CreatorViewHolder(view, delegate, creators)
}
}
| 1
| null |
1
| 1
|
d76d4736780b156d2b8133e794cca2de6b408f28
| 680
|
kotlin_api_marvel
|
MIT License
|
app_pemantau/src/main/java/app/trian/pemantau/ui/pages/onboard/OnboardViewModel.kt
|
triandamai
| 510,087,041
| false
|
{"Kotlin": 499465}
|
package app.trian.pemantau.ui.pages.onboard
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class OnboardViewModel @Inject constructor() : ViewModel() {
}
| 0
|
Kotlin
|
0
| 0
|
608d28a7800a39ee9ded14c6d85b7e7db770d01a
| 238
|
pantau-odp-v2
|
Apache License 2.0
|
app/src/main/java/com/kobrakid/retroachievements/view/ui/SettingsFragment.kt
|
KobraKid
| 194,746,591
| false
| null |
package com.kobrakid.retroachievements.view.ui
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import android.widget.CompoundButton
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.kobrakid.retroachievements.Consts
import com.kobrakid.retroachievements.R
import com.kobrakid.retroachievements.databinding.FragmentSettingsBinding
import com.kobrakid.retroachievements.viewmodel.SettingsViewModel
class SettingsFragment : Fragment() {
private val viewModel: SettingsViewModel by viewModels()
private var _binding: FragmentSettingsBinding? = null
private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
_binding = FragmentSettingsBinding.inflate(inflater, container, false)
activity?.title = "Settings"
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.settingsThemeDropdown.apply {
try {
adapter = object : ArrayAdapter<Consts.Theme>(requireContext(), android.R.layout.simple_spinner_dropdown_item, Consts.Theme.values()) {
override fun isEnabled(position: Int): Boolean {
return Consts.Theme.values()[position].enabled
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
val textView = super.getDropDownView(position, convertView, parent) as TextView
if (isEnabled(position)) {
val typedValue = TypedValue()
context.theme.resolveAttribute(R.attr.colorPrimary, typedValue, true)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
textView.setTextColor(context.resources.getColor(typedValue.resourceId, activity?.theme))
else
textView.setTextColor(ContextCompat.getColor(context, typedValue.resourceId))
} else {
textView.setTextColor(Color.GRAY)
}
return textView
}
}
} catch (e: IllegalStateException) {
Log.e(TAG, "Context was null", e)
return // no need to continue if this fragment is not attached to a context
}
onItemSelectedListener = object : OnItemSelectedListener {
override fun onNothingSelected(adapterView: AdapterView<*>?) {}
override fun onItemSelected(adapterView: AdapterView<*>, view: View?, pos: Int, id: Long) {
if (isEnabled) viewModel.setTheme(pos)
}
}
}
viewModel.settings.observe(viewLifecycleOwner) {
val themeIndex = Consts.Theme.values()
.indexOfFirst { theme -> theme.themeAttr == it.theme }
.coerceAtLeast(0)
binding.settingsCurrentTheme.text = getString(R.string.settings_current_theme, if (themeIndex == 0) "<none>" else Consts.Theme.values()[themeIndex].themeName)
binding.settingsCurrentUser.text = if (it.user == "") getString(R.string.settings_no_current_user) else getString(R.string.settings_current_user, it.user)
binding.settingsThemeDropdown.setSelection(themeIndex)
binding.settingsHideConsoles.isChecked = it.hideEmptyConsoles
binding.settingsHideGames.isChecked = it.hideEmptyGames
binding.settingsHideConsolesWarning.visibility = if (it.hideEmptyConsoles) View.GONE else View.VISIBLE
binding.settingsHideGamesWarning.visibility = if (it.hideEmptyGames) View.GONE else View.VISIBLE
}
viewModel.loading.observe(viewLifecycleOwner) {
binding.settingsApplyingFade.visibility = if (it) View.VISIBLE else View.GONE
binding.settingsApplying.visibility = if (it) View.VISIBLE else View.GONE
}
viewModel.activityNeedsRecreating.observe(viewLifecycleOwner) {
if (it) {
viewModel.onRecreate()
activity?.recreate()
}
}
binding.settingsHideConsoles.setOnCheckedChangeListener { _: CompoundButton?, b: Boolean -> viewModel.setHideConsoles(context, b) }
binding.settingsHideGames.setOnCheckedChangeListener { _: CompoundButton?, b: Boolean -> viewModel.setHideGames(context, b) }
binding.settingsLogoutButton.setOnClickListener { viewModel.logout(context) }
binding.settingsApply.setOnClickListener { viewModel.applyTheme(context) }
viewModel.init(context)
}
companion object {
private val TAG = Consts.BASE_TAG + SettingsFragment::class.java.simpleName
}
}
| 3
|
Kotlin
|
0
| 1
|
d62d3f1643f020b99f43ae663052ca181f797104
| 5,483
|
RetroAchievements
|
MIT License
|
src/main/kotlin/com/github/strindberg/emacsj/actions/word/UpperCaseAction.kt
|
strindberg
| 719,602,205
| false
|
{"Kotlin": 286724}
|
package com.github.strindberg.emacsj.actions.word
import com.github.strindberg.emacsj.word.ChangeType
import com.github.strindberg.emacsj.word.WordChangeHandler
import com.intellij.openapi.editor.actions.TextComponentEditorAction
class UpperCaseAction : TextComponentEditorAction(WordChangeHandler(ChangeType.UPPER))
| 3
|
Kotlin
|
1
| 9
|
798a061f215c8ab2d3bbb67e4ba2afd12d8554d2
| 319
|
emacsj
|
MIT License
|
src/main/kotlin/no/nav/syfo/plugins/Features.kt
|
navikt
| 526,559,029
| false
|
{"Kotlin": 241578, "TypeScript": 72510, "JavaScript": 867, "Dockerfile": 699, "CSS": 389, "HTML": 356}
|
package no.nav.syfo.plugins
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.routing.*
import no.nav.syfo.altinn.registerAltinnStatusApi
import no.nav.syfo.identendring.registerFnrApi
import no.nav.syfo.identendring.registerPersonApi
import no.nav.syfo.legeerklaering.registerDeleteLegeerklaeringApi
import no.nav.syfo.metrics.monitorHttpRequests
import no.nav.syfo.narmesteleder.registrerNarmestelederApi
import no.nav.syfo.oppgave.registerHentOppgaverApi
import no.nav.syfo.saf.api.registerJournalpostApi
import no.nav.syfo.sykmelding.delete_sykmelding.registerDeleteSykmeldingApi
import no.nav.syfo.sykmeldingsopplysninger.registerSykmeldingsOpplysningerApi
fun Application.configureFeatures() {
routing {
authenticate(if (application.developmentMode) "local" else "jwt") {
route("/api") {
registerFnrApi()
registerDeleteSykmeldingApi()
registerHentOppgaverApi()
registrerNarmestelederApi()
registerDeleteLegeerklaeringApi()
registerJournalpostApi()
registerPersonApi()
registerSykmeldingsOpplysningerApi()
registerAltinnStatusApi()
}
}
}
intercept(ApplicationCallPipeline.Monitoring, monitorHttpRequests(this.developmentMode))
}
| 1
|
Kotlin
|
0
| 0
|
68ad7e710fe08ca0506f3518a70b40a4231226f4
| 1,370
|
macgyver
|
MIT License
|
app/src/main/java/com/damianogiusti/viewstatesdemo/BaseScreen.kt
|
damianogiusti
| 130,755,941
| false
|
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Proguard": 2, "Kotlin": 17, "XML": 13, "Java": 2}
|
package com.damianogiusti.viewstatesdemo
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import com.damianogiusti.statedispatcher.ScreenState
import com.damianogiusti.statedispatcher.StateDispatcher
import io.reactivex.disposables.CompositeDisposable
import kotlin.reflect.KClass
/**
* Created by <NAME> on 20/04/18.
*/
abstract class BaseScreen @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
val dispatcher: StateDispatcher
get() = (context as BaseActivity).dispatcher
abstract val screenType: KClass<out ScreenState>
private val compositeDisposable = CompositeDisposable()
override fun onAttachedToWindow() {
super.onAttachedToWindow()
compositeDisposable.add(dispatcher
.showEvents(screenType)
.subscribe({
visibility = View.VISIBLE
}))
compositeDisposable.add(dispatcher
.hideEvents(screenType)
.subscribe({
visibility = View.GONE
}))
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
compositeDisposable.clear()
}
}
| 0
|
Kotlin
|
0
| 0
|
b5bd47653f50bb5b8aadc6fe6372f0fddda4f9f8
| 1,312
|
state-dispatcher
|
Apache License 2.0
|
src/main/kotlin/com/demonwav/mcdev/nbt/tags/TagLongArray.kt
|
Earthcomputer
| 240,984,777
| false
| null |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt.tags
import java.io.DataOutputStream
class TagLongArray(override val value: LongArray) : NbtValueTag<LongArray>(LongArray::class.java) {
override val payloadSize = 4 + value.size * 8
override val typeId = NbtTypeId.LONG_ARRAY
override fun write(stream: DataOutputStream) {
stream.writeInt(value.size)
for (l in value) {
stream.writeLong(l)
}
}
override fun toString() = toString(StringBuilder(), 0, WriterState.COMPOUND).toString()
override fun toString(sb: StringBuilder, indentLevel: Int, writerState: WriterState): StringBuilder {
value.joinTo(buffer = sb, separator = ", ", prefix = "longs(", postfix = ")")
return sb
}
override fun valueEquals(otherValue: LongArray) = this.value.contentEquals(otherValue)
// This makes IntelliJ happy - and angry at the same time
@Suppress("RedundantOverride")
override fun equals(other: Any?) = super.equals(other)
override fun hashCode() = this.value.contentHashCode()
override fun valueCopy() = value.copyOf(value.size)
}
| 204
| null |
2
| 23
|
ab8aaeb8804c7a8b2e439e063a73cb12d0a9d4b5
| 1,234
|
MinecraftDev
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsciagcareersinductionapi/data/jsonprofile/CurrentSupportState.kt
|
ministryofjustice
| 620,258,376
| false
| null |
package uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.data.jsonprofile
data class CurrentSupportState(
var supportDeclined: SupportDeclined?,
var supportAccepted: SupportAccepted?,
)
| 0
|
Kotlin
|
0
| 0
|
008ad77d00e5556e115024169e3f1bddb8f62607
| 200
|
hmpps-ciag-careers-induction-api
|
MIT License
|
core/src/main/kotlin/org/virtuslab/bazelsteward/core/common/UpdateLogic.kt
|
VirtusLab
| 567,694,906
| false
| null |
package org.virtuslab.bazelsteward.core.common
import org.virtuslab.bazelsteward.core.library.BumpingStrategy
import org.virtuslab.bazelsteward.core.library.Library
import org.virtuslab.bazelsteward.core.library.SemanticVersion
import org.virtuslab.bazelsteward.core.library.Version
import org.virtuslab.bazelsteward.core.library.VersioningSchema
data class UpdateSuggestion(val currentLibrary: Library, val suggestedVersion: Version)
data class UpdateRules(
val versioningSchema: VersioningSchema = VersioningSchema.Loose,
val bumpingStrategy: BumpingStrategy = BumpingStrategy.Minor,
val pinningStrategy: PinningStrategy = PinningStrategy.None,
val enabled: Boolean = true,
)
class UpdateLogic {
fun selectUpdate(
library: Library,
availableVersions: List<Version>,
updateRules: UpdateRules,
): UpdateSuggestion? {
fun checkPreRelease(): List<Pair<Version, SemanticVersion>> =
availableVersions
.filter { version -> updateRules.pinningStrategy.test(version) }
.mapNotNull { version -> version.toSemVer(updateRules.versioningSchema)?.let { version to it } }
.filter { it.second.prerelease.isBlank() }
fun maxAvailableVersion(filterVersionComponent: (a: SemanticVersion) -> Boolean): Version? =
checkPreRelease()
.filter { filterVersionComponent(it.second) }
.maxByOrNull { it.second }
?.first
fun selectDefault(): UpdateSuggestion? =
library.version.toSemVer(updateRules.versioningSchema)
?.takeIf { version -> version.prerelease.isBlank() }
?.let { version ->
val maxPatch =
maxAvailableVersion { a -> a.major == version.major && a.minor == version.minor && a.patch > version.patch }
val maxMinor = maxAvailableVersion { a -> a.major == version.major && a.minor > version.minor }
val maxMajor = maxAvailableVersion { a -> a.major > version.major }
val nextVersion = when (updateRules.bumpingStrategy) {
BumpingStrategy.Default -> maxPatch ?: maxMinor ?: maxMajor
BumpingStrategy.Latest -> maxMajor ?: maxMinor ?: maxPatch
BumpingStrategy.Minor -> maxMinor ?: maxPatch ?: maxMajor
else -> null
}
nextVersion?.let { UpdateSuggestion(library, it) }
}
fun maxAvailableVersionByDate(): Version? =
checkPreRelease()
.map { it.first }
.filter { it.date != null }
.maxByOrNull { it.date!! }
fun selectByDate(): UpdateSuggestion? {
return library.version.toSemVer(updateRules.versioningSchema)
?.takeIf { version -> version.prerelease.isBlank() }
?.let {
maxAvailableVersionByDate()?.let {
if (it.value != library.version.value) {
UpdateSuggestion(library, it)
} else {
null
}
}
}
}
if (!updateRules.enabled) return null
return if (updateRules.bumpingStrategy == BumpingStrategy.LatestByDate) {
selectByDate()
} else {
selectDefault()
}
}
}
| 40
|
Kotlin
|
5
| 9
|
f0764aacc0b13b1296eb8cc6cd062546ed1914ff
| 3,077
|
bazel-steward
|
Apache License 2.0
|
app/src/main/java/org/sehproject/sss/viewmodel/GroupViewModel.kt
|
urarik
| 426,300,081
| false
|
{"Kotlin": 225112}
|
package org.sehproject.sss.viewmodel
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import org.sehproject.sss.UserInfo
import org.sehproject.sss.datatype.Group
import org.sehproject.sss.datatype.User
import org.sehproject.sss.logic.GroupLogic
import org.sehproject.sss.repository.FriendRepository
import org.sehproject.sss.repository.GroupRepository
import org.sehproject.sss.utils.SingleLiveEvent
class GroupViewModel : ViewModel() {
val groupLogic = GroupLogic(this)
val groupRepository = GroupRepository()
val friendRepository = FriendRepository()
val createGroupEvent = SingleLiveEvent<Int>()
val setColorEvent = SingleLiveEvent<Group>()
val createGroupCompleteEvent = SingleLiveEvent<Group>()
val deleteGroupEvent = SingleLiveEvent<Int>()
val deleteGroupCompleteEvent = SingleLiveEvent<Any>()
val editGroupEvent = SingleLiveEvent<Group>()
val editGroupCompleteEvent = SingleLiveEvent<Group>()
val inviteGroupEvent = SingleLiveEvent<Int>()
val inviteGroupCompleteEvent = SingleLiveEvent<Any>()
val kickOutGroupEvent = SingleLiveEvent<Int>()
val kickOutGroupCompleteEvent = SingleLiveEvent<Any>()
val viewGroupDetailsEvent = SingleLiveEvent<Int>()
val exitGroupCompleteEvent = SingleLiveEvent<Any>()
val sortEvent = SingleLiveEvent<Any>()
val acceptGroupInviteEvent = SingleLiveEvent<Any>()
val refuseGroupInviteEvent = SingleLiveEvent<Any>()
val friendListLiveData = MutableLiveData<List<User>>()
val groupLiveData = MutableLiveData<Group>()
val groupListLiveData = MutableLiveData<List<Group>>()
val selectedGroupUserList = mutableListOf<String>()
val cancelInviteGroupEvent = SingleLiveEvent<Any>()
val editGroupFailEvent = SingleLiveEvent<String>()
fun setFriendList(gid: Int) {
if(gid == -1)
friendRepository.getFriendList { _, list ->
friendListLiveData.value = list
}
else
groupRepository.getParticipantList(gid) {code, list ->
var cnt = 0
var mlist: MutableList<User>? = null
mlist = if (list != null)
list as MutableList<User>
else
mutableListOf()
if(code == 0) {
for (i in mlist) {
if (i.userId == UserInfo.userId) {
mlist.removeAt(cnt)
break
}
cnt++
}
friendListLiveData.value = mlist
}
}
}
fun setGroupList()
{
groupRepository.getGroupList { i, list ->
var mlist: MutableList<Group>? = null
if(i == 0) {
mlist = list as MutableList<Group>
groupListLiveData.value = groupLogic.sortGroupByName(mlist)
}
}
}
fun setGroup(gid: Int?) {
if(gid == null) groupLiveData.value = Group()
else {
groupRepository.getGroup(gid) { code, group ->
Log.d("TAG", group.toString())
if (code == 0) {
groupLiveData.value = group
}
}
groupRepository.getParticipantList(gid) { code, participants ->
if(code ==0)
friendListLiveData.value = participants
else if (code == 1)
friendListLiveData.value = listOf()
}
}
}
}
| 0
|
Kotlin
|
1
| 2
|
f851dd57b2d6e350d02a58870b8d5b417a599d7e
| 3,591
|
SSS
|
MIT License
|
android/src/main/java/id/kotlin/multiplatform/AppExt.kt
|
budioktaviyan
| 152,530,352
| false
|
{"Swift": 20233, "Kotlin": 14563, "Ruby": 266}
|
package id.kotlin.multiplatform
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.MemoryCategory
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.module.AppGlideModule
@GlideModule
class GlideModule : AppGlideModule()
internal fun ImageView.load(url: String) {
val context: Context = this.context
Glide.get(context).setMemoryCategory(MemoryCategory.NORMAL)
GlideApp.with(context).load(url).diskCacheStrategy(DiskCacheStrategy.RESOURCE).into(this)
}
internal fun ViewGroup?.inflate(context: Context, layoutRes: Int, attachToRoot: Boolean): View =
LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot)
| 0
|
Swift
|
0
| 4
|
1cf3062ca1114020805805c97767a819d0d55cfe
| 880
|
movies-multiplatform
|
MIT License
|
mobzy-features/src/main/kotlin/com/mineinabyss/mobzy/features/initializers/SetSlimeSize.kt
|
MineInAbyss
| 142,800,887
| false
|
{"Kotlin": 136533}
|
package com.mineinabyss.mobzy.features.initializers
import com.mineinabyss.geary.autoscan.AutoScan
import com.mineinabyss.geary.systems.GearyListener
import com.mineinabyss.geary.systems.accessors.Pointers
import com.mineinabyss.idofront.serialization.IntRangeSerializer
import com.mineinabyss.idofront.typealiases.BukkitEntity
import com.mineinabyss.idofront.util.randomOrMin
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import org.bukkit.entity.Slime
@JvmInline
@Serializable
@SerialName("mobzy:set.slime_size")
value class SetSlimeSize(@Serializable(with = IntRangeSerializer::class) val size: IntRange)
@AutoScan
class SetSlimeSizeSystem : GearyListener() {
private val Pointers.slimeSize by get<SetSlimeSize>().whenSetOnTarget()
private val Pointers.bukkit by get<BukkitEntity>().whenSetOnTarget()
override fun Pointers.handle() {
val slime = (bukkit as? Slime) ?: return
slime.size = slimeSize.size.randomOrMin()
}
}
| 9
|
Kotlin
|
8
| 43
|
c3b007ca794292886b3f13e607bb0fbbac46f285
| 996
|
Mobzy
|
MIT License
|
app/src/main/java/com/example/testandroidpro/view/TopBar.kt
|
Android-Project-Group-6
| 772,969,042
| false
|
{"Kotlin": 135436}
|
package com.example.testandroidpro.view
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.example.testandroidpro.R
import com.example.testandroidpro.viewmodel.AdViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TopBar(navController: NavController, adViewModel: AdViewModel, screen:String) {
var expanded by remember { mutableStateOf(false) }
val context = LocalContext.current
val density = LocalDensity.current
val fontSize = remember { mutableStateOf(0.sp) }
TopAppBar(
modifier = Modifier
.fillMaxWidth()
.onGloballyPositioned { layoutCoordinates ->
val newFontSize = with(density) {
layoutCoordinates.size.height
.toDp()
.toPx() / density.density
} * 0.7f
fontSize.value = newFontSize.sp
},
title = { },
actions = {
Row(
modifier = Modifier
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Row(
modifier = Modifier
.weight(1f)
,
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically
) {
if(screen != context.getString(R.string.homePage)) {
IconButton(
onClick = { navController.popBackStack() }
) {
Icon(Icons.Default.ArrowBack, contentDescription = "Back")
}
}
}
Row(
modifier = Modifier
.weight(8f)
,
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(R.string.ComNameHead),
modifier = Modifier
,
textAlign = TextAlign.Center,
fontSize = fontSize.value,
color = Color.Black
)
Text(
text = stringResource(R.string.ComNameBody),
modifier = Modifier
,
textAlign = TextAlign.Center,
fontSize = fontSize.value,
color = Color(0xFFFF69B4)
)
}
Row(
modifier = Modifier
.weight(1f)
,
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically
) {
if ((screen != context.getString(R.string.supportPage))&&(screen != context.getString(R.string.signupPage))) {
IconButton(
onClick = {
expanded = !expanded
}
) {
Icon(Icons.Filled.MoreVert, contentDescription = null)
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }) {
when (screen) {
context.getString(R.string.homePage) -> {
DropdownMenuItem(
text = { Text(stringResource(R.string.drop_info)) },
onClick = { navController.navigate(context.getString(R.string.infoPage)) }
)
}
context.getString(R.string.infoPage) -> {
DropdownMenuItem(
text = { Text(stringResource(R.string.ads_list)) },
onClick = { navController.navigate(context.getString(R.string.homePage)) }
)
}
else -> {
DropdownMenuItem(
text = { Text(stringResource(R.string.drop_info)) },
onClick = { navController.navigate(context.getString(R.string.infoPage)) }
)
DropdownMenuItem(
text = { Text(stringResource(R.string.ads_list)) },
onClick = { navController.navigate(context.getString(R.string.homePage)) }
)
}
}
DropdownMenuItem(
text = { Text(stringResource(R.string.drop_support)) },
onClick = {
navController.navigate(context.getString(R.string.supportPage))
}
)
DropdownMenuItem(
text = { Text(stringResource(R.string.drop_signOut)) },
onClick = {
adViewModel.userSignOut(navController)
}
)
}
}
}
}
}
)
}
| 19
|
Kotlin
|
0
| 0
|
fe68c254ee27154a7768ec4ea060c6cc602bcfa5
| 7,125
|
AdFusion
|
MIT License
|
app/src/main/java/jp/cordea/ribsdemo/ui/region/RegionRemoteDataSource.kt
|
CORDEA
| 163,973,049
| false
| null |
package jp.cordea.ribsdemo.ui.region
import io.reactivex.Maybe
import jp.cordea.ribsdemo.api.VultrApiClient
import jp.cordea.ribsdemo.api.response.Region
import javax.inject.Inject
class RegionRemoteDataSource @Inject constructor(
private val apiClient: VultrApiClient
) : RegionDataSource {
override fun fetchRegion(): Maybe<Collection<Region>> = apiClient.getRegions().map { it.values }
}
| 0
|
Kotlin
|
0
| 2
|
3ff23b50b9d59ca42ba95cdf437d36f2ddd4bda0
| 401
|
RIBsDemo
|
Apache License 2.0
|
sample/src/commonMain/kotlin/ui/components/Center.kt
|
ShreyashKore
| 793,195,317
| false
|
{"Kotlin": 126894, "Swift": 750}
|
package com.gyanoba.inspektor.sample.ui.components
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@Composable
fun Center(modifier: Modifier = Modifier.fillMaxSize(), content: @Composable () -> Unit) {
Box(modifier, contentAlignment = Alignment.Center) {
content()
}
}
| 6
|
Kotlin
|
0
| 3
|
8eba601d9bfc102574d56864918718e5f09b36f1
| 456
|
inspektor
|
MIT License
|
src/main/kotlin/org/example/chess/util/BoardInfo.kt
|
lachiestewart
| 866,509,538
| false
|
{"Kotlin": 29823, "Java": 328}
|
package org.example.chess.util
enum class BoardInfo(val value: Int) {
HEIGHT(8),
WIDTH(8);
}
| 0
|
Kotlin
|
0
| 0
|
410b1751a739739c10116d39c3daa14010535006
| 101
|
kotlin-chess
|
MIT License
|
demos/android/demos-kotlin/src/main/java/com/antgroup/antv/f2/kotlinsamples/ChartModel.kt
|
antvis
| 313,171,555
| false
|
{"C++": 1597834, "Java": 106313, "Objective-C++": 72606, "Objective-C": 24679, "CMake": 10793, "TypeScript": 4086, "C": 3548, "Ruby": 2100, "JavaScript": 2065, "Shell": 51}
|
package com.antgroup.antv.f2.kotlinsamples
import com.antgroup.antv.f2.F2CanvasView
import java.io.Serializable
/**
* @author weiqing.tang
* @date 2022-06-20
*/
class ChartModel : Serializable {
@JvmField
var title: String
@JvmField
var adapterClass: Class<out F2CanvasView.Adapter?>
var horizontal = false
constructor(title: String, adapterClass: Class<out F2CanvasView.Adapter?>) {
this.title = title
this.adapterClass = adapterClass
}
constructor(
title: String,
adapterClass: Class<out F2CanvasView.Adapter?>,
horizontal: Boolean
) {
this.title = title
this.adapterClass = adapterClass
this.horizontal = horizontal
}
}
| 5
|
C++
|
21
| 210
|
dfb6d904e2dfa279a3e5c519a10aac7791955e48
| 733
|
F2Native
|
MIT License
|
android/app/src/main/java/com/example/bachelorproef/application/MyApplication.kt
|
BrackeNavaron
| 251,107,076
| false
| null |
package com.example.bachelorproef.application
import androidx.multidex.MultiDexApplication
import com.example.bachelorproef.viewmodel.*
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.core.context.startKoin
import org.koin.dsl.module
class MyApplication : MultiDexApplication() {
override fun onCreate() {
super.onCreate()
setupKoin()
}
/**
* Setup DI with Koin.
*/
private fun setupKoin(){
startKoin {
androidLogger()
androidContext(this@MyApplication)
modules(listOf(viewModelModule))
}
}
private val viewModelModule = module {
viewModel {
ShowcaseViewModel(get())
}
viewModel {
PagerViewModel()
}
viewModel {
ListViewModel()
}
viewModel {
AnimationViewModel()
}
viewModel {
FormViewModel(get())
}
//Get this VM: by sharedViewModel()
viewModel {
SharedViewModel()
}
viewModel {
AsyncViewModel(get())
}
}
}
| 0
|
Kotlin
|
0
| 0
|
30b9e1803903f1144386a2fb0c6e8be229822cf5
| 1,233
|
bachproef_sourcecode
|
MIT License
|
cryptohash/src/nativeDarwin32Test/kotlin/com/appmattus/crypto/internal/core/ios/SHA1.kt
|
appmattus
| 347,486,833
| false
| null |
/*
* Copyright 2021 Appmattus Limited
*
* 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.appmattus.crypto.internal.core.ios
import com.appmattus.crypto.Algorithm
import com.appmattus.crypto.Digest
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.alloc
import kotlinx.cinterop.free
import kotlinx.cinterop.get
import kotlinx.cinterop.nativeHeap
import kotlinx.cinterop.ptr
import kotlinx.cinterop.set
import kotlinx.cinterop.usePinned
import platform.CoreCrypto.CC_SHA1_BLOCK_LONG
import platform.CoreCrypto.CC_SHA1_CTX
import platform.CoreCrypto.CC_SHA1_DIGEST_LENGTH
import platform.CoreCrypto.CC_SHA1_Final
import platform.CoreCrypto.CC_SHA1_Init
import platform.CoreCrypto.CC_SHA1_Update
@Suppress("EXPERIMENTAL_API_USAGE")
internal class SHA1 : Digest<SHA1> {
private var hashObject: CC_SHA1_CTX? = null
private val hashObjectPtr: CPointer<CC_SHA1_CTX>
get() = hashObject?.ptr ?: nativeHeap.alloc<CC_SHA1_CTX>().run {
hashObject = this
CC_SHA1_Init(ptr)
ptr
}
override fun update(input: Byte) {
update(ByteArray(1) { input })
}
override fun update(input: ByteArray) {
update(input, 0, input.size)
}
override fun update(input: ByteArray, offset: Int, length: Int) {
if (length > 0) {
input.usePinned {
CC_SHA1_Update(hashObjectPtr, it.addressOf(offset), length.toUInt())
}
}
}
override fun digest(): ByteArray {
val digest = UByteArray(CC_SHA1_DIGEST_LENGTH)
digest.usePinned {
CC_SHA1_Final(it.addressOf(0), hashObjectPtr)
}
reset()
return digest.toByteArray()
}
override fun digest(input: ByteArray): ByteArray {
update(input)
return digest()
}
/**
* Completes the hash computation by performing final
* operations such as padding.
*
* @param output the output buffer in which to store the digest
*
* @param offset offset to start from in the output buffer
*
* @param length number of bytes within buf allotted for the digest. This
* implementation does not return partial digests. The presence of this
* parameter is solely for consistency in our API's. If the value of this
* parameter is less than the actual digest length, the method will throw
* an Exception.
* This parameter is ignored if its value is greater than or equal to
* the actual digest length.
*
* @return the length of the digest stored in the output buffer.
*/
override fun digest(output: ByteArray, offset: Int, length: Int): Int {
val digest = digest()
if (length < digest.size) throw IllegalArgumentException("partial digests not returned")
if (output.size - offset < digest.size) throw IllegalArgumentException("insufficient space in the output buffer to store the digest")
digest.copyInto(output, offset, 0, digest.size)
return digest.size
}
override val digestLength: Int
get() = CC_SHA1_DIGEST_LENGTH
override fun reset() {
hashObject?.let { nativeHeap.free(it) }
hashObject = null
}
override fun copy(): SHA1 {
val digest = SHA1()
hashObject?.let { hashObject ->
digest.hashObject = nativeHeap.alloc {
h0 = hashObject.h0
h1 = hashObject.h1
h2 = hashObject.h2
h3 = hashObject.h3
h4 = hashObject.h4
Nl = hashObject.Nl
Nh = hashObject.Nh
for (i in 0..CC_SHA1_BLOCK_LONG.toInt()) {
data[i] = hashObject.data[i]
}
num = hashObject.num
}
}
return digest
}
override val blockLength: Int
get() = Algorithm.SHA_1.blockLength
override fun toString() = Algorithm.SHA_1.algorithmName
}
| 0
|
Kotlin
|
4
| 66
|
89524539c86213c3df67e56e11f153b29cd96f98
| 4,515
|
crypto
|
Apache License 2.0
|
geary-papermc-tracking/src/main/kotlin/com/mineinabyss/geary/papermc/tracking/entities/systems/UntrackOnRemoveBukkitComponent.kt
|
MineInAbyss
| 592,086,123
| false
| null |
package com.mineinabyss.geary.papermc.tracking.entities.systems
import com.mineinabyss.geary.annotations.Handler
import com.mineinabyss.geary.components.events.EntityRemoved
import com.mineinabyss.geary.datatypes.family.family
import com.mineinabyss.geary.papermc.datastore.encodeComponentsTo
import com.mineinabyss.geary.papermc.tracking.entities.gearyMobs
import com.mineinabyss.geary.systems.GearyListener
import com.mineinabyss.geary.systems.accessors.EventScope
import com.mineinabyss.geary.systems.accessors.TargetScope
import com.mineinabyss.idofront.typealiases.BukkitEntity
class UntrackOnRemoveBukkitComponent : GearyListener() {
private val TargetScope.bukkit by get<BukkitEntity>()
private val EventScope.removed by family { has<EntityRemoved>() }
@Handler
fun TargetScope.persistComponents() {
gearyMobs.bukkit2Geary.remove(bukkit.entityId)
entity.encodeComponentsTo(bukkit)
}
}
| 0
|
Kotlin
|
0
| 1
|
afb0722015f1d6206b89cc09e210814361decd47
| 931
|
geary-papermc
|
MIT License
|
app/src/main/java/com/waleska404/algorithms/ui/quicksort/QuickSortViewModel.kt
|
waleska404
| 717,751,405
| false
|
{"Kotlin": 113924}
|
package com.waleska404.algorithms.ui.quicksort
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.waleska404.algorithms.domain.quicksort.QuickSort
import com.waleska404.algorithms.ui.core.config.GAME_DELAY_IN_MS
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class QuickSortViewModel @Inject constructor(
private val quickSort: QuickSort
) : ViewModel() {
private var _isSorting = MutableStateFlow(false)
val isSorting: StateFlow<Boolean> = _isSorting
private var _listToSort = MutableStateFlow(getRandomSortingList())
val listToSort: StateFlow<QuickSortList> = _listToSort
private fun getRandomSortingList(size: Int = 9): QuickSortList {
val list = (0 until size).map {
QuickSortItem(
id = it,
isPivot = false,
isLeftPointer = false,
isRightPointer = false,
alreadyOrdered = false,
value = (30..100).random(),
inSortingRange = false,
)
}
return QuickSortList(list = list)
}
fun randomizeCurrentList(size: Int = listToSort.value.list.size) {
_listToSort.value = getRandomSortingList(size)
}
fun startSorting() {
val dataList = _listToSort.value.toDataList()
_isSorting.value = true
var lastLeftPointer = 0
var lastRightPointer = 0
viewModelScope.launch {
quickSort.runQuickSort(dataList, 0, dataList.size - 1, GAME_DELAY_IN_MS).collect { quickSortInfo ->
// mark the elements that are being considered for the sorting
checkInSortingRange(quickSortInfo.sortingSubarray)
// base case: sorting only one element
if (quickSortInfo.baseCase) {
val pivot = quickSortInfo.currentPivot
if (!listToSort.value.list[pivot].alreadyOrdered) {
val newListCompare = _listToSort.value.list.toMutableList()
newListCompare[pivot] = newListCompare[pivot].copy(isPivot = true)
_listToSort.value = _listToSort.value.copy(list = newListCompare)
delay(GAME_DELAY_IN_MS)
val newListSorted = _listToSort.value.list.toMutableList()
newListSorted[pivot] = newListSorted[pivot].copy(isPivot = false, alreadyOrdered = true)
_listToSort.value = _listToSort.value.copy(list = newListSorted)
}
} else {
// sorting more than one element
val pivot = quickSortInfo.currentPivot
val leftPointer = quickSortInfo.currentLeft
val rightPointer = quickSortInfo.currentRight
// uncheck latest items as being compared
val newListCompare = _listToSort.value.list.toMutableList()
newListCompare[lastLeftPointer] =
newListCompare[lastLeftPointer].copy(isLeftPointer = false, isRightPointer = false)
newListCompare[lastRightPointer] =
newListCompare[lastRightPointer].copy(isRightPointer = false, isLeftPointer = false)
lastLeftPointer = leftPointer
lastRightPointer = rightPointer
// mark current items as being compared
newListCompare[pivot] = newListCompare[pivot].copy(isPivot = true)
newListCompare[leftPointer] = newListCompare[leftPointer].copy(isLeftPointer = true)
newListCompare[rightPointer] = newListCompare[rightPointer].copy(isRightPointer = true)
_listToSort.value = _listToSort.value.copy(list = newListCompare)
delay(GAME_DELAY_IN_MS)
// swap if necessary
if (quickSortInfo.shouldSwapPointers) {
swapOnCurrentList(leftPointer, rightPointer)
}
if (quickSortInfo.shouldSwapPivot) {
swapOnCurrentList(pivot, rightPointer)
delay(GAME_DELAY_IN_MS)
val newListAfterSwap = _listToSort.value.list.toMutableList()
newListAfterSwap[pivot] = newListAfterSwap[pivot].copy(
isRightPointer = false,
isLeftPointer = false,
)
newListAfterSwap[rightPointer] = newListAfterSwap[rightPointer].copy(
alreadyOrdered = true,
isPivot = false,
)
newListAfterSwap[leftPointer] = newListAfterSwap[leftPointer].copy(
isRightPointer = false,
isLeftPointer = false,
)
_listToSort.value = _listToSort.value.copy(list = newListAfterSwap)
}
delay(GAME_DELAY_IN_MS)
}
}
_isSorting.value = false
resetColors()
}
}
private fun resetColors() {
val newList = mutableListOf<QuickSortItem>()
for (i in _listToSort.value.list) {
newList.add(
i.copy(
isPivot = false,
isLeftPointer = false,
isRightPointer = false,
alreadyOrdered = false
)
)
}
_listToSort.value = _listToSort.value.copy(list = newList)
}
private fun swapOnCurrentList(i: Int, j: Int) {
val newListSwap = _listToSort.value.list.toMutableList()
val temp = newListSwap[i].copy()
newListSwap[i] = newListSwap[j].copy()
newListSwap[j] = temp
_listToSort.value = _listToSort.value.copy(list = newListSwap)
}
private fun checkInSortingRange(range: Pair<Int, Int>) {
val newList = _listToSort.value.list.toMutableList().mapIndexed { index, value ->
value.copy(inSortingRange = index in range.first..range.second)
}
_listToSort.value = _listToSort.value.copy(list = newList)
}
}
| 0
|
Kotlin
|
1
| 5
|
482f3f7dcc27af14214a36d20a2d5a3e09e23866
| 6,558
|
algorithms-visualizer
|
MIT License
|
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/lambda/CfnEventSourceMappingSourceAccessConfigurationPropertyDsl.kt
|
cloudshiftinc
| 667,063,030
| false
| null |
@file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.lambda
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.services.lambda.CfnEventSourceMapping
/**
* An array of the authentication protocol, VPC components, or virtual host to secure and define
* your event source.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.lambda.*;
* SourceAccessConfigurationProperty sourceAccessConfigurationProperty =
* SourceAccessConfigurationProperty.builder()
* .type("type")
* .uri("uri")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-eventsourcemapping-sourceaccessconfiguration.html)
*/
@CdkDslMarker
public class CfnEventSourceMappingSourceAccessConfigurationPropertyDsl {
private val cdkBuilder: CfnEventSourceMapping.SourceAccessConfigurationProperty.Builder =
CfnEventSourceMapping.SourceAccessConfigurationProperty.builder()
/**
* @param type The type of authentication protocol, VPC components, or virtual host for your
* event source. For example: `"Type":"SASL_SCRAM_512_AUTH"` .
* * `BASIC_AUTH` – (Amazon MQ) The AWS Secrets Manager secret that stores your broker
* credentials.
* * `BASIC_AUTH` – (Self-managed Apache Kafka) The Secrets Manager ARN of your secret key used
* for SASL/PLAIN authentication of your Apache Kafka brokers.
* * `VPC_SUBNET` – (Self-managed Apache Kafka) The subnets associated with your VPC. Lambda
* connects to these subnets to fetch data from your self-managed Apache Kafka cluster.
* * `VPC_SECURITY_GROUP` – (Self-managed Apache Kafka) The VPC security group used to manage
* access to your self-managed Apache Kafka brokers.
* * `SASL_SCRAM_256_AUTH` – (Self-managed Apache Kafka) The Secrets Manager ARN of your secret
* key used for SASL SCRAM-256 authentication of your self-managed Apache Kafka brokers.
* * `SASL_SCRAM_512_AUTH` – (Amazon MSK, Self-managed Apache Kafka) The Secrets Manager ARN of
* your secret key used for SASL SCRAM-512 authentication of your self-managed Apache Kafka
* brokers.
* * `VIRTUAL_HOST` –- (RabbitMQ) The name of the virtual host in your RabbitMQ broker. Lambda
* uses this RabbitMQ host as the event source. This property cannot be specified in an
* UpdateEventSourceMapping API call.
* * `CLIENT_CERTIFICATE_TLS_AUTH` – (Amazon MSK, self-managed Apache Kafka) The Secrets Manager
* ARN of your secret key containing the certificate chain (X.509 PEM), private key (PKCS#8
* PEM), and private key password (optional) used for mutual TLS authentication of your
* MSK/Apache Kafka brokers.
* * `SERVER_ROOT_CA_CERTIFICATE` – (Self-managed Apache Kafka) The Secrets Manager ARN of your
* secret key containing the root CA certificate (X.509 PEM) used for TLS encryption of your
* Apache Kafka brokers.
*/
public fun type(type: String) {
cdkBuilder.type(type)
}
/**
* @param uri The value for your chosen configuration in `Type` . For example: `"URI":
* "arn:aws:secretsmanager:us-east-1:01234567890:secret:MyBrokerSecretName"` .
*/
public fun uri(uri: String) {
cdkBuilder.uri(uri)
}
public fun build(): CfnEventSourceMapping.SourceAccessConfigurationProperty = cdkBuilder.build()
}
| 3
| null |
0
| 3
|
c59c6292cf08f0fc3280d61e7f8cff813a608a62
| 3,779
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/queries/StreamMeasurements.kt
|
world-federation-of-advertisers
| 349,561,061
| false
|
{"Kotlin": 10143809, "Starlark": 951001, "C++": 627937, "CUE": 193010, "HCL": 162357, "TypeScript": 101485, "Python": 77600, "Shell": 20877, "CSS": 9620, "Go": 8063, "JavaScript": 5305, "HTML": 2489}
|
// Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.kingdom.deploy.gcloud.spanner.queries
import com.google.cloud.spanner.Statement
import org.wfanet.measurement.gcloud.common.toGcloudTimestamp
import org.wfanet.measurement.gcloud.spanner.appendClause
import org.wfanet.measurement.gcloud.spanner.bind
import org.wfanet.measurement.internal.kingdom.Measurement
import org.wfanet.measurement.internal.kingdom.StreamMeasurementsRequest
import org.wfanet.measurement.kingdom.deploy.common.DuchyIds
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.DuchyNotFoundException
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.BaseSpannerReader
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.MeasurementReader
class StreamMeasurements(
view: Measurement.View,
requestFilter: StreamMeasurementsRequest.Filter,
limit: Int = 0,
) : SimpleSpannerQuery<MeasurementReader.Result>() {
override val reader: BaseSpannerReader<MeasurementReader.Result> =
buildReader(view, requestFilter, limit)
companion object {
private const val LIMIT_PARAM = "limit"
private const val EXTERNAL_MEASUREMENT_CONSUMER_ID_PARAM = "externalMeasurementConsumerId"
private const val EXTERNAL_MEASUREMENT_CONSUMER_CERTIFICATE_ID_PARAM =
"externalMeasurementConsumerCertificateId"
private const val UPDATED_AFTER = "updatedAfter"
private const val UPDATED_BEFORE = "updatedBefore"
private const val CREATED_BEFORE = "createdBefore"
private const val CREATED_AFTER = "createdAfter"
private const val STATES_PARAM = "states"
private const val DUCHY_ID_PARAM = "duchyId"
private object AfterParams {
const val UPDATE_TIME = "after_updateTime"
const val EXTERNAL_MEASUREMENT_CONSUMER_ID = "after_externalMeasurementConsumerId"
const val EXTERNAL_MEASUREMENT_ID = "after_externalMeasurementId"
const val EXTERNAL_COMPUTATION_ID = "after_externalComputationId"
}
private fun buildReader(
view: Measurement.View,
requestFilter: StreamMeasurementsRequest.Filter,
limit: Int,
): MeasurementReader {
val orderByClause = getOrderByClause(view)
return MeasurementReader(view).apply {
this.orderByClause = orderByClause
fillStatementBuilder {
appendWhereClause(requestFilter)
appendClause(orderByClause)
if (limit > 0) {
appendClause("LIMIT @$LIMIT_PARAM")
bind(LIMIT_PARAM to limit.toLong())
}
}
}
}
private fun getOrderByClause(view: Measurement.View): String {
return when (view) {
Measurement.View.COMPUTATION ->
"ORDER BY Measurements.UpdateTime ASC, ExternalComputationId ASC"
Measurement.View.DEFAULT,
Measurement.View.FULL ->
"ORDER BY Measurements.UpdateTime ASC, ExternalMeasurementConsumerId ASC, " +
"ExternalMeasurementId ASC"
Measurement.View.UNRECOGNIZED -> error("Unrecognized View")
}
}
private fun Statement.Builder.appendWhereClause(filter: StreamMeasurementsRequest.Filter) {
val conjuncts = mutableListOf<String>()
if (filter.externalMeasurementConsumerId != 0L) {
conjuncts.add("ExternalMeasurementConsumerId = @$EXTERNAL_MEASUREMENT_CONSUMER_ID_PARAM")
bind(EXTERNAL_MEASUREMENT_CONSUMER_ID_PARAM to filter.externalMeasurementConsumerId)
}
if (filter.externalMeasurementConsumerCertificateId != 0L) {
conjuncts.add(
"""
@$EXTERNAL_MEASUREMENT_CONSUMER_CERTIFICATE_ID_PARAM IN (
SELECT ExternalMeasurementConsumerCertificateId
FROM MeasurementConsumerCertificates
WHERE
MeasurementConsumerCertificates.MeasurementConsumerId = Measurements.MeasurementConsumerId
AND MeasurementConsumerCertificates.CertificateId = Measurements.CertificateId
)
"""
.trimIndent()
)
bind(
EXTERNAL_MEASUREMENT_CONSUMER_CERTIFICATE_ID_PARAM to
filter.externalMeasurementConsumerCertificateId
)
}
if (filter.statesValueList.isNotEmpty()) {
conjuncts.add("Measurements.State IN UNNEST(@$STATES_PARAM)")
bind(STATES_PARAM).toInt64Array(filter.statesValueList.map { it.toLong() })
}
if (filter.hasUpdatedAfter()) {
conjuncts.add("Measurements.UpdateTime > @$UPDATED_AFTER")
bind(UPDATED_AFTER).to(filter.updatedAfter.toGcloudTimestamp())
}
if (filter.hasUpdatedBefore()) {
conjuncts.add("Measurements.UpdateTime < @$UPDATED_BEFORE")
bind(UPDATED_BEFORE to filter.updatedBefore.toGcloudTimestamp())
}
if (filter.hasCreatedBefore()) {
conjuncts.add("Measurements.CreateTime < @$CREATED_BEFORE")
bind(CREATED_BEFORE to filter.createdBefore.toGcloudTimestamp())
}
if (filter.hasCreatedAfter()) {
conjuncts.add("Measurements.CreateTime > @$CREATED_AFTER")
bind(CREATED_AFTER to filter.createdAfter.toGcloudTimestamp())
}
if (filter.externalDuchyId.isNotEmpty()) {
val duchyId: Long =
DuchyIds.getInternalId(filter.externalDuchyId)
?: throw DuchyNotFoundException(filter.externalDuchyId)
conjuncts.add(
"""
@$DUCHY_ID_PARAM IN (
SELECT DuchyId
FROM ComputationParticipants
WHERE
ComputationParticipants.MeasurementConsumerId = Measurements.MeasurementConsumerId
AND ComputationParticipants.MeasurementId = Measurements.MeasurementId
)
"""
.trimIndent()
)
bind(DUCHY_ID_PARAM).to(duchyId)
}
if (filter.hasAfter()) {
@Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") // Protobuf case fields cannot be null.
when (filter.after.keyCase) {
StreamMeasurementsRequest.Filter.After.KeyCase.MEASUREMENT -> {
// CASE implements short-circuiting, which fixes performance issues with this filter.
conjuncts.add(
"""
CASE
WHEN Measurements.UpdateTime > @${AfterParams.UPDATE_TIME} THEN TRUE
WHEN Measurements.UpdateTime = @${AfterParams.UPDATE_TIME}
AND ExternalMeasurementConsumerId > @${AfterParams.EXTERNAL_MEASUREMENT_CONSUMER_ID} THEN TRUE
WHEN Measurements.UpdateTime = @${AfterParams.UPDATE_TIME}
AND ExternalMeasurementConsumerId = @${AfterParams.EXTERNAL_MEASUREMENT_CONSUMER_ID}
AND ExternalMeasurementId > @${AfterParams.EXTERNAL_MEASUREMENT_ID} THEN TRUE
ELSE FALSE
END
"""
.trimIndent()
)
bind(AfterParams.UPDATE_TIME).to(filter.after.updateTime.toGcloudTimestamp())
bind(
AfterParams.EXTERNAL_MEASUREMENT_CONSUMER_ID to
filter.after.measurement.externalMeasurementConsumerId
)
bind(
AfterParams.EXTERNAL_MEASUREMENT_ID to filter.after.measurement.externalMeasurementId
)
}
StreamMeasurementsRequest.Filter.After.KeyCase.COMPUTATION -> {
conjuncts.add(
"""
(
Measurements.UpdateTime > @${AfterParams.UPDATE_TIME}
OR (
Measurements.UpdateTime = @${AfterParams.UPDATE_TIME}
AND ExternalComputationId > @${AfterParams.EXTERNAL_COMPUTATION_ID}
)
)
"""
.trimIndent()
)
bind(AfterParams.UPDATE_TIME).to(filter.after.updateTime.toGcloudTimestamp())
bind(
AfterParams.EXTERNAL_COMPUTATION_ID to filter.after.computation.externalComputationId
)
}
StreamMeasurementsRequest.Filter.After.KeyCase.KEY_NOT_SET ->
throw IllegalArgumentException("key not set")
}
}
if (filter.hasAfter() || filter.hasUpdatedAfter()) {
// Include shard ID to use sharded index on UpdateTime appropriately.
conjuncts.add("MeasurementIndexShardId != -1")
}
if (conjuncts.isEmpty()) {
return
}
appendClause("WHERE ")
append(conjuncts.joinToString(" AND "))
}
}
}
| 150
|
Kotlin
|
11
| 36
|
ba2d2d8d3d4527d844e6d168273b1c2fabfd5d4e
| 8,999
|
cross-media-measurement
|
Apache License 2.0
|
kotlin-react-router/src/jsMain/generated/react/router/UseRevalidatorResult.kt
|
JetBrains
| 93,250,841
| false
|
{"Kotlin": 12635434, "JavaScript": 423801}
|
// Generated by Karakum - do not modify it manually!
package react.router
import remix.run.router.RevalidationState
sealed external interface UseRevalidatorResult {
var revalidate: () -> Unit
var state: RevalidationState
}
| 38
|
Kotlin
|
162
| 1,347
|
997ed3902482883db4a9657585426f6ca167d556
| 234
|
kotlin-wrappers
|
Apache License 2.0
|
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/entityresolution/CfnIdMappingWorkflowDsl.kt
|
cloudshiftinc
| 667,063,030
| false
|
{"Kotlin": 70198112}
|
@file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.entityresolution
import io.cloudshiftdev.awscdkdsl.CfnTagDsl
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.Any
import kotlin.String
import kotlin.Unit
import kotlin.collections.Collection
import kotlin.collections.MutableList
import software.amazon.awscdk.CfnTag
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.entityresolution.CfnIdMappingWorkflow
import software.constructs.Construct
/**
* Creates an `IdMappingWorkflow` object which stores the configuration of the data processing job
* to be run.
*
* Each `IdMappingWorkflow` must have a unique workflow name. To modify an existing workflow, use
* the `UpdateIdMappingWorkflow` API.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.entityresolution.*;
* CfnIdMappingWorkflow cfnIdMappingWorkflow = CfnIdMappingWorkflow.Builder.create(this,
* "MyCfnIdMappingWorkflow")
* .idMappingTechniques(IdMappingTechniquesProperty.builder()
* .idMappingType("idMappingType")
* .providerProperties(ProviderPropertiesProperty.builder()
* .providerServiceArn("providerServiceArn")
* // the properties below are optional
* .intermediateSourceConfiguration(IntermediateSourceConfigurationProperty.builder()
* .intermediateS3Path("intermediateS3Path")
* .build())
* .providerConfiguration(Map.of(
* "providerConfigurationKey", "providerConfiguration"))
* .build())
* .build())
* .inputSourceConfig(List.of(IdMappingWorkflowInputSourceProperty.builder()
* .inputSourceArn("inputSourceArn")
* .schemaArn("schemaArn")
* .build()))
* .outputSourceConfig(List.of(IdMappingWorkflowOutputSourceProperty.builder()
* .outputS3Path("outputS3Path")
* // the properties below are optional
* .kmsArn("kmsArn")
* .build()))
* .roleArn("roleArn")
* .workflowName("workflowName")
* // the properties below are optional
* .description("description")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-idmappingworkflow.html)
*/
@CdkDslMarker
public class CfnIdMappingWorkflowDsl(
scope: Construct,
id: String,
) {
private val cdkBuilder: CfnIdMappingWorkflow.Builder =
CfnIdMappingWorkflow.Builder.create(scope, id)
private val _inputSourceConfig: MutableList<Any> = mutableListOf()
private val _outputSourceConfig: MutableList<Any> = mutableListOf()
private val _tags: MutableList<CfnTag> = mutableListOf()
/**
* A description of the workflow.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-idmappingworkflow.html#cfn-entityresolution-idmappingworkflow-description)
*
* @param description A description of the workflow.
*/
public fun description(description: String) {
cdkBuilder.description(description)
}
/**
* An object which defines the `idMappingType` and the `providerProperties` .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-idmappingworkflow.html#cfn-entityresolution-idmappingworkflow-idmappingtechniques)
*
* @param idMappingTechniques An object which defines the `idMappingType` and the
* `providerProperties` .
*/
public fun idMappingTechniques(idMappingTechniques: IResolvable) {
cdkBuilder.idMappingTechniques(idMappingTechniques)
}
/**
* An object which defines the `idMappingType` and the `providerProperties` .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-idmappingworkflow.html#cfn-entityresolution-idmappingworkflow-idmappingtechniques)
*
* @param idMappingTechniques An object which defines the `idMappingType` and the
* `providerProperties` .
*/
public fun idMappingTechniques(
idMappingTechniques: CfnIdMappingWorkflow.IdMappingTechniquesProperty
) {
cdkBuilder.idMappingTechniques(idMappingTechniques)
}
/**
* A list of `InputSource` objects, which have the fields `InputSourceARN` and `SchemaName` .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-idmappingworkflow.html#cfn-entityresolution-idmappingworkflow-inputsourceconfig)
*
* @param inputSourceConfig A list of `InputSource` objects, which have the fields
* `InputSourceARN` and `SchemaName` .
*/
public fun inputSourceConfig(vararg inputSourceConfig: Any) {
_inputSourceConfig.addAll(listOf(*inputSourceConfig))
}
/**
* A list of `InputSource` objects, which have the fields `InputSourceARN` and `SchemaName` .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-idmappingworkflow.html#cfn-entityresolution-idmappingworkflow-inputsourceconfig)
*
* @param inputSourceConfig A list of `InputSource` objects, which have the fields
* `InputSourceARN` and `SchemaName` .
*/
public fun inputSourceConfig(inputSourceConfig: Collection<Any>) {
_inputSourceConfig.addAll(inputSourceConfig)
}
/**
* A list of `InputSource` objects, which have the fields `InputSourceARN` and `SchemaName` .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-idmappingworkflow.html#cfn-entityresolution-idmappingworkflow-inputsourceconfig)
*
* @param inputSourceConfig A list of `InputSource` objects, which have the fields
* `InputSourceARN` and `SchemaName` .
*/
public fun inputSourceConfig(inputSourceConfig: IResolvable) {
cdkBuilder.inputSourceConfig(inputSourceConfig)
}
/**
* A list of `IdMappingWorkflowOutputSource` objects, each of which contains fields
* `OutputS3Path` and `Output` .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-idmappingworkflow.html#cfn-entityresolution-idmappingworkflow-outputsourceconfig)
*
* @param outputSourceConfig A list of `IdMappingWorkflowOutputSource` objects, each of which
* contains fields `OutputS3Path` and `Output` .
*/
public fun outputSourceConfig(vararg outputSourceConfig: Any) {
_outputSourceConfig.addAll(listOf(*outputSourceConfig))
}
/**
* A list of `IdMappingWorkflowOutputSource` objects, each of which contains fields
* `OutputS3Path` and `Output` .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-idmappingworkflow.html#cfn-entityresolution-idmappingworkflow-outputsourceconfig)
*
* @param outputSourceConfig A list of `IdMappingWorkflowOutputSource` objects, each of which
* contains fields `OutputS3Path` and `Output` .
*/
public fun outputSourceConfig(outputSourceConfig: Collection<Any>) {
_outputSourceConfig.addAll(outputSourceConfig)
}
/**
* A list of `IdMappingWorkflowOutputSource` objects, each of which contains fields
* `OutputS3Path` and `Output` .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-idmappingworkflow.html#cfn-entityresolution-idmappingworkflow-outputsourceconfig)
*
* @param outputSourceConfig A list of `IdMappingWorkflowOutputSource` objects, each of which
* contains fields `OutputS3Path` and `Output` .
*/
public fun outputSourceConfig(outputSourceConfig: IResolvable) {
cdkBuilder.outputSourceConfig(outputSourceConfig)
}
/**
* The Amazon Resource Name (ARN) of the IAM role.
*
* AWS Entity Resolution assumes this role to create resources on your behalf as part of
* workflow execution.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-idmappingworkflow.html#cfn-entityresolution-idmappingworkflow-rolearn)
*
* @param roleArn The Amazon Resource Name (ARN) of the IAM role.
*/
public fun roleArn(roleArn: String) {
cdkBuilder.roleArn(roleArn)
}
/**
* The tags used to organize, track, or control access for this resource.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-idmappingworkflow.html#cfn-entityresolution-idmappingworkflow-tags)
*
* @param tags The tags used to organize, track, or control access for this resource.
*/
public fun tags(tags: CfnTagDsl.() -> Unit) {
_tags.add(CfnTagDsl().apply(tags).build())
}
/**
* The tags used to organize, track, or control access for this resource.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-idmappingworkflow.html#cfn-entityresolution-idmappingworkflow-tags)
*
* @param tags The tags used to organize, track, or control access for this resource.
*/
public fun tags(tags: Collection<CfnTag>) {
_tags.addAll(tags)
}
/**
* The name of the workflow.
*
* There can't be multiple `IdMappingWorkflows` with the same name.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-entityresolution-idmappingworkflow.html#cfn-entityresolution-idmappingworkflow-workflowname)
*
* @param workflowName The name of the workflow.
*/
public fun workflowName(workflowName: String) {
cdkBuilder.workflowName(workflowName)
}
public fun build(): CfnIdMappingWorkflow {
if (_inputSourceConfig.isNotEmpty()) cdkBuilder.inputSourceConfig(_inputSourceConfig)
if (_outputSourceConfig.isNotEmpty()) cdkBuilder.outputSourceConfig(_outputSourceConfig)
if (_tags.isNotEmpty()) cdkBuilder.tags(_tags)
return cdkBuilder.build()
}
}
| 0
|
Kotlin
|
0
| 3
|
256ad92aebe2bcf9a4160089a02c76809dbbedba
| 10,536
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
src/main/kotlin/com/github/adriantodt/dragontech/block/virus/AliveVirusOreBlock.kt
|
annathelibri
| 51,792,240
| false
|
{"Kotlin": 39662, "Java": 1375}
|
package com.github.adriantodt.dragontech.block.virus
import com.github.adriantodt.dragontech.dracony.DraconyVirus
import net.minecraft.block.Block
import net.minecraft.block.BlockState
import net.minecraft.enchantment.EnchantmentHelper
import net.minecraft.enchantment.Enchantments
import net.minecraft.item.ItemStack
import net.minecraft.server.world.ServerWorld
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
import java.util.*
class AliveVirusOreBlock(settings: Settings, private val expFun: (Random) -> Int = { 0 }) : Block(settings) {
override fun onStacksDropped(state: BlockState, world: World, pos: BlockPos, stack: ItemStack) {
if (EnchantmentHelper.getLevel(
Enchantments.SILK_TOUCH,
stack
) == 0) {
val i = expFun(world.random)
if (i > 0) {
dropExperience(world, pos, i)
}
}
}
override fun randomTick(state: BlockState, world: ServerWorld, pos: BlockPos, random: Random) {
DraconyVirus.virusTick(world, pos)
}
override fun rainTick(world: World, pos: BlockPos) {
DraconyVirus.virusRainTick(world, pos)
}
}
| 1
|
Kotlin
|
0
| 1
|
bc48a187d11876f7fd04601f058d2210f24669d8
| 1,198
|
DragonTech
|
Creative Commons Zero v1.0 Universal
|
compiler/testData/diagnostics/tests/dataFlow/IsExpression.fir.kt
|
android
| 263,405,600
| false
| null |
fun f(a: Boolean, b: Int) {}
fun foo(a: Any) {
<!INAPPLICABLE_CANDIDATE!>f<!>(a is Int, a)
1 <!INAPPLICABLE_CANDIDATE!>+<!> a
}
| 1
| null |
37
| 316
|
74126637a097f5e6b099a7b7a4263468ecfda144
| 136
|
kotlin
|
Apache License 2.0
|
src/main/kotlin/examples/modules/ProcessingExample.kt
|
radianceteam
| 306,208,297
| false
| null |
package examples.modules
import com.radiance.tonclient.Abi
import com.radiance.tonclient.await
import examples.Helper
import java.util.concurrent.atomic.AtomicInteger
class ProcessingExample {
suspend fun waitMessage() {
val keys = Helper.crypto.generateRandomSignKeys().await()
val encoded = Helper.abi.encodeMessage(Helper.eventsAbi, null, Abi.DeploySet(Helper.eventsTvc, null, null),Abi.CallSet("constructor", Abi.FunctionHeader(Int.MAX_VALUE, null, keys.public), null), Abi.Signer.Keys(keys), null).await()
Helper.getGramsFromGiver(encoded.address)!!.await()
var events = listOf<String>()
val transCounter = AtomicInteger()
val subscription = Helper.net.subscribeCollection("transactions", null, "id account_addr") { event ->
if (event.result.findValue("account_addr").asText() == encoded.address) {
transCounter.incrementAndGet()
}
}.await()
val blockId = Helper.processing.sendMessage(encoded.message, Helper.eventsAbi, true) { event ->
events.plus(event.type)
}.await()
// -- there is currently an issue with the time out
// Helper.processing.waitForTransaction(Helper.eventsAbi, encoded.message, blockId, true) { event ->
// events.plus(event.type)
// }.await()
Helper.net.unsubscribe(subscription).await()
Helper.assertNotEquals("Transaction counter", transCounter.get(), 0)
}
}
| 0
|
Kotlin
|
1
| 2
|
c9e2f2fcc2a1b7d1bf307246f2034e7186378644
| 1,483
|
ton-client-kotlin
|
Apache License 2.0
|
module-configuration/module-configuration-core/src/main/kotlin/taboolib/module/configuration/util/SectionToMap.kt
|
TabooLib
| 457,856,137
| false
|
{"Kotlin": 536645, "Java": 319776}
|
@file:Isolated
package taboolib.module.configuration.util
import taboolib.common.Isolated
import taboolib.library.configuration.ConfigurationSection
fun <V> ConfigurationSection.getMapAs(path: String = "", transfer: Any.() -> V): Map<String, V> {
return getMap<String, Any>(path).map { it.key to transfer(it.value) }.toMap()
}
@Suppress("UNCHECKED_CAST")
fun <K, V> ConfigurationSection.getMap(path: String = ""): Map<K, V> {
val map = HashMap<K, V>()
getConfigurationSection(path)?.let { section ->
section.getKeys(false).forEach { key ->
try {
map[key as K] = section[key] as V
} catch (ex: Throwable) {
ex.printStackTrace()
}
}
}
return map
}
| 0
|
Kotlin
|
0
| 1
|
26aa5b91bc8e515a10652ca6d4c92e4a196005aa
| 753
|
taboolib-modules
|
MIT License
|
kool-editor-model/src/commonMain/kotlin/de/fabmax/kool/editor/components/MaterialComponent.kt
|
kool-engine
| 81,503,047
| false
| null |
package de.fabmax.kool.editor.components
import de.fabmax.kool.editor.api.*
import de.fabmax.kool.editor.data.ComponentInfo
import de.fabmax.kool.editor.data.EntityId
import de.fabmax.kool.editor.data.MaterialComponentData
import de.fabmax.kool.editor.data.MaterialShaderData
import de.fabmax.kool.modules.ksl.KslShader
import de.fabmax.kool.modules.ksl.ModelMatrixComposition
import de.fabmax.kool.scene.Mesh
import de.fabmax.kool.util.launchOnMainThread
import de.fabmax.kool.util.logT
import de.fabmax.kool.util.logW
class MaterialComponent(
gameEntity: GameEntity,
componentInfo: ComponentInfo<MaterialComponentData>
) :
GameEntityDataComponent<MaterialComponentData>(gameEntity, componentInfo),
EditorScene.SceneShaderDataListener
{
val id: EntityId get() = gameEntity.id
val name: String get() = gameEntity.name
val shaderData: MaterialShaderData get() = data.shaderData
private val listeners by cachedProjectComponents<ListenerComponent>()
suspend fun applyMaterialTo(mesh: Mesh, sceneShaderData: SceneShaderData, modelMats: List<ModelMatrixComposition>): Boolean {
mesh.isCastingShadow = shaderData.genericSettings.isCastingShadow
val meshKey = MeshLayoutKey(mesh)
val shader = sceneShaderData.shaderCache.getOrPutShaderCache(this).getOrPut(meshKey) {
logT { "Creating new material shader $name (for mesh: ${mesh.name})" }
data.createShader(sceneShaderData, modelMats)
}
if (mesh.shader == shader) {
return true
}
if (shader is KslShader && shader.findRequiredVertexAttributes().any { it !in mesh.geometry.vertexAttributes }) {
val missing = shader.findRequiredVertexAttributes() - mesh.geometry.vertexAttributes.toSet()
logW { "Material $name: Unable to apply material to mesh ${mesh.name}, missing attributes: $missing" }
return false
}
mesh.shader = shader
return true
}
override fun setPersistent(componentData: MaterialComponentData) {
super.setPersistent(componentData)
gameEntity.setPersistent(gameEntity.entityData.settings.copy(name = componentData.name))
}
override fun onDataChanged(oldData: MaterialComponentData, newData: MaterialComponentData) {
gameEntity.name = newData.name
launchOnMainThread {
project.createdScenes.values.forEach { scene ->
scene.shaderData.shaderCache.getShaderCache(this)?.let { shaders ->
val removeShaders = shaders.values.filter { !newData.updateShader(it, scene.shaderData) }
shaders.values -= removeShaders.toSet()
}
}
listeners.forEach { it.onMaterialChanged(this, data) }
}
}
override fun onSceneShaderDataChanged(scene: EditorScene, sceneShaderData: SceneShaderData) {
val sceneShaders = scene.shaderData.shaderCache.getShaderCache(this) ?: return
launchOnMainThread {
val removeShaders = sceneShaders.values.filter { !data.updateShader(it, sceneShaderData) }
sceneShaders.values -= removeShaders.toSet()
listeners.forEach { it.onMaterialChanged(this, data) }
}
}
companion object {
const val DEFAULT_MATERIAL_NAME = "<\\Default/>"
}
fun interface ListenerComponent {
suspend fun onMaterialChanged(component: MaterialComponent, materialData: MaterialComponentData)
}
}
fun MaterialComponent.isDefaultMaterial(): Boolean {
return name == MaterialComponent.DEFAULT_MATERIAL_NAME
}
| 11
| null |
20
| 303
|
8d05acd3e72ff2fc115d0939bf021a5f421469a5
| 3,606
|
kool
|
Apache License 2.0
|
precompose/src/commonMain/kotlin/moe/tlaster/precompose/navigation/BackStackEntry.kt
|
Tlaster
| 349,750,473
| false
| null |
package moe.tlaster.precompose.navigation
import moe.tlaster.precompose.lifecycle.Lifecycle
import moe.tlaster.precompose.lifecycle.LifecycleOwner
import moe.tlaster.precompose.lifecycle.LifecycleRegistry
import moe.tlaster.precompose.navigation.route.ComposeRoute
import moe.tlaster.precompose.navigation.route.SceneRoute
import moe.tlaster.precompose.navigation.transition.NavTransition
import moe.tlaster.precompose.viewmodel.ViewModelStore
import moe.tlaster.precompose.viewmodel.ViewModelStoreOwner
class BackStackEntry internal constructor(
val id: Long,
val route: ComposeRoute,
val path: String,
val pathMap: Map<String, String>,
val queryString: QueryString? = null,
internal val viewModel: NavControllerViewModel,
) : ViewModelStoreOwner, LifecycleOwner {
private var destroyAfterTransition = false
internal val navTransition: NavTransition?
get() = if (route is SceneRoute) route.navTransition else null
override val viewModelStore: ViewModelStore
get() = viewModel.get(id = id)
private val lifecycleRegistry by lazy {
LifecycleRegistry()
}
override val lifecycle: Lifecycle
get() = lifecycleRegistry
fun active() {
lifecycleRegistry.currentState = Lifecycle.State.Active
}
fun inActive() {
lifecycleRegistry.currentState = Lifecycle.State.InActive
if (destroyAfterTransition) {
destroy()
}
}
fun destroy() {
if (lifecycleRegistry.currentState != Lifecycle.State.InActive) {
destroyAfterTransition = true
} else {
lifecycleRegistry.currentState = Lifecycle.State.Destroyed
viewModelStore.clear()
}
}
fun hasRoute(route: String): Boolean {
return this.route.route == route
}
}
internal inline fun BackStackEntry.hasRoute(route: String, path: String, includePath: Boolean): Boolean {
return if (includePath) {
hasRoute(route = route) && this.path == path
} else {
hasRoute(route = route)
}
}
inline fun <reified T> BackStackEntry.path(path: String, default: T? = null): T? {
val value = pathMap[path] ?: return default
return convertValue(value)
}
inline fun <reified T> BackStackEntry.query(name: String, default: T? = null): T? {
return queryString?.query(name, default)
}
inline fun <reified T> BackStackEntry.queryList(name: String): List<T?> {
val value = queryString?.map?.get(name) ?: return emptyList()
return value.map { convertValue(it) }
}
inline fun <reified T> convertValue(value: String): T? {
return when (T::class) {
Int::class -> value.toIntOrNull()
Long::class -> value.toLongOrNull()
String::class -> value
Boolean::class -> value.toBooleanStrictOrNull()
Float::class -> value.toFloatOrNull()
Double::class -> value.toDoubleOrNull()
else -> throw NotImplementedError()
} as T
}
| 3
| null |
14
| 201
|
fec3ff13d1b7862b3aa944f0ff49511a336bcb83
| 2,958
|
PreCompose
|
MIT License
|
sample/src/main/java/cn/thens/kdroid/sample/test/TestRefreshActivity.kt
|
7hens
| 83,793,536
| false
| null |
package cn.thens.kdroid.sample.test
import android.os.Bundle
import androidx.recyclerview.widget.GridLayoutManager
import cn.thens.kdroid.sample.R
import cn.thens.kdroid.sample.common.app.BaseActivity
import cn.thens.kdroid.sample.launcher.AppItemAdapter
import kotlinx.android.synthetic.main.activity_test_refresh.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class TestRefreshActivity : BaseActivity() {
private val appItemAdapter by lazy { AppItemAdapter() }
private val context = this
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_test_refresh)
vList.adapter = appItemAdapter
vList.layoutManager = GridLayoutManager(this, 4)
appItemAdapter.refill(AppItemAdapter.getAppList(this))
vRefreshLayout.setOnRefreshListener {
launch {
delay(1000L)
val appList = AppItemAdapter.getAppList(context)
appItemAdapter.refill(appList)
vRefreshLayout.finishRefresh()
}
}
vRefreshLayout.setOnLoadmoreListener {
launch {
delay(1000L)
val appList = AppItemAdapter.getAppList(context)
appItemAdapter.addAll(appList)
appItemAdapter.notifyDataSetChanged()
vRefreshLayout.finishLoadmore()
}
}
}
override fun onResume() {
super.onResume()
}
fun testError() {
Thread { makeError() }.start()
makeError()
}
fun makeError() {
val list = ArrayList<Int>()
list[1]
}
}
| 1
| null |
1
| 2
|
7cca59e8b5074bf2f628d2a0fb48c96f33953bc3
| 1,688
|
kdroid
|
Apache License 2.0
|
libs/navigation/core/src/commonMain/kotlin/com/edugma/navigation/core/compose/ComposeArgumentsStore.kt
|
Edugma
| 474,423,768
| false
|
{"Kotlin": 1065114, "Swift": 1255, "Shell": 331, "HTML": 299}
|
package com.edugma.navigation.core.compose
import androidx.core.bundle.Bundle
import com.edugma.navigation.core.destination.ArgumentsStore
class ComposeArgumentsStore(
private val arguments: Bundle,
) : ArgumentsStore {
@Suppress("UNCHECKED_CAST", "DEPRECATION")
override fun <T> get(key: String): T? {
return arguments.get(key) as T
}
}
| 1
|
Kotlin
|
0
| 3
|
d9149728b9dee61606d7c46d80bc474a77f46362
| 364
|
app
|
MIT License
|
sample-android/src/main/java/com/mobilejazz/kmmsample/application/ui/common/ExceptionToStringMapperExt.kt
|
mobilejazz
| 193,985,847
| false
| null |
package com.mobilejazz.kmmsample.application.ui.common
import android.content.Context
import com.harmony.kotlin.data.datasource.network.error.NetworkConnectivityException
import com.mobilejazz.kmmsample.application.R
fun Throwable.toLocalizedErrorMessage(context: Context) =
context.getString(
when (this) {
is NetworkConnectivityException -> R.string.ls_generic_connectivity_error_message
else -> R.string.ls_generic_error_message
}
)
| 4
|
Kotlin
|
0
| 8
|
19ca40a45392578a4724020327c096c841d3a460
| 462
|
harmony-kotlin
|
Apache License 2.0
|
app/src/main/java/org/stepic/droid/di/course_list/CourseListScope.kt
|
Ujjawal-Anand
| 142,415,269
| false
| null |
package org.stepic.droid.di.course_list
import javax.inject.Scope
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class CourseListScope
| 0
| null |
0
| 1
|
256a90051eefe8db83f7053914004905bbb1f8d0
| 148
|
stepik-android
|
Apache License 2.0
|
app/src/main/java/com/chandistudios/taskrapid/ui/task/add/AddTask.kt
|
chubozeko
| 491,210,477
| false
|
{"Kotlin": 149040}
|
package com.chandistudios.taskrapid.ui.task.add
import android.os.Build
import android.util.Log
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.Icon
import androidx.compose.material.icons.filled.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.chandistudios.taskrapid.data.entity.Task
import com.chandistudios.taskrapid.data.entity.TaskType
import com.chandistudios.taskrapid.ui.task.*
import com.google.accompanist.insets.systemBarsPadding
import com.google.android.gms.maps.model.LatLng
import kotlinx.coroutines.launch
import java.util.TimeZone
@RequiresApi(Build.VERSION_CODES.O)
@Composable
fun AddTask(
onBackPress: () -> Unit,
navController: NavController,
viewModel: AddTaskViewModel = viewModel(),
) {
val viewState by viewModel.state.collectAsState()
val coroutineScope = rememberCoroutineScope()
Surface {
val name = rememberSaveable { mutableStateOf("") }
val description = rememberSaveable { mutableStateOf("") }
val icon = rememberSaveable { mutableStateOf<Long>(0) }
val date = rememberSaveable { mutableStateOf("") }
val time = rememberSaveable { mutableStateOf("") }
val locationX = rememberSaveable { mutableStateOf("") }
val locationY = rememberSaveable { mutableStateOf("") }
val taskType = rememberSaveable { mutableStateOf("") }
val addNotiTime = rememberSaveable { mutableStateOf(false) }
val notiTime = rememberSaveable { mutableStateOf("") }
val notiTimeValue = rememberSaveable { mutableStateOf<Long>(0) }
val context = LocalContext.current
val latlng = navController
.currentBackStackEntry
?.savedStateHandle
?.getLiveData<LatLng>("location_data")
?.value
Column(
modifier = Modifier
.fillMaxSize()
.systemBarsPadding()
) {
TopAppBar {
IconButton(
onClick = { onBackPress() },
) {
Icon(
imageVector = Icons.Default.ArrowBack,
contentDescription = null
)
}
Text(text = "Add New Task: " + name.value)
}
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top,
modifier = Modifier.padding(16.dp)
) {
OutlinedTextField(
value = name.value,
onValueChange = { data -> name.value = data },
label = { Text(text = "Task Name")},
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(8.dp))
OutlinedTextField(
value = description.value,
onValueChange = { data -> description.value = data },
label = { Text(text = "Task Description")},
modifier = Modifier.fillMaxWidth(),
singleLine = false,
maxLines = 2
)
Spacer(modifier = Modifier.height(8.dp))
Row (
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceEvenly,
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
) {
Text(
text = "Select Task Icon: ",
maxLines = 1,
style = MaterialTheme.typography.body1,
)
Spacer(modifier = Modifier.width(8.dp))
IconDropdown(
taskIcons = viewState.taskIcons,
icon = icon
)
}
Spacer(modifier = Modifier.height(8.dp))
DatePicker(
context = context,
date = date
)
TimePicker(
context = context,
time = time
)
Spacer(modifier = Modifier.height(8.dp))
Row (
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceEvenly
) {
Text(
text = "Task Location: ",
maxLines = 1,
style = MaterialTheme.typography.body1,
)
Spacer(modifier = Modifier.width(8.dp))
// OutlinedTextField(
// value = description.value,
// onValueChange = { data -> description.value = data },
// label = { Text(text = "Task Description")},
// singleLine = false,
// maxLines = 2
// )
// Spacer(modifier = Modifier.width(8.dp))
if (latlng == null) {
OutlinedButton(
onClick = { navController.navigate("map") },
modifier = Modifier.height(55.dp))
{
Text(text = "Select location...")
}
} else {
Text(text = "Lat: ${latlng.latitude}; \nLong: ${latlng.longitude}")
}
}
// Text(
// text = "Lat: " + locationX.value + ", Long: " + locationY.value,
// maxLines = 1,
// style = MaterialTheme.typography.body1,
// )
Spacer(modifier = Modifier.height(8.dp))
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceEvenly,
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
) {
Text(
text = "Task Importance: ",
maxLines = 1,
style = MaterialTheme.typography.body1,
)
Spacer(modifier = Modifier.width(8.dp))
TypeDropdown(
taskTypes = viewState.taskTypes,
type = taskType
)
}
Spacer(modifier = Modifier.height(12.dp))
/*TODO (HW3): Add reminder notification options*/
if (time.value != "") {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceEvenly,
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
) {
Checkbox(
checked = addNotiTime.value,
onCheckedChange = { data -> addNotiTime.value = data }
)
Text(text = "Add reminder notification")
}
}
Spacer(modifier = Modifier.height(8.dp))
if (addNotiTime.value) {
NotificationDropdown(
notiTimes = viewState.notiTimes,
notiTimeValue = notiTimeValue
)
}
Spacer(modifier = Modifier.height(12.dp))
Button(
onClick = {
if (name.value != "" && taskType.value != "") {
Log.i("AddTask",
"Notification time: " + parseNotificationTime(time.value, notiTimeValue.value) +
" ; Task Time: " + time.value.toTime().time.toTimeString() +
" ; timezone offset: " + getGMTOffset())
coroutineScope.launch {
viewModel.saveTask(
Task(
taskName = name.value,
taskDescription = description.value,
taskIcon = icon.value,
taskDate = date.value,
taskTime = time.value,
locationX = locationX.value,
locationY = locationY.value,
taskTypeId = getTaskTypeId(
viewState.taskTypes,
taskType.value
),
taskNoti = when(addNotiTime.value) {
true -> 1
else -> 0
},
notificationTime = parseNotificationTime(time.value, notiTimeValue.value),
notiTimeValue = notiTimeValue.value
)
)
}
Toast.makeText(context,"Task '${name.value}' has been Added!", Toast.LENGTH_SHORT).show()
onBackPress()
} else {
Toast.makeText(context,"Task Name and Type CANNOT be empty!", Toast.LENGTH_LONG).show()
}
},
colors = ButtonDefaults.buttonColors(backgroundColor = MaterialTheme.colors.secondary),
modifier = Modifier
.fillMaxWidth()
.size(55.dp)
) {
Text("Save Task")
}
}
}
}
}
private fun getTaskTypeId(types: List<TaskType>, taskType: String): Long {
return types.first { type -> type.name == taskType }.id
}
| 0
|
Kotlin
|
0
| 0
|
96c4ce4c2eeab713aecbb2b4997d7fc3c83937eb
| 11,440
|
TaskRapid
|
MIT License
|
app/src/main/java/com/chandistudios/taskrapid/ui/task/add/AddTask.kt
|
chubozeko
| 491,210,477
| false
|
{"Kotlin": 149040}
|
package com.chandistudios.taskrapid.ui.task.add
import android.os.Build
import android.util.Log
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.Icon
import androidx.compose.material.icons.filled.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.chandistudios.taskrapid.data.entity.Task
import com.chandistudios.taskrapid.data.entity.TaskType
import com.chandistudios.taskrapid.ui.task.*
import com.google.accompanist.insets.systemBarsPadding
import com.google.android.gms.maps.model.LatLng
import kotlinx.coroutines.launch
import java.util.TimeZone
@RequiresApi(Build.VERSION_CODES.O)
@Composable
fun AddTask(
onBackPress: () -> Unit,
navController: NavController,
viewModel: AddTaskViewModel = viewModel(),
) {
val viewState by viewModel.state.collectAsState()
val coroutineScope = rememberCoroutineScope()
Surface {
val name = rememberSaveable { mutableStateOf("") }
val description = rememberSaveable { mutableStateOf("") }
val icon = rememberSaveable { mutableStateOf<Long>(0) }
val date = rememberSaveable { mutableStateOf("") }
val time = rememberSaveable { mutableStateOf("") }
val locationX = rememberSaveable { mutableStateOf("") }
val locationY = rememberSaveable { mutableStateOf("") }
val taskType = rememberSaveable { mutableStateOf("") }
val addNotiTime = rememberSaveable { mutableStateOf(false) }
val notiTime = rememberSaveable { mutableStateOf("") }
val notiTimeValue = rememberSaveable { mutableStateOf<Long>(0) }
val context = LocalContext.current
val latlng = navController
.currentBackStackEntry
?.savedStateHandle
?.getLiveData<LatLng>("location_data")
?.value
Column(
modifier = Modifier
.fillMaxSize()
.systemBarsPadding()
) {
TopAppBar {
IconButton(
onClick = { onBackPress() },
) {
Icon(
imageVector = Icons.Default.ArrowBack,
contentDescription = null
)
}
Text(text = "Add New Task: " + name.value)
}
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top,
modifier = Modifier.padding(16.dp)
) {
OutlinedTextField(
value = name.value,
onValueChange = { data -> name.value = data },
label = { Text(text = "Task Name")},
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(8.dp))
OutlinedTextField(
value = description.value,
onValueChange = { data -> description.value = data },
label = { Text(text = "Task Description")},
modifier = Modifier.fillMaxWidth(),
singleLine = false,
maxLines = 2
)
Spacer(modifier = Modifier.height(8.dp))
Row (
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceEvenly,
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
) {
Text(
text = "Select Task Icon: ",
maxLines = 1,
style = MaterialTheme.typography.body1,
)
Spacer(modifier = Modifier.width(8.dp))
IconDropdown(
taskIcons = viewState.taskIcons,
icon = icon
)
}
Spacer(modifier = Modifier.height(8.dp))
DatePicker(
context = context,
date = date
)
TimePicker(
context = context,
time = time
)
Spacer(modifier = Modifier.height(8.dp))
Row (
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceEvenly
) {
Text(
text = "Task Location: ",
maxLines = 1,
style = MaterialTheme.typography.body1,
)
Spacer(modifier = Modifier.width(8.dp))
// OutlinedTextField(
// value = description.value,
// onValueChange = { data -> description.value = data },
// label = { Text(text = "Task Description")},
// singleLine = false,
// maxLines = 2
// )
// Spacer(modifier = Modifier.width(8.dp))
if (latlng == null) {
OutlinedButton(
onClick = { navController.navigate("map") },
modifier = Modifier.height(55.dp))
{
Text(text = "Select location...")
}
} else {
Text(text = "Lat: ${latlng.latitude}; \nLong: ${latlng.longitude}")
}
}
// Text(
// text = "Lat: " + locationX.value + ", Long: " + locationY.value,
// maxLines = 1,
// style = MaterialTheme.typography.body1,
// )
Spacer(modifier = Modifier.height(8.dp))
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceEvenly,
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
) {
Text(
text = "Task Importance: ",
maxLines = 1,
style = MaterialTheme.typography.body1,
)
Spacer(modifier = Modifier.width(8.dp))
TypeDropdown(
taskTypes = viewState.taskTypes,
type = taskType
)
}
Spacer(modifier = Modifier.height(12.dp))
/*TODO (HW3): Add reminder notification options*/
if (time.value != "") {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceEvenly,
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
) {
Checkbox(
checked = addNotiTime.value,
onCheckedChange = { data -> addNotiTime.value = data }
)
Text(text = "Add reminder notification")
}
}
Spacer(modifier = Modifier.height(8.dp))
if (addNotiTime.value) {
NotificationDropdown(
notiTimes = viewState.notiTimes,
notiTimeValue = notiTimeValue
)
}
Spacer(modifier = Modifier.height(12.dp))
Button(
onClick = {
if (name.value != "" && taskType.value != "") {
Log.i("AddTask",
"Notification time: " + parseNotificationTime(time.value, notiTimeValue.value) +
" ; Task Time: " + time.value.toTime().time.toTimeString() +
" ; timezone offset: " + getGMTOffset())
coroutineScope.launch {
viewModel.saveTask(
Task(
taskName = name.value,
taskDescription = description.value,
taskIcon = icon.value,
taskDate = date.value,
taskTime = time.value,
locationX = locationX.value,
locationY = locationY.value,
taskTypeId = getTaskTypeId(
viewState.taskTypes,
taskType.value
),
taskNoti = when(addNotiTime.value) {
true -> 1
else -> 0
},
notificationTime = parseNotificationTime(time.value, notiTimeValue.value),
notiTimeValue = notiTimeValue.value
)
)
}
Toast.makeText(context,"Task '${name.value}' has been Added!", Toast.LENGTH_SHORT).show()
onBackPress()
} else {
Toast.makeText(context,"Task Name and Type CANNOT be empty!", Toast.LENGTH_LONG).show()
}
},
colors = ButtonDefaults.buttonColors(backgroundColor = MaterialTheme.colors.secondary),
modifier = Modifier
.fillMaxWidth()
.size(55.dp)
) {
Text("Save Task")
}
}
}
}
}
private fun getTaskTypeId(types: List<TaskType>, taskType: String): Long {
return types.first { type -> type.name == taskType }.id
}
| 0
|
Kotlin
|
0
| 0
|
96c4ce4c2eeab713aecbb2b4997d7fc3c83937eb
| 11,440
|
TaskRapid
|
MIT License
|
app/src/main/java/com/mine/betterthanyourtimer/viewModels/TimerViewModel.kt
|
esthcarelle
| 639,895,606
| false
| null |
package com.mine.betterthanyourtimer.viewModels
import android.os.CountDownTimer
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
class TimerViewModel : ViewModel() {
private var timer: CountDownTimer? = null
private val _remainingTime = MutableStateFlow(totalTime)
val remainingTime: StateFlow<Long> = _remainingTime
private var _isRunning = MutableStateFlow(false)
val isRunning: StateFlow<Boolean> = _isRunning
private fun createTimer() {
timer = object : CountDownTimer(totalTime, interval) {
override fun onTick(p0: Long) {
_remainingTime.value = p0
}
override fun onFinish() {
_remainingTime.value = totalTime
_isRunning.value = false
}
}
}
fun startTimer() {
createTimer()
timer?.start()
_isRunning.value = true
}
fun onResetTimer() {
if (_isRunning.value) {
timer?.cancel()
_remainingTime.value = totalTime
_isRunning.value = false
}
}
override fun onCleared() {
super.onCleared()
timer?.cancel()
_remainingTime.value = totalTime
}
companion object {
const val totalTime = 60 * 1000L
const val interval = 1 * 1000L
}
}
| 0
|
Kotlin
|
0
| 1
|
c8abc2f5e8a1d4f9085c0cae8df1e4e15ce7a2af
| 1,403
|
BetterThanYourTimer
|
MIT License
|
pml-core/src/main/kotlin/com/luggsoft/pml/core/SelectorGrammar.kt
|
dan-lugg
| 398,328,973
| false
|
{"Kotlin": 79391, "HTML": 11490}
|
package com.luggsoft.pml.core
import com.github.h0tk3y.betterParse.combinators.and
import com.github.h0tk3y.betterParse.combinators.asJust
import com.github.h0tk3y.betterParse.combinators.leftAssociative
import com.github.h0tk3y.betterParse.combinators.map
import com.github.h0tk3y.betterParse.combinators.oneOrMore
import com.github.h0tk3y.betterParse.combinators.optional
import com.github.h0tk3y.betterParse.combinators.or
import com.github.h0tk3y.betterParse.combinators.separatedTerms
import com.github.h0tk3y.betterParse.combinators.skip
import com.github.h0tk3y.betterParse.grammar.Grammar
import com.github.h0tk3y.betterParse.grammar.parser
import com.github.h0tk3y.betterParse.lexer.RegexToken
import com.github.h0tk3y.betterParse.lexer.literalToken
import com.github.h0tk3y.betterParse.lexer.regexToken
import com.github.h0tk3y.betterParse.parser.ParseException
import com.github.h0tk3y.betterParse.parser.Parser
import com.luggsoft.pml.Selector
import com.luggsoft.pml.core.ast.AccessMemberExpression
import com.luggsoft.pml.core.ast.DeepSelectorElement
import com.luggsoft.pml.core.ast.ElementMatcher
import com.luggsoft.pml.core.ast.Expression
import com.luggsoft.pml.core.ast.FlatSelectorElement
import com.luggsoft.pml.core.ast.InvokeMemberExpression
import com.luggsoft.pml.core.ast.MemberExpression
import com.luggsoft.pml.core.ast.NameElementMatcher
import com.luggsoft.pml.core.ast.Operator
import com.luggsoft.pml.core.ast.RootExpression
import com.luggsoft.pml.core.ast.ScopedExpression
import com.luggsoft.pml.core.ast.SelectorElement
import com.luggsoft.pml.core.ast.ValueExpression
import com.luggsoft.pml.core.ast.WildElementMatcher
import com.luggsoft.pml.core.boxing.DoubleBox
import com.luggsoft.pml.core.boxing.FloatBox
import com.luggsoft.pml.core.boxing.IntBox
import com.luggsoft.pml.core.boxing.LongBox
import com.luggsoft.pml.core.boxing.StringBox
import org.intellij.lang.annotations.Language
/**
* # Selectors
*
* Selectors follow a simple syntax, as expressed below:
* ```
* _____Element,_Matcher_____
* / \
*
* ( ( '>' | '~' ) ( <name> | '*' ) ( '{' <expression> '}' )? )+
*
* \____________________/
* Optional
* Expression
* ```
*
* ## Elements
*
* `>` The element should perform a "flat" search; as in, only the direct children of the parent
*
* `~` The element should perform a "deep" search; as in, all descendants of the parent
*
* ## Matchers
*
* `<name>` The matching is done on the provided name; as in, a named match
*
* `*` The matching is done on all names; as in, a wildcard match
*
* # Expressions
*
* Expressions use a syntax similar to most C-like languages; probably most like Groovy or Kotlin.
* Expressions also follow similar operator associativity and precedence rules.
*
* `$` Refers to "this"; as in, the current context object
*
*/
class SelectorGrammar : Grammar<Selector>()
{
// <editor-fold desc="Tokens">
val spaceToken by expressionToken(pattern = "\\s*", ignore = true)
val commentToken by expressionToken(pattern = "/\\*.+?\\*/", ignore = true)
val commaToken by literalToken(text = ",")
val flatToken by literalToken(text = ">")
val deepToken by literalToken(text = "~")
val wildToken by literalToken(text = "*")
val rootToken by literalToken(text = "$")
val lParenToken by literalToken(text = "(")
val rParenToken by literalToken(text = ")")
val lBraceToken by literalToken(text = "{")
val rBraceToken by literalToken(text = "}")
val nullToken by literalToken(text = "null")
val intOrLongNumberToken by expressionToken(pattern = "[+-]?([1-9][0-9]*|0)[il]")
val floatOrDoubleNumberToken by expressionToken(pattern = "[+-]?([1-9][0-9]*|0)\\.[0-9]+[fd]")
val numberToken by or(
intOrLongNumberToken,
floatOrDoubleNumberToken,
)
val stringToken by expressionToken(pattern = "'((\\\\'|[^'])*)'")
val trueBooleanToken by literalToken(text = "true")
val falseBooleanToken by literalToken(text = "false")
val identifierToken by expressionToken(pattern = "[a-zA-Z_][a-zA-Z0-9_]*")
val scopedOperatorToken by literalToken(text = Operator.SCOPED.symbol)
val compareSpecialOperatorToken by literalToken(text = Operator.COMPARE_SPECIAL_LIKE.symbol)
val compareRelativeLteOperatorToken by literalToken(text = Operator.COMPARE_RELATIVE_LTE.symbol)
val compareRelativeGteOperatorToken by literalToken(text = Operator.COMPARE_RELATIVE_GTE.symbol)
val compareRelativeLtOperatorToken by literalToken(text = Operator.COMPARE_RELATIVE_LT.symbol)
val compareRelativeGtOperatorToken by literalToken(text = Operator.COMPARE_RELATIVE_GT.symbol)
val compareAbsoluteEqOperatorToken by literalToken(text = Operator.COMPARE_ABSOLUTE_EQ.symbol)
val compareAbsoluteNeqOperatorToken by literalToken(text = Operator.COMPARE_ABSOLUTE_NEQ.symbol)
val logicalConjunctOperatorToken by literalToken(text = Operator.LOGICAL_CONJUNCT.symbol)
val logicalDisjunctOperatorToken by literalToken(text = Operator.LOGICAL_DISJUNCT.symbol)
val compareRelativeOperatorToken by or(
compareRelativeLteOperatorToken,
compareRelativeGteOperatorToken,
compareRelativeLtOperatorToken,
compareRelativeGtOperatorToken,
)
val compareAbsoluteOperatorToken by or(
compareAbsoluteEqOperatorToken,
compareAbsoluteNeqOperatorToken,
)
// </editor-fold>
// <editor-fold desc="Expression Parsers">
val rootExpressionParser: Parser<RootExpression> by rootToken asJust RootExpression
val numberValueExpressionParser: Parser<ValueExpression> by numberToken map expression@{ tokenMatch ->
return@expression ValueExpression(
valueBox = when (val type = tokenMatch.text.takeLast(1))
{
"i" -> IntBox(value = tokenMatch.text.dropLast(1).toInt())
"l" -> LongBox(value = tokenMatch.text.dropLast(1).toLong())
"f" -> FloatBox(value = tokenMatch.text.dropLast(1).toFloat())
"d" -> DoubleBox(value = tokenMatch.text.dropLast(1).toDouble())
else -> throw NumberFormatException("Unexpected type suffix, '$type'")
}
)
}
val stringValueExpressionParser: Parser<ValueExpression> by stringToken map expression@{ tokenMatch ->
return@expression ValueExpression(
valueBox = StringBox(
value = tokenMatch.text.substring(1, tokenMatch.text.length - 1),
),
)
}
val nullValueExpressionParser: Parser<ValueExpression> by nullToken asJust ValueExpression.Null
val trueBooleanValueExpressionParser: Parser<ValueExpression> by trueBooleanToken asJust ValueExpression.True
val falseBooleanValueExpressionParser: Parser<ValueExpression> by falseBooleanToken asJust ValueExpression.False
val valueExpressionParser: Parser<ValueExpression> by or(
nullValueExpressionParser,
numberValueExpressionParser,
stringValueExpressionParser,
trueBooleanValueExpressionParser,
falseBooleanValueExpressionParser,
)
val accessMemberExpressionParser: Parser<AccessMemberExpression> by identifierToken map expression@{ tokenMatch ->
return@expression AccessMemberExpression(
name = tokenMatch.text,
)
}
val invokeMemberExpressionParser: Parser<InvokeMemberExpression> by identifierToken and skip(lParenToken) and separatedTerms(parser(::logicalDisjunctExpressionParser), commaToken, true) and skip(rParenToken) map expression@{ (tokenMatch, argumentExpressions) ->
return@expression InvokeMemberExpression(name = tokenMatch.text, argumentExpressions = argumentExpressions)
}
val memberExpressionParser: Parser<MemberExpression> by or(
invokeMemberExpressionParser,
accessMemberExpressionParser,
)
val expressionParser: Parser<Expression> by or(
rootExpressionParser,
valueExpressionParser,
memberExpressionParser,
skip(lParenToken) and parser(::logicalDisjunctExpressionParser) and skip(rParenToken),
)
val scopedExpressionParser: Parser<Expression> by leftAssociative(expressionParser, scopedOperatorToken) expression@{ leftExpression, _, rightExpression ->
return@expression ScopedExpression(
expression = leftExpression, memberExpression = when (rightExpression)
{
is MemberExpression -> rightExpression
else -> throw ParseException(
errorResult = TreeErrorResult(
message = "Expected ${MemberExpression::class.simpleName}, instead received ${rightExpression::class.simpleName}",
)
)
}
)
}
val compareSpecialOperatorParser: Parser<Operator> by compareSpecialOperatorToken map Operator.Companion::fromTokenMatch
val compareSpecialExpressionParser: Parser<Expression> by leftAssociative(scopedExpressionParser, compareSpecialOperatorParser, ::leftAssociativeToInvokeMemberExpression)
val compareRelativeOperatorParser: Parser<Operator> by compareRelativeOperatorToken map Operator.Companion::fromTokenMatch
val compareRelativeExpressionParser: Parser<Expression> by leftAssociative(compareSpecialExpressionParser, compareRelativeOperatorParser, ::leftAssociativeToInvokeMemberExpression)
val compareAbsoluteOperatorParser: Parser<Operator> by compareAbsoluteOperatorToken map Operator.Companion::fromTokenMatch
val compareAbsoluteExpressionParser: Parser<Expression> by leftAssociative(compareRelativeExpressionParser, compareAbsoluteOperatorParser, ::leftAssociativeToInvokeMemberExpression)
val logicalConjunctOperatorParser: Parser<Operator> by logicalConjunctOperatorToken map Operator.Companion::fromTokenMatch
val logicalConjunctExpressionParser: Parser<Expression> by leftAssociative(compareAbsoluteExpressionParser, logicalConjunctOperatorParser, ::leftAssociativeToInvokeMemberExpression)
val logicalDisjunctOperatorParser: Parser<Operator> by logicalDisjunctOperatorToken map Operator.Companion::fromTokenMatch
val logicalDisjunctExpressionParser: Parser<Expression> by leftAssociative(logicalConjunctExpressionParser, logicalDisjunctOperatorParser, ::leftAssociativeToInvokeMemberExpression)
// </editor-fold>
// <editor-fold desc="Selector Parsers">
val nameElementMatcherParser: Parser<NameElementMatcher> by identifierToken and optional(skip(lBraceToken) and logicalDisjunctExpressionParser and skip(rBraceToken)) map matcher@{ (tokenMatch, expression) ->
return@matcher NameElementMatcher(
name = tokenMatch.text,
expression = expression,
)
}
val wildElementMatcherParser: Parser<WildElementMatcher> by skip(wildToken) and optional(skip(lBraceToken) and logicalDisjunctExpressionParser and skip(rBraceToken)) map matcher@{ expression ->
return@matcher WildElementMatcher(
expression = expression,
)
}
val elementMatcherParser: Parser<ElementMatcher> by or(
nameElementMatcherParser,
wildElementMatcherParser,
)
val flatSelectorElementParser: Parser<FlatSelectorElement> by skip(flatToken) and elementMatcherParser map element@{ elementMatcher ->
return@element FlatSelectorElement(
elementMatcher = elementMatcher,
)
}
val deepSelectorElementParser: Parser<DeepSelectorElement> by skip(deepToken) and elementMatcherParser map element@{ elementMatcher ->
return@element DeepSelectorElement(
elementMatcher = elementMatcher,
)
}
val selectorElementParser: Parser<SelectorElement> by or(
flatSelectorElementParser,
deepSelectorElementParser,
)
val selectorParser: Parser<Selector> by oneOrMore(selectorElementParser) map selector@{ selectorElements ->
return@selector DefaultSelector(
selectorElements = selectorElements,
)
}
override val rootParser: Parser<Selector> by selectorParser
// </editor-fold>
private companion object
{
fun leftAssociativeToInvokeMemberExpression(leftExpression: Expression, operator: Operator, rightExpression: Expression): InvokeMemberExpression = InvokeMemberExpression(
name = operator.name, argumentExpressions = listOf(
leftExpression,
rightExpression,
)
)
fun expressionToken(@Language("RegExp") pattern: String, ignore: Boolean = false): RegexToken = regexToken(
pattern = pattern,
ignore = ignore,
)
fun <T> or(vararg parsers: Parser<T>): Parser<T> = parsers.reduce { orParser, parser -> orParser or parser }
}
}
| 0
|
Kotlin
|
0
| 1
|
b1e04df112090475593b0144dae77e2f938a890e
| 12,967
|
luggsoft-pml
|
MIT License
|
sqlite/integration-tests/driver-conformance-test/src/commonTest/kotlin/androidx/sqlite/driver/test/BaseBundledConformanceTest.kt
|
androidx
| 256,589,781
| false
| null |
/*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.sqlite.driver.test
import androidx.kruth.assertThat
import androidx.sqlite.use
import kotlin.test.Test
abstract class BaseBundledConformanceTest : BaseConformanceTest() {
@Test
fun readSQLiteVersion() {
val connection = getDriver().open(":memory:")
try {
val version = connection.prepare("SELECT sqlite_version()").use {
it.step()
it.getText(0)
}
// The bundled androidx SQLite version compiled and statically included
assertThat(version).isEqualTo(EXPECTED_SQLITE_VERSION)
} finally {
connection.close()
}
}
companion object {
const val EXPECTED_SQLITE_VERSION = "3.42.0"
}
}
| 28
| null |
945
| 5,125
|
55c737bfb7a7320ac5b43787306f0c3af169f420
| 1,367
|
androidx
|
Apache License 2.0
|
dependency-injection/test-component/src/main/kotlin/studio/lunabee/di/FrameworkTestModule.kt
|
LunabeeStudio
| 624,544,471
| false
|
{"Kotlin": 2677344, "Java": 11977, "Python": 3979}
|
/*
* Copyright (c) 2023 Lunabee Studio
*
* 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.
*
* Created by Lunabee Studio / Date - 9/29/2023 - for the oneSafe6 SDK.
* Last modified 9/29/23, 9:58 PM
*/
package studio.lunabee.di
import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.util.Log
import androidx.hilt.work.HiltWorkerFactory
import androidx.work.Configuration
import androidx.work.WorkManager
import androidx.work.impl.utils.SynchronousExecutor
import androidx.work.testing.WorkManagerTestInitHelper
import com.lunabee.lbcore.helper.LBLoadingVisibilityDelayDelegate
import com.lunabee.lbloading.DelayedLoadingManager
import com.lunabee.lbloading.LoadingManager
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import studio.lunabee.onesafe.SettingsDefaults
import studio.lunabee.onesafe.commonui.usecase.AndroidResizeIconUseCaseFactory
import studio.lunabee.onesafe.domain.LoadFileCancelAllUseCase
import studio.lunabee.onesafe.domain.manager.IsAppBlockedUseCase
import studio.lunabee.onesafe.domain.model.safe.SafeId
import studio.lunabee.onesafe.domain.model.safe.SafeSettings
import studio.lunabee.onesafe.domain.qualifier.ArchiveCacheDir
import studio.lunabee.onesafe.domain.qualifier.BuildNumber
import studio.lunabee.onesafe.domain.qualifier.InternalBackupMimetype
import studio.lunabee.onesafe.domain.qualifier.RemoteDir
import studio.lunabee.onesafe.domain.qualifier.StoreBetaTrack
import studio.lunabee.onesafe.domain.qualifier.VersionName
import studio.lunabee.onesafe.domain.repository.FileRepository
import studio.lunabee.onesafe.domain.usecase.ResizeIconUseCase
import studio.lunabee.onesafe.domain.usecase.clipboard.ClipboardClearUseCase
import studio.lunabee.onesafe.domain.usecase.clipboard.ClipboardContainsSafeDataUseCase
import studio.lunabee.onesafe.domain.usecase.clipboard.ClipboardScheduleClearUseCase
import studio.lunabee.onesafe.domain.usecase.settings.DefaultSafeSettingsProvider
import studio.lunabee.onesafe.test.OSTestConfig
import studio.lunabee.onesafe.test.OSTestConfig.clock
import java.io.File
import java.util.UUID
import javax.inject.Singleton
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
@Module
@InstallIn(SingletonComponent::class)
object FrameworkTestModule {
const val RESIZE_ICON_SIZE: Int = 50
const val ICON_DIR: String = "testDir"
@Provides
@Singleton
internal fun provideResizeIconUseCase(
@ApplicationContext context: Context,
androidResizeIconUseCaseFactory: AndroidResizeIconUseCaseFactory,
): ResizeIconUseCase {
val tmpDir = File(context.cacheDir, ICON_DIR)
return androidResizeIconUseCaseFactory.create(
width = RESIZE_ICON_SIZE,
height = RESIZE_ICON_SIZE,
tmpDir = tmpDir,
)
}
@Provides
@BuildNumber
fun provideBuildNumber(): Int = 0
@Provides
@VersionName
fun provideVersionName(): String = "6.0.0.0"
@Provides
@ArchiveCacheDir(type = ArchiveCacheDir.Type.AutoBackup)
fun provideArchiveAutoBackupDirectory(@ApplicationContext context: Context): File {
return File(context.cacheDir, "keep_archiveAutoBackup")
}
@Provides
@ArchiveCacheDir(type = ArchiveCacheDir.Type.Message)
fun provideArchiveMessageDirectory(@ApplicationContext context: Context): File {
return File(context.cacheDir, "keep_archivemessage")
}
@Provides
@ArchiveCacheDir(type = ArchiveCacheDir.Type.Export)
fun provideArchiveExportedDirectory(@ApplicationContext context: Context): File {
return File(context.cacheDir, "keep_archiveExported")
}
@Provides
fun provideLoadFileCancelAllUseCase(
fileRepository: FileRepository,
): LoadFileCancelAllUseCase {
return object : LoadFileCancelAllUseCase {
override suspend operator fun invoke(itemId: UUID) {
fileRepository.deleteItemDir(itemId)
}
override suspend operator fun invoke() {
fileRepository.deletePlainFilesCacheDir()
}
}
}
@Provides
@InternalBackupMimetype
fun provideInternalBackupMimetype(): String {
return "application/onesafe6_debug"
}
@Provides
@RemoteDir(RemoteDir.Type.Backups)
fun provideRemoteBackupsDir(): String = "OS6 Test auto-backups"
@Provides
@StoreBetaTrack
fun provideStoreBetaTrack(): Boolean = false
@Provides
@Singleton
fun provideLoadingManager(): LoadingManager = DelayedLoadingManager(LBLoadingVisibilityDelayDelegate())
@Provides
fun provideIsAppBlockedUseCase(loadingManager: LoadingManager): IsAppBlockedUseCase = object : IsAppBlockedUseCase {
override fun flow(): Flow<Boolean> = loadingManager.loadingState.map { it.isBlocking }
override suspend operator fun invoke(): Boolean = loadingManager.loadingState.value.isBlocking
}
@Provides
fun provideClipboardClearUseCase(): ClipboardClearUseCase {
return object : ClipboardClearUseCase {
override suspend fun invoke(safeId: SafeId) {
/* no-op */
}
}
}
@Provides
@Singleton
fun provideWorkManager(@ApplicationContext context: Context, workerFactory: HiltWorkerFactory): WorkManager {
initializeWorkManager(context, workerFactory)
return WorkManager.getInstance(context)
}
@SuppressLint("RestrictedApi")
private fun initializeWorkManager(context: Context, workerFactory: HiltWorkerFactory) {
val config = Configuration.Builder()
.setMinimumLoggingLevel(Log.DEBUG)
.setExecutor(SynchronousExecutor())
.setWorkerFactory(workerFactory)
.build()
WorkManagerTestInitHelper.initializeTestWorkManager(context, config)
}
@Provides
fun provideDefaultSafeSettingsProvider(): DefaultSafeSettingsProvider = object : DefaultSafeSettingsProvider {
override fun invoke(): SafeSettings =
SafeSettings(
version = Int.MAX_VALUE,
materialYou = SettingsDefaults.MaterialYouSettingDefault,
automation = SettingsDefaults.AutomationSettingDefault,
displayShareWarning = SettingsDefaults.DisplayShareWarningDefault,
allowScreenshot = SettingsDefaults.AllowScreenshotSettingDefault,
shakeToLock = SettingsDefaults.ShakeToLockSettingDefault,
bubblesPreview = SettingsDefaults.BubblesPreviewDefault,
cameraSystem = OSTestConfig.cameraSystem,
autoLockOSKHiddenDelay = SettingsDefaults.AutoLockInactivityDelayMsDefault.milliseconds,
verifyPasswordInterval = SettingsDefaults.VerifyPasswordIntervalDefault,
bubblesHomeCardCtaState = SettingsDefaults.BubblesPreviewCardDefault,
autoLockInactivityDelay = SettingsDefaults.AutoLockInactivityDelayMsDefault.milliseconds,
autoLockAppChangeDelay = SettingsDefaults.AutoLockAppChangeDelayMsDefault.milliseconds,
clipboardDelay = SettingsDefaults.ClipboardClearDelayMsDefault.milliseconds,
bubblesResendMessageDelay = SettingsDefaults.BubblesResendMessageDelayMsDefault.milliseconds,
autoLockOSKInactivityDelay = SettingsDefaults.AutoLockInactivityDelayMsDefault.milliseconds,
autoBackupEnabled = SettingsDefaults.AutoBackupEnabledDefault,
autoBackupFrequency = SettingsDefaults.AutoBackupFrequencyMsDefault.milliseconds,
autoBackupMaxNumber = SettingsDefaults.AutoBackupMaxNumberDefault,
cloudBackupEnabled = SettingsDefaults.CloudBackupEnabledDefault,
keepLocalBackupEnabled = SettingsDefaults.KeepLocalBackupEnabledDefault,
itemOrdering = SettingsDefaults.ItemOrderingDefault,
itemLayout = SettingsDefaults.ItemLayoutDefault,
enableAutoBackupCtaState = SettingsDefaults.EnableAutoBackupCtaState,
lastPasswordVerification = SettingsDefaults.lastPasswordVerificationDefault(clock),
independentSafeInfoCtaState = SettingsDefaults.independentSafeInfoCtaState(clock),
)
}
@Provides
fun provideAppComponents(): Array<ComponentName> {
return arrayOf(
ComponentName("studio.lunabee.onesafe", "studio.lunabee.onesafe.MainActivity"),
)
}
@Provides
fun provideClipboardShouldClearUseCase(): ClipboardContainsSafeDataUseCase {
return object : ClipboardContainsSafeDataUseCase {
override fun invoke(): Boolean? = null
}
}
@Provides
fun provideClipboardScheduleClearUseCase(): ClipboardScheduleClearUseCase {
return object : ClipboardScheduleClearUseCase {
override suspend fun setup(clearDelay: Duration, safeId: SafeId) {
/* no-op */
}
override fun cancel() {
/* no-op */
}
}
}
}
| 1
|
Kotlin
|
1
| 2
|
a34f0ddaf9dc649c2f2082dc2526921bb1a491df
| 9,813
|
oneSafe6_SDK_Android
|
Apache License 2.0
|
domain/src/main/kotlin/com/arturogutierrez/openticator/interactor/CompletableUseCase.kt
|
dandycheung
| 239,232,057
| false
| null |
package com.arturogutierrez.openticator.interactor
import com.arturogutierrez.openticator.executor.PostExecutionThread
import com.arturogutierrez.openticator.executor.ThreadExecutor
import io.reactivex.Completable
import io.reactivex.CompletableObserver
import io.reactivex.disposables.Disposables
import io.reactivex.schedulers.Schedulers
abstract class CompletableUseCase<in Params> constructor(
private val threadExecutor: ThreadExecutor,
private val postExecutionThread: PostExecutionThread) {
private val subscription = Disposables.empty()
protected abstract fun buildObservable(params: Params): Completable
fun execute(params: Params, observer: CompletableObserver) {
buildObservable(params)
.subscribeOn(Schedulers.from(threadExecutor))
.observeOn(postExecutionThread.scheduler)
.subscribeWith(observer)
}
fun unsubscribe() {
if (!subscription.isDisposed) {
subscription.dispose()
}
}
}
| 1
| null |
1
| 1
|
ccbbd93291eee705948752089c03b386d1fb81cf
| 962
|
Openticator
|
Apache License 2.0
|
app/core/src/com/creations/games/think/asset/FontSize.kt
|
atulanand206
| 384,773,755
| false
| null |
package com.creations.games.think.asset
enum class FontSize(val value: Int) {
F10(10),
F12(12),
F14(14),
F18(18),
F20(20),
}
| 8
|
Go
|
0
| 0
|
abd2ee00f1f2cf9b031349f3c854186eacf69d6a
| 145
|
find
|
MIT License
|
bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/command/message/MessageCommand.kt
|
Nyrheim
| 269,929,653
| true
|
{"Kotlin": 2944589, "Java": 1237516, "HTML": 94789, "JavaScript": 640, "CSS": 607}
|
/*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.chat.bukkit.command.message
import com.rpkit.chat.bukkit.RPKChatBukkit
import com.rpkit.chat.bukkit.chatgroup.RPKChatGroupImpl
import com.rpkit.chat.bukkit.chatgroup.RPKChatGroupProvider
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
/**
* Message command.
* Messages a chat group or an individual.
*/
class MessageCommand(private val plugin: RPKChatBukkit): CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (args.size >= 2) {
if (sender is Player) {
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val chatGroupProvider = plugin.core.serviceManager.getServiceProvider(RPKChatGroupProvider::class)
val senderMinecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender)
if (senderMinecraftProfile != null) {
var chatGroup = chatGroupProvider.getChatGroup(args[0])
if (chatGroup != null) {
if (sender.hasPermission("rpkit.chat.command.chatgroup.message")) {
if (chatGroup.memberMinecraftProfiles.any { memberMinecraftProfile ->
memberMinecraftProfile.id == senderMinecraftProfile.id }) {
val message = StringBuilder()
for (i in 1 until args.size) {
message.append(args[i]).append(" ")
}
chatGroup.sendMessage(senderMinecraftProfile, message.toString())
} else {
sender.sendMessage(plugin.messages["chat-group-message-invalid-not-a-member"])
}
} else {
sender.sendMessage(plugin.messages["no-permission-chat-group-message"])
}
} else if (plugin.server.getPlayer(args[0]) != null) {
if (sender.hasPermission("rpkit.chat.command.message")) {
val receiver = plugin.server.getPlayer(args[0])
if (receiver == null) {
sender.sendMessage(plugin.messages["message-invalid-target"])
return true
}
val receiverMinecraftProfile = minecraftProfileProvider.getMinecraftProfile(receiver)
if (receiverMinecraftProfile != null) {
if (receiverMinecraftProfile != senderMinecraftProfile) {
val chatGroup1 = chatGroupProvider.getChatGroup("_pm_" + sender.name + "_" + receiver.name)
val chatGroup2 = chatGroupProvider.getChatGroup("_pm_" + receiver.name + "_" + sender.name)
when {
chatGroup1 != null -> chatGroup = chatGroup1
chatGroup2 != null -> chatGroup = chatGroup2
else -> {
chatGroup = RPKChatGroupImpl(plugin, name = "_pm_" + sender.getName() + "_" + receiver.name)
chatGroupProvider.addChatGroup(chatGroup)
chatGroup.addMember(senderMinecraftProfile)
chatGroup.addMember(receiverMinecraftProfile)
}
}
val message = StringBuilder()
for (i in 1 until args.size) {
message.append(args[i]).append(" ")
}
chatGroup.sendMessage(senderMinecraftProfile, message.toString())
} else {
sender.sendMessage(plugin.messages["message-invalid-self"])
}
} else {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
}
} else {
sender.sendMessage(plugin.messages["no-permission-message"])
}
} else {
sender.sendMessage(plugin.messages["message-invalid-target"])
}
} else {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
}
} else {
sender.sendMessage(plugin.messages["not-from-console"])
}
} else {
sender.sendMessage(plugin.messages["message-usage"])
}
return true
}
}
| 0
| null |
0
| 0
|
f2196a76e0822b2c60e4a551de317ed717bbdc7e
| 5,856
|
RPKit
|
Apache License 2.0
|
widget/src/main/java/com/angcyo/widget/layout/RSoftInputLayout.kt
|
angcyo
| 229,037,615
| false
| null |
package com.angcyo.widget.layout
import android.animation.Animator
import android.animation.ObjectAnimator
import android.animation.TimeInterpolator
import android.animation.ValueAnimator
import android.animation.ValueAnimator.AnimatorUpdateListener
import android.app.Activity
import android.content.Context
import android.graphics.Rect
import android.os.Build
import android.util.AttributeSet
import android.view.*
import android.view.animation.DecelerateInterpolator
import android.widget.FrameLayout
import androidx.core.view.GravityCompat
import com.angcyo.library.L.w
import com.angcyo.library.ex.toDpi
import com.angcyo.widget.R
import com.angcyo.widget.base.getStatusBarHeight
import com.angcyo.widget.base.hideSoftInput
import com.orhanobut.hawk.Hawk
import java.util.*
/**
* Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved.
* 项目名称:
* 类的描述:支持透明状态栏, 支持Dialog, 支持动画
*
*
* 重写于2019-8-19
* 原理:
* API < 21
* 键盘弹出, 只会回调 onSizeChanged , 相差的高度就是键盘的高度
*
*
* API >= 21
* 如果未激活 View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN, 那么和 API < 21 的处理方式一样
* 键盘弹出, 会回调 onApplyWindowInsets , insets.getSystemWindowInsetBottom, 就是键盘的高度
* 此时onSizeChange方法不会执行, 应为系统是用 PaddingBottom的方式, 为键盘腾出空间
*
*
*
*
* 使用方式:
*
*
* 1. android:windowSoftInputMode="adjustResize"
*
*
* 2.
*
* <pre>
* <RSoftInputLayout2>
* <第一个必须是内容布局>
* <第二个会被识别为emoji布局, 非必须>
* <其他子布局>
* <其他子布局>
* <其他子布局>
* ...
* </RSoftInputLayout2>
</pre> *
*
*
*
*
*
*
* 创建人员:Robi
* 创建时间:2016/12/21 9:01
* 修改人员:Robi
* 修改时间:2019-8-19
* 修改备注:
* Version: 1.0.0
*/
class RSoftInputLayout : FrameLayout {
/**
* 动画执行回调, 可以修改动画执行的值
*/
var animatorCallback: AnimatorCallback? = null
/**
* 当键盘未显示过时, 默认的键盘高度
*/
var defaultKeyboardHeight = -1
/**
* 由于延迟操作带来的意图延迟, 此变量不考虑无延迟
*/
var wantIntentAction = INTENT_NONE
/**
* 当前用户操作的意图
*/
var intentAction = INTENT_NONE
set(value) {
if (value == INTENT_NONE || field != value) {
if (field != INTENT_NONE) {
lastIntentAction = field
}
}
field = value
wantIntentAction = value
}
/**
* 最后一次有效的操作意图
*/
var lastIntentAction = intentAction
/**
* 最后一次的意图, 用来实现表情布局状态恢复
*/
var lastRestoreIntentAction = intentAction
//2级缓存状态
var lastRestoreIntentAction2 = intentAction
var contentLayoutMaxHeight = 0
//键盘/emoji 当前显示的高度
var bottomCurrentShowHeight = 0
//动画过程中的高度变量
var bottomCurrentShowHeightAnim = 0
//动画进度
var animProgress = 0f
var lastKeyboardHeight = 0
var contentLayout: View? = null
var emojiLayout: View? = null
var mEmojiLayoutChangeListeners =
HashSet<OnEmojiLayoutChangeListener>()
/**
* 是否激活控件
*/
private var enableSoftInput = true
private var enableSoftInputAnim = true
/**
* 隐藏和显示的动画 分开控制
*/
private var enableSoftInputAnimShow = true
//<editor-fold defaultState="collapsed" desc="核心方法">
private var enableSoftInputAnimHide = true
/**
* 可以关闭此开关, 当键盘弹出时, 只有事件回调, 没有界面size处理. (API>=21)
*/
private var enableSoftInputInset = true
/**
* 频繁切换键盘, 延迟检查时长.
* 如果开启了手机的安全密码输入键盘, 可以适当的加大延迟时间. 消除抖动.
*/
private var switchCheckDelay = 0
//</editor-fold defaultstate="collapsed" desc="事件相关">
//<editor-fold defaultstate="collapsed" desc="静态区">
var animDuration: Long = 240
private set
/**
* 在软键盘展示的过程中, 动态改变此paddingTop, 需要开启 [enableSoftInputAnim]
* 大于0, 表示激活属性
*/
private var animPaddingTop = -1
/**
* 键盘完全显示时, 依旧需要的padding大小
*/
private var animPaddingMinTop = 0
/**
* 激活表情布局恢复, (如:显示键盘之前是表情布局, 那么隐藏键盘后就会显示表情布局)
*/
private var enableEmojiRestore = false
private var delaySizeChanged: Runnable? = null
private var insetRunnable: Runnable? = null
//</editor-fold defaultstate="collapsed" desc="核心方法">
//<editor-fold defaultstate="collapsed" desc="辅助方法">
private var checkSizeChanged: Runnable? = null
private var mValueAnimator: ValueAnimator? = null
constructor(context: Context) : super(context) {
initLayout(context, null)
}
constructor(
context: Context,
attrs: AttributeSet?
) : super(context, attrs) {
initLayout(context, attrs)
}
private fun initLayout(
context: Context,
attrs: AttributeSet?
) {
val array = context.obtainStyledAttributes(attrs, R.styleable.RSoftInputLayout)
defaultKeyboardHeight = array.getDimensionPixelOffset(
R.styleable.RSoftInputLayout_r_default_soft_input_height,
defaultKeyboardHeight
)
animPaddingTop = array.getDimensionPixelOffset(
R.styleable.RSoftInputLayout_r_soft_input_anim_padding_top,
animPaddingTop
)
animPaddingMinTop = array.getDimensionPixelOffset(
R.styleable.RSoftInputLayout_r_soft_input_anim_padding_min_top,
animPaddingMinTop
)
enableSoftInput =
array.getBoolean(R.styleable.RSoftInputLayout_r_enable_soft_input, enableSoftInput)
enableSoftInputAnim = array.getBoolean(
R.styleable.RSoftInputLayout_r_enable_soft_input_anim,
enableSoftInputAnim
)
setEnableSoftInputAnim(enableSoftInputAnim)
enableSoftInputAnimShow = array.getBoolean(
R.styleable.RSoftInputLayout_r_enable_soft_input_anim_show,
enableSoftInputAnimShow
)
enableSoftInputAnimHide = array.getBoolean(
R.styleable.RSoftInputLayout_r_enable_soft_input_anim_hide,
enableSoftInputAnimHide
)
enableEmojiRestore = array.getBoolean(
R.styleable.RSoftInputLayout_r_enable_emoji_restore,
enableEmojiRestore
)
enableSoftInputInset = array.getBoolean(
R.styleable.RSoftInputLayout_r_enable_soft_input_inset,
enableSoftInputInset
)
switchCheckDelay =
array.getInt(R.styleable.RSoftInputLayout_r_switch_check_delay, switchCheckDelay)
animDuration =
array.getInt(R.styleable.RSoftInputLayout_r_anim_duration, animDuration.toInt())
.toLong()
array.recycle()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val widthSize = MeasureSpec.getSize(widthMeasureSpec)
val heightSize = MeasureSpec.getSize(heightMeasureSpec)
val maxWidth = widthSize - paddingLeft - paddingRight
val animPaddingTop = calcAnimPaddingTop()
val maxHeight = heightSize - paddingTop - paddingBottom - animPaddingTop
val layoutFullScreen =
isLayoutFullScreen(context)
val softKeyboardShow = isSoftKeyboardShow
val emojiLayoutShow = isEmojiLayoutShow
var bottomHeight = bottomCurrentShowHeight
if (isInEditMode) {
if (emojiLayout == null) {
defaultKeyboardHeight = 0
}
bottomHeight = defaultKeyboardHeight
}
if (isAnimStart) {
bottomHeight = bottomCurrentShowHeightAnim
}
if (contentLayout != null) {
val layoutParams =
contentLayout!!.layoutParams as LayoutParams
contentLayoutMaxHeight = if (layoutFullScreen) {
maxHeight - bottomHeight - layoutParams.topMargin - layoutParams.bottomMargin
} else {
if (softKeyboardShow) { //这里加动画, 体验不好.
// if (isAnimStart()) {
// contentLayoutMaxHeight = (int) (maxHeight - layoutParams.topMargin - layoutParams.bottomMargin
// + bottomCurrentShowHeight * (1 - animProgress));
// } else {
// contentLayoutMaxHeight = maxHeight - layoutParams.topMargin - layoutParams.bottomMargin;
// }
maxHeight - layoutParams.topMargin - layoutParams.bottomMargin
} else {
maxHeight - bottomHeight - layoutParams.topMargin - layoutParams.bottomMargin
}
}
val contentLayoutMaxWidth =
maxWidth - layoutParams.leftMargin - layoutParams.rightMargin
if (layoutParams.height != ViewGroup.LayoutParams.MATCH_PARENT) {
measureChildWithMargins(
contentLayout, widthMeasureSpec, 0,
heightMeasureSpec, 0
)
}
if (contentLayout!!.measuredHeight > contentLayoutMaxHeight
|| layoutParams.height == ViewGroup.LayoutParams.MATCH_PARENT
) {
contentLayout!!.measure(
MeasureSpec.makeMeasureSpec(contentLayoutMaxWidth, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(contentLayoutMaxHeight, MeasureSpec.EXACTLY)
)
}
// L.i("内容高度:" + contentLayout.getMeasuredHeight() +
// " max: " + maxHeight + ":" + contentLayoutMaxHeight + " anim:" + isAnimStart()
// + " top:" + animPaddingTop + " wa:" + wantIntentAction + " la:" + lastIntentAction);
}
if (emojiLayout != null) {
emojiLayout!!.measure(
MeasureSpec.makeMeasureSpec(maxWidth, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(validBottomHeight(), MeasureSpec.EXACTLY)
)
}
measureOther(widthMeasureSpec, heightMeasureSpec)
setMeasuredDimension(widthSize, heightSize)
}
override fun onLayout(
changed: Boolean,
left: Int,
top: Int,
right: Int,
bottom: Int
) {
val l = paddingLeft
var t = paddingTop + calcAnimPaddingTop()
var r = 0
var b = 0
if (contentLayout != null) {
val layoutParams =
contentLayout!!.layoutParams as LayoutParams
r = l + contentLayout!!.measuredWidth
b = t + contentLayoutMaxHeight
t = b - layoutParams.bottomMargin - contentLayout!!.measuredHeight
contentLayout!!.layout(l, t, r, b)
t = contentLayout!!.bottom
}
if (emojiLayout != null) {
if (isSoftKeyboardShow) {
t = measuredHeight
} else if (!isEnableSoftInputAnim() && intentAction == INTENT_HIDE_KEYBOARD) {
t = measuredHeight
}
r = l + emojiLayout!!.measuredWidth
b = t + emojiLayout!!.measuredHeight
emojiLayout!!.layout(l, t, r, b)
}
layoutOther()
}
override fun onSizeChanged(
w: Int,
h: Int,
oldw: Int,
oldh: Int
) { // L.i("sizeChanged:" + oldw + "->" + w + " " + oldh + "->" + h +
// " " + intentAction + " k:" + isSoftKeyboardShow() + " anim:" + isAnimStart());
//低版本适配
var h = h
var oldh = oldh
val layoutFullScreen =
isLayoutFullScreen(context)
if (!layoutFullScreen) {
if (intentAction == INTENT_SHOW_EMOJI && checkSizeChanged == null) {
return
}
if (isFirstLayout(oldw, oldh)) {
if (isSoftKeyboardShow) { //软件盘默认是显示状态
oldh = h + softKeyboardHeight
}
}
if (handleSizeChange(w, h, oldw, oldh)) { //有可能是键盘弹出了
val diffHeight = oldh - h
val softKeyboardShow = isSoftKeyboardShow
wantIntentAction = if (diffHeight > 0) {
if (softKeyboardShow) {
INTENT_SHOW_KEYBOARD
} else {
INTENT_SHOW_EMOJI
}
} else {
if (lastIntentAction == INTENT_SHOW_EMOJI) {
INTENT_HIDE_EMOJI
} else {
INTENT_HIDE_KEYBOARD
}
}
}
} else { //高版本, 默认显示键盘适配
if (oldw == 0 && oldh == 0) {
if (isSoftKeyboardShow) {
oldh = h
h = oldh - softKeyboardHeight
}
}
}
//用来解决, 快速切换 emoji布局和键盘或者普通键盘和密码键盘 时, 闪烁的不良体验.
if (delaySizeChanged != null) {
removeCallbacks(delaySizeChanged)
}
delaySizeChanged = DelaySizeChangeRunnable(w, h, oldw, oldh, wantIntentAction)
if (switchCheckDelay > 0) {
postDelayed(delaySizeChanged, switchCheckDelay.toLong())
} else {
delaySizeChanged?.run()
}
}
private fun initDefaultKeyboardHeight() { //恢复上一次键盘的高度
if (defaultKeyboardHeight < 0) {
var lastKeyboardHeight = 0
if (!isInEditMode) {
lastKeyboardHeight = Hawk.get(KEY_KEYBOARD_HEIGHT, 0)
}
defaultKeyboardHeight = if (lastKeyboardHeight <= 0) {
(275 * resources.displayMetrics.density).toInt()
} else {
lastKeyboardHeight
}
}
}
private fun isFirstLayout(oldw: Int, oldh: Int): Boolean {
return oldw == 0 && oldh == 0 && intentAction == INTENT_NONE
}
private fun handleSizeChange(w: Int, h: Int, oldw: Int, oldh: Int): Boolean {
var result = false
val isFirstLayout = isFirstLayout(oldw, oldh)
val diffHeight = oldh - h
if (isFirstLayout) { //布局第一次显示在界面上, 需要排除默认键盘展示的情况
result = diffHeight != 0
} else {
if (oldw != 0 && w != oldw) { //有可能屏幕旋转了
} else {
result = diffHeight != 0
}
}
return result
}
private fun clearIntentAction() {
intentAction = INTENT_NONE
}
private fun measureOther(widthMeasureSpec: Int, heightMeasureSpec: Int) {
for (i in 2 until childCount) {
val child = getChildAt(i)
if (child.visibility != View.GONE) {
measureChildWithMargins(
child, widthMeasureSpec, 0,
heightMeasureSpec, 0
)
}
}
}
private fun layoutOther() {
val count = childCount
val parentLeft = paddingLeft
val parentRight = measuredWidth - paddingRight
val parentTop = paddingTop
val parentBottom = measuredHeight - paddingBottom
val forceLeftGravity = false
for (i in 2 until count) {
val child = getChildAt(i)
if (child.visibility != View.GONE) {
val lp =
child.layoutParams as LayoutParams
val width = child.measuredWidth
val height = child.measuredHeight
var childLeft = 0
var childTop: Int
var gravity = lp.gravity
if (gravity == -1) {
gravity = Gravity.TOP or Gravity.LEFT
}
val layoutDirection =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
layoutDirection
} else {
0
}
val absoluteGravity = GravityCompat.getAbsoluteGravity(gravity, layoutDirection)
val verticalGravity = gravity and Gravity.VERTICAL_GRAVITY_MASK
when (absoluteGravity and Gravity.HORIZONTAL_GRAVITY_MASK) {
Gravity.CENTER_HORIZONTAL -> childLeft =
parentLeft + (parentRight - parentLeft - width) / 2 +
lp.leftMargin - lp.rightMargin
Gravity.RIGHT -> if (!forceLeftGravity) {
childLeft = parentRight - width - lp.rightMargin
}
Gravity.LEFT -> childLeft = parentLeft + lp.leftMargin
else -> childLeft = parentLeft + lp.leftMargin
}
childTop = when (verticalGravity) {
Gravity.TOP -> parentTop + lp.topMargin
Gravity.CENTER_VERTICAL -> parentTop + (parentBottom - parentTop - height) / 2 +
lp.topMargin - lp.bottomMargin
Gravity.BOTTOM -> parentBottom - height - lp.bottomMargin
else -> parentTop + lp.topMargin
}
child.layout(childLeft, childTop, childLeft + width, childTop + height)
}
}
}
override fun addView(
child: View,
index: Int,
params: ViewGroup.LayoutParams
) {
super.addView(child, index, params)
val childCount = childCount
/*请按顺序布局*/if (childCount > 0) {
contentLayout = getChildAt(0)
}
if (childCount > 1) {
emojiLayout = getChildAt(1)
}
if (haveChildSoftInput(child)) {
setEnableSoftInput(false)
}
}
/**
* 解决RSoftInputLayout嵌套RSoftInputLayout的问题
*/
private fun haveChildSoftInput(child: View): Boolean {
if (child is ViewGroup) {
for (i in 0 until child.childCount) {
return haveChildSoftInput(child.getChildAt(i))
}
}
return child is RSoftInputLayout
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
initDefaultKeyboardHeight()
if (!isInEditMode && isEnabled && enableSoftInput) {
setFitsSystemWindows()
//setClipToPadding(false);//未知作用
}
//必须放在post里面调用, 才会生效
post { adjustResize(context) }
}
override fun fitSystemWindows(insets: Rect): Boolean { //此方法会触发 dispatchApplyWindowInsets
insets[0, 0, 0] = 0
super.fitSystemWindows(insets)
return isEnableSoftInput()
}
override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets { //Fragment+Fragment中使用此控件支持.
if (!isEnableSoftInput()) {
return super.onApplyWindowInsets(insets)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
val insetBottom = insets.systemWindowInsetBottom
// L.i("onApplyWindowInsets:" + insetBottom + " " +
// intentAction + " w:" + getMeasuredWidth() + " h:" + getMeasuredHeight());
if (measuredWidth <= 0 && measuredHeight <= 0) {
return super.onApplyWindowInsets(insets)
}
if (isSoftKeyboardShow && insetBottom <= 0) { //软件已经显示, 此时却要隐藏键盘. ViewPager中, 使用此控件支持.
//当启动一个新的Activity时, 也会触发此场景.
post {
if (!isSoftKeyboardShow) {
insetBottom(0)
}
}
return super.onApplyWindowInsets(insets)
}
val action: Int
action = if (insetBottom > 0) {
INTENT_SHOW_KEYBOARD
} else {
INTENT_HIDE_KEYBOARD
}
if (insetRunnable != null) {
if (action == wantIntentAction) { //之前已有相同操作
return insets.replaceSystemWindowInsets(0, 0, 0, 0)
}
wantIntentAction = action
removeCallbacks(insetRunnable)
}
insetRunnable = InsetRunnable(insetBottom)
//键盘切换到键盘, 延迟检查. 防止是普通键盘切换到密码键盘
if (lastIntentAction == INTENT_NONE || switchCheckDelay <= 0) { //第一次不检查
insetRunnable?.run()
} else {
postDelayed(insetRunnable, switchCheckDelay.toLong())
}
//替换掉系统的默认处理方式(setPadding)
//系统会使用setPadding的方式, 为键盘留出空间
return insets.replaceSystemWindowInsets(0, 0, 0, 0)
}
return super.onApplyWindowInsets(insets)
}
//底部需要腾出距离
private fun insetBottom(height: Int) {
// L.i("插入:" + height + ":" + getMeasuredHeight() +
// " isFirstLayout:" + isFirstLayout(getMeasuredWidth(), getMeasuredHeight()));
val measuredWidth = measuredWidth
val measuredHeight = measuredHeight
if (height > 0) { //键盘弹出
checkSizeChanged = KeyboardRunnable(
measuredWidth, measuredHeight - height,
measuredWidth, measuredHeight
)
} else { //键盘隐藏
var hideHeight = bottomCurrentShowHeight
if (bottomCurrentShowHeight <= 0) {
hideHeight = lastKeyboardHeight
}
checkSizeChanged = KeyboardRunnable(
measuredWidth, measuredHeight,
measuredWidth, measuredHeight - hideHeight
)
}
checkOnSizeChanged(false)
}
private fun checkOnSizeChanged(delay: Boolean) {
if (checkSizeChanged == null) {
return
}
removeCallbacks(checkSizeChanged)
if (delay) {
post(checkSizeChanged)
} else {
checkSizeChanged!!.run()
}
}
//</editor-fold defaultstate="collapsed" desc="辅助方法">
//<editor-fold defaultstate="collapsed" desc="属性操作">
/**
* 判断键盘是否显示
*/
val isSoftKeyboardShow: Boolean
get() {
if (isInEditMode) {
return false
}
val screenHeight = screenHeightPixels
val keyboardHeight = softKeyboardHeight
return screenHeight != keyboardHeight && keyboardHeight > 50.toDpi()
}
/**
* 获取键盘的高度
*/
val softKeyboardHeight: Int
get() = getSoftKeyboardHeight(this)
/**
* 屏幕高度(不包含虚拟导航键盘的高度)
*/
private val screenHeightPixels: Int
private get() = resources.displayMetrics.heightPixels
//</editor-fold defaultstate="collapsed" desc="属性操作">
//<editor-fold defaultstate="collapsed" desc="方法控制">
private fun startAnim(
bottomHeightFrom: Int,
bottomHeightTo: Int,
duration: Long
) { // L.i("动画:from:" + bottomHeightFrom + "->" + bottomHeightTo);
var duration = duration
cancelAnim()
var from = bottomHeightFrom
var to = bottomHeightTo
if (animatorCallback != null) {
val preStart = animatorCallback!!.onAnimatorPreStart(
wantIntentAction,
bottomHeightFrom,
bottomHeightTo,
duration
)
from = preStart[0]
to = preStart[1]
duration = preStart[2].toLong()
}
mValueAnimator = ObjectAnimator.ofInt(from, to)
mValueAnimator?.setDuration(duration)
if (animatorCallback == null) {
mValueAnimator?.setInterpolator(DecelerateInterpolator())
} else {
mValueAnimator?.setInterpolator(animatorCallback!!.getInterpolator(wantIntentAction))
}
mValueAnimator?.addUpdateListener(AnimatorUpdateListener { animation ->
val animatedFraction = animation.animatedFraction
val animatedValue = animation.animatedValue as Int
animProgress = animatedFraction
bottomCurrentShowHeightAnim = if (animatorCallback == null) {
animatedValue
} else {
animatorCallback!!.onUpdateAnimatorValue(
intentAction,
animatedFraction,
animatedValue
)
}
requestLayout()
})
mValueAnimator?.addListener(object : Animator.AnimatorListener {
override fun onAnimationStart(animation: Animator) {}
override fun onAnimationEnd(animation: Animator) {
clearIntentAction()
if (animatorCallback != null) {
animatorCallback!!.onAnimatorEnd(lastIntentAction, false)
}
}
override fun onAnimationCancel(animation: Animator) { //clearIntentAction();
if (animatorCallback != null) {
animatorCallback!!.onAnimatorEnd(wantIntentAction, true)
}
}
override fun onAnimationRepeat(animation: Animator) {}
})
mValueAnimator?.start()
if (animatorCallback != null) {
animatorCallback!!.onAnimatorStart(wantIntentAction)
}
}
private fun cancelAnim() {
mValueAnimator?.cancel()
mValueAnimator = null
}
//动画是否执行中
private val isAnimStart: Boolean
private get() = mValueAnimator != null && mValueAnimator!!.isRunning
//表情布局有效的高度
private fun validBottomHeight(): Int { //没显示过键盘, 默认高度
var bottomHeight = defaultKeyboardHeight
if (lastKeyboardHeight > 0) { //显示过键盘, 有键盘的高度
bottomHeight = lastKeyboardHeight
}
return bottomHeight
}
private fun calcAnimPaddingTop(): Int {
if (animPaddingTop <= 0) {
return 0
}
if (isInEditMode) {
return animPaddingTop
}
var result = animPaddingTop
val animStart = isAnimStart
val statusBarHeight: Int = getStatusBarHeight()
val layoutFullScreen =
isLayoutFullScreen(context)
if (isSoftKeyboardShow || isEmojiLayoutShow) {
if (animStart && intentAction != lastIntentAction) {
result = (animPaddingTop * (1 - animProgress)).toInt()
result = Math.max(result, statusBarHeight + animPaddingMinTop)
} else if (lastIntentAction == INTENT_NONE || lastIntentAction == INTENT_HIDE_EMOJI || lastIntentAction == INTENT_HIDE_KEYBOARD
) {
} else if (layoutFullScreen) {
result = statusBarHeight + animPaddingMinTop
} else {
result = animPaddingMinTop
}
} else {
if (wantIntentAction == INTENT_HIDE_EMOJI ||
wantIntentAction == INTENT_HIDE_KEYBOARD
) {
if (animStart && wantIntentAction != lastIntentAction) {
result = (animPaddingTop * animProgress).toInt()
result = Math.max(result, statusBarHeight + animPaddingMinTop)
} else if (layoutFullScreen) {
result = statusBarHeight + animPaddingMinTop
} else {
result = animPaddingMinTop
}
}
}
return result
}
fun setFitsSystemWindows() {
fitsSystemWindows = isEnabled && enableSoftInput
}
fun isEnableSoftInput(): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
fitsSystemWindows && isEnabled && enableSoftInput
} else {
isEnabled && enableSoftInput
}
}
fun setEnableSoftInput(enableSoftInput: Boolean) {
if (this.enableSoftInput == enableSoftInput) {
return
}
val keyboardShow = isSoftKeyboardShow
this.enableSoftInput = enableSoftInput
if (enableSoftInput) {
isEnabled = true
fitsSystemWindows = true
} else {
fitsSystemWindows = false
}
if (keyboardShow && !enableSoftInput) { //已经显示了软键盘, 这个时候禁用控件, 恢复默认布局
intentAction = INTENT_HIDE_KEYBOARD
insetBottom(0)
} else {
requestLayout()
}
}
fun isEnableSoftInputAnim(): Boolean {
return enableSoftInputAnimHide || enableSoftInputAnimShow
}
fun setEnableSoftInputAnim(enableSoftInputAnim: Boolean) {
this.enableSoftInputAnim = enableSoftInputAnim
enableSoftInputAnimHide = enableSoftInputAnim
enableSoftInputAnimShow = enableSoftInputAnim
}
val isEmojiLayoutShow: Boolean
get() {
var result = false
if (isSoftKeyboardShow) {
return false
}
if (emojiLayout != null) {
if (isAnimStart) {
result = bottomCurrentShowHeight > 0
} else if (emojiLayout!!.measuredHeight > 0 && emojiLayout!!.top < measuredHeight - paddingBottom && emojiLayout!!.bottom >= measuredHeight - paddingBottom
) {
result = true
}
}
return result
}
/**
* 返回按键处理
*
* @return true 表示可以关闭界面
*/
fun requestBackPressed(): Boolean {
if (isSoftKeyboardShow) {
if (intentAction == INTENT_HIDE_KEYBOARD) {
return false
}
intentAction = INTENT_HIDE_KEYBOARD
hideSoftInput()
return false
}
if (isEmojiLayoutShow) {
hideEmojiLayout()
return false
}
return true
}
/**
* 显示表情布局
*/
fun showEmojiLayout(
height: Int = validBottomHeight(),
force: Boolean = false
) {
if (force) {
lastKeyboardHeight = height
} else {
if (isEmojiLayoutShow) {
return
}
if (intentAction == INTENT_SHOW_EMOJI) {
return
}
}
if (isSoftKeyboardShow) {
hideSoftInput()
}
intentAction = INTENT_SHOW_EMOJI
insetBottom(height)
}
/**
* 隐藏表情布局
*/
fun hideEmojiLayout() {
if (intentAction == INTENT_HIDE_EMOJI) {
return
}
if (isEmojiLayoutShow) {
intentAction = INTENT_HIDE_EMOJI
insetBottom(0)
}
}
//</editor-fold defaultstate="collapsed" desc="方法控制">
//<editor-fold defaultstate="collapsed" desc="事件相关">
fun setEnableSoftInputAnimShow(enableSoftInputAnimShow: Boolean) {
this.enableSoftInputAnimShow = enableSoftInputAnimShow
}
fun setEnableSoftInputAnimHide(enableSoftInputAnimHide: Boolean) {
this.enableSoftInputAnimHide = enableSoftInputAnimHide
}
fun setSwitchCheckDelay(switchCheckDelay: Int) {
this.switchCheckDelay = switchCheckDelay
}
fun setAnimPaddingTop(animPaddingTop: Int) {
this.animPaddingTop = animPaddingTop
requestLayout()
}
fun setAnimPaddingMinTop(animPaddingMinTop: Int) {
this.animPaddingMinTop = animPaddingMinTop
}
fun addOnEmojiLayoutChangeListener(listener: OnEmojiLayoutChangeListener) {
mEmojiLayoutChangeListeners.add(listener)
adjustResize(context)
}
fun removeOnEmojiLayoutChangeListener(listener: OnEmojiLayoutChangeListener?) {
mEmojiLayoutChangeListeners.remove(listener)
}
private fun notifyEmojiLayoutChangeListener(
isEmojiShow: Boolean,
isKeyboardShow: Boolean,
height: Int
) {
w(hashCode().toString() + " 表情:" + isEmojiShow + " 键盘:" + isKeyboardShow + " 高度:" + height)
if (isKeyboardShow && !isInEditMode) {
Hawk.put(KEY_KEYBOARD_HEIGHT, height)
}
val iterator: Iterator<OnEmojiLayoutChangeListener> =
mEmojiLayoutChangeListeners.iterator()
while (iterator.hasNext()) {
iterator.next().onEmojiLayoutChange(isEmojiShow, isKeyboardShow, height)
}
}
interface OnEmojiLayoutChangeListener {
/**
* @param height EmojiLayout弹出的高度 或者 键盘弹出的高度
* @param isEmojiShow 表情布局是否显示了
* @param isKeyboardShow 键盘是否显示了
*/
fun onEmojiLayoutChange(
isEmojiShow: Boolean,
isKeyboardShow: Boolean,
height: Int
)
}
class AnimatorCallback {
/**
* 动画需要执行的值
*
* @return 按照入参顺序, 返回对应修改后的值
*/
fun onAnimatorPreStart(
intentAction: Int,
bottomHeightFrom: Int,
bottomHeightTo: Int,
duration: Long
): IntArray {
return intArrayOf(bottomHeightFrom, bottomHeightTo, duration.toInt())
}
/**
* 动画执行过程中的值
*/
fun onUpdateAnimatorValue(
intentAction: Int,
animatedFraction: Float,
animatedValue: Int
): Int {
return animatedValue
}
fun getInterpolator(intentAction: Int): TimeInterpolator {
return DecelerateInterpolator()
}
fun onAnimatorStart(intentAction: Int) {}
fun onAnimatorEnd(intentAction: Int, isCancel: Boolean) {}
}
//</editor-fold defaultstate="collapsed" desc="静态区">
private inner class KeyboardRunnable(var w: Int, var h: Int, var oldw: Int, var oldh: Int) :
Runnable {
override fun run() {
onSizeChanged(w, h, oldw, oldh)
checkSizeChanged = null
}
}
private inner class DelaySizeChangeRunnable(
var w: Int,
var h: Int,
var oldw: Int,
var oldh: Int,
var delayIntentAction: Int
) : Runnable {
override fun run() {
val oldBottomCurrentShowHeight = bottomCurrentShowHeight
// L.i("doSizeChanged:" + oldw + "->" + w + " " + oldh + "->" + h + " " + oldBottomCurrentShowHeight + " " + intentAction);
bottomCurrentShowHeight = 0
var needAnim = isEnableSoftInputAnim()
if (handleSizeChange(w, h, oldw, oldh)) { //有可能是键盘弹出了
var diffHeight = oldh - h
val softKeyboardShow = isSoftKeyboardShow
var emojiLayoutShow = false
if (softKeyboardShow) {
lastRestoreIntentAction2 = lastRestoreIntentAction
} else {
lastRestoreIntentAction = intentAction
}
val layoutFullScreen =
isLayoutFullScreen(context)
//低版本, 普通输入框和密码输入框切换适配
if (!layoutFullScreen) {
if (softKeyboardShow) {
diffHeight = softKeyboardHeight
}
}
if (diffHeight > 0) { //当用代码调整了布局的height属性, 也会回调此方法.
if (enableSoftInputInset) {
bottomCurrentShowHeight = diffHeight
}
if (softKeyboardShow) {
lastKeyboardHeight = diffHeight
emojiLayoutShow = false
} else {
emojiLayoutShow =
intentAction == INTENT_SHOW_EMOJI
//有可能是表情布局显示
}
//键盘显示
if (!enableSoftInputAnimShow) {
needAnim = false
}
notifyEmojiLayoutChangeListener(emojiLayoutShow, softKeyboardShow, diffHeight)
if (needAnim && enableSoftInputInset) {
if (isAnimStart) {
startAnim(
Math.abs(bottomCurrentShowHeightAnim),
diffHeight,
animDuration
)
} else {
startAnim(oldBottomCurrentShowHeight, diffHeight, animDuration)
}
}
} else {
if (lastRestoreIntentAction2 == INTENT_SHOW_EMOJI && enableEmojiRestore) {
emojiLayoutShow = true
diffHeight = -diffHeight
bottomCurrentShowHeight = diffHeight
lastRestoreIntentAction2 = INTENT_NONE
}
notifyEmojiLayoutChangeListener(emojiLayoutShow, false, diffHeight)
if (isFirstLayout(oldw, oldh)) {
needAnim = false
}
//键盘显示或者表情显示
if (!enableSoftInputAnimHide) {
needAnim = false
}
if (needAnim && !emojiLayoutShow) {
if (isAnimStart) {
startAnim(
Math.abs(bottomCurrentShowHeightAnim),
0,
animDuration
)
} else {
startAnim(Math.abs(diffHeight), 0, animDuration)
}
}
}
//低版本适配
if (!layoutFullScreen) {
intentAction = delayIntentAction
}
requestLayout()
}
if (!needAnim) {
clearIntentAction()
}
delaySizeChanged = null
}
}
private inner class InsetRunnable(var insetBottom: Int) : Runnable {
override fun run() {
if (intentAction <= INTENT_HIDE_KEYBOARD) {
if (insetBottom > 0) {
intentAction = INTENT_SHOW_KEYBOARD
} else {
intentAction = INTENT_HIDE_KEYBOARD
}
cancelAnim()
insetBottom(insetBottom)
}
insetRunnable = null
}
}
companion object {
const val INTENT_NONE = 0
const val INTENT_SHOW_KEYBOARD = 1
const val INTENT_HIDE_KEYBOARD = 2
const val INTENT_SHOW_EMOJI = 3
const val INTENT_HIDE_EMOJI = 4
const val KEY_KEYBOARD_HEIGHT = "key_keyboard_height"
fun isLayoutFullScreen(context: Context?): Boolean {
if (context == null) {
return false
}
return if (context is Activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val window = context.window
val systemUiVisibility = window.decorView.systemUiVisibility
systemUiVisibility and View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN == View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
} else {
false
}
} else {
false
}
}
fun getSoftKeyboardHeight(view: View): Int {
var view = view
val context = view.context
var screenHeight = 0
val isLollipop = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
if (context is Activity && isLayoutFullScreen(context)) {
val window = context.window
view = window.decorView
screenHeight =
window.findViewById<View>(Window.ID_ANDROID_CONTENT)
.measuredHeight
} else {
screenHeight = view.resources.displayMetrics.heightPixels
if (isLollipop) {
screenHeight += view.getStatusBarHeight()
}
}
val rect = Rect()
view.getWindowVisibleDisplayFrame(rect)
val visibleBottom = rect.bottom
return screenHeight - visibleBottom
}
fun adjustResize(context: Context?) { //resize 必备条件
if (context is Activity) {
val window = context.window
val softInputMode = window.attributes.softInputMode
if (softInputMode and WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
!= WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
) {
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
}
}
}
}
}
| 0
| null |
6
| 5
|
10ad5753c3ff675d7f7513db5d98665bcf6f7418
| 40,159
|
UICore
|
MIT License
|
src/gaea/src/main/kotlin/com/synebula/gaea/data/date/AlignTime.kt
|
synebula-myths
| 205,819,036
| false
| null |
package com.synebula.gaea.data.date
import java.util.*
import kotlin.math.ceil
import kotlin.math.floor
/**
* 校准时间。
* 根据标准时间和间隔时间,获取就近的校准时间。
* 如:2019-1-1 10:10:25, 根据标准时间2019-1-1 10:10:00按40s的间隔会校准为2019-1-1 10:10:40.
*/
class AlignTime {
/**
* 间隔时间,默认为1s
*/
var intervalSeconds = 1
/**
* 标准时间。默认为2018-1-1 0:0:0
*/
var baseTime = DateTime(2018, 0, 1, 0, 0, 0)
constructor(intervalSeconds: Int) {
this.intervalSeconds = intervalSeconds
}
constructor(baseTime: DateTime) {
this.baseTime = baseTime
}
constructor(baseTime: DateTime, intervalSeconds: Int) {
this.baseTime = baseTime
this.intervalSeconds = intervalSeconds
}
/**
* 获取就近的校准时间。
* 如果时间刚好是正点时间,则输出该时间。如果不是正点时间则输出大于该时间的校准正点时间。
*/
fun ceilingTime(): DateTime {
return ceilingTime(DateTime(Date()))
}
/**
* 获取就近的校准时间。
* 如果时间刚好是正点时间,则输出该时间。如果不是正点时间则输出大于该时间的校准正点时间。
*/
fun ceilingTime(lastTime: DateTime): DateTime {
return this.ceilingTime(lastTime, this.intervalSeconds)
}
/**
* 获取就近的校准时间。
* 如果时间刚好是正点时间,则输出该时间。如果不是正点时间则输出大于该时间的校准正点时间。
*/
fun ceilingTime(intervalSeconds: Int): DateTime {
return this.ceilingTime(this.baseTime, intervalSeconds)
}
/**
* 获取就近的校准时间。
* 如果时间刚好是正点时间,则输出该时间。如果不是正点时间则输出大于该时间的校准正点时间。
*/
fun ceilingTime(lastTime: DateTime, intervalSeconds: Int): DateTime {
val span = lastTime - this.baseTime
val count = ceil(span.totalSeconds / intervalSeconds).toInt()
val newTime = DateTime(this.baseTime.date)
newTime.addSecond(count * intervalSeconds)
return newTime
}
/**
* 获取就近的校准时间。
* 如果时间刚好是正点时间,则输出该时间。如果不是正点时间则输出小于该时间的校准正点时间。
*/
fun floorTime(): DateTime {
return floorTime(DateTime(Date()))
}
/**
* 获取就近的校准时间。
* 如果时间刚好是正点时间,则输出该时间。如果不是正点时间则输出小于该时间的校准正点时间。
*/
fun floorTime(lastTime: DateTime): DateTime {
return this.floorTime(lastTime, this.intervalSeconds)
}
/**
* 获取就近的校准时间。
* 如果时间刚好是正点时间,则输出该时间。如果不是正点时间则输出小于该时间的校准正点时间。
*/
fun floorTime(intervalSeconds: Int): DateTime {
return this.floorTime(this.baseTime, intervalSeconds)
}
/**
* 获取就近的校准时间。
* 如果时间刚好是正点时间,则输出该时间。如果不是正点时间则输出小于该时间的校准正点时间。
*/
fun floorTime(lastTime: DateTime, intervalSeconds: Int): DateTime {
val span = lastTime - this.baseTime
val count = floor(span.totalSeconds / intervalSeconds).toInt()
val newTime = DateTime(this.baseTime.date)
newTime.addSecond(count * intervalSeconds)
return newTime
}
}
| 0
|
Kotlin
|
0
| 0
|
c39f9d77c3a3b2bdc308a724f2be19c1ec1bd00c
| 2,697
|
gaea
|
MIT License
|
finance/src/integration-test/kotlin/net/corda/finance/flows/test/CashConfigDataFlowTest.kt
|
carolynequinn
| 153,584,745
| false
|
{"Gradle": 69, "INI": 28, "Markdown": 77, "Shell": 20, "Text": 13, "Ignore List": 10, "Java Properties": 3, "Batchfile": 4, "XML": 92, "Java": 113, "Kotlin": 1513, "YAML": 4, "Makefile": 2, "Python": 7, "Gherkin": 3, "Groovy": 2, "RPM Spec": 1, "CSS": 10, "SVG": 4, "PowerShell": 1, "JSON": 2, "AppleScript": 1, "HTML": 7, "JavaScript": 17, "reStructuredText": 132, "TeX": 6, "BibTeX": 1}
|
package net.corda.finance.flows.test
import net.corda.core.messaging.startFlow
import net.corda.core.utilities.getOrThrow
import net.corda.finance.EUR
import net.corda.finance.USD
import net.corda.finance.flows.CashConfigDataFlow
import net.corda.testing.driver.DriverParameters
import net.corda.testing.driver.driver
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class CashConfigDataFlowTest {
@Test
fun `issuable currencies are read in from node config`() {
driver(DriverParameters(
extraCordappPackagesToScan = listOf("net.corda.finance.flows"),
notarySpecs = emptyList())) {
val node = startNode(customOverrides = mapOf("custom" to mapOf("issuableCurrencies" to listOf("EUR", "USD")))).getOrThrow()
val config = node.rpc.startFlow(::CashConfigDataFlow).returnValue.getOrThrow()
assertThat(config.issuableCurrencies).containsExactly(EUR, USD)
}
}
}
| 1
| null |
1
| 1
|
cc75a65f9233b5ac0bcdc5e03c2af032c43fbba5
| 976
|
corda
|
Apache License 2.0
|
src/main/kotlin/me/stockingd/current/operators/runningFold.kt
|
dmstocking
| 375,025,377
| false
| null |
package me.stockingd.current.operators
import me.stockingd.current.Current
import me.stockingd.current.current
fun <T, S> Current<T>.runningFold(initialValue: S, action: (S, T) -> S): Current<S> = current {
var current = initialValue
collect {
current = action(current, it)
emit(current)
}
}
| 0
|
Kotlin
|
0
| 0
|
b79f8ceb1db49ae3cc8754758c14ffb9c6703e58
| 322
|
current
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppschallengesupportinterventionplanapi/service/ReferralService.kt
|
ministryofjustice
| 797,799,207
| false
|
{"Kotlin": 602050, "PLpgSQL": 47102, "Mermaid": 30603, "Shell": 1890, "Dockerfile": 1387}
|
package uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.service
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.domain.toModel
import uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.enumeration.DomainEventType.CSIP_UPDATED
import uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.events.PublishCsipEvent
import uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.exception.MissingReferralException
import uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.exception.ResourceAlreadyExistException
import uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.exception.verify
import uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.model.ContributoryFactor
import uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.model.request.CreateContributoryFactorRequest
import uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.model.request.UpdateContributoryFactorRequest
import uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.repository.ContributoryFactorRepository
import uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.repository.CsipRecordRepository
import uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.repository.ReferenceDataRepository
import uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.repository.getActiveReferenceData
import uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.repository.getContributoryFactor
import uk.gov.justice.digital.hmpps.hmppschallengesupportinterventionplanapi.repository.getCsipRecord
import java.util.UUID
@Service
@Transactional
class ReferralService(
private val csipRecordRepository: CsipRecordRepository,
private val referenceDataRepository: ReferenceDataRepository,
private val factorRepository: ContributoryFactorRepository,
) {
@PublishCsipEvent(CSIP_UPDATED)
fun addContributoryFactor(
recordUuid: UUID,
request: CreateContributoryFactorRequest,
): ContributoryFactor {
val record = csipRecordRepository.getCsipRecord(recordUuid)
val referral = requireNotNull(record.referral) { MissingReferralException(recordUuid) }
verify(referral.contributoryFactors().none { it.contributoryFactorType.code == request.factorTypeCode }) {
ResourceAlreadyExistException("Contributory factor already part of referral")
}
return referral.addContributoryFactor(request, referenceDataRepository::getActiveReferenceData).toModel()
}
@PublishCsipEvent(CSIP_UPDATED)
fun updateContributoryFactor(factorId: UUID, request: UpdateContributoryFactorRequest): ContributoryFactor {
val factor = factorRepository.getContributoryFactor(factorId)
verify(
factor.referral.contributoryFactors()
.none { it.contributoryFactorType.code == request.factorTypeCode && it.id != factorId },
) {
ResourceAlreadyExistException("Contributory factor already part of referral")
}
return factor.update(request, referenceDataRepository::getActiveReferenceData).toModel()
}
}
| 3
|
Kotlin
|
0
| 0
|
ea8d2c7bdd5368708b13675e3707efa42fda6537
| 3,288
|
hmpps-challenge-support-intervention-plan-api
|
MIT License
|
src/main/kotlin/no/nav/fo/veilarbregistrering/besvarelse/UtdanningSvar.kt
|
navikt
| 131,013,336
| false
|
{"Kotlin": 892346, "PLpgSQL": 853, "PLSQL": 546, "Dockerfile": 87}
|
package no.nav.fo.veilarbregistrering.besvarelse
import no.nav.fo.veilarbregistrering.metrics.Metric
enum class UtdanningSvar : Metric {
INGEN_UTDANNING,
GRUNNSKOLE,
VIDEREGAENDE_GRUNNUTDANNING,
VIDEREGAENDE_FAGBREV_SVENNEBREV,
HOYERE_UTDANNING_1_TIL_4,
HOYERE_UTDANNING_5_ELLER_MER,
INGEN_SVAR;
override fun fieldName(): String = "utdanning"
override fun value(): String = this.toString()
}
| 17
|
Kotlin
|
5
| 6
|
b608c00bb1a2d1fce4fa7703b24f51e692ad5860
| 431
|
veilarbregistrering
|
MIT License
|
src/main/kotlin/com/emberjs/xml/EmberXmlElementDescriptorProvider.kt
|
patricklx
| 412,986,421
| false
| null |
package com.emberjs
import com.emberjs.EmberXmlElementDescriptor.Companion.forTag
import com.intellij.psi.impl.source.html.HtmlFileImpl
import com.intellij.psi.impl.source.xml.XmlElementDescriptorProvider
import com.intellij.psi.xml.XmlTag
import com.intellij.xml.XmlElementDescriptor
class EmberXmlElementDescriptorProvider : XmlElementDescriptorProvider {
override fun getDescriptor(tag: XmlTag?): XmlElementDescriptor? {
if (tag == null) return null
if (tag.containingFile.name.endsWith(".gjs")) {
return forTag(tag)
}
if (tag.containingFile.name.endsWith(".gts")) {
return forTag(tag)
}
val containingFile = tag.containingFile as? HtmlFileImpl ?: return null
val language = containingFile.contentElementType?.language ?: return null
if (language.id !== "Handlebars") return null
return forTag(tag)
}
}
| 56
| null |
5
| 9
|
a5dcace3902fb2ccc70ae310a4d427d7037b8857
| 917
|
intellij-emberjs-experimental
|
Apache License 2.0
|
viz/d2v-viz-js/src/main/kotlin/io/data2viz/viz/SvgViz.kt
|
wbuchanan
| 131,614,774
| true
|
{"Kotlin": 1388605, "HTML": 41196, "JavaScript": 36763}
|
package io.data2viz.viz
import io.data2viz.core.CssClass
import io.data2viz.core.Point
import io.data2viz.path.PathAdapter
import io.data2viz.path.SvgPath
import org.w3c.dom.Element
import org.w3c.dom.svg.SVGElement
import kotlin.browser.document
actual fun newRect(): Rect = RectDOM()
actual fun newLine(): Line = LineDOM()
actual fun newCircle(): Circle = CircleDOM()
actual fun newGroup(): Group = ParentElement()
actual fun newText(): Text = TextDOM()
actual fun newPath(): PathVizElement = PathDOM()
fun createSVGElement(name: String, classes: String = "") = document.createElementNS("http://www.w3.org/2000/svg", name).apply {
if (classes.isNotBlank())
setAttribute("class", classes)
}
fun selectOrCreateSvg(): SVGElement {
var svgElement = document.querySelector("svg") as SVGElement?
if (svgElement == null) {
svgElement = createSVGElement("svg") as SVGElement
document.querySelector("body")!!.append(svgElement)
}
return svgElement
}
/**
* Looks for the first parent which is a svg Element.
* @throws IllegalStateException if the current element has no svg as parent
*/
fun Element.svg():Element {
fun parent(child:Element, predicate:(Element) -> Boolean): Element {
var parent = child.parentElement
while (parent != null && !predicate(parent)){
parent = parent.parentElement
}
if (parent == null) throw IllegalArgumentException("No parent matching the predicate")
return parent
}
return parent(this) {it.localName == "svg"}
}
/**
* Bootstrap a VizContext on a existing SVG element.
*/
fun Element.viz(init: VizContext.() -> Unit): VizContext {
val root = createSVGElement("g")
append(root)
val context = ParentElement(root)
init(context)
return context
}
interface DOMVizElement {
val domElement: Element
}
class ParentElement(override val domElement: Element = createSVGElement("g")) : VizContext, DOMVizElement,
StyledElement by StyledDelegate(domElement),
Transformable by TransformableDelegate(domElement) {
init {
check(domElement.namespaceURI == "http://www.w3.org/2000/svg")
}
override fun add(vizElement: VizElement) {
when (vizElement) {
is PathDOM -> {
val element = createSVGElement("path")
domElement.append(element)
element.setAttribute("d", vizElement.svgPath.path)
}
else -> domElement.appendChild((vizElement as DOMVizElement).domElement)
}
}
override fun remove(vizElement: VizElement) {
domElement.removeChild((vizElement as DOMVizElement).domElement)
}
override fun path(init: PathVizElement.() -> Unit): PathVizElement {
val svgPath = SvgPath()
val element = createSVGElement("path")
domElement.append(element)
val item = PathDOM(element, svgPath)
init(item)
element.setAttribute("d", svgPath.path)
return item
}
override fun setStyle(style: String) {
domElement.setAttribute("style", style)
}
override fun circle(init: Circle.() -> Unit): Circle {
val circle = CircleDOM(createSVGElement("circle"))
init(circle)
domElement.append(circle.domElement)
return circle
}
override fun group(init: Group.() -> Unit): Group {
val group = ParentElement(createSVGElement("g"))
init(group)
domElement.append(group.domElement)
return group
}
override fun line(init: Line.() -> Unit): Line {
val line = LineDOM()
init(line)
domElement.append(line.domElement)
return line
}
override fun rect(init: Rect.() -> Unit): Rect {
val rect = RectDOM()
init(rect)
domElement.append(rect.domElement)
return rect
}
override fun text(init: Text.() -> Unit): Text {
val text = TextDOM()
init(text)
domElement.append(text.domElement)
return text
}
}
interface AccessByAttributes {
fun setAttribute(name: String, value: String?)
fun getAttribute(name: String): String?
}
interface ElementWrapper : AccessByAttributes, DOMVizElement {
override val domElement: Element
override fun setAttribute(name: String, value: String?) {
if (value != null)
domElement.setAttribute(name, value)
else
domElement.removeAttribute(name)
}
override fun getAttribute(name: String) = domElement.getAttribute(name)
}
class PathDOM(override val domElement: Element = createSVGElement("path"), val svgPath: SvgPath = SvgPath()) : PathVizElement, ElementWrapper,
PathAdapter by svgPath,
HasFill,
HasStroke by StrokeDelegate(domElement),
StyledElement by StyledDelegate(domElement),
Transformable by TransformableDelegate(domElement) {
override var fill by FillDelegate()
}
//@SvgTagMarker
class CircleDOM(override val domElement: Element = createSVGElement("circle")) : ElementWrapper, Circle,
HasFill,
HasStroke by StrokeDelegate(domElement),
StyledElement by StyledDelegate(domElement),
Transformable by TransformableDelegate(domElement) {
override var stateManager: StateManager? = null
override var fill by FillDelegate()
override var cx: Double by DoubleAttributePropertyDelegate()
override var cy: Double by DoubleAttributePropertyDelegate()
override var radius: Double by DoubleAttributePropertyDelegate()
}
class LineDOM(override val domElement: Element = createSVGElement("line")) : ElementWrapper, Line,
HasFill,
HasStroke by StrokeDelegate(domElement),
StyledElement by StyledDelegate(domElement),
Transformable by TransformableDelegate(domElement) {
override var fill by FillDelegate()
override var x1: Double by DoubleAttributePropertyDelegate()
override var y1: Double by DoubleAttributePropertyDelegate()
override var x2: Double by DoubleAttributePropertyDelegate()
override var y2: Double by DoubleAttributePropertyDelegate()
}
class RectDOM(override val domElement: Element = createSVGElement("rect")) : ElementWrapper, Rect,
HasFill,
HasStroke by StrokeDelegate(domElement),
StyledElement by StyledDelegate(domElement),
Transformable by TransformableDelegate(domElement) {
override var stateManager: StateManager? = null
override var fill by FillDelegate()
override var x: Double by DoubleAttributePropertyDelegate()
override var y: Double by DoubleAttributePropertyDelegate()
override var width: Double by DoubleAttributePropertyDelegate()
override var height: Double by DoubleAttributePropertyDelegate()
override var rx: Double by DoubleAttributePropertyDelegate()
override var ry: Double by DoubleAttributePropertyDelegate()
}
val propertyMapping = mapOf(
"radius" to "r"
)
class TransformableDelegate(val element: Element) : Transformable {
override fun transform(init: Transform.() -> Unit) {
element.setAttribute("transform", TransformSvg().apply(init).toCommand())
}
}
class TransformSvg : Transform {
private val commands = mutableMapOf<String, String>()
fun translate(newPoint: Point) {
commands.put("translate", "translate(${newPoint.x}, ${newPoint.y})")
}
override fun translate(x: Double, y: Double) {
commands.put("translate", "translate($x, $y)")
}
fun scale(x: Number = 1, y: Number = x) {
commands.put("scale", "scale($x, $y)")
}
fun skewX(a: Number) {
commands.put("skewX", "skewX($a)")
}
fun skewY(a: Number) {
commands.put("skewY", "skewX($a)")
}
override fun rotate(degrees: Double, x: Double, y: Double) {
commands.put("rotate", "rotate($degrees, $x, $y)")
}
internal fun toCommand(): String = commands.values.joinToString(" ")
}
class StyledDelegate(val element: Element): StyledElement {
override fun addClass(cssClass: CssClass) {
element.classList.add(cssClass.name)
}
}
| 0
|
Kotlin
|
0
| 0
|
1e34ed8863f3c104363a58be45d738571429be3a
| 8,132
|
data2viz
|
Apache License 2.0
|
app/src/main/java/mustafaozhan/github/com/androcat/dagger/component/ViewModelComponent.kt
|
Mhd80
| 182,587,112
| false
|
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 2, "Proguard": 1, "Kotlin": 34, "XML": 32, "Java": 2, "JavaScript": 3}
|
package mustafaozhan.github.com.androcat.dagger.component
import dagger.Subcomponent
import mustafaozhan.github.com.androcat.annontation.PerViewModel
import mustafaozhan.github.com.androcat.dagger.module.ViewModelModule
import mustafaozhan.github.com.androcat.main.activity.MainActivityViewModel
import mustafaozhan.github.com.androcat.main.fragment.MainFragmentViewModel
import mustafaozhan.github.com.androcat.settings.SettingsFragmentViewModel
/**
* Created by <NAME> on 2018-07-22.
*/
@PerViewModel
@Subcomponent(modules = [(ViewModelModule::class)])
interface ViewModelComponent {
fun inject(mainActivityViewModel: MainActivityViewModel)
fun inject(mainFragmentViewModel: MainFragmentViewModel)
fun inject(settingsFragmentViewModel: SettingsFragmentViewModel)
}
| 1
| null |
1
| 1
|
1225aec91c0d209cdd6f18b694c329dfc3b8dd74
| 782
|
AndroCat
|
Apache License 2.0
|
mordant/src/commonTest/kotlin/com/github/ajalt/mordant/terminal/HtmlRendererTest.kt
|
ajalt
| 104,693,921
| false
| null |
package com.github.ajalt.mordant.terminal
import com.github.ajalt.mordant.rendering.TextColors.blue
import com.github.ajalt.mordant.rendering.TextColors.red
import io.kotest.matchers.shouldBe
import kotlin.js.JsName
import kotlin.test.Test
class HtmlRendererTest {
private val vt = TerminalRecorder()
private val t = Terminal(terminalInterface = vt)
init {
t.print(red("red red"))
t.println("plain")
t.print(blue("blue blue"))
}
@Test
@JsName("no_frame")
fun `no frame`() {
vt.outputAsHtml(backgroundColor = null) shouldBe """
|<html><body>
|<pre style="font-family: monospace"><code>
|<span style="color: #800000">red red</span><span>plain</span>
|<span style="color: #000080">blue blue</span>
|</code></pre>
|</body></html>
""".trimMargin()
}
@Test
@JsName("frame_no_body_tag")
fun `frame no body tag`() {
vt.outputAsHtml(includeCodeTag = false, includeBodyTag = false) shouldBe """
|<div style="border-radius: 8px;width: fit-content;padding: 0.5em 1em;filter: drop-shadow(0.5em 0.5em 0.5em black);background-color: rgb(12 12 12);">\n<div style="margin: -0.75em 0px;font-size: 2em"><span style="color: #ff5f56;">⏺ </span><span style="color: #ffbd2e;">⏺ </span><span style="color: #27c93f;">⏺ </span></div>
|<pre style="font-family: monospace">
|<span style="color: #800000">red red</span><span>plain</span>
|<span style="color: #000080">blue blue</span>
|</pre>
|</div>
""".trimMargin()
}
}
| 18
| null |
34
| 946
|
059b9a71ecbaececb0a58a197981295b0e5e0aec
| 1,613
|
mordant
|
Apache License 2.0
|
src/main/kotlin/com/sudosan/database/SchemaDetailsExtractor.kt
|
juliennix
| 286,098,484
| false
|
{"Java": 876004, "ANTLR": 31582, "Kotlin": 18361}
|
package com.sudosan.database
import com.sudosan.App
import com.sudosan.packageEntityName
import com.sudosan.entity.database.Column
import com.sudosan.entity.database.Database
import com.sudosan.entity.database.Table
import com.sudosan.entity.java.ClassMetadata
import org.neo4j.ogm.session.SessionFactory
import org.slf4j.LoggerFactory
import java.sql.DatabaseMetaData
import java.sql.DriverManager
import java.sql.ResultSet
class SchemaDetailsExtractor {
private val log = LoggerFactory.getLogger(SchemaDetailsExtractor::class.java)
val databaseName = "immcbuilder"
val userName = "root"
val password = "password"
val mySQLPort = "3306"
val hostUrl = "localhost"
fun extractDatabaseStructure() {
val sessionFactory = SessionFactory(App().configuration, packageEntityName)
val session = sessionFactory.openSession()
sessionFactory.close()
// Setup the connection with the DB
Class.forName("com.mysql.cj.jdbc.Driver")
val conn = DriverManager.getConnection("jdbc:mysql://" + hostUrl
+ ":" + mySQLPort, userName, password)
// --- LISTING DATABASE SCHEMA NAMES ---
var resultSet = conn.metaData.catalogs
while (resultSet.next()) {
log.info("Schema Name = " + resultSet.getString("TABLE_CAT"))
}
resultSet.close()
val database = Database(databaseName)
// --- LISTING DATABASE TABLE NAMES ---
val types = arrayOf("TABLE")
resultSet = conn.metaData
.getTables(databaseName, null, "%", types)
var tableName: String
while (resultSet.next()) {
tableName = resultSet.getString(3)
log.info("Table Name = $tableName")
// --- LISTING DATABASE COLUMN NAMES ---
val meta = conn.metaData
val columns = meta.getColumns(databaseName, null, tableName, "%")
val table = Table(tableName)
database.addTable(table)
table.database = database
val primaryKeys: List<String> = getPrimaryKeyList(meta, table)
val foreignKeys: HashMap<Column, Column> = getForeignKeyList(meta, table)
while (columns.next()) {
val columnName = columns.getString(4)
log.info("Column Name of table " + tableName + " = "
+ columnName)
val column = Column(tableName, columnName)
column.table = table
if (primaryKeys.contains(columnName)) {
column.isPrimary = true
}
if (foreignKeys.containsKey(column)) {
val foreignColumn = foreignKeys[column]!!
column.foreignKeyColumn = column.foreignKeyColumn.plus(foreignColumn)
}
table.addColumn(column)
session.save(column)
session.load(ClassMetadata::class.java, column.tableAndColumnName)
}
}
resultSet.close()
sessionFactory.close()
}
private fun getPrimaryKeyList(meta: DatabaseMetaData, table: Table): MutableList<String> {
val primaryKeysResultSet: ResultSet = meta.getPrimaryKeys(null, null, table.tableName)
val primaryKeys = mutableListOf<String>()
while (primaryKeysResultSet.next()) {
val columnName = primaryKeysResultSet.getString("COLUMN_NAME")
primaryKeys.add(columnName)
}
return primaryKeys
}
private fun getForeignKeyList(meta: DatabaseMetaData, table: Table): HashMap<Column, Column> {
val foreignKeysResultSet: ResultSet = meta.getImportedKeys(null, null, table.tableName)
val foreignKeys = hashMapOf<Column, Column>()
while (foreignKeysResultSet.next()) {
// Add table
val primaryTableName = foreignKeysResultSet.getString("PKTABLE_NAME")
table.foreignKeyTable = table.foreignKeyTable.plus(Table(primaryTableName))
val foreignTableName = foreignKeysResultSet.getString("FKTABLE_NAME")
val primaryColumnKey = foreignKeysResultSet.getString("PKCOLUMN_NAME")
val foreignColumnName = foreignKeysResultSet.getString("FKCOLUMN_NAME")
foreignKeys[Column(foreignTableName, foreignColumnName)] = Column(primaryTableName, primaryColumnKey)
}
return foreignKeys
}
}
| 1
| null |
1
| 1
|
8d1aab3f3c9541fb510394de833725054665c684
| 4,428
|
data-extractor
|
MIT License
|
feature/order/src/main/java/com/niyaj/order/OrderScreen.kt
|
skniyajali
| 644,752,474
| false
|
{"Kotlin": 5045629, "Shell": 16584, "Ruby": 1461, "Java": 232}
|
/*
* Copyright 2024 Sk Niyaj Ali
*
* 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.niyaj.order
import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.content.Intent
import android.os.Build
import android.util.Log
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.rememberMultiplePermissionsState
import com.niyaj.common.tags.OrderTestTags.DELETE_ORDER
import com.niyaj.common.tags.OrderTestTags.DELETE_ORDER_MESSAGE
import com.niyaj.common.utils.findActivity
import com.niyaj.common.utils.isToday
import com.niyaj.common.utils.openAppSettings
import com.niyaj.common.utils.toMilliSecond
import com.niyaj.common.utils.toPrettyDate
import com.niyaj.designsystem.components.PoposOutlinedAssistChip
import com.niyaj.designsystem.icon.PoposIcons
import com.niyaj.designsystem.theme.PoposRoomTheme
import com.niyaj.order.components.OrderedItemLayout
import com.niyaj.order.destinations.DeliveryPartnerScreenDestination
import com.niyaj.order.destinations.OrderDetailsScreenDestination
import com.niyaj.print.OrderPrintViewModel
import com.niyaj.print.PrintEvent
import com.niyaj.ui.components.BluetoothPermissionDialog
import com.niyaj.ui.components.HandleBluetoothPermissionState
import com.niyaj.ui.components.OrderTab
import com.niyaj.ui.components.OrderTabs
import com.niyaj.ui.components.OrderTabsContent
import com.niyaj.ui.components.ShareableOrderDetails
import com.niyaj.ui.components.StandardScaffoldWithOutDrawer
import com.niyaj.ui.event.ShareViewModel
import com.niyaj.ui.parameterProvider.OrderPreviewData
import com.niyaj.ui.utils.DevicePreviews
import com.niyaj.ui.utils.Screens
import com.niyaj.ui.utils.TrackScreenViewEvent
import com.niyaj.ui.utils.UiEvent
import com.niyaj.ui.utils.rememberCaptureController
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.annotation.RootNavGraph
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import com.vanpra.composematerialdialogs.MaterialDialog
import com.vanpra.composematerialdialogs.datetime.date.datepicker
import com.vanpra.composematerialdialogs.message
import com.vanpra.composematerialdialogs.rememberMaterialDialogState
import com.vanpra.composematerialdialogs.title
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import java.time.LocalDate
@RootNavGraph(start = true)
@Destination(route = Screens.ORDER_SCREEN)
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun OrderScreen(
navigator: DestinationsNavigator,
onClickEditOrder: (Int) -> Unit,
viewModel: OrderViewModel = hiltViewModel(),
shareViewModel: ShareViewModel = hiltViewModel(),
printViewModel: OrderPrintViewModel = hiltViewModel(),
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val captureController = rememberCaptureController()
val snackbarHostState = remember { SnackbarHostState() }
val dineInOrders by viewModel.dineInOrders.collectAsStateWithLifecycle()
val dineOutOrders by viewModel.dineOutOrders.collectAsStateWithLifecycle()
val selectedDate by viewModel.selectedDate.collectAsStateWithLifecycle()
val enableBluetoothContract = rememberLauncherForActivityResult(
ActivityResultContracts.StartActivityForResult(),
) {}
// This intent will open the enable bluetooth dialog
val enableBluetoothIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
val bluetoothManager = remember {
context.getSystemService(BluetoothManager::class.java)
}
val bluetoothAdapter: BluetoothAdapter? = remember {
bluetoothManager.adapter
}
val printOrder: (Int) -> Unit = {
if (bluetoothAdapter?.isEnabled == true) {
// Bluetooth is on print the receipt
printViewModel.enqueuePrintOrderWorker(it)
} else {
// Bluetooth is off, ask user to turn it on
enableBluetoothContract.launch(enableBluetoothIntent)
printViewModel.enqueuePrintOrderWorker(it)
}
}
val showSearchBar = viewModel.showSearchBar.collectAsStateWithLifecycle().value
val showShareDialog = shareViewModel.showDialog.collectAsStateWithLifecycle().value
val bluetoothPermissionsState =
// Checks if the device has Android 12 or above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
rememberMultiplePermissionsState(
permissions = listOf(
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.BLUETOOTH_CONNECT,
Manifest.permission.BLUETOOTH_SCAN,
),
)
} else {
rememberMultiplePermissionsState(
permissions = listOf(
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
),
)
}
LaunchedEffect(key1 = true) {
viewModel.eventFlow.collectLatest { event ->
when (event) {
is UiEvent.OnSuccess -> {
val result = snackbarHostState.showSnackbar(
message = event.successMessage,
actionLabel = "View",
duration = SnackbarDuration.Short,
)
if (result == SnackbarResult.ActionPerformed) {
navigator.navigate(Screens.CART_SCREEN)
}
}
is UiEvent.OnError -> {
snackbarHostState.showSnackbar(
message = event.errorMessage,
duration = SnackbarDuration.Short,
)
}
}
}
}
LaunchedEffect(key1 = true) {
printViewModel.eventFlow.collectLatest { event ->
when (event) {
is UiEvent.OnError -> {
snackbarHostState.showSnackbar(
message = event.errorMessage,
duration = SnackbarDuration.Short,
)
}
else -> {}
}
}
}
BackHandler(true) {
if (showSearchBar) {
viewModel.closeSearchBar()
} else {
navigator.popBackStack()
}
}
TrackScreenViewEvent(screenName = Screens.ORDER_SCREEN)
HandleBluetoothPermissionState(
multiplePermissionsState = bluetoothPermissionsState,
onSuccessful = {
OrderScreenContent(
modifier = Modifier,
dineInOrders = dineInOrders,
dineOutOrders = dineOutOrders,
selectedDate = selectedDate,
snackbarHostState = snackbarHostState,
showSearchBar = showSearchBar,
searchText = viewModel.searchText.value,
onOpenSearchBar = viewModel::openSearchBar,
onSearchTextChanged = viewModel::searchTextChanged,
onClearClick = viewModel::clearSearchText,
onBackClick = {
if (showSearchBar) {
viewModel.closeSearchBar()
} else {
navigator.popBackStack()
}
},
onClickPrintDeliveryReport = {
navigator.navigate(DeliveryPartnerScreenDestination)
},
onClickPrintOrder = printOrder,
onOrderEvent = viewModel::onOrderEvent,
onNavigateToHomeScreen = {
navigator.navigate(Screens.HOME_SCREEN)
},
onClickOrderDetails = {
navigator.navigate(OrderDetailsScreenDestination(it))
},
onClickEditOrder = onClickEditOrder,
onClickShareOrder = {
shareViewModel.onShowDialog()
viewModel.onOrderEvent(OrderEvent.GetShareableDetails(it))
},
)
},
onError = { shouldShowRationale ->
BluetoothPermissionDialog(
onClickRequestPermission = {
bluetoothPermissionsState.launchMultiplePermissionRequest()
},
onDismissRequest = navigator::navigateUp,
shouldShowRationale = shouldShowRationale,
onClickOpenSettings = {
context.findActivity().openAppSettings()
},
)
},
)
AnimatedVisibility(
visible = showShareDialog,
) {
val orderDetails = viewModel.orderDetails.collectAsStateWithLifecycle().value
val charges = viewModel.charges.collectAsStateWithLifecycle().value
ShareableOrderDetails(
captureController = captureController,
orderDetails = orderDetails,
charges = charges,
onDismiss = shareViewModel::onDismissDialog,
onClickShare = {
captureController.captureLongScreenshot()
},
onCaptured = { bitmap, error ->
bitmap?.let {
scope.launch {
val uri = shareViewModel.saveImage(it, context)
uri?.let {
shareViewModel.shareContent(context, "Share Image", uri)
}
}
}
error?.let {
Log.d("Capturable", "Error: ${it.message}\n${it.stackTrace.joinToString()}")
}
},
onClickPrintOrder = {
shareViewModel.onDismissDialog()
printViewModel.onPrintEvent(PrintEvent.PrintOrder(it))
},
)
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
internal fun OrderScreenContent(
modifier: Modifier = Modifier,
dineInOrders: OrderState,
dineOutOrders: OrderState,
selectedDate: String,
showSearchBar: Boolean,
searchText: String,
onOpenSearchBar: () -> Unit,
onSearchTextChanged: (String) -> Unit,
onClearClick: () -> Unit,
onBackClick: () -> Unit,
onClickPrintDeliveryReport: () -> Unit,
onClickPrintOrder: (Int) -> Unit,
onOrderEvent: (OrderEvent) -> Unit,
onNavigateToHomeScreen: () -> Unit,
onClickOrderDetails: (Int) -> Unit,
onClickEditOrder: (Int) -> Unit,
onClickShareOrder: (Int) -> Unit,
snackbarHostState: SnackbarHostState = remember { SnackbarHostState() },
) {
val dialogState = rememberMaterialDialogState()
val deleteOrderState = rememberMaterialDialogState()
var deletableOrder by remember { mutableIntStateOf(0) }
val pagerState = rememberPagerState(
initialPage = 0,
initialPageOffsetFraction = 0f,
pageCount = { 2 },
)
val showSearchIcon = if (pagerState.currentPage == 0) {
if (dineOutOrders is OrderState.Success) dineOutOrders.data.isNotEmpty() else false
} else {
if (dineInOrders is OrderState.Success) dineInOrders.data.isNotEmpty() else false
}
StandardScaffoldWithOutDrawer(
modifier = modifier,
title = if (selectedDate.isNotEmpty() && !selectedDate.isToday) "" else "Orders",
showSearchBar = showSearchBar,
showSearchIcon = showSearchIcon,
searchText = searchText,
searchPlaceholderText = "Search for orders...",
openSearchBar = onOpenSearchBar,
onSearchTextChanged = onSearchTextChanged,
onClearClick = onClearClick,
onBackClick = onBackClick,
snackbarHostState = snackbarHostState,
navActions = {
if (selectedDate.isNotEmpty() && !selectedDate.isToday) {
PoposOutlinedAssistChip(
text = selectedDate.toPrettyDate(),
icon = PoposIcons.CalenderMonth,
onClick = {
dialogState.show()
},
trailingIcon = PoposIcons.ArrowDown,
)
} else {
IconButton(
onClick = {
dialogState.show()
},
) {
Icon(
imageVector = PoposIcons.Today,
contentDescription = "Choose Date",
)
}
}
if (showSearchIcon) {
if (pagerState.currentPage == 0) {
IconButton(
onClick = onClickPrintDeliveryReport,
) {
Icon(
imageVector = PoposIcons.DeliveryDining,
contentDescription = "Print Delivery Reports",
)
}
}
}
},
) {
val showDineOutBadge = if (dineOutOrders is OrderState.Success) {
dineOutOrders.data.isNotEmpty()
} else {
false
}
val showDineInBadge = if (dineInOrders is OrderState.Success) {
dineInOrders.data.isNotEmpty()
} else {
false
}
val tabs = listOf(
OrderTab.DineOutOrder {
OrderedItemLayout(
orderState = dineOutOrders,
showSearchBar = showSearchBar,
onClickPrintOrder = onClickPrintOrder,
onClickDelete = {
deleteOrderState.show()
deletableOrder = it
},
onMarkedAsProcessing = {
onOrderEvent(OrderEvent.MarkedAsProcessing(it))
},
onNavigateToHomeScreen = onNavigateToHomeScreen,
onClickOrderDetails = onClickOrderDetails,
onClickEditOrder = onClickEditOrder,
onClickShareOrder = onClickShareOrder,
)
},
OrderTab.DineInOrder {
OrderedItemLayout(
orderState = dineInOrders,
showSearchBar = showSearchBar,
onClickPrintOrder = onClickPrintOrder,
onClickDelete = {
deleteOrderState.show()
deletableOrder = it
},
onMarkedAsProcessing = {
onOrderEvent(OrderEvent.MarkedAsProcessing(it))
},
onNavigateToHomeScreen = onNavigateToHomeScreen,
onClickOrderDetails = onClickOrderDetails,
onClickEditOrder = onClickEditOrder,
onClickShareOrder = onClickShareOrder,
)
},
)
Column(
modifier = Modifier
.fillMaxSize(),
horizontalAlignment = Alignment.Start,
verticalArrangement = Arrangement.Top,
) {
OrderTabs(
tabs = listOf(
OrderTab.DineOutOrder(showDineOutBadge),
OrderTab.DineInOrder(showDineInBadge),
),
pagerState = pagerState,
)
OrderTabsContent(tabs = tabs, pagerState = pagerState)
}
}
MaterialDialog(
dialogState = deleteOrderState,
buttons = {
positiveButton(
text = "Delete",
onClick = {
onOrderEvent(OrderEvent.DeleteOrder(deletableOrder))
deletableOrder = 0
},
)
negativeButton(
text = "Cancel",
onClick = {
deleteOrderState.hide()
deletableOrder = 0
},
)
},
) {
title(text = DELETE_ORDER)
message(text = DELETE_ORDER_MESSAGE)
}
MaterialDialog(
dialogState = dialogState,
buttons = {
positiveButton("Ok")
negativeButton("Cancel")
},
) {
datepicker(
allowedDateValidator = { date ->
date <= LocalDate.now()
},
) { date ->
onOrderEvent(OrderEvent.SelectDate(date.toMilliSecond))
}
}
}
@DevicePreviews
@Composable
private fun OrderScreenContentLoadingPreview() {
PoposRoomTheme {
OrderScreenContent(
dineInOrders = OrderState.Loading,
dineOutOrders = OrderState.Loading,
selectedDate = "",
showSearchBar = false,
searchText = "",
onOpenSearchBar = {},
onSearchTextChanged = {},
onClearClick = {},
onBackClick = {},
onClickPrintDeliveryReport = {},
onClickPrintOrder = {},
onOrderEvent = {},
onNavigateToHomeScreen = {},
onClickOrderDetails = {},
onClickEditOrder = {},
onClickShareOrder = {},
)
}
}
@DevicePreviews
@Composable
private fun OrderScreenContentEmptyPreview() {
PoposRoomTheme {
OrderScreenContent(
dineInOrders = OrderState.Empty,
dineOutOrders = OrderState.Empty,
selectedDate = "",
showSearchBar = false,
searchText = "",
onOpenSearchBar = {},
onSearchTextChanged = {},
onClearClick = {},
onBackClick = {},
onClickPrintDeliveryReport = {},
onClickPrintOrder = {},
onOrderEvent = {},
onNavigateToHomeScreen = {},
onClickOrderDetails = {},
onClickEditOrder = {},
onClickShareOrder = {},
)
}
}
@DevicePreviews
@Composable
private fun OrderScreenContentSuccessPreview() {
PoposRoomTheme {
OrderScreenContent(
dineInOrders = OrderState.Success(OrderPreviewData.dineInOrders),
dineOutOrders = OrderState.Success(OrderPreviewData.dineOutOrders),
selectedDate = "",
showSearchBar = false,
searchText = "",
onOpenSearchBar = {},
onSearchTextChanged = {},
onClearClick = {},
onBackClick = {},
onClickPrintDeliveryReport = {},
onClickPrintOrder = {},
onOrderEvent = {},
onNavigateToHomeScreen = {},
onClickOrderDetails = {},
onClickEditOrder = {},
onClickShareOrder = {},
)
}
}
| 39
|
Kotlin
|
0
| 1
|
e6c13d3175e83ba4eac80426edf6942f46518f11
| 20,698
|
PoposRoom
|
Apache License 2.0
|
common/src/commonTest/kotlin/net/rafaeltoledo/kotlin/SampleTests.kt
|
rafaeltoledo
| 198,742,482
| false
| null |
package net.rafaeltoledo.kotlin
import kotlin.test.Test
import kotlin.test.assertTrue
class SampleTests {
@Test
fun testMe() {
assertTrue(Sample().checkMe() > 0)
}
@Test
fun testProxy() {
assertTrue(Proxy().proxyHello().isNotEmpty())
}
}
| 0
|
Kotlin
|
1
| 9
|
e653cfb6f777dcf040780d70ba73c8e0bca9cc02
| 281
|
mpp-kotlin
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.