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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
idea/idea-jvm/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinDebuggerCaches.kt | JakeWharton | 99,388,807 | false | null | /*
* Copyright 2010-2015 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.idea.debugger.evaluate
import com.intellij.debugger.SourcePosition
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.libraries.LibraryUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.containers.MultiMap
import org.apache.log4j.Logger
import org.jetbrains.annotations.TestOnly
import org.jetbrains.eval4j.Value
import org.jetbrains.kotlin.analyzer.AnalysisResult
import org.jetbrains.kotlin.codegen.ClassBuilderFactories
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.analyzeAndGetResult
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks
import org.jetbrains.kotlin.idea.debugger.BinaryCacheKey
import org.jetbrains.kotlin.idea.debugger.BytecodeDebugInfo
import org.jetbrains.kotlin.idea.debugger.createWeakBytecodeDebugInfoStorage
import org.jetbrains.kotlin.idea.debugger.evaluate.classLoading.ClassToLoad
import org.jetbrains.kotlin.idea.runInReadActionWithWriteActionPriorityWithPCE
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.KtCodeFragment
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.types.KotlinType
import java.util.*
import java.util.concurrent.ConcurrentHashMap
class KotlinDebuggerCaches(project: Project) {
private val cachedCompiledData = CachedValuesManager.getManager(project).createCachedValue(
{
CachedValueProvider.Result<MultiMap<String, CompiledDataDescriptor>>(
MultiMap.create(), PsiModificationTracker.MODIFICATION_COUNT)
}, false)
private val cachedClassNames = CachedValuesManager.getManager(project).createCachedValue(
{
CachedValueProvider.Result<MutableMap<PsiElement, List<String>>>(
ConcurrentHashMap<PsiElement, List<String>>(),
PsiModificationTracker.MODIFICATION_COUNT)
}, false)
private val cachedTypeMappers = CachedValuesManager.getManager(project).createCachedValue(
{
CachedValueProvider.Result<MutableMap<PsiElement, KotlinTypeMapper>>(
ConcurrentHashMap<PsiElement, KotlinTypeMapper>(),
PsiModificationTracker.MODIFICATION_COUNT)
}, false)
private val debugInfoCache = CachedValuesManager.getManager(project).createCachedValue(
{
CachedValueProvider.Result(
createWeakBytecodeDebugInfoStorage(),
PsiModificationTracker.MODIFICATION_COUNT)
}, false)
companion object {
private val LOG = Logger.getLogger(KotlinDebuggerCaches::class.java)!!
fun getInstance(project: Project) = ServiceManager.getService(project, KotlinDebuggerCaches::class.java)!!
fun getOrCreateCompiledData(
codeFragment: KtCodeFragment,
sourcePosition: SourcePosition,
evaluationContext: EvaluationContextImpl,
create: (KtCodeFragment, SourcePosition) -> CompiledDataDescriptor
): CompiledDataDescriptor {
val evaluateExpressionCache = getInstance(codeFragment.project)
val text = "${codeFragment.importsToString()}\n${codeFragment.text}"
val cached = synchronized<Collection<CompiledDataDescriptor>>(evaluateExpressionCache.cachedCompiledData) {
val cache = evaluateExpressionCache.cachedCompiledData.value!!
cache[text]
}
val answer = cached.firstOrNull {
it.sourcePosition == sourcePosition || evaluateExpressionCache.canBeEvaluatedInThisContext(it, evaluationContext)
}
if (answer != null) {
return answer
}
val newCompiledData = create(codeFragment, sourcePosition)
LOG.debug("Compile bytecode for ${codeFragment.text}")
synchronized(evaluateExpressionCache.cachedCompiledData) {
evaluateExpressionCache.cachedCompiledData.value.putValue(text, newCompiledData)
}
return newCompiledData
}
fun <T : PsiElement> getOrComputeClassNames(psiElement: T?, create: (T) -> ComputedClassNames): List<String> {
if (psiElement == null) return Collections.emptyList()
val cache = getInstance(runReadAction { psiElement.project })
val classNamesCache = cache.cachedClassNames.value
val cachedValue = classNamesCache[psiElement]
if (cachedValue != null) return cachedValue
val computedClassNames = create(psiElement)
if (computedClassNames.shouldBeCached) {
classNamesCache[psiElement] = computedClassNames.classNames
}
return computedClassNames.classNames
}
fun getOrCreateTypeMapper(psiElement: PsiElement): KotlinTypeMapper {
val cache = getInstance(runReadAction { psiElement.project })
val file = runReadAction { psiElement.containingFile as KtFile }
val isInLibrary = runReadAction { LibraryUtil.findLibraryEntry(file.virtualFile, file.project) } != null
val key = if (!isInLibrary) file else psiElement
val typeMappersCache = cache.cachedTypeMappers.value
val cachedValue = typeMappersCache[key]
if (cachedValue != null) return cachedValue
val newValue = if (!isInLibrary) {
createTypeMapperForSourceFile(file)
}
else {
val element = getElementToCreateTypeMapperForLibraryFile(psiElement)
createTypeMapperForLibraryFile(element, file)
}
typeMappersCache[key] = newValue
return newValue
}
fun getOrReadDebugInfoFromBytecode(
project: Project,
jvmName: JvmClassName,
file: VirtualFile): BytecodeDebugInfo? {
val cache = getInstance(project)
return cache.debugInfoCache.value[BinaryCacheKey(project, jvmName, file)]
}
private fun getElementToCreateTypeMapperForLibraryFile(element: PsiElement?) =
runReadAction { element as? KtElement ?: PsiTreeUtil.getParentOfType(element, KtElement::class.java)!! }
private fun createTypeMapperForLibraryFile(element: KtElement, file: KtFile): KotlinTypeMapper =
runInReadActionWithWriteActionPriorityWithPCE {
createTypeMapper(file, element.analyzeAndGetResult())
}
private fun createTypeMapperForSourceFile(file: KtFile): KotlinTypeMapper =
runInReadActionWithWriteActionPriorityWithPCE {
createTypeMapper(file, file.analyzeWithAllCompilerChecks().apply(AnalysisResult::throwIfError))
}
private fun createTypeMapper(file: KtFile, analysisResult: AnalysisResult): KotlinTypeMapper {
val state = GenerationState.Builder(
file.project,
ClassBuilderFactories.THROW_EXCEPTION,
analysisResult.moduleDescriptor,
analysisResult.bindingContext,
listOf(file),
CompilerConfiguration.EMPTY
).build()
state.beforeCompile()
return state.typeMapper
}
@TestOnly fun addTypeMapper(file: KtFile, typeMapper: KotlinTypeMapper) {
getInstance(file.project).cachedTypeMappers.value[file] = typeMapper
}
}
private fun canBeEvaluatedInThisContext(compiledData: CompiledDataDescriptor, context: EvaluationContextImpl): Boolean {
val frameVisitor = FrameVisitor(context)
return compiledData.parameters.all { p ->
val (name, jetType) = p
val value = frameVisitor.findValue(name, asmType = null, checkType = false, failIfNotFound = false)
if (value == null) return@all false
val thisDescriptor = value.asmType.getClassDescriptor(context.debugProcess.searchScope)
val superClassDescriptor = jetType.constructor.declarationDescriptor as? ClassDescriptor
return@all thisDescriptor != null && superClassDescriptor != null && runReadAction { DescriptorUtils.isSubclass(thisDescriptor, superClassDescriptor) }
}
}
data class CompiledDataDescriptor(
val classes: List<ClassToLoad>,
val sourcePosition: SourcePosition,
val parameters: ParametersDescriptor
)
class ParametersDescriptor : Iterable<Parameter> {
private val list = ArrayList<Parameter>()
fun add(name: String, jetType: KotlinType, value: Value? = null) {
list.add(Parameter(name, jetType, value))
}
override fun iterator() = list.iterator()
}
data class Parameter(val callText: String, val type: KotlinType, val value: Value? = null)
class ComputedClassNames(val classNames: List<String>, val shouldBeCached: Boolean) {
companion object {
val EMPTY = ComputedClassNames.Cached(emptyList())
fun Cached(classNames: List<String>) = ComputedClassNames(classNames, true)
fun Cached(className: String) = ComputedClassNames(Collections.singletonList(className), true)
fun NonCached(classNames: List<String>) = ComputedClassNames(classNames, false)
}
fun distinct() = ComputedClassNames(classNames.distinct(), shouldBeCached)
operator fun plus(other: ComputedClassNames) = ComputedClassNames(
classNames + other.classNames, shouldBeCached && other.shouldBeCached)
}
}
private fun String?.toList() = if (this == null) emptyList() else listOf(this) | 12 | null | 4 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 11,169 | kotlin | Apache License 2.0 |
src/main/kotlin/com/salesforce/revoman/output/report/failure/ResponseFailure.kt | salesforce-misc | 677,000,343 | false | null | /**
* ************************************************************************************************
* Copyright (c) 2023, Salesforce, Inc. All rights reserved. SPDX-License-Identifier: Apache License
* Version 2.0 For full license text, see the LICENSE file in the repo root or
* http://www.apache.org/licenses/LICENSE-2.0
* ************************************************************************************************
*/
package com.salesforce.revoman.output.report.failure
import com.salesforce.revoman.output.ExeType.TESTS_JS
import com.salesforce.revoman.output.ExeType.UNMARSHALL_RESPONSE
import com.salesforce.revoman.output.report.TxnInfo
import org.http4k.core.Request
import org.http4k.core.Response
sealed class ResponseFailure : ExeFailure() {
abstract val requestInfo: TxnInfo<Request>
abstract val responseInfo: TxnInfo<Response>
data class TestsJSFailure(
override val failure: Throwable,
override val requestInfo: TxnInfo<Request>,
override val responseInfo: TxnInfo<Response>,
) : ResponseFailure() {
override val exeType = TESTS_JS
}
data class UnmarshallResponseFailure(
override val failure: Throwable,
override val requestInfo: TxnInfo<Request>,
override val responseInfo: TxnInfo<Response>
) : ResponseFailure() {
override val exeType = UNMARSHALL_RESPONSE
}
}
| 9 | null | 5 | 6 | 1c4aa93c77a28d1d1482da14a4afbdabf3991f14 | 1,346 | ReVoman | Apache License 2.0 |
ui/src/test/java/ru/tinkoff/acquiring/sdk/redesign/cards/list/CardsDeleteViewModelTest.kt | itlogic | 293,802,517 | true | {"Kotlin": 1162428, "Java": 29422} | package ru.tinkoff.acquiring.sdk.redesign.cards.list
import androidx.lifecycle.SavedStateHandle
import app.cash.turbine.test
import common.MutableCollector
import common.assertByClassName
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import org.junit.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import ru.tinkoff.acquiring.sdk.AcquiringSdk
import ru.tinkoff.acquiring.sdk.models.options.screen.SavedCardsOptions
import ru.tinkoff.acquiring.sdk.redesign.cards.list.models.CardItemUiModel
import ru.tinkoff.acquiring.sdk.redesign.cards.list.presentation.CardsListViewModel
import ru.tinkoff.acquiring.sdk.redesign.cards.list.ui.CardListEvent
import ru.tinkoff.acquiring.sdk.redesign.cards.list.ui.CardListMode
import ru.tinkoff.acquiring.sdk.redesign.cards.list.ui.CardsListState
import ru.tinkoff.acquiring.sdk.requests.RemoveCardRequest
import ru.tinkoff.acquiring.sdk.responses.RemoveCardResponse
import ru.tinkoff.acquiring.sdk.utils.*
import java.lang.Exception
import java.util.concurrent.Executors
/**
* Created by <NAME>
*/
internal class CardsDeleteViewModelTest {
val defaultContent = CardsListState.Content(
CardListMode.ADD, false, listOf(createCard("1"), createCard("2")),
)
val extendsContent = CardsListState.Content(
CardListMode.ADD, false, listOf(createCard("1"), createCard("2"), createCard("3")),
)
@Test
fun `when card delete complete`() = runBlocking {
with(Environment(initState = defaultContent)) {
eventCollector.takeValues(2)
setResponse(RequestResult.Success(RemoveCardResponse(1)))
val card = createCard("1")
vm.deleteCard(card, "")
eventCollector.joinWithTimeout()
eventCollector.flow.test {
assertByClassName(CardListEvent.RemoveCardProgress(mock()), awaitItem())
assertByClassName(CardListEvent.RemoveCardSuccess(card, null), awaitItem())
awaitComplete()
}
}
}
@Test
fun `when card delete throw error`() = runBlocking {
with(Environment(initState = defaultContent)) {
eventCollector.takeValues(2)
setResponse(RequestResult.Failure(Exception()))
vm.deleteCard(createCard("1"), "")
eventCollector.joinWithTimeout()
eventCollector.flow.test {
assertByClassName(CardListEvent.RemoveCardProgress(mock()), awaitItem())
assertByClassName(CardListEvent.ShowCardDeleteError(mock()), awaitItem())
awaitComplete()
}
}
}
@Test
fun `when card delete without key`() = runBlocking {
with(Environment(initState = defaultContent)) {
eventCollector.takeValues(2)
setResponse(RequestResult.Failure(Exception()))
vm.deleteCard(createCard("1"), null)
eventCollector.joinWithTimeout()
eventCollector.flow.test {
awaitItem()
assertByClassName(CardListEvent.ShowError, awaitItem())
awaitComplete()
}
}
}
@Test
fun `when card delete is offline`() = runBlocking {
with(Environment(initState = defaultContent)) {
eventCollector.takeValues(2)
setResponse(RequestResult.Failure(Exception()))
setOnline(false)
vm.deleteCard(createCard("1"), "")
eventCollector.joinWithTimeout()
eventCollector.flow.test {
awaitItem()
assertByClassName(CardListEvent.ShowError, awaitItem())
awaitComplete()
}
}
}
@Test
fun `when card delete multiply show last card`() = runBlocking {
with(Environment(initState = extendsContent)) {
stateCollector.takeValues(2)
setResponse(RequestResult.Success(RemoveCardResponse(1)))
vm.deleteCard(createCard("1"), "")
setResponse(RequestResult.Success(RemoveCardResponse(2)))
vm.deleteCard(createCard("2"), "")
stateCollector.joinWithTimeout()
stateCollector.flow.test {
assertByClassName(CardsListState.Content::class.java, awaitItem().javaClass)
assertByClassName(CardsListState.Content::class.java, awaitItem().javaClass)
awaitComplete()
}
}
}
class Environment(
initState: CardsListState,
val connectionMock: ConnectionChecker = mock { on { isOnline() } doReturn true },
val asdk: AcquiringSdk = mock { },
val savedStateHandler: SavedStateHandle = mock { on { get<SavedCardsOptions>(any()) } doReturn SavedCardsOptions() }
) {
val dispatcher: CoroutineDispatcher =
Executors.newSingleThreadExecutor().asCoroutineDispatcher()
val vm = CardsListViewModel(
savedStateHandle = savedStateHandler,
asdk,
connectionMock,
BankCaptionProvider { "Tinkoff" },
CoroutineManager(dispatcher, dispatcher)
).apply {
stateFlow.value = initState
}
val eventCollector = MutableCollector<CardListEvent>(vm.eventFlow)
val stateCollector = MutableCollector<CardsListState>(vm.stateFlow)
fun setState(initState: CardsListState) {
vm.stateFlow.value = initState
}
fun setOnline(isOnline: Boolean) {
whenever(connectionMock.isOnline()).doReturn(isOnline)
}
fun setResponse(response: RequestResult<out RemoveCardResponse>) {
val request: RemoveCardRequest =
mock { on { executeFlow() } doReturn MutableStateFlow(response) }
whenever(asdk.removeCard(any())).doReturn(request)
}
}
private fun createCard(idMock: String): CardItemUiModel = mock { on { id } doReturn idMock }
} | 0 | Kotlin | 0 | 0 | 8de009c2ae6ca40843c74799429346fcfa74820c | 6,040 | AcquiringSdkAndroid | Apache License 2.0 |
src/test/kotlin/com/github/mpe85/grampa/rule/ConditionalRuleTests.kt | mpe85 | 138,511,038 | false | {"Kotlin": 270203, "Java": 1073} | package com.github.mpe85.grampa.rule
import com.github.mpe85.grampa.context.ParserContext
import com.github.mpe85.grampa.context.RuleContext
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import io.mockk.every
import io.mockk.mockk
import java.util.function.Predicate
class ConditionalRuleTests : StringSpec({
"equals/hashCode/ToString" {
val predicate = Predicate<RuleContext<String>> { true }
val empty = EmptyRule<String>()
val never = NeverRule<String>()
val rule1 = ConditionalRule(predicate::test, empty, never)
val rule2 = ConditionalRule(predicate::test, EmptyRule(), NeverRule())
val rule3 = ConditionalRule(predicate::test, empty)
rule1 shouldBe rule2
rule1 shouldNotBe rule3
rule1 shouldNotBe Any()
rule1.hashCode() shouldBe rule2.hashCode()
rule1.hashCode() shouldNotBe rule3.hashCode()
rule1.toString() shouldBe "ConditionalRule(condition=" +
"fun java.util.function.Predicate<T>.test(T): kotlin.Boolean, thenRule=EmptyRule, elseRule=NeverRule)"
rule2.toString() shouldBe "ConditionalRule(condition=" +
"fun java.util.function.Predicate<T>.test(T): kotlin.Boolean, thenRule=EmptyRule, elseRule=NeverRule)"
rule3.toString() shouldBe "ConditionalRule(condition=" +
"fun java.util.function.Predicate<T>.test(T): kotlin.Boolean, thenRule=EmptyRule, elseRule=null)"
}
"Rule match" {
val ctx = mockk<ParserContext<String>>().apply {
every { atEndOfInput } returns false
every { currentChar } returns 'a'
every { advanceIndex(1) } returns true
}
ConditionalRule<String>({ true }, CharPredicateRule('a')).match(ctx) shouldBe true
ConditionalRule<String>({ false }, CharPredicateRule('b')).match(ctx) shouldBe true
ConditionalRule<String>({ true }, CharPredicateRule('a'), CharPredicateRule('b')).match(ctx) shouldBe true
ConditionalRule<String>({ false }, CharPredicateRule('a'), CharPredicateRule('b')).match(ctx) shouldBe false
}
})
| 7 | Kotlin | 1 | 13 | 5a59969dd2c6b464f28b513579b2ea3cae182ab8 | 2,160 | grampa | MIT License |
mybatis-plus-spring/src/test/kotlin/com/baomidou/mybatisplus/test/kotlin/User.kt | baomidou | 65,987,043 | false | {"Java": 2664861, "Kotlin": 34733, "FreeMarker": 15242} | package com.baomidou.mybatisplus.test.kotlin
import com.baomidou.mybatisplus.annotation.TableField
import com.baomidou.mybatisplus.annotation.TableName
@TableName("sys_user")
class User {
var id: Int? = null
@TableField("username")
var name: String? = null
var roleId: Int? = null
}
| 74 | Java | 4308 | 16,378 | bbf2b671b5ad2492033a2b03a4c99b56c02d7701 | 304 | mybatis-plus | Apache License 2.0 |
api/common/src/main/kotlin/uk/co/baconi/oauth/api/common/authorisation/AuthorisationCodeRepository.kt | beercan1989 | 345,334,044 | false | null | package uk.co.baconi.oauth.api.common.authorisation
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.transaction
import uk.co.baconi.oauth.api.common.client.ClientId
import uk.co.baconi.oauth.api.common.scope.ScopesSerializer
import uk.co.baconi.oauth.api.common.authentication.AuthenticatedUsername
import java.time.Instant
import java.util.*
class AuthorisationCodeRepository(private val database: Database) {
// TODO - Consider automatic expiration of token records.
companion object {
private const val BASIC = "basic"
private const val PKCE = "pkce"
}
fun insert(new: AuthorisationCode) {
transaction(database) {
AuthorisationCodeTable.insertAndGetId {
it[id] = new.value
when (new) {
is AuthorisationCode.Basic -> {
it[type] = BASIC
}
is AuthorisationCode.PKCE -> {
it[type] = PKCE
it[codeChallenge] = new.codeChallenge.value
it[codeChallengeMethod] = new.codeChallengeMethod.name
}
}
it[username] = new.username.value
it[clientId] = new.clientId.value
it[issuedAt] = new.issuedAt
it[expiresAt] = new.expiresAt
it[scopes] = new.scopes.let(ScopesSerializer::serialize)
it[redirectUri] = new.redirectUri
it[state] = new.state
}
}
}
fun findById(id: UUID): AuthorisationCode? {
return transaction(database) {
AuthorisationCodeTable
.select { AuthorisationCodeTable.id eq id }
.firstOrNull()
?.let(::toAuthorisationCode)
}
}
fun deleteById(id: UUID) {
transaction(database) {
AuthorisationCodeTable.deleteWhere { AuthorisationCodeTable.id eq id }
}
}
fun deleteExpired() {
transaction(database) {
AuthorisationCodeTable.deleteWhere { AuthorisationCodeTable.expiresAt lessEq Instant.now() }
}
}
private fun toAuthorisationCode(it: ResultRow): AuthorisationCode {
return when (val type = it[AuthorisationCodeTable.type]) {
BASIC -> AuthorisationCode.Basic(
value = it[AuthorisationCodeTable.id].value,
username = it[AuthorisationCodeTable.username].let(::AuthenticatedUsername),
clientId = it[AuthorisationCodeTable.clientId].let(::ClientId),
issuedAt = it[AuthorisationCodeTable.issuedAt],
expiresAt = it[AuthorisationCodeTable.expiresAt],
scopes = it[AuthorisationCodeTable.scopes].let(ScopesSerializer::deserialize),
redirectUri = it[AuthorisationCodeTable.redirectUri],
state = it[AuthorisationCodeTable.state],
)
PKCE -> AuthorisationCode.PKCE(
value = it[AuthorisationCodeTable.id].value,
username = it[AuthorisationCodeTable.username].let(::AuthenticatedUsername),
clientId = it[AuthorisationCodeTable.clientId].let(::ClientId),
issuedAt = it[AuthorisationCodeTable.issuedAt],
expiresAt = it[AuthorisationCodeTable.expiresAt],
scopes = it[AuthorisationCodeTable.scopes].let(ScopesSerializer::deserialize),
redirectUri = it[AuthorisationCodeTable.redirectUri],
state = it[AuthorisationCodeTable.state],
codeChallenge = CodeChallenge(checkNotNull(it[AuthorisationCodeTable.codeChallenge])),
codeChallengeMethod = enumValueOf(checkNotNull(it[AuthorisationCodeTable.codeChallengeMethod])),
)
else -> throw IllegalStateException("Unknown authorisation code type: $type")
}
}
} | 0 | Kotlin | 0 | 0 | e6377891fe624b9bc15abde0de4a31660584b00a | 3,959 | oauth-api | Apache License 2.0 |
ci/docker/image-builder/src/main/kotlin/ru/avito/image_builder/Main.kt | avito-tech | 230,265,582 | false | null | package ru.avito.image_builder
import kotlinx.cli.ArgParser
import kotlinx.cli.ExperimentalCli
import ru.avito.image_builder.internal.cli.BuildImage
import ru.avito.image_builder.internal.cli.PublishEmceeImage
import ru.avito.image_builder.internal.cli.PublishEmceeWorker
import ru.avito.image_builder.internal.cli.PublishEmulator
import ru.avito.image_builder.internal.cli.PublishImage
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.logging.Level
import java.util.logging.LogRecord
import java.util.logging.Logger
import java.util.logging.SimpleFormatter
public object Main {
@OptIn(ExperimentalCli::class)
@JvmStatic
public fun main(args: Array<String>) {
Logger.getLogger("").apply {
level = Level.INFO
for (handler in handlers) {
level = Level.INFO
// Sets up logging format similar to Emcee queue
handler.formatter = object : SimpleFormatter() {
// 2022-11-28 16:05:30.500
val dateFormatter = SimpleDateFormat("yyyy-MM-dd kk:mm:ss.SSS", Locale.ROOT)
override fun format(record: LogRecord): String {
// [INFO] 2022-11-25 16:05:30.500: Message
return "[${record.level}] ${dateFormatter.format(Date(record.millis))}: ${record.message}\n"
}
}
}
}
val parser = ArgParser(
programName = "image-builder",
)
parser.subcommands(
BuildImage("build", "Build image"),
PublishImage("publish", "Build and publish image"),
PublishEmulator("publishEmulator", "Build and publish Android emulator image"),
PublishEmceeImage("publishEmceeImage", "Build and publish Emcee queue image"),
PublishEmceeWorker("publishEmceeWorker", "Build and publish Emcee worker image")
)
parser.parse(sanitizeEmptyArgs(args))
}
private fun sanitizeEmptyArgs(args: Array<String>): Array<String> {
return if (args.isEmpty()) {
arrayOf("--help")
} else {
args
}
}
}
| 7 | null | 50 | 414 | bc94abf5cbac32ac249a653457644a83b4b715bb | 2,215 | avito-android | MIT License |
libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/targets/jvm/KotlinJvmCompilation.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@file:Suppress("PackageDirectoryMismatch") // Old package for compatibility
package org.jetbrains.kotlin.gradle.plugin.mpp
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.SourceSet
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.compile.JavaCompile
import org.jetbrains.kotlin.gradle.dsl.*
import org.jetbrains.kotlin.gradle.plugin.*
import org.jetbrains.kotlin.gradle.plugin.KotlinPluginLifecycle.Stage.AfterFinaliseDsl
import org.jetbrains.kotlin.gradle.plugin.internal.JavaSourceSetsAccessor
import org.jetbrains.kotlin.gradle.plugin.mpp.compilationImpl.KotlinCompilationImpl
import org.jetbrains.kotlin.gradle.plugin.variantImplementationFactory
import org.jetbrains.kotlin.gradle.targets.jvm.KotlinJvmTarget
import org.jetbrains.kotlin.gradle.tasks.KotlinCompilationTask
import org.jetbrains.kotlin.gradle.utils.CompletableFuture
import org.jetbrains.kotlin.gradle.utils.Future
import org.jetbrains.kotlin.gradle.utils.lenient
import javax.inject.Inject
@Suppress("TYPEALIAS_EXPANSION_DEPRECATION", "DEPRECATION")
open class KotlinJvmCompilation @Inject internal constructor(
compilation: KotlinCompilationImpl,
) : DeprecatedAbstractKotlinCompilationToRunnableFiles<KotlinJvmOptions>(compilation),
DeprecatedKotlinCompilationWithResources<KotlinJvmOptions> {
final override val target: KotlinJvmTarget = compilation.target as KotlinJvmTarget
@Suppress("DEPRECATION")
@Deprecated(
"To configure compilation compiler options use 'compileTaskProvider':\ncompilation.compileTaskProvider.configure{\n" +
" compilerOptions {}\n}"
)
override val compilerOptions: DeprecatedHasCompilerOptions<KotlinJvmCompilerOptions> =
compilation.compilerOptions.castCompilerOptionsType()
@Deprecated("Replaced with compileTaskProvider", replaceWith = ReplaceWith("compileTaskProvider"))
@Suppress("UNCHECKED_CAST", "DEPRECATION")
override val compileKotlinTaskProvider: TaskProvider<out org.jetbrains.kotlin.gradle.tasks.KotlinCompile>
get() = compilation.compileKotlinTaskProvider as TaskProvider<out org.jetbrains.kotlin.gradle.tasks.KotlinCompile>
@Suppress("DEPRECATION")
@Deprecated("Accessing task instance directly is deprecated", replaceWith = ReplaceWith("compileTaskProvider"))
override val compileKotlinTask: org.jetbrains.kotlin.gradle.tasks.KotlinCompile
get() = compilation.compileKotlinTask as org.jetbrains.kotlin.gradle.tasks.KotlinCompile
@Suppress("UNCHECKED_CAST")
override val compileTaskProvider: TaskProvider<out KotlinCompilationTask<KotlinJvmCompilerOptions>>
get() = compilation.compileTaskProvider as TaskProvider<KotlinCompilationTask<KotlinJvmCompilerOptions>>
/**
* **Note**: requesting this too early (right after target creation and before any target configuration) may falsely return `null`
* value, but later target will be configured to run with Java enabled. If possible, please use [compileJavaTaskProviderSafe].
*/
val compileJavaTaskProvider: TaskProvider<out JavaCompile>?
get() = if (target.withJavaEnabled) {
val project = target.project
val javaSourceSets = project.variantImplementationFactory<JavaSourceSetsAccessor.JavaSourceSetsAccessorVariantFactory>()
.getInstance(project)
.sourceSets
val javaSourceSet = javaSourceSets.getByName(compilationName)
project.tasks.withType(JavaCompile::class.java).named(javaSourceSet.compileJavaTaskName)
} else null
/**
* Alternative to [compileJavaTaskProvider] to safely receive [JavaCompile] task provider when [KotlinJvmTarget.withJavaEnabled]
* will be enabled after call to this method.
*/
internal val compileJavaTaskProviderSafe: Provider<JavaCompile> = target.project.providers
.provider { javaSourceSet.lenient.getOrNull() }
.flatMap { javaSourceSet ->
checkNotNull(javaSourceSet)
project.tasks.named(javaSourceSet.compileJavaTaskName, JavaCompile::class.java)
}
internal val javaSourceSet: Future<SourceSet?> get() = javaSourceSetImpl
private val javaSourceSetImpl: CompletableFuture<SourceSet?> = CompletableFuture<SourceSet?>().also { future ->
/**
* If no SourceSet was set until 'AfterFinaliseDsl', then user really did never call into 'withJava', hence
* we can complete the Future with 'null' notifying everybody, that there won't be any java source set associated with
* this compilation
*/
target.project.launchInStage(AfterFinaliseDsl) {
if (!future.isCompleted) {
future.complete(null)
}
}
}
internal fun maybeCreateJavaSourceSet(): SourceSet {
check(target.withJavaEnabled)
val sourceSet = target.project.javaSourceSets.maybeCreate(compilationName)
javaSourceSetImpl.complete(sourceSet)
return sourceSet
}
override val processResourcesTaskName: String
get() = compilation.processResourcesTaskName ?: error("Missing 'processResourcesTaskName'")
}
| 183 | null | 5771 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 5,373 | kotlin | Apache License 2.0 |
libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/targets/jvm/KotlinJvmCompilation.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@file:Suppress("PackageDirectoryMismatch") // Old package for compatibility
package org.jetbrains.kotlin.gradle.plugin.mpp
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.SourceSet
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.compile.JavaCompile
import org.jetbrains.kotlin.gradle.dsl.*
import org.jetbrains.kotlin.gradle.plugin.*
import org.jetbrains.kotlin.gradle.plugin.KotlinPluginLifecycle.Stage.AfterFinaliseDsl
import org.jetbrains.kotlin.gradle.plugin.internal.JavaSourceSetsAccessor
import org.jetbrains.kotlin.gradle.plugin.mpp.compilationImpl.KotlinCompilationImpl
import org.jetbrains.kotlin.gradle.plugin.variantImplementationFactory
import org.jetbrains.kotlin.gradle.targets.jvm.KotlinJvmTarget
import org.jetbrains.kotlin.gradle.tasks.KotlinCompilationTask
import org.jetbrains.kotlin.gradle.utils.CompletableFuture
import org.jetbrains.kotlin.gradle.utils.Future
import org.jetbrains.kotlin.gradle.utils.lenient
import javax.inject.Inject
@Suppress("TYPEALIAS_EXPANSION_DEPRECATION", "DEPRECATION")
open class KotlinJvmCompilation @Inject internal constructor(
compilation: KotlinCompilationImpl,
) : DeprecatedAbstractKotlinCompilationToRunnableFiles<KotlinJvmOptions>(compilation),
DeprecatedKotlinCompilationWithResources<KotlinJvmOptions> {
final override val target: KotlinJvmTarget = compilation.target as KotlinJvmTarget
@Suppress("DEPRECATION")
@Deprecated(
"To configure compilation compiler options use 'compileTaskProvider':\ncompilation.compileTaskProvider.configure{\n" +
" compilerOptions {}\n}"
)
override val compilerOptions: DeprecatedHasCompilerOptions<KotlinJvmCompilerOptions> =
compilation.compilerOptions.castCompilerOptionsType()
@Deprecated("Replaced with compileTaskProvider", replaceWith = ReplaceWith("compileTaskProvider"))
@Suppress("UNCHECKED_CAST", "DEPRECATION")
override val compileKotlinTaskProvider: TaskProvider<out org.jetbrains.kotlin.gradle.tasks.KotlinCompile>
get() = compilation.compileKotlinTaskProvider as TaskProvider<out org.jetbrains.kotlin.gradle.tasks.KotlinCompile>
@Suppress("DEPRECATION")
@Deprecated("Accessing task instance directly is deprecated", replaceWith = ReplaceWith("compileTaskProvider"))
override val compileKotlinTask: org.jetbrains.kotlin.gradle.tasks.KotlinCompile
get() = compilation.compileKotlinTask as org.jetbrains.kotlin.gradle.tasks.KotlinCompile
@Suppress("UNCHECKED_CAST")
override val compileTaskProvider: TaskProvider<out KotlinCompilationTask<KotlinJvmCompilerOptions>>
get() = compilation.compileTaskProvider as TaskProvider<KotlinCompilationTask<KotlinJvmCompilerOptions>>
/**
* **Note**: requesting this too early (right after target creation and before any target configuration) may falsely return `null`
* value, but later target will be configured to run with Java enabled. If possible, please use [compileJavaTaskProviderSafe].
*/
val compileJavaTaskProvider: TaskProvider<out JavaCompile>?
get() = if (target.withJavaEnabled) {
val project = target.project
val javaSourceSets = project.variantImplementationFactory<JavaSourceSetsAccessor.JavaSourceSetsAccessorVariantFactory>()
.getInstance(project)
.sourceSets
val javaSourceSet = javaSourceSets.getByName(compilationName)
project.tasks.withType(JavaCompile::class.java).named(javaSourceSet.compileJavaTaskName)
} else null
/**
* Alternative to [compileJavaTaskProvider] to safely receive [JavaCompile] task provider when [KotlinJvmTarget.withJavaEnabled]
* will be enabled after call to this method.
*/
internal val compileJavaTaskProviderSafe: Provider<JavaCompile> = target.project.providers
.provider { javaSourceSet.lenient.getOrNull() }
.flatMap { javaSourceSet ->
checkNotNull(javaSourceSet)
project.tasks.named(javaSourceSet.compileJavaTaskName, JavaCompile::class.java)
}
internal val javaSourceSet: Future<SourceSet?> get() = javaSourceSetImpl
private val javaSourceSetImpl: CompletableFuture<SourceSet?> = CompletableFuture<SourceSet?>().also { future ->
/**
* If no SourceSet was set until 'AfterFinaliseDsl', then user really did never call into 'withJava', hence
* we can complete the Future with 'null' notifying everybody, that there won't be any java source set associated with
* this compilation
*/
target.project.launchInStage(AfterFinaliseDsl) {
if (!future.isCompleted) {
future.complete(null)
}
}
}
internal fun maybeCreateJavaSourceSet(): SourceSet {
check(target.withJavaEnabled)
val sourceSet = target.project.javaSourceSets.maybeCreate(compilationName)
javaSourceSetImpl.complete(sourceSet)
return sourceSet
}
override val processResourcesTaskName: String
get() = compilation.processResourcesTaskName ?: error("Missing 'processResourcesTaskName'")
}
| 183 | null | 5771 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 5,373 | kotlin | Apache License 2.0 |
androidApp/src/main/java/press/editor/UrlPopupMenu.kt | saket | 201,701,386 | false | null | package press.editor
import android.content.Context
import android.graphics.Point
import android.text.style.URLSpan
import android.view.View
import androidx.appcompat.view.menu.MenuPopupHelper
import androidx.appcompat.widget.PopupMenu
import me.saket.press.shared.localization.strings
import press.extensions.reflect
class UrlPopupMenu(
context: Context,
anchor: View,
url: String
) : PopupMenu(context, anchor) {
init {
val openString = context.strings().editor.open_url
val editString = context.strings().editor.edit_url
menu.add(openString)
menu.add(editString)
setOnMenuItemClickListener { item ->
if (item.title == openString) {
URLSpan(url).onClick(anchor)
}
false
}
}
fun showAt(location: Point) {
val popupHelper = reflect<PopupMenu>().field("mPopup")?.get(this) as? MenuPopupHelper
val tryShowMethod = reflect<MenuPopupHelper>().method("tryShow", Int::class.java, Int::class.java)
if (popupHelper != null && tryShowMethod != null) {
tryShowMethod.invoke(popupHelper, location.x, location.y)
} else {
show()
}
}
}
| 13 | null | 110 | 1,849 | 5f64350ec51402f3e6aeff145cbc35438780a03c | 1,126 | press | Apache License 2.0 |
sdk/examples/fido2demo/src/main/java/com/ibm/security/verifysdk/fido2/demoapp/model/IvCreds.kt | ibm-security-verify | 430,929,749 | false | {"Kotlin": 366062} | /*
* Copyright contributors to the IBM Security Verify FIDO2 Sample App for Android project
*/
package com.ibm.security.verifysdk.fido2.demoapp.model
import kotlinx.serialization.Serializable
@Serializable
data class IvCreds(
val name: String = "ivcreds-name",
val username: String = "ivcreds-username",
val email: String = "ivcreds-email",
val AZN_CRED_PRINCIPAL_NAME: String
)
| 1 | Kotlin | 4 | 1 | fd09a6d0c6586059e5d1cd00451b32dfbfe6e36a | 401 | verify-sdk-android | MIT License |
server/src/main/com/broll/gainea/server/core/cards/impl/play/C_Spion.kt | Rolleander | 253,573,579 | false | {"Kotlin": 426720, "Java": 265966, "HTML": 1714, "CSS": 1069, "JavaScript": 24} | package com.broll.gainea.server.core.cards.impl.play
import com.broll.gainea.server.core.cards.Card
import com.broll.gainea.server.core.utils.getHostileLocations
class C_Spion : Card(8, "Spion", "Platziert einen Soldat auf ein besetztes Land eines anderen Spielers ohne einen Kampf.") {
override val isPlayable: Boolean
get() = true
override fun play() {
val locations = game.getHostileLocations(owner)
placeUnitHandler.placeSoldier(owner, locations.toList())
}
}
| 0 | Kotlin | 1 | 3 | 35593a78a4b81e1758cc9bca23e78fb14b427334 | 503 | Gainea | MIT License |
src/main/kotlin/com/fiap/order/usecases/SearchCustomerUseCase.kt | FIAP-3SOAT-G15 | 794,350,212 | false | {"Kotlin": 146232, "HCL": 4525, "Dockerfile": 283} | package com.fiap.order.usecases
import com.fiap.order.domain.entities.Customer
interface SearchCustomerUseCase {
fun searchByName(name: String): List<Customer>
}
| 1 | Kotlin | 0 | 1 | 0af711519d99107aff1ec93f60d3f2defa47e7d5 | 168 | orders-api | MIT License |
vector/src/main/java/im/vector/app/features/roommemberprofile/RoomMemberProfileController.kt | tchapgouv | 340,329,238 | false | null | /*
* Copyright 2020 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package im.vector.app.features.roommemberprofile
import com.airbnb.epoxy.TypedEpoxyController
import im.vector.app.R
import im.vector.app.core.epoxy.profiles.buildProfileAction
import im.vector.app.core.epoxy.profiles.buildProfileSection
import im.vector.app.core.resources.StringProvider
import im.vector.app.core.ui.list.genericFooterItem
import org.matrix.android.sdk.api.session.Session
import org.matrix.android.sdk.api.session.room.model.Membership
import org.matrix.android.sdk.api.session.room.powerlevels.PowerLevelsHelper
import org.matrix.android.sdk.api.session.room.powerlevels.Role
import javax.inject.Inject
class RoomMemberProfileController @Inject constructor(
private val stringProvider: StringProvider,
private val session: Session
) : TypedEpoxyController<RoomMemberProfileViewState>() {
var callback: Callback? = null
interface Callback {
fun onIgnoreClicked()
fun onTapVerify()
fun onShowDeviceList()
fun onShowDeviceListNoCrossSigning()
fun onOpenDmClicked()
fun onJumpToReadReceiptClicked()
fun onMentionClicked()
fun onEditPowerLevel(currentRole: Role)
fun onKickClicked(isSpace: Boolean)
fun onBanClicked(isSpace: Boolean, isUserBanned: Boolean)
fun onCancelInviteClicked()
fun onInviteClicked()
}
override fun buildModels(data: RoomMemberProfileViewState?) {
if (data?.userMatrixItem?.invoke() == null) {
return
}
if (data.showAsMember) {
buildRoomMemberActions(data)
} else {
buildUserActions(data)
}
}
private fun buildUserActions(state: RoomMemberProfileViewState) {
val ignoreActionTitle = state.buildIgnoreActionTitle() ?: return
// More
buildProfileSection(stringProvider.getString(R.string.room_profile_section_more))
buildProfileAction(
id = "ignore",
title = ignoreActionTitle,
destructive = true,
editable = false,
divider = false,
action = { callback?.onIgnoreClicked() }
)
if (!state.isMine) {
buildProfileAction(
id = "direct",
editable = false,
title = stringProvider.getString(R.string.room_member_open_or_create_dm),
action = { callback?.onOpenDmClicked() }
)
}
}
private fun buildRoomMemberActions(state: RoomMemberProfileViewState) {
if (!state.isSpace) {
buildSecuritySection(state)
}
buildMoreSection(state)
buildAdminSection(state)
}
private fun buildSecuritySection(state: RoomMemberProfileViewState) {
// Security
buildProfileSection(stringProvider.getString(R.string.room_profile_section_security))
val host = this
if (state.isRoomEncrypted) {
if (state.userMXCrossSigningInfo != null) {
// Cross signing is enabled for this user
if (state.userMXCrossSigningInfo.isTrusted()) {
// User is trusted
val icon = if (state.allDevicesAreTrusted) {
R.drawable.ic_shield_trusted
} else {
R.drawable.ic_shield_warning
}
val titleRes = if (state.allDevicesAreTrusted) {
R.string.verification_profile_verified
} else {
R.string.verification_profile_warning
}
buildProfileAction(
id = "learn_more",
title = stringProvider.getString(titleRes),
editable = true,
icon = icon,
tintIcon = false,
divider = false,
action = { callback?.onShowDeviceList() }
)
} else {
// Not trusted, propose to verify
if (!state.isMine) {
buildProfileAction(
id = "learn_more",
title = stringProvider.getString(R.string.verification_profile_verify),
editable = true,
icon = R.drawable.ic_shield_black,
divider = false,
action = { callback?.onTapVerify() }
)
} else {
buildProfileAction(
id = "learn_more",
title = stringProvider.getString(R.string.room_profile_section_security_learn_more),
editable = false,
divider = false,
action = { callback?.onShowDeviceListNoCrossSigning() }
)
}
genericFooterItem {
id("verify_footer")
text(host.stringProvider.getString(R.string.room_profile_encrypted_subtitle))
centered(false)
}
}
} else {
buildProfileAction(
id = "learn_more",
title = stringProvider.getString(R.string.room_profile_section_security_learn_more),
editable = false,
divider = false,
subtitle = stringProvider.getString(R.string.room_profile_encrypted_subtitle),
action = { callback?.onShowDeviceListNoCrossSigning() }
)
}
} else {
genericFooterItem {
id("verify_footer_not_encrypted")
text(host.stringProvider.getString(R.string.room_profile_not_encrypted_subtitle))
centered(false)
}
}
}
private fun buildMoreSection(state: RoomMemberProfileViewState) {
// More
if (!state.isMine) {
val membership = state.asyncMembership() ?: return
buildProfileSection(stringProvider.getString(R.string.room_profile_section_more))
buildProfileAction(
id = "direct",
editable = false,
title = stringProvider.getString(R.string.room_member_open_or_create_dm),
action = { callback?.onOpenDmClicked() }
)
if (!state.isSpace && state.hasReadReceipt) {
buildProfileAction(
id = "read_receipt",
editable = false,
title = stringProvider.getString(R.string.room_member_jump_to_read_receipt),
action = { callback?.onJumpToReadReceiptClicked() }
)
}
val ignoreActionTitle = state.buildIgnoreActionTitle()
if (!state.isSpace) {
buildProfileAction(
id = "mention",
title = stringProvider.getString(R.string.room_participants_action_mention),
editable = false,
divider = ignoreActionTitle != null,
action = { callback?.onMentionClicked() }
)
}
val canInvite = state.actionPermissions.canInvite
if (canInvite && (membership == Membership.LEAVE || membership == Membership.KNOCK)) {
buildProfileAction(
id = "invite",
title = stringProvider.getString(R.string.room_participants_action_invite),
destructive = false,
editable = false,
divider = ignoreActionTitle != null,
action = { callback?.onInviteClicked() }
)
}
if (ignoreActionTitle != null) {
buildProfileAction(
id = "ignore",
title = ignoreActionTitle,
destructive = true,
editable = false,
divider = false,
action = { callback?.onIgnoreClicked() }
)
}
}
}
private fun buildAdminSection(state: RoomMemberProfileViewState) {
val powerLevelsContent = state.powerLevelsContent ?: return
val powerLevelsStr = state.userPowerLevelString() ?: return
val powerLevelsHelper = PowerLevelsHelper(powerLevelsContent)
val userPowerLevel = powerLevelsHelper.getUserRole(state.userId)
val myPowerLevel = powerLevelsHelper.getUserRole(session.myUserId)
if ((!state.isMine && myPowerLevel <= userPowerLevel)) {
return
}
val membership = state.asyncMembership() ?: return
val canKick = !state.isMine && state.actionPermissions.canKick
val canBan = !state.isMine && state.actionPermissions.canBan
val canEditPowerLevel = state.actionPermissions.canEditPowerLevel
if (canKick || canBan || canEditPowerLevel) {
buildProfileSection(stringProvider.getString(R.string.room_profile_section_admin))
}
if (canEditPowerLevel) {
buildProfileAction(
id = "edit_power_level",
editable = true,
title = stringProvider.getString(R.string.power_level_title),
subtitle = powerLevelsStr,
divider = canKick || canBan,
editableRes = R.drawable.ic_edit,
action = { callback?.onEditPowerLevel(userPowerLevel) }
)
}
if (canKick) {
when (membership) {
Membership.JOIN -> {
buildProfileAction(
id = "kick",
editable = false,
divider = canBan,
destructive = true,
title = stringProvider.getString(R.string.room_participants_action_kick),
action = { callback?.onKickClicked(state.isSpace) }
)
}
Membership.INVITE -> {
buildProfileAction(
id = "cancel_invite",
title = stringProvider.getString(R.string.room_participants_action_cancel_invite),
divider = canBan,
destructive = true,
editable = false,
action = { callback?.onCancelInviteClicked() }
)
}
else -> Unit
}
}
if (canBan) {
val banActionTitle = if (membership == Membership.BAN) {
stringProvider.getString(R.string.room_participants_action_unban)
} else {
stringProvider.getString(R.string.room_participants_action_ban)
}
buildProfileAction(
id = "ban",
editable = false,
destructive = true,
title = banActionTitle,
action = { callback?.onBanClicked(state.isSpace, membership == Membership.BAN) }
)
}
}
private fun RoomMemberProfileViewState.buildIgnoreActionTitle(): String? {
val isIgnored = isIgnored() ?: return null
return if (isIgnored) {
stringProvider.getString(R.string.unignore)
} else {
stringProvider.getString(R.string.ignore)
}
}
}
| 96 | null | 7 | 9 | a2c060c687b0aa69af681138c5788d6933d19860 | 12,621 | tchap-android | Apache License 2.0 |
compose/ui/ui/src/test/kotlin/androidx/compose/ui/graphics/GraphicsLayerScopeTest.kt | RikkaW | 389,105,112 | false | null | /*
* Copyright 2020 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.compose.ui.graphics
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.geometry.toRect
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import com.google.common.truth.Truth.assertThat
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class GraphicsLayerScopeTest {
@Test
fun initialValuesAreCorrect() {
GraphicsLayerScope().assertCorrectDefaultValuesAreCorrect()
}
@Test
fun resetValuesAreCorrect() {
val scope = GraphicsLayerScope() as ReusableGraphicsLayerScope
scope.scaleX = 2f
scope.scaleY = 2f
scope.alpha = 0.5f
scope.translationX = 5f
scope.translationY = 5f
scope.shadowElevation = 5f
scope.rotationX = 5f
scope.rotationY = 5f
scope.rotationZ = 5f
scope.cameraDistance = 5f
scope.transformOrigin = TransformOrigin(0.7f, 0.1f)
scope.shape = object : Shape {
override fun createOutline(
size: Size,
layoutDirection: LayoutDirection,
density: Density
) = Outline.Rectangle(size.toRect())
}
scope.clip = true
scope.size = Size(100f, 200f)
scope.reset()
scope.assertCorrectDefaultValuesAreCorrect()
}
@Test
fun testDpPixelConversions() {
val scope = GraphicsLayerScope() as ReusableGraphicsLayerScope
scope.graphicsDensity = Density(2.0f, 3.0f)
with(scope) {
assertEquals(4.0f, 2f.dp.toPx())
assertEquals(6.0f, 3f.dp.toSp().toPx())
}
}
@Test
fun testGraphicsLayerSize() {
val scope = GraphicsLayerScope() as ReusableGraphicsLayerScope
scope.size = Size(2560f, 1400f)
with(scope) {
assertEquals(2560f, size.width)
assertEquals(1400f, size.height)
}
}
fun GraphicsLayerScope.assertCorrectDefaultValuesAreCorrect() {
assertThat(scaleX).isEqualTo(1f)
assertThat(scaleY).isEqualTo(1f)
assertThat(alpha).isEqualTo(1f)
assertThat(translationX).isEqualTo(0f)
assertThat(translationY).isEqualTo(0f)
assertThat(shadowElevation).isEqualTo(0f)
assertThat(rotationX).isEqualTo(0f)
assertThat(rotationY).isEqualTo(0f)
assertThat(rotationZ).isEqualTo(0f)
assertThat(cameraDistance).isEqualTo(DefaultCameraDistance)
assertThat(transformOrigin).isEqualTo(TransformOrigin.Center)
assertThat(shape).isEqualTo(RectangleShape)
assertThat(clip).isEqualTo(false)
assertThat(size).isEqualTo(Size.Unspecified)
}
}
| 29 | null | 937 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 3,426 | androidx | Apache License 2.0 |
app/src/main/java/com/umang/reminderapp/ui/components/ToDoItemCards/ToDoItemCardClicked.kt | umangSharmacs | 805,851,021 | false | {"Kotlin": 112570} | package com.umang.reminderapp.ui.components.ToDoItemCards
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.AssistChip
import androidx.compose.material3.AssistChipDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CheckboxDefaults
import androidx.compose.material3.ElevatedAssistChip
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedCard
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.umang.reminderapp.data.classes.TodoItem
import com.umang.reminderapp.ui.theme.ReminderAppTheme
@Composable
fun ToDoItemCardClicked(
modifier: Modifier = Modifier,
item: TodoItem,
onClick: () -> Unit,
onEdit: () -> Unit,
onDelete: () -> Unit
) {
OutlinedCard(
modifier = modifier,
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer,
),
shape = MaterialTheme.shapes.large,
onClick = onClick
) {
Column(){
// TOP ROW
Row(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
) {
//Checkbox
Checkbox(
modifier = Modifier.weight(1f),
checked = item.completed,
colors = CheckboxDefaults.colors(
checkedColor = MaterialTheme.colorScheme.primary,
checkmarkColor = MaterialTheme.colorScheme.onPrimary
),
onCheckedChange = { item.completed != item.completed }
)
// TITLE
Text(
modifier = Modifier.weight(4f),
text = item.title,
// color = MaterialTheme.colorScheme.onSecondaryContainer
)
// DUE DATE
Column(modifier = Modifier.weight(2f)) {
Text(
modifier = Modifier.padding(start = 5.dp, end = 5.dp),
text = "Due By",
// color = MaterialTheme.colorScheme.onSecondaryContainer
)
Text(text = item.dueDate)
}
}
// TAGS
Row(){
Spacer(modifier = Modifier.weight(1f))
// Tags row
LazyRow(
contentPadding = PaddingValues(
top = 16.dp,
end = 12.dp,
bottom = 16.dp
),
modifier = Modifier.weight(6f)
) {
items(item.tags.size) { index ->
AssistChip(
colors = AssistChipDefaults.assistChipColors(
containerColor = MaterialTheme.colorScheme.background,
labelColor = MaterialTheme.colorScheme.onBackground
),
modifier = Modifier.padding(2.dp),
onClick = { },
label = { Text(text = item.tags[index]) }
)
}
}
}
Card(
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.tertiaryContainer,
contentColor = MaterialTheme.colorScheme.onTertiaryContainer,
),
shape = MaterialTheme.shapes.large
){
// DESCRIPTION
Row(modifier=Modifier.padding(5.dp)) {
Spacer(modifier = Modifier.weight(1f))
Text(
modifier = Modifier
.padding(end = 15.dp, bottom = 15.dp)
.weight(6f),
text = item.description
)
}
// EDIT AND DELETE
Row(modifier = modifier
.fillMaxWidth()
.padding(5.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Start,
){
Spacer(modifier = Modifier.weight(1f))
Row(modifier = Modifier.weight(6f)) {
// EDIT
ElevatedAssistChip(
modifier = Modifier.padding(5.dp),
onClick = onEdit ,
leadingIcon = {Icon(imageVector = Icons.Default.Edit, contentDescription = "Edit")},
label = { Text(text = "Edit") }
)
// DELETE
ElevatedAssistChip(
modifier = Modifier.padding(5.dp),
onClick = onDelete ,
leadingIcon = {Icon(imageVector = Icons.Default.Delete, contentDescription = "Delete")},
label = { Text(text = "Delete") }
)
}
}
}
}
}
}
@Preview
@Composable
fun ToDoItemCardClickedPreview() {
val item = TodoItem()
item.title = "TitleTitleTitleTitleTitleTitleTitleTitle"
item.tags = listOf("tag1", "tag2")
item.description = "Hello World. THis is a test description to see the result of the text overflow"
ReminderAppTheme {
ToDoItemCardClicked(item = item, onClick = { }, onEdit = {}, onDelete = {})
}
} | 0 | Kotlin | 0 | 0 | 76a0ebe9c27a0340172fed34acfd35fe90115d0f | 6,781 | ReminderApp | MIT License |
scale/src/commonMain/kotlin/io/data2viz/scale/Quantize.kt | data2viz | 89,368,762 | false | null | /*
* Copyright (c) 2018-2019. data2viz sàrl.
*
* 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 io.data2viz.scale
/**
* Quantize scales are similar to linear scales, except they use a discrete rather than continuous range.
*
* The continuous input domain is divided into uniform segments based on the number of values
* in (i.e., the cardinality of) the output range.
* Each range value y can be expressed as a quantized linear function of the domain value x: y = m round(x) + b.
*/
public class QuantizeScale<R> internal constructor() : Scale<Double, R>, StrictlyContinuousDomain<Double>, DiscreteRange<R> {
private val quantizedDomain:MutableList<Double> = mutableListOf(.5)
// copy the value (no binding intended)
override var range: List<R> = listOf()
get() = field.toList()
set(value) {
field = value.toList()
rescale()
}
override var domain: StrictlyContinuous<Double> = intervalOf(0.0, 1.0)
get() = field
set(value) {
field = value
rescale()
}
private fun rescale() {
quantizedDomain.clear()
val size = range.size - 1
for(index in 0 until size) {
val element = ((index + 1) * domain.end - (index - size) * domain.start) / (size + 1)
quantizedDomain.add(element)
}
}
override fun invoke(domainValue: Double): R {
return range[bisectRight(quantizedDomain, domainValue, naturalOrder(), 0, range.size - 1)]
}
public fun invertExtent(rangeValue: R): List<Double> {
val i = range.indexOf(rangeValue)
val size = range.size - 1
return when {
i < 0 -> listOf(Double.NaN, Double.NaN)
i < 1 -> listOf(domain.start, quantizedDomain.first())
i >= size -> listOf(quantizedDomain[size - 1], domain.end)
else -> listOf(quantizedDomain[i - 1], quantizedDomain[i])
}
}
override fun copy(): QuantizeScale<R> {
return QuantizeScale<R>().also{
it.domain = domain
it.range = range
it.rescale()
}
}
}
| 80 | null | 29 | 400 | bc4ed872c526264727f868f5127e48462301dbf8 | 2,673 | data2viz | Apache License 2.0 |
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsinterventionsservice/service/DeliverySessionsServiceTest.kt | ministryofjustice | 312,544,431 | false | null | package uk.gov.justice.digital.hmpps.hmppsinterventionsservice.service
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Test
import org.mockito.ArgumentCaptor
import org.mockito.ArgumentMatchers
import org.mockito.kotlin.any
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.atLeastOnce
import org.mockito.kotlin.eq
import org.mockito.kotlin.firstValue
import org.mockito.kotlin.isNull
import org.mockito.kotlin.mock
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.springframework.http.HttpStatus
import org.springframework.web.server.ResponseStatusException
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.events.ActionPlanAppointmentEventPublisher
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.AppointmentDeliveryType
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.AppointmentSessionType
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.AppointmentType.SERVICE_DELIVERY
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.Attended
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.AuthUser
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.DeliverySession
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.repository.ActionPlanRepository
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.repository.AppointmentRepository
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.repository.AuthUserRepository
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.repository.DeliverySessionRepository
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.util.ActionPlanFactory
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.util.AuthUserFactory
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.util.DeliverySessionFactory
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.util.ReferralFactory
import java.time.OffsetDateTime
import java.util.UUID
import javax.persistence.EntityExistsException
import javax.persistence.EntityNotFoundException
internal class DeliverySessionsServiceTest {
private val actionPlanRepository: ActionPlanRepository = mock()
private val deliverySessionRepository: DeliverySessionRepository = mock()
private val authUserRepository: AuthUserRepository = mock()
private val actionPlanAppointmentEventPublisher: ActionPlanAppointmentEventPublisher = mock()
private val communityAPIBookingService: CommunityAPIBookingService = mock()
private val appointmentRepository: AppointmentRepository = mock()
private val appointmentService: AppointmentService = mock()
private val actionPlanFactory = ActionPlanFactory()
private val deliverySessionFactory = DeliverySessionFactory()
private val authUserFactory = AuthUserFactory()
private val referralFactory = ReferralFactory()
private val deliverySessionsService = DeliverySessionService(
deliverySessionRepository, actionPlanRepository,
authUserRepository, actionPlanAppointmentEventPublisher,
communityAPIBookingService, appointmentService, appointmentRepository,
)
private fun createActor(userName: String = "action_plan_session_test"): AuthUser =
authUserFactory.create(userName = userName)
.also { whenever(authUserRepository.save(it)).thenReturn(it) }
@Test
fun `create unscheduled sessions creates one for each action plan session`() {
val actionPlan = actionPlanFactory.create(numberOfSessions = 3)
whenever(deliverySessionRepository.findByReferralIdAndSessionNumber(eq(actionPlan.referral.id), any())).thenReturn(null)
whenever(authUserRepository.save(actionPlan.createdBy)).thenReturn(actionPlan.createdBy)
whenever(deliverySessionRepository.save(any())).thenAnswer { it.arguments[0] }
deliverySessionsService.createUnscheduledSessionsForActionPlan(actionPlan)
verify(deliverySessionRepository, times(3)).save(any())
}
@Test
fun `create unscheduled sessions where there is a previously approved action plan`() {
val newActionPlanId = UUID.randomUUID()
val referral = referralFactory.createSent()
val previouslyApprovedActionPlan = actionPlanFactory.createApproved(numberOfSessions = 2, referral = referral)
val newActionPlan = actionPlanFactory.createSubmitted(id = newActionPlanId, numberOfSessions = 3, referral = referral)
referral.actionPlans = mutableListOf(previouslyApprovedActionPlan, newActionPlan)
whenever(deliverySessionRepository.findAllByActionPlanId(any())).thenReturn(listOf(deliverySessionFactory.createAttended(), deliverySessionFactory.createAttended()))
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(eq(newActionPlan.id), any())).thenReturn(null)
whenever(authUserRepository.save(newActionPlan.createdBy)).thenReturn(newActionPlan.createdBy)
whenever(deliverySessionRepository.save(any())).thenAnswer { it.arguments[0] }
deliverySessionsService.createUnscheduledSessionsForActionPlan(newActionPlan)
verify(deliverySessionRepository, times(1)).save(any())
}
@Test
fun `create unscheduled sessions throws exception if session already exists`() {
val actionPlan = actionPlanFactory.create(numberOfSessions = 1)
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlan.id, 1))
.thenReturn(deliverySessionFactory.createUnscheduled(sessionNumber = 1))
assertThrows(EntityExistsException::class.java) {
deliverySessionsService.createUnscheduledSessionsForActionPlan(actionPlan)
}
}
@Test
fun `updates a session appointment for an unscheduled session`() {
val session = deliverySessionFactory.createUnscheduled()
val actionPlanId = UUID.randomUUID()
val sessionNumber = session.sessionNumber
val user = createActor("scheduler")
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, sessionNumber)).thenReturn(session)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
val appointmentTime = OffsetDateTime.now().plusHours(1)
val durationInMinutes = 200
val updatedSession = deliverySessionsService.updateSessionAppointment(
actionPlanId,
sessionNumber,
appointmentTime,
durationInMinutes,
user,
AppointmentDeliveryType.PHONE_CALL,
AppointmentSessionType.ONE_TO_ONE,
null
)
verify(appointmentService, times(1)).createOrUpdateAppointmentDeliveryDetails(any(), eq(AppointmentDeliveryType.PHONE_CALL), eq(AppointmentSessionType.ONE_TO_ONE), isNull(), isNull())
assertThat(updatedSession.currentAppointment?.appointmentTime).isEqualTo(appointmentTime)
assertThat(updatedSession.currentAppointment?.durationInMinutes).isEqualTo(durationInMinutes)
assertThat(updatedSession.currentAppointment?.createdBy?.userName).isEqualTo("scheduler")
assertThat(updatedSession.currentAppointment?.attended).isNull()
assertThat(updatedSession.currentAppointment?.additionalAttendanceInformation).isNull()
assertThat(updatedSession.currentAppointment?.notifyPPOfAttendanceBehaviour).isNull()
assertThat(updatedSession.currentAppointment?.attendanceBehaviour).isNull()
assertThat(updatedSession.currentAppointment?.attendanceSubmittedAt).isNull()
assertThat(updatedSession.currentAppointment?.attendanceSubmittedBy).isNull()
assertThat(updatedSession.currentAppointment?.attendanceBehaviourSubmittedAt).isNull()
assertThat(updatedSession.currentAppointment?.attendanceBehaviourSubmittedBy).isNull()
assertThat(updatedSession.currentAppointment?.appointmentFeedbackSubmittedAt).isNull()
assertThat(updatedSession.currentAppointment?.appointmentFeedbackSubmittedBy).isNull()
}
@Test
fun `create session appointment for a historic appointment`() {
val session = deliverySessionFactory.createUnscheduled()
val actionPlanId = UUID.randomUUID()
val sessionNumber = session.sessionNumber
val user = createActor("scheduler")
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, sessionNumber)).thenReturn(session)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
val appointmentTime = OffsetDateTime.now()
val durationInMinutes = 200
val updatedSession = deliverySessionsService.updateSessionAppointment(
actionPlanId,
sessionNumber,
appointmentTime,
durationInMinutes,
user,
AppointmentDeliveryType.PHONE_CALL,
AppointmentSessionType.ONE_TO_ONE,
null,
null,
Attended.YES,
"additional information",
false,
"description"
)
verify(appointmentService, times(1)).createOrUpdateAppointmentDeliveryDetails(any(), eq(AppointmentDeliveryType.PHONE_CALL), eq(AppointmentSessionType.ONE_TO_ONE), isNull(), isNull())
verify(actionPlanAppointmentEventPublisher).attendanceRecordedEvent(updatedSession)
verify(actionPlanAppointmentEventPublisher).behaviourRecordedEvent(updatedSession)
verify(actionPlanAppointmentEventPublisher).sessionFeedbackRecordedEvent(updatedSession)
assertThat(updatedSession.currentAppointment?.appointmentTime).isEqualTo(appointmentTime)
assertThat(updatedSession.currentAppointment?.durationInMinutes).isEqualTo(durationInMinutes)
assertThat(updatedSession.currentAppointment?.createdBy?.userName).isEqualTo("scheduler")
assertThat(updatedSession.currentAppointment?.attended).isEqualTo(Attended.YES)
assertThat(updatedSession.currentAppointment?.additionalAttendanceInformation).isEqualTo("additional information")
assertThat(updatedSession.currentAppointment?.notifyPPOfAttendanceBehaviour).isEqualTo(false)
assertThat(updatedSession.currentAppointment?.attendanceBehaviour).isEqualTo("description")
assertThat(updatedSession.currentAppointment?.attendanceSubmittedAt).isNotNull
assertThat(updatedSession.currentAppointment?.attendanceSubmittedBy).isNotNull
assertThat(updatedSession.currentAppointment?.attendanceBehaviourSubmittedAt).isNotNull
assertThat(updatedSession.currentAppointment?.attendanceBehaviourSubmittedBy).isNotNull
assertThat(updatedSession.currentAppointment?.appointmentFeedbackSubmittedAt).isNotNull
assertThat(updatedSession.currentAppointment?.appointmentFeedbackSubmittedBy).isNotNull
}
@Test
fun `updates session appointment for a historic appointment non attended`() {
val session = deliverySessionFactory.createUnscheduled()
val actionPlanId = UUID.randomUUID()
val sessionNumber = session.sessionNumber
val user = createActor("scheduler")
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, sessionNumber)).thenReturn(session)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
val appointmentTime = OffsetDateTime.now()
val durationInMinutes = 200
val updatedSession = deliverySessionsService.updateSessionAppointment(
actionPlanId,
sessionNumber,
appointmentTime,
durationInMinutes,
user,
AppointmentDeliveryType.PHONE_CALL,
AppointmentSessionType.ONE_TO_ONE,
null,
null,
Attended.NO,
"additional information"
)
verify(appointmentService, times(1)).createOrUpdateAppointmentDeliveryDetails(any(), eq(AppointmentDeliveryType.PHONE_CALL), eq(AppointmentSessionType.ONE_TO_ONE), isNull(), isNull())
assertThat(updatedSession.currentAppointment?.appointmentTime).isEqualTo(appointmentTime)
assertThat(updatedSession.currentAppointment?.durationInMinutes).isEqualTo(durationInMinutes)
assertThat(updatedSession.currentAppointment?.createdBy?.userName).isEqualTo("scheduler")
assertThat(updatedSession.currentAppointment?.attended).isEqualTo(Attended.NO)
assertThat(updatedSession.currentAppointment?.additionalAttendanceInformation).isEqualTo("additional information")
assertThat(updatedSession.currentAppointment?.notifyPPOfAttendanceBehaviour).isNull()
assertThat(updatedSession.currentAppointment?.attendanceBehaviour).isNull()
assertThat(updatedSession.currentAppointment?.attendanceSubmittedAt).isNotNull
assertThat(updatedSession.currentAppointment?.attendanceSubmittedBy).isEqualTo(user)
assertThat(updatedSession.currentAppointment?.attendanceBehaviourSubmittedAt).isNull()
assertThat(updatedSession.currentAppointment?.attendanceBehaviourSubmittedBy).isNull()
assertThat(updatedSession.currentAppointment?.appointmentFeedbackSubmittedAt).isNotNull
assertThat(updatedSession.currentAppointment?.appointmentFeedbackSubmittedBy).isEqualTo(user)
}
@Test
fun `updates a session appointment for a scheduled session`() {
val originalTime = OffsetDateTime.now()
val originalDuration = 60
val session = deliverySessionFactory.createScheduled(appointmentTime = originalTime, durationInMinutes = originalDuration)
val actionPlanId = UUID.randomUUID()
val sessionNumber = session.sessionNumber
val user = createActor("re-scheduler")
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, sessionNumber)).thenReturn(session)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
val newTime = OffsetDateTime.now()
val newDuration = 200
val updatedSession = deliverySessionsService.updateSessionAppointment(
actionPlanId,
sessionNumber,
newTime,
newDuration,
user,
AppointmentDeliveryType.PHONE_CALL,
AppointmentSessionType.ONE_TO_ONE,
null
)
verify(appointmentService, times(1)).createOrUpdateAppointmentDeliveryDetails(any(), eq(AppointmentDeliveryType.PHONE_CALL), eq(AppointmentSessionType.ONE_TO_ONE), isNull(), isNull())
assertThat(updatedSession.currentAppointment?.appointmentTime).isEqualTo(newTime)
assertThat(updatedSession.currentAppointment?.durationInMinutes).isEqualTo(newDuration)
assertThat(updatedSession.currentAppointment?.createdBy?.userName).isNotEqualTo("re-scheduler")
assertThat(updatedSession.currentAppointment?.attended).isNull()
assertThat(updatedSession.currentAppointment?.additionalAttendanceInformation).isNull()
assertThat(updatedSession.currentAppointment?.notifyPPOfAttendanceBehaviour).isNull()
assertThat(updatedSession.currentAppointment?.attendanceBehaviour).isNull()
assertThat(updatedSession.currentAppointment?.attendanceSubmittedAt).isNull()
assertThat(updatedSession.currentAppointment?.attendanceSubmittedBy).isNull()
assertThat(updatedSession.currentAppointment?.attendanceBehaviourSubmittedAt).isNull()
assertThat(updatedSession.currentAppointment?.attendanceBehaviourSubmittedBy).isNull()
assertThat(updatedSession.currentAppointment?.appointmentFeedbackSubmittedAt).isNull()
}
@Test
fun `makes a booking when a session is updated`() {
val session = deliverySessionFactory.createScheduled()
val actionPlanId = UUID.randomUUID()
val sessionNumber = session.sessionNumber
val referral = session.referral
val createdByUser = createActor("scheduler")
val appointmentTime = OffsetDateTime.now()
val durationInMinutes = 15
whenever(
communityAPIBookingService.book(
referral,
session.currentAppointment,
appointmentTime,
durationInMinutes,
SERVICE_DELIVERY,
null
)
).thenReturn(999L)
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, sessionNumber))
.thenReturn(session)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
val updatedSession = deliverySessionsService.updateSessionAppointment(
actionPlanId,
sessionNumber,
appointmentTime,
durationInMinutes,
createdByUser,
AppointmentDeliveryType.PHONE_CALL,
AppointmentSessionType.ONE_TO_ONE,
null
)
assertThat(updatedSession).isEqualTo(session)
verify(appointmentService, times(1)).createOrUpdateAppointmentDeliveryDetails(any(), eq(AppointmentDeliveryType.PHONE_CALL), eq(AppointmentSessionType.ONE_TO_ONE), isNull(), isNull())
verify(communityAPIBookingService).book(
referral,
session.currentAppointment,
appointmentTime,
durationInMinutes,
SERVICE_DELIVERY,
null
)
verify(appointmentRepository, times(1)).saveAndFlush(
ArgumentMatchers.argThat {
it.deliusAppointmentId == 999L
}
)
}
@Test
fun `does not make a booking when a session is updated because timings aren't present`() {
val session = deliverySessionFactory.createScheduled()
val actionPlanId = UUID.randomUUID()
val sessionNumber = session.sessionNumber
val referral = session.referral
val createdByUser = createActor("scheduler")
val appointmentTime = OffsetDateTime.now()
val durationInMinutes = 15
whenever(
communityAPIBookingService.book(
referral,
session.currentAppointment,
appointmentTime,
durationInMinutes,
SERVICE_DELIVERY,
null
)
).thenReturn(null)
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, sessionNumber)).thenReturn(session)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
deliverySessionsService.updateSessionAppointment(
actionPlanId,
sessionNumber,
appointmentTime,
durationInMinutes,
createdByUser,
AppointmentDeliveryType.PHONE_CALL,
AppointmentSessionType.ONE_TO_ONE,
null
)
verify(appointmentService, times(1)).createOrUpdateAppointmentDeliveryDetails(any(), eq(AppointmentDeliveryType.PHONE_CALL), eq(AppointmentSessionType.ONE_TO_ONE), isNull(), isNull())
verify(appointmentRepository, times(1)).saveAndFlush(
ArgumentMatchers.argThat {
it.deliusAppointmentId == null
}
)
}
@Test
fun `updates a session and throws exception if it not exists`() {
val actionPlanId = UUID.randomUUID()
val sessionNumber = 1
val appointmentTime = OffsetDateTime.now()
val durationInMinutes = 15
whenever(deliverySessionRepository.findByReferralIdAndSessionNumber(actionPlanId, sessionNumber)).thenReturn(null)
val exception = assertThrows(EntityNotFoundException::class.java) {
deliverySessionsService.updateSessionAppointment(
actionPlanId,
sessionNumber,
appointmentTime,
durationInMinutes,
authUserFactory.create(),
AppointmentDeliveryType.PHONE_CALL,
AppointmentSessionType.ONE_TO_ONE,
null
)
}
assertThat(exception.message).isEqualTo("Action plan session not found [actionPlanId=$actionPlanId, sessionNumber=$sessionNumber]")
}
@Test
fun `gets a session`() {
val time = OffsetDateTime.now()
val duration = 500
val session = deliverySessionFactory.createScheduled(sessionNumber = 1, appointmentTime = time, durationInMinutes = duration)
whenever(deliverySessionRepository.findByReferralIdAndSessionNumber(session.referral.id, 1)).thenReturn(session)
val actualSession = deliverySessionsService.getSession(session.referral.id, 1)
assertThat(actualSession.sessionNumber).isEqualTo(1)
assertThat(actualSession.currentAppointment?.appointmentTime).isEqualTo(time)
assertThat(actualSession.currentAppointment?.durationInMinutes).isEqualTo(duration)
}
@Test
fun `gets a session and throws exception if it not exists`() {
val referralId = UUID.randomUUID()
val sessionNumber = 1
whenever(deliverySessionRepository.findByReferralIdAndSessionNumber(referralId, sessionNumber)).thenReturn(null)
val exception = assertThrows(EntityNotFoundException::class.java) {
deliverySessionsService.getSession(referralId, sessionNumber)
}
assertThat(exception.message).isEqualTo("Action plan session not found [referralId=$referralId, sessionNumber=$sessionNumber]")
}
@Test
fun `gets all sessions for an action plan`() {
val time = OffsetDateTime.now()
val duration = 500
val session = deliverySessionFactory.createScheduled(sessionNumber = 1, appointmentTime = time, durationInMinutes = duration)
val referralId = UUID.randomUUID()
whenever(deliverySessionRepository.findAllByReferralId(referralId)).thenReturn(listOf(session))
val sessions = deliverySessionsService.getSessions(referralId)
assertThat(sessions.first().sessionNumber).isEqualTo(1)
assertThat(sessions.first().currentAppointment?.appointmentTime).isEqualTo(time)
assertThat(sessions.first().currentAppointment?.durationInMinutes).isEqualTo(duration)
}
@Test
fun `update session with attendance`() {
val attended = Attended.YES
val additionalInformation = "extra info"
val existingSession = deliverySessionFactory.createScheduled(sessionNumber = 1)
val actionPlanId = UUID.randomUUID()
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, 1))
.thenReturn(existingSession)
whenever(deliverySessionRepository.save(any())).thenReturn(existingSession)
val actor = createActor("attendance_submitter")
val savedSession = deliverySessionsService.recordAppointmentAttendance(actor, actionPlanId, 1, attended, additionalInformation)
val argumentCaptor: ArgumentCaptor<DeliverySession> = ArgumentCaptor.forClass(DeliverySession::class.java)
// verify(appointmentEventPublisher).appointmentNotAttendedEvent(existingSession)
verify(deliverySessionRepository).save(argumentCaptor.capture())
assertThat(argumentCaptor.firstValue.currentAppointment?.attended).isEqualTo(attended)
assertThat(argumentCaptor.firstValue.currentAppointment?.additionalAttendanceInformation).isEqualTo(additionalInformation)
assertThat(argumentCaptor.firstValue.currentAppointment?.attendanceSubmittedAt).isNotNull
assertThat(argumentCaptor.firstValue.currentAppointment?.attendanceSubmittedBy?.userName).isEqualTo("attendance_submitter")
assertThat(savedSession).isNotNull
}
@Test
fun `update session with attendance - no session found`() {
val actionPlanId = UUID.randomUUID()
val sessionNumber = 1
val attended = Attended.YES
val additionalInformation = "extra info"
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, sessionNumber))
.thenReturn(null)
val actor = createActor()
val exception = assertThrows(EntityNotFoundException::class.java) {
deliverySessionsService.recordAppointmentAttendance(actor, actionPlanId, 1, attended, additionalInformation)
}
assertThat(exception.message).isEqualTo("Action plan session not found [actionPlanId=$actionPlanId, sessionNumber=$sessionNumber]")
}
@Test
fun `updating session behaviour sets relevant fields`() {
val actionPlanId = UUID.randomUUID()
val session = deliverySessionFactory.createScheduled()
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(any(), any())).thenReturn(session)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
val actor = createActor("behaviour_submitter")
val updatedSession = deliverySessionsService.recordBehaviour(actor, actionPlanId, 1, "not good", false)
verify(deliverySessionRepository, times(1)).save(session)
assertThat(updatedSession).isSameAs(session)
assertThat(session.currentAppointment?.attendanceBehaviour).isEqualTo("not good")
assertThat(session.currentAppointment?.notifyPPOfAttendanceBehaviour).isFalse
assertThat(session.currentAppointment?.attendanceBehaviourSubmittedAt).isNotNull
assertThat(session.currentAppointment?.attendanceBehaviourSubmittedBy?.userName).isEqualTo("behaviour_submitter")
}
@Test
fun `updating session behaviour for missing session throws error`() {
val actor = createActor()
whenever(deliverySessionRepository.findByReferralIdAndSessionNumber(any(), any())).thenReturn(null)
assertThrows(EntityNotFoundException::class.java) {
deliverySessionsService.recordBehaviour(actor, UUID.randomUUID(), 1, "not good", false)
}
}
@Test
fun `session feedback cant be submitted more than once`() {
val session = deliverySessionFactory.createScheduled()
val actionPlanId = UUID.randomUUID()
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, 1)).thenReturn(session)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
val actor = createActor()
deliverySessionsService.recordAppointmentAttendance(actor, actionPlanId, 1, Attended.YES, "")
deliverySessionsService.recordBehaviour(actor, actionPlanId, 1, "bad", false)
deliverySessionsService.submitSessionFeedback(actionPlanId, 1, actor)
val exception = assertThrows(ResponseStatusException::class.java) {
deliverySessionsService.submitSessionFeedback(actionPlanId, 1, actor)
}
assertThat(exception.status).isEqualTo(HttpStatus.CONFLICT)
}
@Test
fun `session feedback can't be submitted without attendance`() {
val session = deliverySessionFactory.createScheduled()
val actionPlanId = UUID.randomUUID()
val actor = createActor()
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, 1)).thenReturn(session)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
deliverySessionsService.recordBehaviour(actor, actionPlanId, 1, "bad", false)
val exception = assertThrows(ResponseStatusException::class.java) {
deliverySessionsService.submitSessionFeedback(actionPlanId, 1, actor)
}
assertThat(exception.status).isEqualTo(HttpStatus.UNPROCESSABLE_ENTITY)
}
@Test
fun `session feedback can be submitted and stores time and actor`() {
val session = deliverySessionFactory.createScheduled()
val actionPlanId = UUID.randomUUID()
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, 1)).thenReturn(
session
)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
val user = createActor()
deliverySessionsService.recordAppointmentAttendance(user, actionPlanId, 1, Attended.YES, "")
deliverySessionsService.recordBehaviour(user, actionPlanId, 1, "bad", true)
val submitter = createActor("test-submitter")
deliverySessionsService.submitSessionFeedback(actionPlanId, 1, submitter)
val sessionCaptor = argumentCaptor<DeliverySession>()
verify(deliverySessionRepository, atLeastOnce()).save(sessionCaptor.capture())
sessionCaptor.allValues.forEach {
if (it == sessionCaptor.lastValue) {
assertThat(it.currentAppointment?.appointmentFeedbackSubmittedAt != null)
assertThat(it.currentAppointment?.appointmentFeedbackSubmittedBy?.userName).isEqualTo("test-submitter")
} else {
assertThat(it.currentAppointment?.appointmentFeedbackSubmittedAt == null)
assertThat(it.currentAppointment?.appointmentFeedbackSubmittedBy == null)
}
}
}
@Test
fun `session feedback emits application events`() {
val user = createActor()
val session = deliverySessionFactory.createScheduled()
val actionPlanId = UUID.randomUUID()
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, 1)).thenReturn(
session
)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
deliverySessionsService.recordAppointmentAttendance(user, actionPlanId, 1, Attended.YES, "")
deliverySessionsService.recordBehaviour(user, actionPlanId, 1, "bad", true)
deliverySessionsService.submitSessionFeedback(actionPlanId, 1, session.referral.createdBy)
verify(actionPlanAppointmentEventPublisher).attendanceRecordedEvent(session)
verify(actionPlanAppointmentEventPublisher).behaviourRecordedEvent(session)
verify(actionPlanAppointmentEventPublisher).sessionFeedbackRecordedEvent(session)
}
@Test
fun `attendance can't be updated once session feedback has been submitted`() {
val user = createActor()
val session = deliverySessionFactory.createAttended()
val actionPlanId = UUID.randomUUID()
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, 1)).thenReturn(session)
assertThrows(ResponseStatusException::class.java) {
deliverySessionsService.recordAppointmentAttendance(user, actionPlanId, 1, Attended.YES, "")
}
}
@Test
fun `behaviour can't be updated once session feedback has been submitted`() {
val user = createActor()
val session = deliverySessionFactory.createAttended()
val actionPlanId = UUID.randomUUID()
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, 1)).thenReturn(session)
assertThrows(ResponseStatusException::class.java) {
deliverySessionsService.recordBehaviour(user, actionPlanId, 1, "bad", false)
}
}
@Test
fun `session feedback can be submitted when session not attended`() {
val session = deliverySessionFactory.createScheduled()
val actionPlanId = UUID.randomUUID()
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, 1)).thenReturn(
session
)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
val user = createActor()
deliverySessionsService.recordAppointmentAttendance(user, actionPlanId, 1, Attended.NO, "")
deliverySessionsService.submitSessionFeedback(actionPlanId, 1, user)
verify(deliverySessionRepository, atLeastOnce()).save(session)
verify(actionPlanAppointmentEventPublisher).attendanceRecordedEvent(session)
verify(actionPlanAppointmentEventPublisher).sessionFeedbackRecordedEvent(session)
}
@Test
fun `session feedback can be submitted when session is attended and there is no behaviour feedback`() {
val session = deliverySessionFactory.createScheduled()
val actionPlanId = UUID.randomUUID()
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, 1)).thenReturn(
session
)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
val user = createActor()
deliverySessionsService.recordAppointmentAttendance(user, actionPlanId, 1, Attended.YES, "")
deliverySessionsService.submitSessionFeedback(actionPlanId, 1, user)
verify(deliverySessionRepository, atLeastOnce()).save(session)
verify(actionPlanAppointmentEventPublisher).attendanceRecordedEvent(session)
verify(actionPlanAppointmentEventPublisher).sessionFeedbackRecordedEvent(session)
}
@Test
fun `makes a booking with delius office location`() {
val session = deliverySessionFactory.createScheduled()
val actionPlanId = UUID.randomUUID()
val sessionNumber = session.sessionNumber
val referral = session.referral
val createdByUser = session.referral.createdBy
val appointmentTime = OffsetDateTime.now()
val durationInMinutes = 15
val npsOfficeCode = "CRS0001"
whenever(
communityAPIBookingService.book(
referral,
session.currentAppointment,
appointmentTime,
durationInMinutes,
SERVICE_DELIVERY,
npsOfficeCode
)
).thenReturn(999L)
whenever(deliverySessionRepository.findAllByActionPlanIdAndSessionNumber(actionPlanId, sessionNumber)).thenReturn(
session
)
whenever(authUserRepository.save(createdByUser)).thenReturn(createdByUser)
whenever(deliverySessionRepository.save(any())).thenReturn(session)
val updatedSession = deliverySessionsService.updateSessionAppointment(
actionPlanId,
sessionNumber,
appointmentTime,
durationInMinutes,
createdByUser,
AppointmentDeliveryType.IN_PERSON_MEETING_PROBATION_OFFICE,
AppointmentSessionType.ONE_TO_ONE,
null,
npsOfficeCode
)
assertThat(updatedSession).isEqualTo(session)
verify(appointmentService, times(1)).createOrUpdateAppointmentDeliveryDetails(any(), eq(AppointmentDeliveryType.IN_PERSON_MEETING_PROBATION_OFFICE), eq(AppointmentSessionType.ONE_TO_ONE), isNull(), eq(npsOfficeCode))
verify(communityAPIBookingService).book(
referral,
session.currentAppointment,
appointmentTime,
durationInMinutes,
SERVICE_DELIVERY,
npsOfficeCode
)
verify(appointmentRepository, times(1)).saveAndFlush(
ArgumentMatchers.argThat {
it.deliusAppointmentId == 999L
}
)
}
}
| 7 | null | 1 | 2 | e77060a93c6736b5bf9032b3c917207d6b809568 | 32,663 | hmpps-interventions-service | MIT License |
mobile_app1/module957/src/main/java/module957packageKt0/Foo446.kt | uber-common | 294,831,672 | false | null | package module1248packageKt0;
annotation class Foo446Fancy
@Foo446Fancy
class Foo446 {
fun foo0(){
module1248packageKt0.Foo445().foo6()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
fun foo4(){
foo3()
}
fun foo5(){
foo4()
}
fun foo6(){
foo5()
}
} | 6 | null | 6 | 72 | 9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e | 329 | android-build-eval | Apache License 2.0 |
mobile_app1/module957/src/main/java/module957packageKt0/Foo446.kt | uber-common | 294,831,672 | false | null | package module1248packageKt0;
annotation class Foo446Fancy
@Foo446Fancy
class Foo446 {
fun foo0(){
module1248packageKt0.Foo445().foo6()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
fun foo4(){
foo3()
}
fun foo5(){
foo4()
}
fun foo6(){
foo5()
}
} | 6 | null | 6 | 72 | 9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e | 329 | android-build-eval | Apache License 2.0 |
app/src/main/java/com/example/jetpackcomposesample/presentation/RecipeApplication.kt | vengateshm | 325,912,870 | false | {"Kotlin": 29422} | package com.example.jetpackcomposesample.presentation
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class RecipeApplication : Application() {
} | 0 | Kotlin | 0 | 1 | 19aa787692ea2be6a37a447597f3b37a15294840 | 188 | android_jetpack_compose_MVVM | Apache License 2.0 |
komapper-core/src/main/kotlin/org/komapper/core/dsl/SchemaDsl.kt | komapper | 349,909,214 | false | null | package org.komapper.core.dsl
import org.komapper.core.dsl.context.SchemaContext
import org.komapper.core.dsl.metamodel.EntityMetamodel
import org.komapper.core.dsl.query.SchemaCreateQuery
import org.komapper.core.dsl.query.SchemaCreateQueryImpl
import org.komapper.core.dsl.query.SchemaDropAllQuery
import org.komapper.core.dsl.query.SchemaDropAllQueryImpl
import org.komapper.core.dsl.query.SchemaDropQuery
import org.komapper.core.dsl.query.SchemaDropQueryImpl
/**
* The entry point for constructing schema related queries.
*/
object SchemaDsl : Dsl {
/**
* Creates a query for creating tables and their associated constraints.
*
* @param metamodels the entity metamodels
*/
fun create(metamodels: List<EntityMetamodel<*, *, *>>): SchemaCreateQuery {
return SchemaCreateQueryImpl(SchemaContext(metamodels))
}
/**
* Creates a query for creating tables and their associated constraints.
*
* @param metamodels the entity metamodels
*/
fun create(vararg metamodels: EntityMetamodel<*, *, *>): SchemaCreateQuery {
return create(metamodels.toList())
}
/**
* Creates a query for dropping tables and their associated constraints.
*
* @param metamodels the entity metamodels
*/
fun drop(metamodels: List<EntityMetamodel<*, *, *>>): SchemaDropQuery {
return SchemaDropQueryImpl(SchemaContext(metamodels))
}
/**
* Creates a query for dropping tables and their associated constraints.
*
* @param metamodels the entity metamodels
*/
fun drop(vararg metamodels: EntityMetamodel<*, *, *>): SchemaDropQuery {
return drop(metamodels.toList())
}
/**
* Creates a query for dropping all tables and their associated constraints.
*/
fun dropAll(): SchemaDropAllQuery {
return SchemaDropAllQueryImpl(SchemaContext())
}
}
| 1 | Kotlin | 0 | 20 | 2a8827d7c410a5366d875578a635b02dc176e989 | 1,900 | komapper | Apache License 2.0 |
qrose-oned/src/commonMain/kotlin/io/github/alexzhirkevich/qrose/oned/Code128Painter.kt | alexzhirkevich | 704,899,229 | false | {"Kotlin": 199162, "HTML": 564} | package io.github.alexzhirkevich.qrose.oned
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.painter.Painter
/**
* Code 128 barcode painter
*
* @param brush code brush
* @param compact Specifies whether to use compact mode for Code-128 code.
* This can yield slightly smaller bar codes. This option and [forceCodeSet] are mutually exclusive.
* @param forceCodeSet Forces which encoding will be used. This option and [compact] are mutually exclusive.
* @param onError called when input content is invalid.
* @param builder build code path using painter size and encoded boolean list.
*
* @see Code128Painter
* */
@Composable
internal fun rememberCode128Painter(
data: String,
brush: Brush = SolidColor(Color.Black),
compact : Boolean = true,
forceCodeSet : Code128Type? = null,
onError : (Throwable) -> Painter = { throw it },
builder : BarcodePathBuilder = ::defaultBarcodeBuilder
) : Painter {
val updatedBuilder by rememberUpdatedState(builder)
return remember(data, brush, forceCodeSet) {
runCatching {
Code128Painter(
data = data,
brush = brush,
compact = compact,
codeSet = forceCodeSet,
builder = { size, code ->
updatedBuilder(size, code)
},
)
}.getOrElse(onError)
}
}
enum class Code128Type(internal val v: Int) {
A(Code128Encoder.CODE_CODE_A),
B(Code128Encoder.CODE_CODE_B),
C(Code128Encoder.CODE_CODE_C)
}
@Stable
fun Code128Painter(
data : String,
brush: Brush = SolidColor(Color.Black),
compact : Boolean = true,
codeSet : Code128Type? = null,
builder : BarcodePathBuilder= ::defaultBarcodeBuilder
) = BarcodePainter(
code = Code128Encoder.encode(data, compact, codeSet),
brush = brush,
builder = builder
)
| 1 | Kotlin | 4 | 219 | 7dca5a15ba9b9eaf507a78b9e0acb3a742022679 | 2,209 | qrose | MIT License |
src/main/kotlin/dev/zacsweers/BlogActivity.kt | ZacSweers | 288,008,412 | false | null | package dev.zacsweers
import com.slack.eithernet.ApiResult
import com.slack.eithernet.ApiResultCallAdapterFactory
import com.slack.eithernet.ApiResultConverterFactory
import com.tickaroo.tikxml.TikXml
import com.tickaroo.tikxml.TypeConverter
import com.tickaroo.tikxml.annotation.Element
import com.tickaroo.tikxml.annotation.PropertyElement
import com.tickaroo.tikxml.annotation.Xml
import com.tickaroo.tikxml.converter.htmlescape.HtmlEscapeStringConverter
import com.tickaroo.tikxml.retrofit.TikXmlConverterFactory
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.create
import retrofit2.http.GET
import java.time.Instant
import java.time.format.DateTimeFormatter
// https://www.zacsweers.dev/rss/
internal interface BlogApi {
@GET("/rss")
suspend fun main(): ApiResult<Feed, Unit>
companion object {
fun create(client: OkHttpClient, tikXml: TikXml): BlogApi {
return Retrofit.Builder()
.baseUrl("https://www.zacsweers.dev")
.validateEagerly(true)
.client(client)
.addCallAdapterFactory(ApiResultCallAdapterFactory)
.addConverterFactory(ApiResultConverterFactory)
.addConverterFactory(TikXmlConverterFactory.create(tikXml))
.build()
.create()
}
}
}
@Xml
data class Feed(
@Element
val channel: Channel
)
@Xml
data class Channel(
@Element
val itemList: List<Entry>,
@PropertyElement
val title: String? = null,
@PropertyElement
val description: String? = null
)
@Xml(name = "item")
data class Entry(
@PropertyElement(converter = HtmlEscapeStringConverter::class)
val title: String,
@PropertyElement
val link: String,
@PropertyElement(converter = InstantTypeConverter::class)
val pubDate: Instant
)
internal class InstantTypeConverter : TypeConverter<Instant> {
override fun write(value: Instant): String = TODO("Unsupported")
override fun read(value: String): Instant {
return Instant.from(DateTimeFormatter.RFC_1123_DATE_TIME.parse(value))
}
}
| 4 | Kotlin | 1 | 15 | fab8139be563d2301749d596dd687bfca945ec48 | 2,001 | ZacSweers | Apache License 2.0 |
Corona-Warn-App/src/main/java/be/sciensano/coronalert/service/diagnosiskey/DiagnosisKeyService.kt | ici-be | 310,042,293 | true | {"Kotlin": 979464, "HTML": 189219} | package be.sciensano.coronalert.service.diagnosiskey
import KeyExportFormat
import be.sciensano.coronalert.storage.k
import be.sciensano.coronalert.storage.r0
import be.sciensano.coronalert.storage.resultChannel
import be.sciensano.coronalert.storage.t0
import be.sciensano.coronalert.storage.t3
import de.rki.coronawarnapp.exception.DiagnosisKeyRetrievalException
import de.rki.coronawarnapp.exception.DiagnosisKeySubmissionException
import de.rki.coronawarnapp.http.WebRequestBuilder
import de.rki.coronawarnapp.storage.LocalData
import timber.log.Timber
/**
* The Diagnosis Key Service is used to interact with the Server to submit and retrieve keys through
* predefined structures.
*
* @throws DiagnosisKeyRetrievalException An Exception thrown when an error occurs during Key Retrieval from the Server
* @throws DiagnosisKeySubmissionException An Exception thrown when an error occurs during Key Reporting to the Server
*/
object DiagnosisKeyService {
private val TAG: String? = DiagnosisKeyService::class.simpleName
/**
* Asynchronously submits keys to the Server with the WebRequestBuilder by retrieving
* keys out of the Google API.
*
*
* @throws de.rki.coronawarnapp.exception.DiagnosisKeySubmissionException An Exception thrown when an error occurs during Key Reporting to the Server
*
* @param keysToReport - KeyList in the Server Format to submit to the Server
*/
suspend fun asyncSubmitKeys(
keysToReport: List<Pair<KeyExportFormat.TemporaryExposureKey, String>>
) {
Timber.d("Diagnosis Keys will be submitted.")
val k = LocalData.k() ?: throw IllegalStateException()
val r0 = LocalData.r0() ?: throw IllegalStateException()
val t0 = LocalData.t0() ?: throw IllegalStateException()
val t3 = LocalData.t3() ?: throw IllegalStateException()
val resultChannel = LocalData.resultChannel()
if (resultChannel == -1) {
throw IllegalStateException()
}
WebRequestBuilder.getInstance().beAsyncSubmitKeysToServer(
k, r0, t0, t3, resultChannel,
keysToReport
)
}
}
| 0 | null | 0 | 0 | 652f37467a375e0857437a0615ecd6e018c9ed78 | 2,160 | cwa-app-android | Apache License 2.0 |
app/src/main/java/com/kotlin/sacalabici/data/models/medals/MedalBase.kt | Saca-la-Bici | 849,110,267 | false | {"Kotlin": 595596} | package com.kotlin.sacalabici.data.models.medals
import com.google.gson.annotations.SerializedName
data class MedalBase(
@SerializedName("_id") val id: String,
@SerializedName("nombre") val name: String,
@SerializedName("imagen") val url: String,
@SerializedName("estado") val state: Boolean,
@SerializedName("idMedalla") val idMedal: Int
) | 1 | Kotlin | 1 | 1 | b8a06baa119ffb0d355d1ae7fe7e607bb8f1c52c | 362 | app-android | MIT License |
app/src/main/java/data/repository/ItemRepository.kt | omertzroya | 809,783,374 | false | {"Kotlin": 31122} | package data.repository
import android.app.Application
import data.local_db.ItemDao
import data.local_db.ItemDataBase
import data.model.Item
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class ItemRepository(application: Application) {
private val itemDao: ItemDao? = ItemDataBase.getDatabase(application.applicationContext)?.itemsDao()
suspend fun addItem(item: Item) {
withContext(Dispatchers.IO) {
itemDao?.addItem(item)
}
}
suspend fun updateItem(item: Item) {
withContext(Dispatchers.IO) {
itemDao?.updateItem(item)
}
}
suspend fun deleteItem(item: Item) {
withContext(Dispatchers.IO) {
itemDao?.deleteItem(item)
}
}
suspend fun deleteAll() {
withContext(Dispatchers.IO) {
itemDao?.deleteAll()
}
}
fun getItems() = itemDao?.getItems()
}
| 0 | Kotlin | 0 | 0 | 1648a953c794a0441a31c9b1e21f1748851414e3 | 932 | CouponChest-Kotlin-App | MIT License |
android/engine/src/test/java/org/smartregister/fhircore/engine/ui/userprofile/UserProfileViewModelTest.kt | opensrp | 339,242,809 | false | null | /*
* Copyright 2021 Ona Systems, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartregister.fhircore.engine.ui.userprofile
import android.os.Looper
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.runs
import io.mockk.spyk
import io.mockk.verify
import javax.inject.Inject
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.robolectric.Shadows
import org.smartregister.fhircore.engine.auth.AccountAuthenticator
import org.smartregister.fhircore.engine.configuration.ConfigurationRegistry
import org.smartregister.fhircore.engine.robolectric.RobolectricTest
import org.smartregister.fhircore.engine.sync.SyncBroadcaster
import org.smartregister.fhircore.engine.sync.SyncInitiator
import org.smartregister.fhircore.engine.ui.register.model.Language
import org.smartregister.fhircore.engine.util.SecureSharedPreference
import org.smartregister.fhircore.engine.util.SharedPreferencesHelper
@HiltAndroidTest
class UserProfileViewModelTest : RobolectricTest() {
@get:Rule var hiltRule = HiltAndroidRule(this)
lateinit var userProfileViewModel: UserProfileViewModel
lateinit var accountAuthenticator: AccountAuthenticator
lateinit var secureSharedPreference: SecureSharedPreference
lateinit var sharedPreferencesHelper: SharedPreferencesHelper
lateinit var configurationRegistry: ConfigurationRegistry
@Inject lateinit var realConfigurationRegistry: ConfigurationRegistry
val syncBroadcaster = SyncBroadcaster
@Before
fun setUp() {
hiltRule.inject()
accountAuthenticator = mockk()
secureSharedPreference = mockk()
sharedPreferencesHelper = mockk()
configurationRegistry = mockk()
userProfileViewModel =
UserProfileViewModel(
syncBroadcaster,
accountAuthenticator,
secureSharedPreference,
sharedPreferencesHelper,
configurationRegistry
)
}
@Test
fun testRunSync() {
val mockSyncInitiator = mockk<SyncInitiator> { every { runSync() } returns Unit }
syncBroadcaster.unRegisterSyncInitiator()
syncBroadcaster.registerSyncInitiator(mockSyncInitiator)
userProfileViewModel.runSync()
verify { mockSyncInitiator.runSync() }
}
@Test
fun testRetrieveUsernameShouldReturnDemo() {
every { secureSharedPreference.retrieveSessionUsername() } returns "demo"
Assert.assertEquals("demo", userProfileViewModel.retrieveUsername())
verify { secureSharedPreference.retrieveSessionUsername() }
}
@Test
fun testLogoutUserShouldCallAuthLogoutService() {
every { accountAuthenticator.logout() } returns Unit
userProfileViewModel.logoutUser()
verify(exactly = 1) { accountAuthenticator.logout() }
Shadows.shadowOf(Looper.getMainLooper()).idle()
Assert.assertTrue(userProfileViewModel.onLogout.value!!)
}
@Test
fun allowSwitchingLanguagesShouldReturnTrueWhenMultipleLanguagesAreConfigured() {
val languages = listOf(Language("es", "Spanish"), Language("en", "English"))
userProfileViewModel = spyk(userProfileViewModel)
every { userProfileViewModel.languages } returns languages
Assert.assertTrue(userProfileViewModel.allowSwitchingLanguages())
}
@Test
fun allowSwitchingLanguagesShouldReturnFalseWhenConfigurationIsFalse() {
val languages = listOf(Language("es", "Spanish"))
userProfileViewModel = spyk(userProfileViewModel)
every { userProfileViewModel.languages } returns languages
Assert.assertFalse(userProfileViewModel.allowSwitchingLanguages())
}
@Test
fun loadSelectedLanguage() {
every { sharedPreferencesHelper.read(SharedPreferencesHelper.LANG, "en") } returns "fr"
Assert.assertEquals("French", userProfileViewModel.loadSelectedLanguage())
verify { sharedPreferencesHelper.read(SharedPreferencesHelper.LANG, "en") }
}
@Test
fun setLanguageShouldCallSharedPreferencesHelperWriteWithSelectedLanguageTagAndPostValue() {
val language = Language("es", "Spanish")
var postedValue: Language? = null
every { sharedPreferencesHelper.write(any(), any<String>()) } just runs
userProfileViewModel.language.observeForever { postedValue = it }
userProfileViewModel.setLanguage(language)
Shadows.shadowOf(Looper.getMainLooper()).idle()
verify { sharedPreferencesHelper.write(SharedPreferencesHelper.LANG, "es") }
Assert.assertEquals(language, postedValue!!)
}
@Test
fun fetchLanguagesShouldReturnEnglishAndSwahiliAsModels() {
every { accountAuthenticator.launchLoginScreen() } just runs
realConfigurationRegistry.loadAppConfigurations("appId", accountAuthenticator) {}
userProfileViewModel =
UserProfileViewModel(
syncBroadcaster,
accountAuthenticator,
secureSharedPreference,
sharedPreferencesHelper,
realConfigurationRegistry
)
val languages = userProfileViewModel.fetchLanguages()
Assert.assertEquals("English", languages[0].displayName)
Assert.assertEquals("en", languages[0].tag)
Assert.assertEquals("Swahili", languages[1].displayName)
Assert.assertEquals("sw", languages[1].tag)
}
@Test
fun languagesLazyPropertyShouldRunFetchLanguagesAndReturnConfiguredLanguages() {
realConfigurationRegistry.appId = "appId"
every { accountAuthenticator.launchLoginScreen() } just runs
userProfileViewModel =
spyk(
UserProfileViewModel(
syncBroadcaster,
accountAuthenticator,
secureSharedPreference,
sharedPreferencesHelper,
realConfigurationRegistry
)
)
every { userProfileViewModel.fetchLanguages() } returns mockk()
val languages = userProfileViewModel.languages
Assert.assertEquals("English", languages[0].displayName)
Assert.assertEquals("en", languages[0].tag)
Assert.assertEquals("Swahili", languages[1].displayName)
Assert.assertEquals("sw", languages[1].tag)
}
}
| 138 | Kotlin | 7 | 16 | 87dc9bc1c909cd5586dbb5d05615918c0ebd9488 | 6,560 | fhircore | Apache License 2.0 |
app/src/main/java/com/teaphy/diffutildemo/callback/DiffCallback.kt | teaphy | 127,724,997 | false | null | package com.teaphy.diffutildemo.callback
import android.os.Bundle
import android.support.v7.util.DiffUtil
import com.teaphy.diffutildemo.bean.DiffBean
import com.teaphy.diffutildemo.global.KEY_DESC
/**
* @desc
* @author Tiany
* @date 2018/4/2 0002
*/
class DiffCallback(private val oldList: List<DiffBean>, private val newList: List<DiffBean>) : DiffUtil.Callback() {
/**
* 被DiffUtil调用,用来判断 两个对象是否是相同的Item。
* 例如,如果你的Item有唯一的id字段,这个方法就 判断id是否相等,或者重写equals方法
*/
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition].name == newList[newItemPosition].name
}
/**
* 老数据集size
*/
override fun getOldListSize(): Int {
return oldList.size
}
/**
* 新数据集size
*/
override fun getNewListSize(): Int {
return newList.size
}
/**
* 被DiffUtil调用,用来检查 两个item是否含有相同的数据
* DiffUtil用返回的信息(true false)来检测当前item的内容是否发生了变化
*/
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val oldBean = oldList[oldItemPosition]
val newBean = newList[newItemPosition]
if (oldBean.desc != newBean.desc) {
return false
}
// //默认两个data内容是相同的
return true
}
override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
val oldBean = oldList[oldItemPosition]
val newBean = newList[newItemPosition]
val bundle = Bundle()
if (oldBean.desc != newBean.desc) {
bundle.putString(KEY_DESC, "getChangePayLoad: " + newBean.desc)
} else { // 如果没有数据变化,返回null
return null
}
return bundle
}
} | 0 | Kotlin | 0 | 9 | 8afe5c39d2306ea2a314bfb32e8808ed998b991f | 1,738 | DiffUtilDemo | Apache License 2.0 |
compiler/fir/analysis-tests/testData/resolve/inference/pcla/doubleSquareBracketsInBuilderArgument.kt | JetBrains | 3,432,266 | false | null | // ISSUE: KT-47982
fun test() {
<!CANNOT_INFER_PARAMETER_TYPE, NEW_INFERENCE_NO_INFORMATION_FOR_PARAMETER!>build<!> {
<!UNSUPPORTED!>[<!UNSUPPORTED!>[]<!>]<!>
}
}
class Buildee<TV>
fun <PTV> build(instructions: Buildee<PTV>.() -> Unit): Buildee<PTV> {
return Buildee<PTV>().apply(instructions)
}
| 182 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 322 | kotlin | Apache License 2.0 |
browser-kotlin/src/jsMain/kotlin/web/canvas/CanvasPath.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6472581} | // Automatically generated - do not modify!
@file:Suppress(
"NON_ABSTRACT_MEMBER_OF_EXTERNAL_INTERFACE",
)
package web.canvas
sealed external interface CanvasPath {
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/arc)
*/
fun arc(
x: Number,
y: Number,
radius: Number,
startAngle: Number,
endAngle: Number,
counterclockwise: Boolean = definedExternally,
): Unit = definedExternally
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/arcTo)
*/
fun arcTo(
x1: Number,
y1: Number,
x2: Number,
y2: Number,
radius: Number,
): Unit = definedExternally
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/bezierCurveTo)
*/
fun bezierCurveTo(
cp1x: Number,
cp1y: Number,
cp2x: Number,
cp2y: Number,
x: Number,
y: Number,
): Unit = definedExternally
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/closePath)
*/
fun closePath(): Unit = definedExternally
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/ellipse)
*/
fun ellipse(
x: Number,
y: Number,
radiusX: Number,
radiusY: Number,
rotation: Number,
startAngle: Number,
endAngle: Number,
counterclockwise: Boolean = definedExternally,
): Unit = definedExternally
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/lineTo)
*/
fun lineTo(
x: Number,
y: Number,
): Unit = definedExternally
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/moveTo)
*/
fun moveTo(
x: Number,
y: Number,
): Unit = definedExternally
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/quadraticCurveTo)
*/
fun quadraticCurveTo(
cpx: Number,
cpy: Number,
x: Number,
y: Number,
): Unit = definedExternally
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/rect)
*/
fun rect(
x: Number,
y: Number,
w: Number,
h: Number,
): Unit = definedExternally
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/roundRect)
*/
fun roundRect(
x: Number,
y: Number,
w: Number,
h: Number,
radii: Any /* number | DOMPointInit | (number | DOMPointInit)[] */ = definedExternally,
): Unit = definedExternally
}
| 0 | Kotlin | 6 | 27 | e8d3760ae4b6f6dc971ca3b242bffed65af5f3d1 | 2,872 | types-kotlin | Apache License 2.0 |
app/src/main/java/com/example/lemonade/MainActivity.kt | google-developer-training | 385,324,701 | false | null | /*
* Copyright (C) 2021 The Android Open Source Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.example.lemonade
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
import com.google.android.material.snackbar.Snackbar
class MainActivity : AppCompatActivity() {
/**
* DO NOT ALTER ANY VARIABLE OR VALUE NAMES OR THEIR INITIAL VALUES.
*
* Anything labeled var instead of val is expected to be changed in the functions but DO NOT
* alter their initial values declared here, this could cause the app to not function properly.
*/
private val LEMONADE_STATE = "LEMONADE_STATE"
private val LEMON_SIZE = "LEMON_SIZE"
private val SQUEEZE_COUNT = "SQUEEZE_COUNT"
// SELECT represents the "pick lemon" state
private val SELECT = "select"
// SQUEEZE represents the "squeeze lemon" state
private val SQUEEZE = "squeeze"
// DRINK represents the "drink lemonade" state
private val DRINK = "drink"
// RESTART represents the state where the lemonade has been drunk and the glass is empty
private val RESTART = "restart"
// Default the state to select
private var lemonadeState = "select"
// Default lemonSize to -1
private var lemonSize = -1
// Default the squeezeCount to -1
private var squeezeCount = -1
private var lemonTree = LemonTree()
private var lemonImage: ImageView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// === DO NOT ALTER THE CODE IN THE FOLLOWING IF STATEMENT ===
if (savedInstanceState != null) {
lemonadeState = savedInstanceState.getString(LEMONADE_STATE, "select")
lemonSize = savedInstanceState.getInt(LEMON_SIZE, -1)
squeezeCount = savedInstanceState.getInt(SQUEEZE_COUNT, -1)
}
// === END IF STATEMENT ===
lemonImage = findViewById(R.id.image_lemon_state)
setViewElements()
lemonImage!!.setOnClickListener {
// TODO: call the method that handles the state when the image is clicked
clickLemonImage()
}
lemonImage!!.setOnLongClickListener {
// TODO: replace 'false' with a call to the function that shows the squeeze count
showSnackbar()
false
}
}
/**
* === DO NOT ALTER THIS METHOD ===
*
* This method saves the state of the app if it is put in the background.
*/
override fun onSaveInstanceState(outState: Bundle) {
outState.putString(LEMONADE_STATE, lemonadeState)
outState.putInt(LEMON_SIZE, lemonSize)
outState.putInt(SQUEEZE_COUNT, squeezeCount)
super.onSaveInstanceState(outState)
}
/**
* Clicking will elicit a different response depending on the state.
* This method determines the state and proceeds with the correct action.
*/
private fun clickLemonImage() {
// TODO: use a conditional statement like 'if' or 'when' to track the lemonadeState
// when the image is clicked we may need to change state to the next step in the
// lemonade making progression (or at least make some changes to the current state in the
// case of squeezing the lemon). That should be done in this conditional statement
// TODO: When the image is clicked in the SELECT state, the state should become SQUEEZE
// - The lemonSize variable needs to be set using the 'pick()' method in the LemonTree class
// - The squeezeCount should be 0 since we haven't squeezed any lemons just yet.
// TODO: When the image is clicked in the SQUEEZE state the squeezeCount needs to be
// INCREASED by 1 and lemonSize needs to be DECREASED by 1.
// - If the lemonSize has reached 0, it has been juiced and the state should become DRINK
// - Additionally, lemonSize is no longer relevant and should be set to -1
// TODO: When the image is clicked in the DRINK state the state should become RESTART
// TODO: When the image is clicked in the RESTART state the state should become SELECT
// TODO: lastly, before the function terminates we need to set the view elements so that the
// UI can reflect the correct state
when(lemonadeState){
SELECT -> {
lemonadeState = SQUEEZE
lemonSize = lemonTree.pick()
squeezeCount = 0
}
SQUEEZE -> {
squeezeCount++
lemonSize--
if(lemonSize == 0) lemonadeState = DRINK
}
DRINK -> {
lemonadeState = RESTART
lemonSize = -1
}
else -> lemonadeState = SELECT
}
setViewElements()
}
/**
* Set up the view elements according to the state.
*/
private fun setViewElements() {
val textAction: TextView = findViewById(R.id.text_action)
// TODO: set up a conditional that tracks the lemonadeState
// TODO: for each state, the textAction TextView should be set to the corresponding string from
// the string resources file. The strings are named to match the state
// TODO: Additionally, for each state, the lemonImage should be set to the corresponding
// drawable from the drawable resources. The drawables have the same names as the strings
// but remember that they are drawables, not strings.
when(lemonadeState){
SELECT -> {
textAction.text = getString(R.string.click_text)
lemonImage?.setImageResource( R.drawable.lemon_tree)
}
SQUEEZE -> {
textAction.text = getString(R.string.squeeze_text)
lemonImage?.setImageResource( R.drawable.lemon_squeeze)
}
DRINK -> {
textAction.text = getString(R.string.drink_text)
lemonImage?.setImageResource( R.drawable.lemon_drink)
}
else -> {
textAction.text = getString(R.string.restart_text)
lemonImage?.setImageResource( R.drawable.lemon_restart)
}
}
}
/**
* === DO NOT ALTER THIS METHOD ===
*
* Long clicking the lemon image will show how many times the lemon has been squeezed.
*/
private fun showSnackbar(): Boolean {
if (lemonadeState != SQUEEZE) {
return false
}
val squeezeText = getString(R.string.squeeze_count, squeezeCount)
Snackbar.make(
findViewById(R.id.constraint_Layout),
squeezeText,
Snackbar.LENGTH_SHORT
).show()
return true
}
}
/**
* A Lemon tree class with a method to "pick" a lemon. The "size" of the lemon is randomized
* and determines how many times a lemon needs to be squeezed before you get lemonade.
*/
class LemonTree {
fun pick(): Int {
return (2..4).random()
}
}
| 40 | null | 42 | 94 | f87aca701d69850320bad8e61f6aeb45fda16a78 | 7,693 | android-basics-kotlin-lemonade-app | Apache License 2.0 |
maplibre/app/src/main/java/danbroid/util/demo/SimpleMapActivity.kt | danbrough | 290,871,172 | false | {"C": 241261, "Kotlin": 199375, "C++": 74987, "Java": 9058, "Shell": 9035, "Go": 304} | package danbroid.util.demo
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import com.mapbox.mapboxsdk.camera.CameraPosition
import com.mapbox.mapboxsdk.geometry.LatLng
import com.mapbox.mapboxsdk.maps.MapView
import com.mapbox.mapboxsdk.maps.MapboxMap
import com.mapbox.mapboxsdk.maps.Style
/**
* Test activity showcasing a simple MapView without any MapboxMap interaction.
*/
class SimpleMapActivity : AppCompatActivity() {
private lateinit var mapView: MapView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map_simple)
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync { mapboxMap: MapboxMap ->
mapboxMap.cameraPosition = CameraPosition.Builder()
.target(LatLng(-41.308618, 174.769413))
.zoom(14.0)
.build()
mapboxMap.setStyle(Style.Builder().fromUri(Style.MAPBOX_STREETS))
}
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
// activity uses singleInstance for testing purposes
// code below provides a default navigation when using the app
onBackPressed()
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun onBackPressed() {
// activity uses singleInstance for testing purposes
// code below provides a default navigation when using the app
// NavUtils.navigateHome(this);
finish()
}
} | 0 | C | 0 | 2 | f5b1b0e0b9688c9fc0e7ff3d6d092ab86bf99fea | 2,204 | misc_demos | Apache License 2.0 |
app/src/main/java/dev/tcode/thinmp/view/screen/MainScreen.kt | tcode-dev | 392,735,283 | false | {"Kotlin": 248408} | package dev.tcode.thinmp.view.screen
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
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.statusBarsPadding
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import dev.tcode.thinmp.R
import dev.tcode.thinmp.constant.StyleConstant
import dev.tcode.thinmp.view.cell.AlbumCellView
import dev.tcode.thinmp.view.cell.GridCellView
import dev.tcode.thinmp.view.cell.ShortcutCellView
import dev.tcode.thinmp.view.dropdownMenu.ShortcutDropdownMenuItemView
import dev.tcode.thinmp.view.layout.MiniPlayerLayoutView
import dev.tcode.thinmp.view.nav.LocalNavigator
import dev.tcode.thinmp.view.row.DropdownMenuView
import dev.tcode.thinmp.view.row.PlainRowView
import dev.tcode.thinmp.view.title.SectionTitleView
import dev.tcode.thinmp.view.util.CustomGridCellsFixed
import dev.tcode.thinmp.view.util.CustomLifecycleEventObserver
import dev.tcode.thinmp.view.util.DividerView
import dev.tcode.thinmp.view.util.EmptyMiniPlayerView
import dev.tcode.thinmp.view.util.gridSpanCount
import dev.tcode.thinmp.viewModel.MainViewModel
@Composable
fun MainScreen(navController: NavController, viewModel: MainViewModel = viewModel()) {
val uiState by viewModel.uiState.collectAsState()
val context = LocalContext.current
val spanCount: Int = gridSpanCount()
val navigator = LocalNavigator.current
CustomLifecycleEventObserver(viewModel)
MiniPlayerLayoutView {
LazyVerticalGrid(columns = CustomGridCellsFixed(spanCount)) {
item(span = { GridItemSpan(spanCount) }) {
Column(
modifier = Modifier
.fillMaxWidth()
.statusBarsPadding()
.padding(start = StyleConstant.PADDING_LARGE.dp)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(bottom = StyleConstant.PADDING_MEDIUM.dp)
.height(StyleConstant.ROW_HEIGHT.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
val expanded = remember { mutableStateOf(false) }
Text(
stringResource(R.string.library),
color = MaterialTheme.colorScheme.primary,
textAlign = TextAlign.Left,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
fontWeight = FontWeight.Bold,
fontSize = StyleConstant.FONT_HUGE.sp
)
Box(contentAlignment = Alignment.Center, modifier = Modifier
.size(StyleConstant.BUTTON_SIZE.dp)
.clickable { expanded.value = !expanded.value }) {
Icon(
painter = painterResource(id = R.drawable.round_more_vert_24),
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(StyleConstant.ICON_SIZE.dp)
)
DropdownMenu(expanded = expanded.value,
offset = DpOffset((-1).dp, 0.dp),
modifier = Modifier.background(MaterialTheme.colorScheme.onBackground),
onDismissRequest = { expanded.value = false }) {
DropdownMenuItem(text = { Text(stringResource(R.string.edit), color = MaterialTheme.colorScheme.primary) }, onClick = {
navigator.mainEdit()
})
}
}
}
DividerView()
}
}
items(items = uiState.menu, span = { GridItemSpan(spanCount) }) { item ->
if (item.visibility) {
PlainRowView(stringResource(item.id), modifier = Modifier.clickable {
navController.navigate(item.key)
})
}
}
if (uiState.shortcutVisibility && uiState.shortcuts.isNotEmpty()) {
item(span = { GridItemSpan(spanCount) }) {
SectionTitleView(stringResource(R.string.shortcut))
}
itemsIndexed(items = uiState.shortcuts) { index, shortcut ->
DropdownMenuView(dropdownContent = { callback ->
val callbackShortcut = {
callback()
viewModel.load(context)
}
ShortcutDropdownMenuItemView(shortcut.itemId, callbackShortcut)
}) { callback ->
GridCellView(index, spanCount) {
ShortcutCellView(shortcut.primaryText, shortcut.secondaryText, shortcut.imageUri, shortcut.type, Modifier.pointerInput(shortcut.url) {
detectTapGestures(onLongPress = { callback() }, onTap = { navController.navigate(shortcut.url) })
})
}
}
}
}
if (uiState.recentlyAlbumsVisibility && uiState.albums.isNotEmpty()) {
item(span = { GridItemSpan(spanCount) }) {
SectionTitleView(stringResource(R.string.recently_added))
}
itemsIndexed(items = uiState.albums) { index, album ->
DropdownMenuView(dropdownContent = { callback ->
val callbackAlbum = {
callback()
viewModel.load(context)
}
ShortcutDropdownMenuItemView(album.albumId, callbackAlbum)
}) { callback ->
GridCellView(index, spanCount) {
AlbumCellView(album.name, album.artistName, album.getImageUri(), Modifier.pointerInput(album.url) {
detectTapGestures(onLongPress = { callback() }, onTap = { navigator.albumDetail(album.id) })
})
}
}
}
}
item(span = { GridItemSpan(spanCount) }) {
EmptyMiniPlayerView()
}
}
}
} | 0 | Kotlin | 0 | 7 | ecd7a7585788d0d4355dbfa596aa56f27dec0087 | 8,462 | ThinMP_Android_Kotlin | MIT License |
core-ui/src/main/kotlin/com/laomuji666/compose/core/ui/we/icons/ChatsSelect.kt | laomuji666 | 844,336,531 | false | {"Kotlin": 235984} | package com.laomuji666.compose.core.ui.we.icons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import kotlin.Suppress
val WeIcons.ChatsSelect: ImageVector
get() {
if (_ChatsSelect != null) {
return _ChatsSelect!!
}
_ChatsSelect = ImageVector.Builder(
name = "WeIcons.ChatsSelect",
defaultWidth = 29.dp,
defaultHeight = 28.dp,
viewportWidth = 29f,
viewportHeight = 28f
).apply {
path(
fill = SolidColor(Color(0xFF39CD80)),
pathFillType = PathFillType.EvenOdd
) {
moveTo(14.875f, 23.333f)
curveTo(21.318f, 23.333f, 26.542f, 18.893f, 26.542f, 13.417f)
curveTo(26.542f, 7.94f, 21.318f, 3.5f, 14.875f, 3.5f)
curveTo(8.432f, 3.5f, 3.208f, 7.94f, 3.208f, 13.417f)
curveTo(3.208f, 16.376f, 4.733f, 19.032f, 7.151f, 20.849f)
lineTo(6.799f, 23.881f)
curveTo(6.762f, 24.201f, 6.991f, 24.491f, 7.311f, 24.528f)
curveTo(7.42f, 24.541f, 7.531f, 24.522f, 7.631f, 24.475f)
lineTo(11.111f, 22.806f)
curveTo(12.292f, 23.148f, 13.558f, 23.333f, 14.875f, 23.333f)
close()
}
}.build()
return _ChatsSelect!!
}
@Suppress("ObjectPropertyName")
private var _ChatsSelect: ImageVector? = null
| 1 | Kotlin | 0 | 99 | 55ebed2733bdbc2330f3297b74b5514fea786ba3 | 1,671 | Quickly-Use-Jetpack-Compose | Apache License 2.0 |
app/src/main/java/com/kcteam/features/viewAllOrder/presentation/OrderSizeQtyDetailsDelAdapter.kt | DebashisINT | 558,234,039 | false | null | package com.breezefieldsalesgypmart.features.viewAllOrder.presentation
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.breezefieldsalesgypmart.R
import com.breezefieldsalesgypmart.app.utils.Toaster
import com.breezefieldsalesgypmart.features.viewAllOrder.interf.NewOrderSizeQtyDelOnClick
import com.breezefieldsalesgypmart.features.viewAllOrder.model.ProductOrder
import kotlinx.android.synthetic.main.row_new_order_size_qty_list.view.*
class OrderSizeQtyDetailsDelAdapter (var context: Context, var size_qty_list:ArrayList<ProductOrder>, val listner: NewOrderSizeQtyDelOnClick):
RecyclerView.Adapter<OrderSizeQtyDetailsDelAdapter.SizeQtyViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SizeQtyViewHolder {
val view= LayoutInflater.from(context).inflate(R.layout.row_new_order_size_qty_list,parent,false)
return SizeQtyViewHolder(view)
}
override fun getItemCount(): Int {
return size_qty_list!!.size
}
override fun onBindViewHolder(holder: SizeQtyViewHolder, position: Int) {
holder.tv_size.text= size_qty_list.get(position).size
holder.tv_qty.text= size_qty_list.get(position).qty
holder.iv_del.visibility = View.INVISIBLE
if(holder.ch_flag.isChecked){
size_qty_list.get(position).isCheckedStatus=true
}else{
size_qty_list.get(position).isCheckedStatus=false
}
holder.ch_flag.setOnClickListener { v: View? ->
if (holder.ch_flag.isChecked()) {
size_qty_list.get(position).isCheckedStatus=true
listner.sizeQtySelListOnClick(size_qty_list)
// listner.sizeQtyListOnClick(size_qty_list.get(position),position)
// holder.iv_del.setOnClickListener{listner.sizeQtyListOnClick(size_qty_list.get(position),position)}
}
else{
size_qty_list.get(position).isCheckedStatus=false
// holder.iv_del.setOnclic
// Toaster.msgShort(context,"No Checkbox Selected For Deleted")
}
}
}
inner class SizeQtyViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
val tv_size=itemView.tv_new_order_size
val tv_qty=itemView.tv_new_order_qty
val iv_del=itemView.iv_new_order_del
val ch_flag = itemView.new_order_size_qty_checked
}
} | 0 | null | 1 | 1 | e6114824d91cba2e70623631db7cbd9b4d9690ed | 2,526 | NationalPlastic | Apache License 2.0 |
src/test/kotlin/no/nav/eessi/pensjon/klienter/fagmodul/FagmodulKlientTest.kt | navikt | 178,813,650 | false | {"Kotlin": 790534, "Shell": 1714, "Dockerfile": 155} | package no.nav.eessi.pensjon.klienter.fagmodul
import io.mockk.every
import io.mockk.mockk
import no.nav.eessi.pensjon.eux.model.buc.SakType.ALDER
import no.nav.eessi.pensjon.listeners.fagmodul.FagmodulKlient
import no.nav.eessi.pensjon.oppgaverouting.SakInformasjon
import no.nav.eessi.pensjon.utils.toJson
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.client.RestTemplate
class FagmodulKlientTest {
private val fagmodulOidcRestTemplate: RestTemplate = mockk()
private val fagmodulKlient = FagmodulKlient(fagmodulOidcRestTemplate)
@Test
fun `Gitt at saktypen ikke er en enum så skal vi kaste RuntimeException`() {
val jsonResponse = getJsonBody("PAM_PAM")
every { fagmodulKlientExchange() } returns ResponseEntity(jsonResponse, HttpStatus.OK)
assertThrows<RuntimeException> {
fagmodulKlient.hentPensjonSaklist("321654987")
}
}
@Test
fun `Gitt at apikallet feiler så skal vi logge en error og returnere en tom liste`() {
every { fagmodulKlientExchange() } throws RuntimeException("En feil oppstod under henting av pensjonsakliste")
assertEquals(emptyList<SakInformasjon>(), fagmodulKlient.hentPensjonSaklist("321654987"))
}
@Test
fun `Gitt at vi har sakType Alder, så skal vi returnere en liste over saksinformasjon`() {
val jsonBody = getJsonBody(ALDER.name)
every { fagmodulKlientExchange() } returns ResponseEntity(jsonBody, HttpStatus.OK)
val result = fagmodulKlient.hentPensjonSaklist("321654987")
assertEquals(jsonBody, result.toJson())
}
private fun fagmodulKlientExchange() = fagmodulOidcRestTemplate.exchange(
"/pensjon/sakliste/321654987",
HttpMethod.GET,
null,
String::class.java
)
private fun getJsonBody(sakType: String) = """
[ {
"sakId" : "321",
"sakType" : "$sakType",
"sakStatus" : "LOPENDE",
"saksbehandlendeEnhetId" : "",
"nyopprettet" : false
} ]
""".trimIndent()
} | 3 | Kotlin | 3 | 5 | e77a3059a567bf93922d6904847b70835dd62052 | 2,362 | eessi-pensjon-journalforing | MIT License |
common/all/src/commonMain/kotlin/com/tunjid/me/common/ui/settings/SettingsRoute.kt | tunjid | 439,670,817 | false | null | /*
* Copyright 2021 Google LLC
*
* 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.tunjid.me.settings
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.unit.dp
import com.tunjid.me.feature.LocalRouteServiceLocator
import com.tunjid.me.scaffold.globalui.InsetFlags
import com.tunjid.me.scaffold.globalui.NavVisibility
import com.tunjid.me.scaffold.globalui.ScreenUiState
import com.tunjid.me.scaffold.globalui.UiState
import com.tunjid.me.scaffold.nav.AppRoute
import com.tunjid.me.scaffold.nav.LocalNavigator
import com.tunjid.treenav.push
import kotlinx.serialization.Serializable
@Serializable
data class SettingsRoute(
override val id: String,
) : AppRoute {
@Composable
override fun Render() {
SettingsScreen(
mutator = LocalRouteServiceLocator.current.locate(this),
)
}
}
@Composable
private fun SettingsScreen(mutator: SettingsMutator) {
val state by mutator.state.collectAsState()
val scrollState = rememberScrollState()
val navigator = LocalNavigator.current
ScreenUiState(
UiState(
toolbarShows = true,
toolbarTitle = "Settings",
navVisibility = NavVisibility.Visible,
insetFlags = InsetFlags.NO_BOTTOM,
statusBarColor = MaterialTheme.colors.primary.toArgb(),
)
)
Column(
modifier = Modifier
.fillMaxWidth()
.verticalScroll(state = scrollState),
horizontalAlignment = Alignment.Start,
) {
state.routes.forEach { path ->
Column(
modifier = Modifier
.fillMaxWidth()
.clickable {
navigator.navigate { currentNav.push(path.toRoute) }
},
content = {
Text(
modifier = Modifier.padding(16.dp),
text = path,
)
}
)
}
}
}
| 0 | Kotlin | 1 | 17 | 710745fa1cc2201458b69c61351fe5f585b87a28 | 3,117 | me | Apache License 2.0 |
app/src/main/java/app/tivi/inject/ApplicationComponent.kt | chrisbanes | 100,624,553 | false | null | /*
* Copyright 2023 Google LLC
*
* 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 app.tivi.inject
import android.app.Application
import android.content.Context
import app.tivi.TiviApplication
import app.tivi.appinitializers.AppInitializers
import app.tivi.common.imageloading.ImageLoadingComponent
import app.tivi.core.analytics.AnalyticsComponent
import app.tivi.core.perf.PerformanceComponent
import app.tivi.data.AndroidSqlDelightDatabaseComponent
import app.tivi.data.episodes.EpisodeBinds
import app.tivi.data.followedshows.FollowedShowsBinds
import app.tivi.data.popularshows.PopularShowsBinds
import app.tivi.data.recommendedshows.RecommendedShowsBinds
import app.tivi.data.search.SearchBinds
import app.tivi.data.showimages.ShowImagesBinds
import app.tivi.data.shows.ShowsBinds
import app.tivi.data.traktauth.RelatedShowsBinds
import app.tivi.data.traktauth.TraktAuthComponent
import app.tivi.data.traktusers.TraktUsersBinds
import app.tivi.data.trendingshows.TrendingShowsBinds
import app.tivi.data.watchedshows.WatchedShowsBinds
import app.tivi.home.ContentViewSetterComponent
import app.tivi.settings.PreferencesComponent
import app.tivi.tasks.TasksComponent
import app.tivi.tasks.TiviWorkerFactory
import app.tivi.tmdb.TmdbComponent
import app.tivi.trakt.TraktComponent
import app.tivi.util.LoggerComponent
import app.tivi.util.PowerControllerComponent
import me.tatarka.inject.annotations.Component
import me.tatarka.inject.annotations.Provides
@Component
@ApplicationScope
abstract class ApplicationComponent(
@get:Provides val application: Application,
) : AndroidSqlDelightDatabaseComponent,
TraktAuthComponent,
TmdbComponent,
TraktComponent,
AppComponent,
NetworkComponent,
TasksComponent,
PowerControllerComponent,
ImageLoadingComponent,
AnalyticsComponent,
PerformanceComponent,
PreferencesComponent,
EpisodeBinds,
FollowedShowsBinds,
PopularShowsBinds,
RecommendedShowsBinds,
RelatedShowsBinds,
SearchBinds,
ShowImagesBinds,
ShowsBinds,
TraktUsersBinds,
TrendingShowsBinds,
WatchedShowsBinds,
LoggerComponent,
ContentViewSetterComponent,
VariantAwareComponent {
abstract val initializers: AppInitializers
abstract val workerFactory: TiviWorkerFactory
companion object {
fun from(context: Context): ApplicationComponent {
return (context.applicationContext as TiviApplication).component
}
}
}
| 20 | null | 792 | 5,749 | 5dc4d831fd801afab556165d547042c517f98875 | 2,985 | tivi | Apache License 2.0 |
plugins/settings-sync/src/com/intellij/settingsSync/CloudConfigServerCommunicator.kt | ingokegel | 72,937,917 | false | null | package com.intellij.settingsSync
import com.intellij.ide.plugins.PluginManagerCore.isRunningFromSources
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.settingsSync.auth.SettingsSyncAuthService
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.delete
import com.intellij.util.io.inputStream
import com.jetbrains.cloudconfig.*
import com.jetbrains.cloudconfig.auth.JbaTokenAuthProvider
import com.jetbrains.cloudconfig.exception.InvalidVersionIdException
import org.jdom.JDOMException
import org.jetbrains.annotations.VisibleForTesting
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStream
import java.util.*
import java.util.concurrent.atomic.AtomicReference
internal const val CROSS_IDE_SYNC_MARKER_FILE = "cross-ide-sync-enabled"
internal const val SETTINGS_SYNC_SNAPSHOT = "settings.sync.snapshot"
internal const val SETTINGS_SYNC_SNAPSHOT_ZIP = "$SETTINGS_SYNC_SNAPSHOT.zip"
private const val CONNECTION_TIMEOUT_MS = 10000
private const val READ_TIMEOUT_MS = 50000
internal open class CloudConfigServerCommunicator : SettingsSyncRemoteCommunicator {
internal open val client get() = _client.value
private val _client = lazy { createCloudConfigClient(clientVersionContext) }
protected val clientVersionContext = CloudConfigVersionContext()
private val lastRemoteErrorRef = AtomicReference<Throwable>()
@VisibleForTesting
@Throws(IOException::class)
protected fun currentSnapshotFilePath(): String? {
try {
val crossIdeSyncEnabled = isFileExists(CROSS_IDE_SYNC_MARKER_FILE)
if (crossIdeSyncEnabled != SettingsSyncLocalSettings.getInstance().isCrossIdeSyncEnabled) {
LOG.info("Cross-IDE sync status on server is: ${enabledOrDisabled(crossIdeSyncEnabled)}. Updating local settings with it.")
SettingsSyncLocalSettings.getInstance().isCrossIdeSyncEnabled = crossIdeSyncEnabled
}
return if (crossIdeSyncEnabled) {
SETTINGS_SYNC_SNAPSHOT_ZIP
}
else {
"${ApplicationNamesInfo.getInstance().productName.lowercase()}/$SETTINGS_SYNC_SNAPSHOT_ZIP"
}
}
catch (e: Throwable) {
if (e is IOException) {
throw e
}
else {
LOG.warn("Couldn't check if $CROSS_IDE_SYNC_MARKER_FILE exists", e)
return null
}
}
}
@Throws(IOException::class)
private fun receiveSnapshotFile(snapshotFilePath: String): Pair<InputStream?, String?> {
return clientVersionContext.doWithVersion(snapshotFilePath, null) { filePath ->
try {
val stream = client.read(filePath)
val actualVersion: String? = clientVersionContext.get(filePath)
if (actualVersion == null) {
LOG.warn("Version not stored in the context for $filePath")
}
Pair(stream, actualVersion)
}
catch (fileNotFound: FileNotFoundException) {
Pair(null, null)
}
}
}
private fun sendSnapshotFile(inputStream: InputStream, knownServerVersion: String?, force: Boolean): SettingsSyncPushResult {
return sendSnapshotFile(inputStream, knownServerVersion, force, clientVersionContext, client)
}
@VisibleForTesting
internal fun sendSnapshotFile(
inputStream: InputStream,
knownServerVersion: String?,
force: Boolean,
versionContext: CloudConfigVersionContext,
cloudConfigClient: CloudConfigFileClientV2
): SettingsSyncPushResult {
val snapshotFilePath: String
val defaultMessage = "Unknown during checking $CROSS_IDE_SYNC_MARKER_FILE"
try {
snapshotFilePath = currentSnapshotFilePath() ?: return SettingsSyncPushResult.Error(defaultMessage)
}
catch (ioe: IOException) {
return SettingsSyncPushResult.Error(ioe.message ?: defaultMessage)
}
val versionToPush: String?
if (force) {
// get the latest server version: pushing with it will overwrite the file in any case
versionToPush = getLatestVersion(snapshotFilePath)?.versionId
}
else {
if (knownServerVersion != null) {
versionToPush = knownServerVersion
}
else {
val serverVersion = getLatestVersion(snapshotFilePath)?.versionId
if (serverVersion == null) {
// no file on the server => just push it there
versionToPush = null
}
else {
// we didn't store the server version locally yet => reject the push to avoid overwriting the server version;
// the next update after the rejected push will store the version information, and subsequent push will be successful.
return SettingsSyncPushResult.Rejected
}
}
}
val serverVersionId = versionContext.doWithVersion(snapshotFilePath, versionToPush) { filePath ->
cloudConfigClient.write(filePath, inputStream)
val actualVersion: String? = versionContext.get(filePath)
if (actualVersion == null) {
LOG.warn("Version not stored in the context for $filePath")
}
actualVersion
}
// errors are thrown as exceptions, and are handled above
return SettingsSyncPushResult.Success(serverVersionId)
}
override fun checkServerState(): ServerState {
try {
val snapshotFilePath = currentSnapshotFilePath() ?: return ServerState.Error("Unknown error during checkServerState")
val latestVersion = client.getLatestVersion(snapshotFilePath)
LOG.debug("Latest version info: $latestVersion")
clearLastRemoteError()
when (latestVersion?.versionId) {
null -> return ServerState.FileNotExists
SettingsSyncLocalSettings.getInstance().knownAndAppliedServerId -> return ServerState.UpToDate
else -> return ServerState.UpdateNeeded
}
}
catch (e: Throwable) {
val message = handleRemoteError(e)
return ServerState.Error(message)
}
}
override fun receiveUpdates(): UpdateResult {
LOG.info("Receiving settings snapshot from the cloud config server...")
try {
val snapshotFilePath = currentSnapshotFilePath() ?: return UpdateResult.Error("Unknown error during receiveUpdates")
val (stream, version) = receiveSnapshotFile(snapshotFilePath)
clearLastRemoteError()
if (stream == null) {
LOG.info("$snapshotFilePath not found on the server")
return UpdateResult.NoFileOnServer
}
val tempFile = FileUtil.createTempFile(SETTINGS_SYNC_SNAPSHOT, UUID.randomUUID().toString() + ".zip")
try {
FileUtil.writeToFile(tempFile, stream.readAllBytes())
val snapshot = SettingsSnapshotZipSerializer.extractFromZip(tempFile.toPath())
return if (snapshot.isDeleted()) UpdateResult.FileDeletedFromServer else UpdateResult.Success(snapshot, version)
}
finally {
FileUtil.delete(tempFile)
}
}
catch (e: Throwable) {
val message = handleRemoteError(e)
return UpdateResult.Error(message)
}
}
override fun push(snapshot: SettingsSnapshot, force: Boolean, expectedServerVersionId: String?): SettingsSyncPushResult {
LOG.info("Pushing setting snapshot to the cloud config server...")
val zip = try {
SettingsSnapshotZipSerializer.serializeToZip(snapshot)
}
catch (e: Throwable) {
LOG.warn(e)
return SettingsSyncPushResult.Error(e.message ?: "Couldn't prepare zip file")
}
try {
val pushResult = sendSnapshotFile(zip.inputStream(), expectedServerVersionId, force)
clearLastRemoteError()
return pushResult
}
catch (ive: InvalidVersionIdException) {
LOG.info("Rejected: version doesn't match the version on server: ${ive.message}")
return SettingsSyncPushResult.Rejected
}
// todo handle authentication failure: propose to login
catch (e: Throwable) {
val message = handleRemoteError(e)
return SettingsSyncPushResult.Error(message)
}
finally {
try {
zip.delete()
}
catch (e: Throwable) {
LOG.warn(e)
}
}
}
private fun clearLastRemoteError(){
if (lastRemoteErrorRef.get() != null) {
LOG.info("Connection to setting sync server is restored")
}
lastRemoteErrorRef.set(null)
}
private fun handleRemoteError(e: Throwable): String {
val defaultMessage = "Error during communication with server"
if (e is IOException) {
if (lastRemoteErrorRef.get()?.message != e.message) {
lastRemoteErrorRef.set(e)
LOG.warn("$defaultMessage: ${e.message}")
}
}
else {
LOG.error(e)
}
return e.message ?: defaultMessage
}
fun downloadSnapshot(filePath: String, version: FileVersionInfo): InputStream? {
val stream = clientVersionContext.doWithVersion(filePath, version.versionId) { path ->
client.read(path)
}
if (stream == null) {
LOG.info("$filePath not found on the server")
}
return stream
}
override fun createFile(filePath: String, content: String) {
client.write(filePath, content.byteInputStream())
}
private fun getLatestVersion(filePath: String): FileVersionInfo? {
return client.getLatestVersion(filePath)
}
@Throws(IOException::class)
override fun deleteFile(filePath: String) {
SettingsSyncLocalSettings.getInstance().knownAndAppliedServerId = null
client.delete(filePath)
}
@Throws(IOException::class)
override fun isFileExists(filePath: String): Boolean {
return client.getLatestVersion(filePath) != null
}
@Throws(Exception::class)
fun fetchHistory(filePath: String): List<FileVersionInfo> {
return client.getVersions(filePath)
}
companion object {
private const val URL_PROVIDER = "https://www.jetbrains.com/config/IdeaCloudConfig.xml"
internal const val DEFAULT_PRODUCTION_URL = "https://cloudconfig.jetbrains.com/cloudconfig"
private const val DEFAULT_DEBUG_URL = "https://stgn.cloudconfig.jetbrains.com/cloudconfig"
internal const val URL_PROPERTY = "idea.settings.sync.cloud.url"
internal val url get() = _url.value
private val _url = lazy {
val explicitUrl = System.getProperty(URL_PROPERTY)
when {
explicitUrl != null -> {
LOG.info("Using SettingSync server URL (from properties): $explicitUrl")
explicitUrl
}
isRunningFromSources() -> {
LOG.info("Using SettingSync server URL (DEBUG): $DEFAULT_DEBUG_URL")
DEFAULT_DEBUG_URL
}
else -> getProductionUrl()
}
}
private fun getProductionUrl(): String {
val configUrl = HttpRequests.request(URL_PROVIDER)
.productNameAsUserAgent()
.connect(HttpRequests.RequestProcessor { request: HttpRequests.Request ->
try {
val documentElement = JDOMUtil.load(request.inputStream)
documentElement.getAttributeValue("baseUrl")
}
catch (e: JDOMException) {
throw IOException(e)
}
}, DEFAULT_PRODUCTION_URL, LOG)
LOG.info("Using SettingSync server URL: $configUrl")
return configUrl
}
internal fun createCloudConfigClient(versionContext: CloudConfigVersionContext): CloudConfigFileClientV2 {
val conf = createConfiguration()
return CloudConfigFileClientV2(url, conf, DUMMY_ETAG_STORAGE, versionContext)
}
private fun createConfiguration(): Configuration {
val userId = SettingsSyncAuthService.getInstance().getUserData()?.id
if (userId == null) {
throw SettingsSyncAuthException("Authentication required")
}
return Configuration().connectTimeout(CONNECTION_TIMEOUT_MS).readTimeout(READ_TIMEOUT_MS).auth(JbaTokenAuthProvider(userId))
}
private val LOG = logger<CloudConfigServerCommunicator>()
@VisibleForTesting
internal val DUMMY_ETAG_STORAGE: ETagStorage = object : ETagStorage {
override fun get(path: String): String? {
return null
}
override fun store(path: String, value: String) {
// do nothing
}
override fun remove(path: String?) {
// do nothing
}
}
}
}
| 284 | null | 5162 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 12,188 | intellij-community | Apache License 2.0 |
analysis/analysis-api-fir/src/org/jetbrains/kotlin/analysis/api/fir/symbols/KtFirPropertyGetterSymbol.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2020 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.analysis.api.fir.symbols
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.analysis.api.fir.KtSymbolByFirBuilder
import org.jetbrains.kotlin.analysis.api.fir.annotations.KtFirAnnotationListForDeclaration
import org.jetbrains.kotlin.analysis.api.fir.findPsi
import org.jetbrains.kotlin.analysis.api.fir.utils.cached
import org.jetbrains.kotlin.analysis.api.symbols.KtPropertyGetterSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtValueParameterSymbol
import org.jetbrains.kotlin.analysis.api.symbols.pointers.KtPsiBasedSymbolPointer
import org.jetbrains.kotlin.analysis.api.symbols.pointers.KtSymbolPointer
import org.jetbrains.kotlin.analysis.api.lifetime.KtLifetimeToken
import org.jetbrains.kotlin.analysis.api.types.KtType
import org.jetbrains.kotlin.analysis.api.lifetime.withValidityAssertion
import org.jetbrains.kotlin.analysis.low.level.api.fir.api.LLFirResolveSession
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.Visibility
import org.jetbrains.kotlin.fir.declarations.impl.FirDefaultPropertyAccessor
import org.jetbrains.kotlin.fir.declarations.synthetic.FirSyntheticPropertyAccessor
import org.jetbrains.kotlin.fir.declarations.utils.isInline
import org.jetbrains.kotlin.fir.declarations.utils.isOverride
import org.jetbrains.kotlin.fir.declarations.utils.modalityOrFinal
import org.jetbrains.kotlin.fir.declarations.utils.visibility
import org.jetbrains.kotlin.fir.resolve.getHasStableParameterNames
import org.jetbrains.kotlin.fir.symbols.impl.FirPropertyAccessorSymbol
import org.jetbrains.kotlin.name.CallableId
internal class KtFirPropertyGetterSymbol(
override val firSymbol: FirPropertyAccessorSymbol,
override val firResolveSession: LLFirResolveSession,
override val token: KtLifetimeToken,
private val builder: KtSymbolByFirBuilder,
) : KtPropertyGetterSymbol(), KtFirSymbol<FirPropertyAccessorSymbol> {
init {
require(firSymbol.isGetter)
}
override val psi: PsiElement? by cached { firSymbol.findPsi() }
override val isDefault: Boolean get() = withValidityAssertion { firSymbol.fir is FirDefaultPropertyAccessor }
override val isInline: Boolean get() = withValidityAssertion { firSymbol.isInline }
override val isOverride: Boolean get() = withValidityAssertion { firSymbol.isOverride }
override val hasBody: Boolean get() = withValidityAssertion { firSymbol.fir.body != null }
override val modality: Modality get() = withValidityAssertion { firSymbol.modalityOrFinal }
override val visibility: Visibility get() = withValidityAssertion { firSymbol.visibility }
override val returnType: KtType get() = withValidityAssertion { firSymbol.returnType(builder) }
override val receiverType: KtType? get() = withValidityAssertion { firSymbol.receiverType(builder) }
override val annotationsList by cached { KtFirAnnotationListForDeclaration.create(firSymbol, firResolveSession.useSiteFirSession, token) }
/**
* Returns [CallableId] of the delegated Java method if the corresponding property of this setter is a synthetic Java property.
* Otherwise, returns `null`
*/
override val callableIdIfNonLocal: CallableId? by cached {
val fir = firSymbol.fir
if (fir is FirSyntheticPropertyAccessor) {
fir.delegate.symbol.callableId
} else null
}
override val valueParameters: List<KtValueParameterSymbol> get() = withValidityAssertion { emptyList() }
override val hasStableParameterNames: Boolean
get() = withValidityAssertion { firSymbol.fir.getHasStableParameterNames(firSymbol.moduleData.session) }
override fun createPointer(): KtSymbolPointer<KtPropertyGetterSymbol> {
KtPsiBasedSymbolPointer.createForSymbolFromSource(this)?.let { return it }
TODO("Creating pointers for getters from library is not supported yet")
}
override fun equals(other: Any?): Boolean = symbolEquals(other)
override fun hashCode(): Int = symbolHashCode()
}
| 4 | null | 5686 | 47,397 | a47dcc227952c0474d27cc385021b0c9eed3fb67 | 4,246 | kotlin | Apache License 2.0 |
app/src/main/java/com/kcteam/features/report/presentation/AchievementAdapter.kt | DebashisINT | 558,234,039 | false | null | package com.prakashspicesfsm.features.report.presentation
import android.content.Context
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.prakashspicesfsm.R
import com.prakashspicesfsm.features.report.model.AchievementDataModel
import kotlinx.android.synthetic.main.inflate_visit_report_item.view.*
/**
* Created by Saikat on 22-Jul-20.
*/
class AchievementAdapter(context: Context, val achvData: ArrayList<AchievementDataModel>?, val listener: OnClickListener) :
RecyclerView.Adapter<AchievementAdapter.MyViewHolder>() {
private val layoutInflater: LayoutInflater
private var context: Context
init {
layoutInflater = LayoutInflater.from(context)
this.context = context
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bindItems(context, achvData, listener)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val v = layoutInflater.inflate(R.layout.inflate_visit_report_item, parent, false)
return MyViewHolder(v)
}
override fun getItemCount(): Int {
return achvData?.size!!
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindItems(context: Context, achvData: ArrayList<AchievementDataModel>?, listener: OnClickListener) {
if (adapterPosition % 2 == 0)
itemView.setBackgroundColor(ContextCompat.getColor(context, R.color.report_screen_bg))
else
itemView.setBackgroundColor(ContextCompat.getColor(context, R.color.white))
itemView.tv_name.text = achvData?.get(adapterPosition)?.member_name
if (!TextUtils.isEmpty(achvData?.get(adapterPosition)?.report_to)) {
itemView.tv_report_to_name.visibility = View.VISIBLE
itemView.tv_report_to_name.text = achvData?.get(adapterPosition)?.report_to
}
else
itemView.tv_report_to_name.visibility = View.GONE
itemView.tv_shop_count.text = achvData?.get(adapterPosition)?.stage_count
itemView.tv_distance.visibility = View.GONE
//itemView.rl_arrow.visibility = View.GONE
itemView.setOnClickListener({
listener.onViewClick(adapterPosition)
})
}
}
interface OnClickListener {
fun onViewClick(adapterPosition: Int)
}
} | 0 | null | 1 | 1 | a9aabcf48662c76db18bcece75cae9ac961da1ed | 2,598 | NationalPlastic | Apache License 2.0 |
src/main/kotlin/org/veupathdb/lib/blast/common/fields/MultiThreadingMode.kt | VEuPathDB | 362,472,079 | false | null | package org.veupathdb.lib.blast.common.fields
import com.fasterxml.jackson.databind.node.ObjectNode
import org.veupathdb.lib.blast.common.FlagMultiThreadingMode
import org.veupathdb.lib.blast.common.FlagNumThreads
import org.veupathdb.lib.blast.serial.BlastField
import org.veupathdb.lib.blast.util.*
private val Def = MultiThreadingModeValue.SplitByDatabase
internal fun ParseMultiThreadingMode(js: ObjectNode) =
js.optInt(FlagMultiThreadingMode) { MultiThreadingMode(parse(it)) }
?: MultiThreadingMode()
/**
* -mt_mode `<Integer, (>=0 and =<1)>`
*
* Multi-thread mode to use in RPS BLAST search:
* * 0 (auto) split by database vols
* * 1 split by queries
*
* Default = `0`
*/
@JvmInline
value class MultiThreadingMode(val value: MultiThreadingModeValue = Def) : BlastField {
override val isDefault get() = value == Def
override val name: String
get() = FlagNumThreads
override fun appendJson(js: ObjectNode) =
js.put(isDefault, FlagMultiThreadingMode, value.ordinal)
override fun appendCliSegment(cli: StringBuilder) =
cli.append(isDefault, FlagMultiThreadingMode, value.ordinal)
override fun appendCliParts(cli: MutableList<String>) =
cli.add(isDefault, FlagMultiThreadingMode, value.ordinal)
override fun clone() = this
}
@Suppress("NOTHING_TO_INLINE")
private inline fun parse(v: Int) =
MultiThreadingModeValue.values()[v.inSet(FlagMultiThreadingMode, 0, 1)]
enum class MultiThreadingModeValue {
SplitByDatabase,
SplitByQuery
} | 20 | Kotlin | 0 | 0 | e0639a45d45fce3e393ab1eff1176c5c75375738 | 1,491 | service-multi-blast | Apache License 2.0 |
app/src/main/java/dialog/AddDrawingDialogFragment.kt | th3kumar | 639,369,031 | false | null | package dialog
import ViewModel.DrawingViewModel
import android.app.Activity.RESULT_OK
import android.app.AlertDialog
import android.app.Dialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
import com.example.doda.R
import com.google.android.material.textfield.TextInputEditText
import data.Drawing
import java.util.*
class AddDrawingDialogFragment : DialogFragment() {
private lateinit var imageView: ImageView
private lateinit var buttonAddImage: Button
private lateinit var editTextTitle: TextInputEditText
private var imageUri: Uri? = null
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialogView = activity?.layoutInflater?.inflate(R.layout.dialog_add_drawing, null)
imageView = dialogView?.findViewById(R.id.dialogImageView)!!
buttonAddImage = dialogView.findViewById(R.id.buttonAddImage)!!
editTextTitle = dialogView.findViewById(R.id.editTextTitle)!!
val builder = AlertDialog.Builder(activity)
builder.setView(dialogView)
.setTitle(getString(R.string.add_drawing))
.setPositiveButton(getString(R.string.save)) { _, _ ->
// Handle positive button click
val title = editTextTitle.text.toString()
saveDrawing(title, imageUri)
}
.setNegativeButton(getString(R.string.cancel), null)
buttonAddImage.setOnClickListener {
// Handle add image button click
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, REQUEST_IMAGE)
}
return builder.create()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_IMAGE && resultCode == RESULT_OK) {
// Get the selected image URI and display it in the ImageView
imageUri = data?.data
imageView.setImageURI(imageUri)
imageView.tag = imageUri
}
}
private fun saveDrawing(title: String, imageUri: Uri?) {
if (title.isBlank() || imageUri == null) {
Toast.makeText(requireContext(), "All fields are necessary, Please try again", Toast.LENGTH_SHORT).show()
return
}
val drawing = Drawing(title = title, imageUri = imageUri.toString(), creationTime = Date().time, markerCount = 0)
val viewModel = ViewModelProvider(requireActivity())[DrawingViewModel::class.java]
viewModel.insertDrawing(drawing)
// Fetch all drawings again to refresh the RecyclerView
//viewModel.getAllDrawings()
Toast.makeText(requireContext(), "Drawing Saved Successfully", Toast.LENGTH_SHORT).show()
}
companion object {
const val REQUEST_IMAGE = 100
}
}
| 0 | Kotlin | 0 | 0 | 894351d6af167026898b0270f5c767862f785800 | 3,098 | doda_App | MIT License |
src/main/kotlin/mixit/talk/repository/TalkRepository.kt | mixitconf | 76,134,720 | false | null | package mixit.talk.repository
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import mixit.talk.model.Talk
import org.slf4j.LoggerFactory
import org.springframework.core.io.ClassPathResource
import org.springframework.data.domain.Sort.Direction.ASC
import org.springframework.data.domain.Sort.Order
import org.springframework.data.domain.Sort.by
import org.springframework.data.mongodb.core.ReactiveMongoTemplate
import org.springframework.data.mongodb.core.count
import org.springframework.data.mongodb.core.find
import org.springframework.data.mongodb.core.findById
import org.springframework.data.mongodb.core.query.Criteria.where
import org.springframework.data.mongodb.core.query.Query
import org.springframework.data.mongodb.core.query.TextCriteria
import org.springframework.data.mongodb.core.query.TextQuery
import org.springframework.data.mongodb.core.query.isEqualTo
import org.springframework.data.mongodb.core.remove
import org.springframework.stereotype.Repository
import reactor.core.publisher.Flux
@Repository
class TalkRepository(
private val template: ReactiveMongoTemplate,
private val objectMapper: ObjectMapper
) {
private val logger = LoggerFactory.getLogger(this.javaClass)
fun initData() {
if (count().block() == 0L) {
listOf(2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2021).forEach { year ->
val talksResource = ClassPathResource("data/talks_$year.json")
val talks: List<Talk> = objectMapper.readValue(talksResource.inputStream)
talks.forEach { save(it).block() }
}
logger.info("Talks data initialization complete")
}
}
fun count() =
template.count<Talk>()
fun findAll(): Flux<Talk> =
template.find<Talk>(Query().with(by(Order(ASC, "start")))).doOnComplete { logger.info("Load all talks") }
fun findFullText(criteria: List<String>): Flux<Talk> {
val textCriteria = TextCriteria()
criteria.forEach { textCriteria.matching(it) }
val query = TextQuery(textCriteria).sortByScore()
return template.find(query)
}
fun findOne(id: String) =
template.findById<Talk>(id)
fun deleteAll() = template.remove<Talk>(Query())
fun deleteOne(id: String) = template.remove<Talk>(Query(where("_id").isEqualTo(id)))
fun deleteByEvent(event: String) = template.remove<Talk>(Query(where("event").isEqualTo(event)))
fun save(talk: Talk) = template.save(talk)
}
| 12 | null | 125 | 526 | cde6cbedac3a6b7dab1978ebf7e18ffe58cde0a1 | 2,548 | mixit | Apache License 2.0 |
data/impl/src/main/kotlin/com/morfly/sample/data/impl/mapping/DataMapper.kt | Morfly | 398,528,749 | false | null | /*
* Copyright 2021 <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.morfly.sample.data.impl.mapping
import com.morfly.sample.data.impl.network.model.PixabayImage
import com.morfly.sample.data.impl.storage.entity.StoredImage
interface DataMapper {
/**
* Maps image model from network api to the storage one.
*/
fun networkToStorage(image: PixabayImage, query: String): StoredImage
} | 2 | Kotlin | 5 | 43 | 93b22c1e198955705ef31aaeadb2b091a90fcdd5 | 934 | compose-arch-sample | MIT License |
apps/etterlatte-migrering/src/test/kotlin/migrering/start/StartMigreringRiverIntegrationTest.kt | navikt | 417,041,535 | false | {"Kotlin": 5723460, "TypeScript": 1348496, "Handlebars": 21854, "Shell": 10666, "HTML": 1776, "Dockerfile": 745, "CSS": 598, "PLpgSQL": 556} | package no.nav.etterlatte.migrering
import com.fasterxml.jackson.module.kotlin.readValue
import io.ktor.server.testing.testApplication
import io.mockk.coEvery
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.runs
import io.mockk.verify
import kotlinx.coroutines.runBlocking
import kotliquery.TransactionalSession
import no.nav.etterlatte.funksjonsbrytere.DummyFeatureToggleService
import no.nav.etterlatte.libs.common.behandling.UtenlandstilknytningType
import no.nav.etterlatte.libs.common.objectMapper
import no.nav.etterlatte.libs.common.pdl.PersonDTO
import no.nav.etterlatte.libs.common.person.Folkeregisteridentifikator
import no.nav.etterlatte.libs.common.rapidsandrivers.EVENT_NAME_KEY
import no.nav.etterlatte.libs.common.toJson
import no.nav.etterlatte.libs.common.utbetaling.UtbetalingResponseDto
import no.nav.etterlatte.libs.common.utbetaling.UtbetalingStatusDto
import no.nav.etterlatte.libs.database.POSTGRES_VERSION
import no.nav.etterlatte.libs.database.hentListe
import no.nav.etterlatte.migrering.grunnlag.Utenlandstilknytningsjekker
import no.nav.etterlatte.migrering.pen.BarnepensjonGrunnlagResponse
import no.nav.etterlatte.migrering.pen.PenKlient
import no.nav.etterlatte.migrering.person.krr.DigitalKontaktinformasjon
import no.nav.etterlatte.migrering.person.krr.KrrKlient
import no.nav.etterlatte.migrering.start.MigrerSpesifikkSakRiver
import no.nav.etterlatte.migrering.start.MigreringFeatureToggle
import no.nav.etterlatte.migrering.start.MigreringRiver
import no.nav.etterlatte.migrering.verifisering.GjenlevendeForelderPatcher
import no.nav.etterlatte.migrering.verifisering.PDLKlient
import no.nav.etterlatte.migrering.verifisering.Verifiserer
import no.nav.etterlatte.opprettInMemoryDatabase
import no.nav.etterlatte.rapidsandrivers.EventNames
import no.nav.etterlatte.rapidsandrivers.migrering.LOPENDE_JANUAR_2024_KEY
import no.nav.etterlatte.rapidsandrivers.migrering.MIGRERING_KJORING_VARIANT
import no.nav.etterlatte.rapidsandrivers.migrering.MigreringKjoringVariant
import no.nav.etterlatte.rapidsandrivers.migrering.MigreringRequest
import no.nav.etterlatte.rapidsandrivers.migrering.Migreringshendelser
import no.nav.etterlatte.rapidsandrivers.migrering.PESYS_ID_KEY
import no.nav.etterlatte.rapidsandrivers.migrering.PesysId
import no.nav.etterlatte.utbetaling.common.EVENT_NAME_OPPDATERT
import no.nav.etterlatte.utbetaling.common.UTBETALING_RESPONSE
import no.nav.helse.rapids_rivers.JsonMessage
import no.nav.helse.rapids_rivers.testsupport.TestRapid
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.testcontainers.containers.PostgreSQLContainer
import org.testcontainers.junit.jupiter.Container
import rapidsandrivers.BEHANDLING_ID_KEY
import rapidsandrivers.HENDELSE_DATA_KEY
import rapidsandrivers.SAK_ID_FLERE_KEY
import rapidsandrivers.SAK_ID_KEY
import java.time.Month
import java.time.YearMonth
import java.util.UUID
import javax.sql.DataSource
internal class MigreringRiverIntegrationTest {
@Container
private val postgreSQLContainer = PostgreSQLContainer<Nothing>("postgres:$POSTGRES_VERSION")
private lateinit var datasource: DataSource
@BeforeEach
fun start() {
datasource = opprettInMemoryDatabase(postgreSQLContainer).dataSource
}
@AfterEach
fun stop() = postgreSQLContainer.stop()
@Test
fun `kan ta imot og handtere respons fra PEN`() {
testApplication {
val repository = PesysRepository(datasource)
val featureToggleService =
DummyFeatureToggleService().also {
it.settBryter(MigreringFeatureToggle.SendSakTilMigrering, true)
}
val responsFraPEN =
objectMapper.readValue<BarnepensjonGrunnlagResponse>(
this::class.java.getResource("/penrespons.json")!!.readText(),
)
val inspector =
TestRapid()
.apply {
val pdlKlient =
mockk<PDLKlient>().also {
every {
it.hentPerson(
any(),
any(),
)
} returns
mockk<PersonDTO>().also {
every { it.vergemaalEllerFremtidsfullmakt } returns emptyList()
}
}
MigrerSpesifikkSakRiver(
rapidsConnection = this,
penKlient =
mockk<PenKlient>()
.also { every { runBlocking { it.hentSak(any(), any()) } } returns responsFraPEN },
pesysRepository = repository,
featureToggleService = featureToggleService,
verifiserer =
Verifiserer(
pdlKlient,
repository,
featureToggleService,
GjenlevendeForelderPatcher(pdlKlient),
mockk<Utenlandstilknytningsjekker>().also {
every { it.finnUtenlandstilknytning(any()) } returns UtenlandstilknytningType.NASJONAL
},
),
krrKlient =
mockk<KrrKlient>().also {
coEvery { it.hentDigitalKontaktinformasjon(any()) } returns
DigitalKontaktinformasjon(
personident = "",
aktiv = true,
kanVarsles = true,
reservert = false,
spraak = "se",
epostadresse = null,
mobiltelefonnummer = null,
sikkerDigitalPostkasse = null,
)
},
)
}
inspector.sendTestMessage(
JsonMessage.newMessage(
mapOf(
EVENT_NAME_KEY to Migreringshendelser.MIGRER_SPESIFIKK_SAK,
SAK_ID_KEY to "22974139",
LOPENDE_JANUAR_2024_KEY to true,
MIGRERING_KJORING_VARIANT to MigreringKjoringVariant.FULL_KJORING,
),
).toJson(),
)
with(repository.hentSaker()) {
assertEquals(1, size)
assertEquals(get(0).id, 22974139)
assertEquals(get(0).foersteVirkningstidspunkt, YearMonth.of(2023, Month.SEPTEMBER))
}
val melding1 = inspector.inspektør.message(0)
val request = objectMapper.readValue(melding1.get(HENDELSE_DATA_KEY).toJson(), MigreringRequest::class.java)
assertEquals(PesysId(22974139), request.pesysId)
assertEquals(Folkeregisteridentifikator.of("06421594773"), request.soeker)
}
}
@Test
fun `Migrer hele veien`() {
val pesysId = PesysId(22974139)
testApplication {
val repository = PesysRepository(datasource)
val featureToggleService =
DummyFeatureToggleService().also {
it.settBryter(MigreringFeatureToggle.SendSakTilMigrering, true)
it.settBryter(MigreringFeatureToggle.OpphoerSakIPesys, true)
}
val responsFraPEN =
objectMapper.readValue<BarnepensjonGrunnlagResponse>(
this::class.java.getResource("/penrespons.json")!!.readText(),
)
val penKlient =
mockk<PenKlient>()
.also { every { runBlocking { it.hentSak(any(), any()) } } returns responsFraPEN }
.also { every { runBlocking { it.opphoerSak(any()) } } just runs }
val inspector =
TestRapid()
.apply {
val pdlKlient =
mockk<PDLKlient>().also {
every {
it.hentPerson(
any(),
any(),
)
} returns
mockk<PersonDTO>().also {
every { it.vergemaalEllerFremtidsfullmakt } returns emptyList()
}
}
MigrerSpesifikkSakRiver(
rapidsConnection = this,
penKlient = penKlient,
pesysRepository = repository,
featureToggleService = featureToggleService,
verifiserer =
Verifiserer(
pdlKlient,
repository,
featureToggleService,
GjenlevendeForelderPatcher(pdlKlient),
mockk<Utenlandstilknytningsjekker>().also {
every { it.finnUtenlandstilknytning(any()) } returns UtenlandstilknytningType.NASJONAL
},
),
krrKlient = mockk<KrrKlient>().also { coEvery { it.hentDigitalKontaktinformasjon(any()) } returns null },
)
LagreKoblingRiver(this, repository)
LyttPaaIverksattVedtakRiver(this, repository, penKlient, featureToggleService)
}
inspector.sendTestMessage(
JsonMessage.newMessage(
mapOf(
EVENT_NAME_KEY to Migreringshendelser.MIGRER_SPESIFIKK_SAK,
SAK_ID_KEY to pesysId.id,
LOPENDE_JANUAR_2024_KEY to true,
MIGRERING_KJORING_VARIANT to MigreringKjoringVariant.FULL_KJORING,
),
).toJson(),
)
with(repository.hentSaker()) {
assertEquals(1, size)
assertEquals(get(0).id, pesysId.id)
assertEquals(get(0).foersteVirkningstidspunkt, YearMonth.of(2023, Month.SEPTEMBER))
assertEquals(repository.hentStatus(pesysId.id), Migreringsstatus.UNDER_MIGRERING)
}
val behandlingId = UUID.randomUUID()
inspector.sendTestMessage(
JsonMessage.newMessage(
mapOf(
EVENT_NAME_KEY to Migreringshendelser.LAGRE_KOPLING,
BEHANDLING_ID_KEY to behandlingId,
PESYS_ID_KEY to pesysId,
),
).toJson(),
)
assertEquals(repository.hentPesysId(behandlingId)?.pesysId, pesysId)
inspector.sendTestMessage(
JsonMessage.newMessage(
mapOf(
EVENT_NAME_KEY to EVENT_NAME_OPPDATERT,
UTBETALING_RESPONSE to
UtbetalingResponseDto(
status = UtbetalingStatusDto.GODKJENT,
vedtakId = 1L,
behandlingId = behandlingId,
feilmelding = null,
),
),
).toJson(),
)
verify { runBlocking { penKlient.opphoerSak(pesysId) } }
assertEquals(repository.hentStatus(pesysId.id), Migreringsstatus.FERDIG)
}
}
@Test
fun `Start migrering med pause`() {
val pesysId = PesysId(22974139)
testApplication {
val repository = PesysRepository(datasource)
val featureToggleService =
DummyFeatureToggleService().also {
it.settBryter(MigreringFeatureToggle.SendSakTilMigrering, true)
it.settBryter(MigreringFeatureToggle.OpphoerSakIPesys, true)
}
val responsFraPEN =
objectMapper.readValue<BarnepensjonGrunnlagResponse>(
this::class.java.getResource("/penrespons.json")!!.readText(),
)
val penKlient =
mockk<PenKlient>()
.also { every { runBlocking { it.hentSak(any(), any()) } } returns responsFraPEN }
.also { every { runBlocking { it.opphoerSak(any()) } } just runs }
val inspector =
TestRapid()
.apply {
val pdlKlient =
mockk<PDLKlient>().also {
every {
it.hentPerson(
any(),
any(),
)
} returns
mockk<PersonDTO>().also {
every { it.vergemaalEllerFremtidsfullmakt } returns emptyList()
}
}
MigrerSpesifikkSakRiver(
rapidsConnection = this,
penKlient = penKlient,
pesysRepository = repository,
featureToggleService = featureToggleService,
verifiserer =
Verifiserer(
pdlKlient,
repository,
featureToggleService,
GjenlevendeForelderPatcher(pdlKlient),
mockk<Utenlandstilknytningsjekker>().also {
every { it.finnUtenlandstilknytning(any()) } returns UtenlandstilknytningType.NASJONAL
},
),
krrKlient = mockk<KrrKlient>().also { coEvery { it.hentDigitalKontaktinformasjon(any()) } returns null },
)
LagreKoblingRiver(this, repository)
PauseMigreringRiver(this, repository)
}
inspector.sendTestMessage(
JsonMessage.newMessage(
mapOf(
EVENT_NAME_KEY to Migreringshendelser.MIGRER_SPESIFIKK_SAK,
SAK_ID_KEY to pesysId.id,
LOPENDE_JANUAR_2024_KEY to true,
MIGRERING_KJORING_VARIANT to MigreringKjoringVariant.MED_PAUSE,
),
).toJson(),
)
assertEquals(1, inspector.inspektør.size)
val oppstartMigreringMelding = inspector.inspektør.message(0)
assertEquals(Migreringshendelser.MIGRER_SAK, oppstartMigreringMelding.get(EVENT_NAME_KEY).asText())
assertEquals(
MigreringKjoringVariant.MED_PAUSE.name,
oppstartMigreringMelding.get(MIGRERING_KJORING_VARIANT).asText(),
)
val behandlingId = UUID.randomUUID()
inspector.sendTestMessage(
JsonMessage.newMessage(
mapOf(
EVENT_NAME_KEY to Migreringshendelser.LAGRE_KOPLING,
BEHANDLING_ID_KEY to behandlingId,
PESYS_ID_KEY to pesysId,
),
).toJson(),
)
inspector.sendTestMessage(
JsonMessage.newMessage(
mapOf(
EVENT_NAME_KEY to Migreringshendelser.PAUSE,
PESYS_ID_KEY to pesysId,
),
).toJson(),
)
with(repository.hentSaker()) {
assertEquals(1, size)
assertEquals(get(0).id, pesysId.id)
assertEquals(get(0).foersteVirkningstidspunkt, YearMonth.of(2023, Month.SEPTEMBER))
assertEquals(repository.hentStatus(pesysId.id), Migreringsstatus.PAUSE)
}
inspector.sendTestMessage(
JsonMessage.newMessage(
mapOf(
EVENT_NAME_KEY to Migreringshendelser.MIGRER_SPESIFIKK_SAK,
SAK_ID_KEY to pesysId.id,
LOPENDE_JANUAR_2024_KEY to true,
MIGRERING_KJORING_VARIANT to MigreringKjoringVariant.FORTSETT_ETTER_PAUSE,
),
).toJson(),
)
assertEquals(3, inspector.inspektør.size)
val forttsettMigreringMelding = inspector.inspektør.message(2)
assertEquals(Migreringshendelser.VEDTAK, forttsettMigreringMelding.get(EVENT_NAME_KEY).asText())
assertEquals(behandlingId.toString(), forttsettMigreringMelding.get(BEHANDLING_ID_KEY).asText())
assertEquals(pesysId.id, forttsettMigreringMelding.get(SAK_ID_KEY).asLong())
assertEquals(Migreringshendelser.VEDTAK, forttsettMigreringMelding.get(EVENT_NAME_KEY).asText())
assertEquals(
MigreringKjoringVariant.FORTSETT_ETTER_PAUSE.name,
forttsettMigreringMelding.get(MIGRERING_KJORING_VARIANT).asText(),
)
}
}
@Test
fun `feiler hvis en person ikke fins i PDL`() {
testApplication {
val pesysid = 22974139L
val repository = PesysRepository(datasource)
val featureToggleService =
DummyFeatureToggleService().also {
it.settBryter(MigreringFeatureToggle.SendSakTilMigrering, true)
}
val responsFraPEN =
objectMapper.readValue<BarnepensjonGrunnlagResponse>(
this::class.java.getResource("/penrespons.json")!!.readText(),
)
val inspector =
TestRapid()
.apply {
val pdlKlient =
mockk<PDLKlient>().also {
every {
it.hentPerson(
any(),
any(),
)
} throws IllegalStateException("")
}
MigrerSpesifikkSakRiver(
rapidsConnection = this,
penKlient =
mockk<PenKlient>()
.also { every { runBlocking { it.hentSak(any(), any()) } } returns responsFraPEN },
pesysRepository = repository,
featureToggleService = featureToggleService,
verifiserer =
Verifiserer(
pdlKlient,
repository,
featureToggleService,
GjenlevendeForelderPatcher(pdlKlient),
mockk<Utenlandstilknytningsjekker>().also { every { it.finnUtenlandstilknytning(any()) } returns null },
),
krrKlient = mockk<KrrKlient>().also { coEvery { it.hentDigitalKontaktinformasjon(any()) } returns null },
)
}
inspector.sendTestMessage(
JsonMessage.newMessage(
mapOf(
EVENT_NAME_KEY to Migreringshendelser.MIGRER_SPESIFIKK_SAK,
SAK_ID_KEY to pesysid,
LOPENDE_JANUAR_2024_KEY to true,
MIGRERING_KJORING_VARIANT to MigreringKjoringVariant.FULL_KJORING,
),
).toJson(),
)
with(inspector.inspektør.message(0)) {
assertEquals(EventNames.FEILA, get(EVENT_NAME_KEY).textValue())
}
assertEquals(Migreringsstatus.VERIFISERING_FEILA, repository.hentStatus(pesysid))
}
}
@Test
fun `Feiler med barn som har vergemaal i PDL`() {
testApplication {
val pesysid = 22974139L
val repository = PesysRepository(datasource)
val featureToggleService =
DummyFeatureToggleService().also {
it.settBryter(MigreringFeatureToggle.SendSakTilMigrering, true)
}
val responsFraPEN =
objectMapper.readValue<BarnepensjonGrunnlagResponse>(
this::class.java.getResource("/penrespons.json")!!.readText(),
)
val inspector =
TestRapid()
.apply {
val pdlKlient =
mockk<PDLKlient>().also {
every {
it.hentPerson(
any(),
any(),
)
} returns
mockk<PersonDTO>().also {
every { it.vergemaalEllerFremtidsfullmakt } returns listOf(mockk())
}
}
MigrerSpesifikkSakRiver(
rapidsConnection = this,
penKlient =
mockk<PenKlient>()
.also { every { runBlocking { it.hentSak(any(), any()) } } returns responsFraPEN },
pesysRepository = repository,
featureToggleService = featureToggleService,
verifiserer =
Verifiserer(
pdlKlient,
repository,
featureToggleService,
GjenlevendeForelderPatcher(pdlKlient),
mockk<Utenlandstilknytningsjekker>().also { every { it.finnUtenlandstilknytning(any()) } returns null },
),
krrKlient = mockk<KrrKlient>().also { coEvery { it.hentDigitalKontaktinformasjon(any()) } returns null },
)
}
inspector.sendTestMessage(
JsonMessage.newMessage(
mapOf(
EVENT_NAME_KEY to Migreringshendelser.MIGRER_SPESIFIKK_SAK,
SAK_ID_KEY to pesysid,
LOPENDE_JANUAR_2024_KEY to true,
MIGRERING_KJORING_VARIANT to MigreringKjoringVariant.FULL_KJORING,
),
).toJson(),
)
with(inspector.inspektør.message(0)) {
assertEquals(EventNames.FEILA, get(EVENT_NAME_KEY).textValue())
}
assertEquals(Migreringsstatus.VERIFISERING_FEILA, repository.hentStatus(pesysid))
}
}
@Test
fun `migrere flere saker samtidig`() {
testApplication {
val inspector =
TestRapid()
.apply {
MigreringRiver(rapidsConnection = this)
}
inspector.sendTestMessage(
JsonMessage.newMessage(
mapOf(
EVENT_NAME_KEY to Migreringshendelser.START_MIGRERING,
SAK_ID_FLERE_KEY to listOf("111", "222", "333"),
LOPENDE_JANUAR_2024_KEY to false,
MIGRERING_KJORING_VARIANT to MigreringKjoringVariant.FULL_KJORING,
),
).toJson(),
)
with(inspector.inspektør.message(0)) {
assertEquals(111L, get(SAK_ID_KEY).asLong())
assertEquals(Migreringshendelser.MIGRER_SPESIFIKK_SAK, get(EVENT_NAME_KEY).asText())
assertEquals(false, get(LOPENDE_JANUAR_2024_KEY).asBoolean())
}
with(inspector.inspektør.message(1)) {
assertEquals(222L, get(SAK_ID_KEY).asLong())
assertEquals(Migreringshendelser.MIGRER_SPESIFIKK_SAK, get(EVENT_NAME_KEY).asText())
assertEquals(false, get(LOPENDE_JANUAR_2024_KEY).asBoolean())
}
with(inspector.inspektør.message(2)) {
assertEquals(333L, get(SAK_ID_KEY).asLong())
assertEquals(Migreringshendelser.MIGRER_SPESIFIKK_SAK, get(EVENT_NAME_KEY).asText())
assertEquals(false, get(LOPENDE_JANUAR_2024_KEY).asBoolean())
}
}
}
}
internal fun PesysRepository.hentSaker(tx: TransactionalSession? = null): List<Pesyssak> =
tx.session {
hentListe(
"SELECT sak from pesyssak WHERE status in('${Migreringsstatus.UNDER_MIGRERING.name}','${Migreringsstatus.PAUSE.name}')",
) {
objectMapper.readValue(it.string("sak"), Pesyssak::class.java)
}
}
| 21 | Kotlin | 0 | 6 | cb2f66b3d6bef0ab72b82ca34a7f2e371ff4269c | 26,384 | pensjon-etterlatte-saksbehandling | MIT License |
src/commonTest/kotlin/com/electrit/protokol/UShortsTest.kt | ikolomiets | 303,030,297 | false | null | package com.electrit.protokol
import kotlin.random.Random
import kotlin.random.nextUInt
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class UShortsTest {
class UShortsData(var list: List<UShort> = emptyList())
object UShortsDataProtokolObject : ProtokolObject<UShortsData> {
override val protokol: Protokol.(UShortsData) -> Unit = {
with(it) {
USHORTS(::list)
}
}
override fun create() = UShortsData()
}
object StrictUShortsDataProtokolObject : ProtokolObject<UShortsData> {
override val protokol: Protokol.(UShortsData) -> Unit = {
with(it) {
USHORTS(::list, { size -> if (size == 0) throw IllegalArgumentException("size can't be 0") }) { value ->
if (value.toInt() == 0) throw IllegalArgumentException("value can't be 0")
}
}
}
override fun create() = UShortsData()
}
@Test
fun test() {
fun assert(list: List<UShort>, po: ProtokolObject<UShortsData>) {
val bytes = ByteArrayProtokolCodec.encode(UShortsData(list), po)
val data = ByteArrayProtokolCodec.decode(bytes, po)
assertEquals(list, data.list)
}
assert(emptyList(), UShortsDataProtokolObject)
assert(List(127) { Random.nextUInt().toUShort() }, UShortsDataProtokolObject) // still one byte for list size
assert(List(128) { Random.nextUInt().toUShort() }, UShortsDataProtokolObject) // two bytes for list size
assertFailsWith<IllegalArgumentException> { assert(emptyList(), StrictUShortsDataProtokolObject) }
assert(listOf(1u, 2u, 3u), StrictUShortsDataProtokolObject)
assertFailsWith<IllegalArgumentException> { assert(listOf(1u, 0u, 3u), StrictUShortsDataProtokolObject) }
}
@Test
fun testParseError() {
assertFailsWith<IllegalArgumentException> {
ByteArrayProtokolCodec.decode(
ByteArrayProtokolCodec.encode(UShortsData(emptyList()), UShortsDataProtokolObject),
StrictUShortsDataProtokolObject
)
}
assertFailsWith<IllegalArgumentException> {
ByteArrayProtokolCodec.decode(
ByteArrayProtokolCodec.encode(UShortsData(listOf(1u, 0u, 3u)), UShortsDataProtokolObject),
StrictUShortsDataProtokolObject
)
}
}
} | 0 | Kotlin | 0 | 1 | 372172824df1958410b7a287f6ed47b822c726a8 | 2,472 | protokol | MIT License |
irrigation-service/src/main/kotlin/banquemisr/com/irrigationsystem/model/dto/request/ChangeStatusRequest.kt | AhmedGodaa | 677,464,074 | false | {"Kotlin": 60005, "Dockerfile": 539, "Shell": 251} | package banquemisr.com.irrigationsystem.model.dto.request
import com.fasterxml.jackson.annotation.JsonProperty
data class ChangeStatusRequest(
@JsonProperty("id") val id: String? = null,
@JsonProperty("irrigationStatus") var irrigationStatus: Boolean? = null,
) | 0 | Kotlin | 0 | 1 | 3a4f90e67d5e78262d99d1c3b01af9d25c81af4b | 271 | IrrigationSystemBM | MIT License |
app/src/main/java/zero/friends/gostopcalculator/util/TabKeyboardDownModifier.kt | ZeroFriends | 412,748,430 | false | null | package zero.friends.gostopcalculator.util
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.runtime.Composable
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
@Composable
@OptIn(ExperimentalComposeUiApi::class)
fun TabKeyboardDownModifier(): Modifier {
val keyboardController = LocalSoftwareKeyboardController.current
val tabKeyboardDownModifier = Modifier.pointerInput(Unit) {
detectTapGestures(onTap = {
keyboardController?.hide()
})
}
return tabKeyboardDownModifier
} | 0 | Kotlin | 1 | 13 | f3faf45cdaf496fe0d06bb73ca813e2097de96a6 | 715 | GoStopCalculator | Apache License 2.0 |
ktor-client/ktor-client-darwin/darwin/src/io/ktor/client/engine/darwin/certificates/CertificatePinner.kt | ktorio | 40,136,600 | false | null | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.engine.darwin.certificates
import io.ktor.client.engine.darwin.*
import io.ktor.client.engine.darwin.internal.legacy.*
import kotlinx.cinterop.*
import platform.CoreCrypto.*
import platform.CoreFoundation.*
import platform.Foundation.*
import platform.Security.*
/**
* Constrains which certificates are trusted. Pinning certificates defends against attacks on
* certificate authorities. It also prevents connections through man-in-the-middle certificate
* authorities either known or unknown to the application's user.
* This class currently pins a certificate's Subject Public Key Info as described on
* [Adam Langley's Weblog](http://goo.gl/AIx3e5). Pins are either base64 SHA-256 hashes as in
* [HTTP Public Key Pinning (HPKP)](http://tools.ietf.org/html/rfc7469) or SHA-1 base64 hashes as
* in Chromium's [static certificates](http://goo.gl/XDh6je).
*
* ## Setting up Certificate Pinning
*
* The easiest way to pin a host is to turn on pinning with a broken configuration and read the
* expected configuration when the connection fails. Be sure to do this on a trusted network, and
* without man-in-the-middle tools like [Charles](http://charlesproxy.com) or
* [Fiddler](http://fiddlertool.com).
*
* For example, to pin `https://publicobject.com`, start with a broken configuration:
*
* ```
* HttpClient(Darwin) {
*
* // ...
*
* engine {
* val builder = CertificatePinner.Builder()
* .add("publicobject.com", "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
* handleChallenge(builder.build())
* }
* }
* ```
*
* As expected, this fails with an exception, see the logs:
*
* ```
* HttpClient: Certificate pinning failure!
* Peer certificate chain:
* sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=: publicobject.com
* sha256/klO23nT2ehFDXCfx3eHTDRESMz3asj1muO+4aIdjiuY=: COMODO RSA Secure Server CA
* sha256/grX4Ta9HpZx6tSHkmCrvpApTQGo67CYDnvprLg5yRME=: COMODO RSA Certification Authority
* sha256/lCppFqbkrlJ3EcVFAkeip0+44VaoJUymbnOaEUk7tEU=: AddTrust External CA Root
* Pinned certificates for publicobject.com:
* sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
* ```
*
* Follow up by pasting the public key hashes from the logs into the
* certificate pinner's configuration:
*
* ```
* val builder = CertificatePinner.Builder()
* .add("publicobject.com", "sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=")
* .add("publicobject.com", "sha256/klO23nT2ehFDXCfx3eHTDRESMz3asj1muO+4aIdjiuY=")
* .add("publicobject.com", "sha256/grX4Ta9HpZx6tSHkmCrvpApTQGo67CYDnvprLg5yRME=")
* .add("publicobject.com", "sha256/lCppFqbkrlJ3EcVFAkeip0+44VaoJUymbnOaEUk7tEU=")
* handleChallenge(builder.build())
* ```
*
* ## Domain Patterns
*
* Pinning is per-hostname and/or per-wildcard pattern. To pin both `publicobject.com` and
* `www.publicobject.com` you must configure both hostnames. Or you may use patterns to match
* sets of related domain names. The following forms are permitted:
*
* * **Full domain name**: you may pin an exact domain name like `www.publicobject.com`. It won't
* match additional prefixes (`us-west.www.publicobject.com`) or suffixes (`publicobject.com`).
*
* * **Any number of subdomains**: Use two asterisks to like `**.publicobject.com` to match any
* number of prefixes (`us-west.www.publicobject.com`, `www.publicobject.com`) including no
* prefix at all (`publicobject.com`). For most applications this is the best way to configure
* certificate pinning.
*
* * **Exactly one subdomain**: Use a single asterisk like `*.publicobject.com` to match exactly
* one prefix (`www.publicobject.com`, `api.publicobject.com`). Be careful with this approach as
* no pinning will be enforced if additional prefixes are present, or if no prefixes are present.
*
* Note that any other form is unsupported. You may not use asterisks in any position other than
* the leftmost label.
*
* If multiple patterns match a hostname, any match is sufficient. For example, suppose pin A
* applies to `*.publicobject.com` and pin B applies to `api.publicobject.com`. Handshakes for
* `api.publicobject.com` are valid if either A's or B's certificate is in the chain.
*
* ## Warning: Certificate Pinning is Dangerous!
*
* Pinning certificates limits your server team's abilities to update their TLS certificates. By
* pinning certificates, you take on additional operational complexity and limit your ability to
* migrate between certificate authorities. Do not use certificate pinning without the blessing of
* your server's TLS administrator!
*
* See also [OWASP: Certificate and Public Key Pinning](https://www.owasp.org/index
* .php/Certificate_and_Public_Key_Pinning).
*
* This class was heavily inspired by OkHttp, which is a great Http library for Android
* https://square.github.io/okhttp/4.x/okhttp/okhttp3/-certificate-pinner/
* https://github.com/square/okhttp/blob/master/okhttp/src/main/java/okhttp3/CertificatePinner.kt
*/
@OptIn(UnsafeNumber::class)
public data class LegacyCertificatePinner(
private val pinnedCertificates: Set<LegacyPinnedCertificate>,
private val validateTrust: Boolean
) : ChallengeHandler {
@OptIn(ExperimentalForeignApi::class)
override fun invoke(
session: NSURLSession,
task: NSURLSessionTask,
challenge: NSURLAuthenticationChallenge,
completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Unit
) {
val hostname = challenge.protectionSpace.host
val matchingPins = findMatchingPins(hostname)
if (matchingPins.isEmpty()) {
println("CertificatePinner: No pins found for host")
completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, null)
return
}
if (challenge.protectionSpace.authenticationMethod !=
NSURLAuthenticationMethodServerTrust
) {
println("CertificatePinner: Authentication method not suitable for pinning")
completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, null)
return
}
val trust = challenge.protectionSpace.serverTrust
if (trust == null) {
println("CertificatePinner: Server trust is not available")
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, null)
return
}
if (validateTrust) {
val hostCFString = CFStringCreateWithCString(null, hostname, kCFStringEncodingUTF8)
hostCFString?.use {
SecPolicyCreateSSL(true, hostCFString)?.use { policy ->
SecTrustSetPolicies(trust, policy)
}
}
if (!trust.trustIsValid()) {
println("CertificatePinner: Server trust is invalid")
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, null)
return
}
}
val certCount = SecTrustGetCertificateCount(trust)
val certificates = (0 until certCount).mapNotNull { index ->
SecTrustGetCertificateAtIndex(trust, index)
}
if (certificates.size != certCount.toInt()) {
println("CertificatePinner: Unknown certificates")
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, null)
return
}
val result = hasOnePinnedCertificate(certificates)
if (result) {
completionHandler(NSURLSessionAuthChallengeUseCredential, challenge.proposedCredential)
} else {
val message = buildErrorMessage(certificates, hostname)
println(message)
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, null)
}
}
/**
* Confirms that at least one of the certificates is pinned
*/
@OptIn(ExperimentalForeignApi::class)
private fun hasOnePinnedCertificate(
certificates: List<SecCertificateRef>
): Boolean = certificates.any { certificate ->
val publicKey = certificate.getPublicKeyBytes() ?: return@any false
// Lazily compute the hashes for each public key.
var sha1: String? = null
var sha256: String? = null
pinnedCertificates.any { pin ->
when (pin.hashAlgorithm) {
LegacyCertificatesInfo.HASH_ALGORITHM_SHA_256 -> {
if (sha256 == null) {
sha256 = publicKey.toSha256String()
}
pin.hash == sha256
}
LegacyCertificatesInfo.HASH_ALGORITHM_SHA_1 -> {
if (sha1 == null) {
sha1 = publicKey.toSha1String()
}
pin.hash == sha1
}
else -> {
println("CertificatePinner: Unsupported hashAlgorithm: ${pin.hashAlgorithm}")
false
}
}
}
}
/**
* Build an error string to display
*/
@OptIn(ExperimentalForeignApi::class)
private fun buildErrorMessage(
certificates: List<SecCertificateRef>,
hostname: String
): String = buildString {
append("Certificate pinning failure!")
append("\n Peer certificate chain:")
for (certificate in certificates) {
append("\n ")
val publicKeyStr = certificate.getPublicKeyBytes()?.toSha256String()
append("${LegacyCertificatesInfo.HASH_ALGORITHM_SHA_256}$publicKeyStr")
append(": ")
val summaryRef = SecCertificateCopySubjectSummary(certificate)
val summary = CFBridgingRelease(summaryRef) as NSString
append("$summary")
}
append("\n Pinned certificates for ")
append(hostname)
append(":")
for (pin in pinnedCertificates) {
append("\n ")
append(pin)
}
}
/**
* Returns list of matching certificates' pins for the hostname. Returns an empty list if the
* hostname does not have pinned certificates.
*/
internal fun findMatchingPins(hostname: String): List<LegacyPinnedCertificate> {
var result: List<LegacyPinnedCertificate> = emptyList()
for (pin in pinnedCertificates) {
if (pin.matches(hostname)) {
if (result.isEmpty()) result = mutableListOf()
(result as MutableList<LegacyPinnedCertificate>).add(pin)
}
}
return result
}
/**
* Evaluates trust for the specified certificate and policies.
*/
@OptIn(ExperimentalForeignApi::class)
private fun SecTrustRef.trustIsValid(): Boolean {
var isValid = false
val version = cValue<NSOperatingSystemVersion> {
majorVersion = 12
minorVersion = 0
patchVersion = 0
}
if (NSProcessInfo().isOperatingSystemAtLeastVersion(version)) {
// https://developer.apple.com/documentation/security/2980705-sectrustevaluatewitherror
isValid = SecTrustEvaluateWithError(this, null)
} else {
// https://developer.apple.com/documentation/security/1394363-sectrustevaluate
memScoped {
val result = alloc<SecTrustResultTypeVar>()
result.value = kSecTrustResultInvalid
val status = SecTrustEvaluate(this@trustIsValid, result.ptr)
if (status == errSecSuccess) {
isValid = result.value == kSecTrustResultUnspecified ||
result.value == kSecTrustResultProceed
}
}
}
return isValid
}
/**
* Gets the public key from the SecCertificate
*/
@OptIn(ExperimentalForeignApi::class)
private fun SecCertificateRef.getPublicKeyBytes(): ByteArray? {
val publicKeyRef = SecCertificateCopyKey(this) ?: return null
return publicKeyRef.use {
val publicKeyAttributes = SecKeyCopyAttributes(publicKeyRef)
val publicKeyTypePointer = CFDictionaryGetValue(publicKeyAttributes, kSecAttrKeyType)
val publicKeyType = CFBridgingRelease(publicKeyTypePointer) as NSString
val publicKeySizePointer = CFDictionaryGetValue(publicKeyAttributes, kSecAttrKeySizeInBits)
val publicKeySize = CFBridgingRelease(publicKeySizePointer) as NSNumber
CFBridgingRelease(publicKeyAttributes)
if (!checkValidKeyType(publicKeyType, publicKeySize)) {
println("CertificatePinner: Public Key not supported type or size")
return null
}
val publicKeyDataRef = SecKeyCopyExternalRepresentation(publicKeyRef, null)
val publicKeyData = CFBridgingRelease(publicKeyDataRef) as NSData
val publicKeyBytes = publicKeyData.toByteArray()
val headerInts = getAsn1HeaderBytes(publicKeyType, publicKeySize)
val header = headerInts.foldIndexed(ByteArray(headerInts.size)) { i, a, v ->
a[i] = v.toByte()
a
}
header + publicKeyBytes
}
}
/**
* Checks that we support the key type and size
*/
@OptIn(ExperimentalForeignApi::class)
private fun checkValidKeyType(publicKeyType: NSString, publicKeySize: NSNumber): Boolean {
val keyTypeRSA = CFBridgingRelease(kSecAttrKeyTypeRSA) as NSString
val keyTypeECSECPrimeRandom = CFBridgingRelease(kSecAttrKeyTypeECSECPrimeRandom) as NSString
val size: Int = publicKeySize.intValue.toInt()
val keys = when (publicKeyType) {
keyTypeRSA -> LegacyCertificatesInfo.rsa
keyTypeECSECPrimeRandom -> LegacyCertificatesInfo.ecdsa
else -> return false
}
return keys.containsKey(size)
}
/**
* Get the [IntArray] of Asn1 headers needed to prepend to the public key to create the
* encoding [ASN1Header](https://docs.oracle.com/middleware/11119/opss/SCRPJ/oracle/security/crypto/asn1/ASN1Header.html)
*/
@OptIn(ExperimentalForeignApi::class)
private fun getAsn1HeaderBytes(publicKeyType: NSString, publicKeySize: NSNumber): IntArray {
val keyTypeRSA = CFBridgingRelease(kSecAttrKeyTypeRSA) as NSString
val keyTypeECSECPrimeRandom = CFBridgingRelease(kSecAttrKeyTypeECSECPrimeRandom) as NSString
val size: Int = publicKeySize.intValue.toInt()
val keys = when (publicKeyType) {
keyTypeRSA -> LegacyCertificatesInfo.rsa
keyTypeECSECPrimeRandom -> LegacyCertificatesInfo.ecdsa
else -> return intArrayOf()
}
return keys[size] ?: intArrayOf()
}
/**
* Converts a [ByteArray] into sha256 base 64 encoded string
*/
@OptIn(ExperimentalUnsignedTypes::class, ExperimentalForeignApi::class)
private fun ByteArray.toSha256String(): String {
val digest = UByteArray(CC_SHA256_DIGEST_LENGTH)
usePinned { inputPinned ->
digest.usePinned { digestPinned ->
CC_SHA256(inputPinned.addressOf(0), this.size.convert(), digestPinned.addressOf(0))
}
}
return digest.toByteArray().toNSData().base64EncodedStringWithOptions(0u)
}
/**
* Converts a [ByteArray] into sha1 base 64 encoded string
*/
@OptIn(ExperimentalUnsignedTypes::class, ExperimentalForeignApi::class)
private fun ByteArray.toSha1String(): String {
val digest = UByteArray(CC_SHA1_DIGEST_LENGTH)
usePinned { inputPinned ->
digest.usePinned { digestPinned ->
CC_SHA1(inputPinned.addressOf(0), this.size.convert(), digestPinned.addressOf(0))
}
}
return digest.toByteArray().toNSData().base64EncodedStringWithOptions(0u)
}
/**
* Builds a configured [LegacyCertificatePinner].
*/
public data class Builder(
private val pinnedCertificates: MutableList<LegacyPinnedCertificate> = mutableListOf(),
private var validateTrust: Boolean = true
) {
/**
* Pins certificates for `pattern`.
*
* @param pattern lower-case host name or wildcard pattern such as `*.example.com`.
* @param pins SHA-256 or SHA-1 hashes. Each pin is a hash of a certificate's
* Subject Public Key Info, base64-encoded and prefixed with either `sha256/` or `sha1/`.
* @return The [Builder] so calls can be chained
*/
public fun add(pattern: String, vararg pins: String): Builder = apply {
pins.forEach { pin ->
this.pinnedCertificates.add(
LegacyPinnedCertificate.new(
pattern,
pin
)
)
}
}
/**
* Whether to valid the trust of the server
* https://developer.apple.com/documentation/security/2980705-sectrustevaluatewitherror
* @param validateTrust
* @return The [Builder] so calls can be chained
*/
public fun validateTrust(validateTrust: Boolean): Builder = apply {
this.validateTrust = validateTrust
}
/**
* Build into a [LegacyCertificatePinner]
* @return [LegacyCertificatePinner]
*/
public fun build(): LegacyCertificatePinner = LegacyCertificatePinner(
pinnedCertificates.toSet(),
validateTrust
)
}
}
| 303 | null | 961 | 9,709 | 9e0eb99aa2a0a6bc095f162328525be1a76edb21 | 17,824 | ktor | Apache License 2.0 |
app/src/main/java/dev/farouk/depensy/ui/expenses/ExpensesViewModel.kt | sabiou | 158,005,012 | false | {"Kotlin": 61261, "Java": 281} | package dev.farouk.depensy.ui.expenses
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import dev.farouk.depensy.data.models.Expense
import dev.farouk.depensy.data.repository.ExpensesRepository
/**
* The viewModel for [ExpensesFragment]
*/
class ExpensesViewModel internal constructor(expensesRepository: ExpensesRepository): ViewModel() {
val expenses: LiveData<List<Expense>> = expensesRepository.getExpenses()
} | 1 | Kotlin | 1 | 13 | d99510a8020a932bcc9848fc3df0e644042fb710 | 446 | depensy-app | Apache License 2.0 |
lattekit-core/src/main/java/io/lattekit/view/LatteTemplateRecyclerAdapter.kt | maannajjar | 54,922,229 | false | null | package io.lattekit.view
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import java.lang.reflect.ParameterizedType
/**
* Created by maan on 3/25/16.
*/
class LatteTemplateRecyclerAdapter(parentView : LatteView) : RecyclerView.Adapter<LatteViewHolder>() {
var data : List<Any> = emptyList()
var templates : List<LatteView> = emptyList()
var parentView = parentView;
override fun getItemCount(): Int = data.size
override fun getItemId(position: Int) = position.toLong()
fun getItem(position: Int) = data[position]
override fun getItemViewType(position: Int): Int {
var item = data[position];
var defaultView: Int = -1;
for (i in 0..templates.size - 1) {
var child = templates.get(i);
if (isMatch(child, item, position)) {
return i;
}
if (child.props.get("defaultView") == true || child.props.get("defaultView") == "true") {
defaultView = i;
}
}
if (defaultView == -1) {
throw Exception("Couldn't find template matching for item " + position);
}
return defaultView;
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): LatteViewHolder? {
var template = templates.get(viewType);
template = template.copy();
template.parentView = parentView
if (template.props["nullUnsafe"] as? Boolean == true) {
return LatteNullUnsafeViewHolder(template);
} else {
return LatteNullSafeViewHolder(template);
}
}
override fun onBindViewHolder(holder: LatteViewHolder?, position: Int) {
holder?.bindView(getItem(position),position)
}
fun isMatch(template: LatteView, item: Any, position: Int): Boolean {
var testLambda = template.props.get("when");
if (testLambda == null) {
return false;
}
if ( (!(testLambda is kotlin.Function1<*, *>) && !(testLambda is kotlin.Function2<*, *, *>))) {
LatteView.log("Warning: 'when' parameter should be a lambda that returns boolean")
return false;
}
var isFn2 = testLambda is kotlin.Function2<*, *, *>
var modelType = (testLambda.javaClass.genericInterfaces.get(0) as ParameterizedType).actualTypeArguments.get(0) as Class<*>
if (modelType.isAssignableFrom(item.javaClass)) {
var secondParamType: Class<*>? = null
if (isFn2) {
secondParamType = (testLambda.javaClass.genericInterfaces.get(0) as ParameterizedType).actualTypeArguments.get(1) as Class<*>;
if (!secondParamType.isAssignableFrom(Integer::class.java)) {
LatteView.log("Warning: second parameter's type is " + secondParamType.name + ". It must be an integer which will contain model index")
return false;
}
}
var isMatch = if (!isFn2) {
(testLambda as Function1<Any,Any>).invoke(item) as Boolean
} else {
(testLambda as Function2<Any,Any,Any>).invoke(item,position) as Boolean
}
return isMatch;
} else {
LatteView.log("Warning: model of type " + item.javaClass.name + " is not assignable to " + modelType)
}
return false;
}
}
abstract class LatteViewHolder(view : View) : RecyclerView.ViewHolder(view) {
open abstract fun bindView(model : Any, modelIndex : Int);
}
class LatteNullSafeViewHolder(template : LatteView) : LatteViewHolder(template.buildView(template.parentView?.activity!!,null)) {
var template : LatteView = template
init {
itemView.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
}
override fun bindView(model : Any, modelIndex : Int) {
template.props.put("model", model);
template.props.put("modelIndex", modelIndex);
template.notifyStateChanged();
itemView.layoutParams = ViewGroup.LayoutParams(template.rootAndroidView?.layoutParams)
}
}
class LatteNullUnsafeViewHolder(template : LatteView) : LatteViewHolder(FrameLayout(template.parentView?.activity!!) ) {
var template : LatteView = template
var isAttached = false;
init {
(itemView as FrameLayout).layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
}
override fun bindView(model : Any, modelIndex : Int) {
template.props.put("model", model);
template.props.put("modelIndex", modelIndex);
if (!isAttached) {
isAttached = true;
(itemView as FrameLayout).addView(template.buildView(template.parentView?.activity!!, null))
} else {
template.notifyStateChanged();
}
}
}
| 12 | Kotlin | 18 | 173 | bcc1e4e759c5be62db30b6398de63555c5b24726 | 4,978 | lattekit | MIT License |
paymentsheet/src/main/java/com/stripe/android/paymentsheet/FormHelper.kt | stripe | 6,926,049 | false | null | package com.stripe.android.paymentsheet
import com.stripe.android.cards.CardAccountRangeRepository
import com.stripe.android.link.LinkConfigurationCoordinator
import com.stripe.android.link.ui.inline.InlineSignupViewState
import com.stripe.android.lpmfoundations.luxe.SupportedPaymentMethod
import com.stripe.android.lpmfoundations.paymentmethod.PaymentMethodMetadata
import com.stripe.android.lpmfoundations.paymentmethod.UiDefinitionFactory
import com.stripe.android.model.PaymentMethod
import com.stripe.android.model.PaymentMethodCode
import com.stripe.android.paymentsheet.forms.FormArgumentsFactory
import com.stripe.android.paymentsheet.forms.FormFieldValues
import com.stripe.android.paymentsheet.model.PaymentSelection
import com.stripe.android.paymentsheet.paymentdatacollection.FormArguments
import com.stripe.android.paymentsheet.ui.transformToPaymentSelection
import com.stripe.android.paymentsheet.viewmodels.BaseSheetViewModel
import com.stripe.android.uicore.elements.FormElement
internal class FormHelper(
private val cardAccountRangeRepositoryFactory: CardAccountRangeRepository.Factory,
private val paymentMethodMetadata: PaymentMethodMetadata,
private val newPaymentSelectionProvider: () -> NewOrExternalPaymentSelection?,
private val selectionUpdater: (PaymentSelection?) -> Unit,
private val linkConfigurationCoordinator: LinkConfigurationCoordinator,
private val onLinkInlineSignupStateChanged: (InlineSignupViewState) -> Unit,
) {
companion object {
fun create(
viewModel: BaseSheetViewModel,
linkInlineHandler: LinkInlineHandler,
paymentMethodMetadata: PaymentMethodMetadata
): FormHelper {
return FormHelper(
cardAccountRangeRepositoryFactory = viewModel.cardAccountRangeRepositoryFactory,
paymentMethodMetadata = paymentMethodMetadata,
newPaymentSelectionProvider = {
viewModel.newPaymentSelection
},
linkConfigurationCoordinator = viewModel.linkHandler.linkConfigurationCoordinator,
onLinkInlineSignupStateChanged = linkInlineHandler::onStateUpdated,
selectionUpdater = {
viewModel.updateSelection(it)
}
)
}
}
fun formElementsForCode(code: String): List<FormElement> {
val currentSelection = newPaymentSelectionProvider()?.takeIf { it.getType() == code }
return paymentMethodMetadata.formElementsForCode(
code = code,
uiDefinitionFactoryArgumentsFactory = UiDefinitionFactory.Arguments.Factory.Default(
cardAccountRangeRepositoryFactory = cardAccountRangeRepositoryFactory,
linkConfigurationCoordinator = linkConfigurationCoordinator,
onLinkInlineSignupStateChanged = onLinkInlineSignupStateChanged,
paymentMethodCreateParams = currentSelection?.getPaymentMethodCreateParams(),
paymentMethodExtraParams = currentSelection?.getPaymentMethodExtraParams(),
),
) ?: emptyList()
}
fun createFormArguments(
paymentMethodCode: PaymentMethodCode,
): FormArguments {
return FormArgumentsFactory.create(
paymentMethodCode = paymentMethodCode,
metadata = paymentMethodMetadata,
)
}
fun onFormFieldValuesChanged(formValues: FormFieldValues?, selectedPaymentMethodCode: String) {
val newSelection = formValues?.transformToPaymentSelection(
paymentMethod = supportedPaymentMethodForCode(selectedPaymentMethodCode),
paymentMethodMetadata = paymentMethodMetadata,
)
selectionUpdater(newSelection)
}
fun requiresFormScreen(selectedPaymentMethodCode: String): Boolean {
val userInteractionAllowed = formElementsForCode(selectedPaymentMethodCode).any { it.allowsUserInteraction }
return userInteractionAllowed ||
selectedPaymentMethodCode == PaymentMethod.Type.USBankAccount.code ||
selectedPaymentMethodCode == PaymentMethod.Type.Link.code
}
private fun supportedPaymentMethodForCode(code: String): SupportedPaymentMethod {
return requireNotNull(paymentMethodMetadata.supportedPaymentMethodForCode(code = code))
}
}
| 92 | null | 644 | 1,277 | 174b27b5a70f75a7bc66fdcce3142f1e51d809c8 | 4,346 | stripe-android | MIT License |
src/main/kotlin/git/semver/plugin/semver/SemVersion.kt | jmongard | 248,187,973 | false | {"Kotlin": 95477} | package git.semver.plugin.semver
import git.semver.plugin.scm.IRefInfo
import org.slf4j.LoggerFactory
class SemVersion(
var sha: String = "",
var major: Int = 0,
var minor: Int = 0,
var patch: Int = 0,
var preRelease: PreRelease = PreRelease.noPreRelease,
var commitCount: Int = 0,
private var bumpPatch: Int = 0,
private var bumpMinor: Int = 0,
private var bumpMajor: Int = 0,
private var bumpPre: Int = 0,
private val lastReleaseMajor: Int = major,
private val lastReleaseMinor: Int = minor
) : Comparable<SemVersion> {
companion object {
private val logger = LoggerFactory.getLogger(SemVersion::class.java)
private const val NUMERIC = "0|[1-9]\\d*"
private const val ALPHA_NUMERIC = "[0-9a-zA-Z-]"
private const val PRE_VERSION = "(?:$NUMERIC|\\d*[a-zA-Z-]$ALPHA_NUMERIC*)"
private val semVersionPattern = (
"""(?<Major>$NUMERIC)\.(?<Minor>$NUMERIC)(?:\.(?<Patch>$NUMERIC)(?:\.(?<Revision>$NUMERIC))?)?"""
+ """(?:-(?<PreRelease>$PRE_VERSION(?:\.$PRE_VERSION)*))?"""
+ """(?:\+(?<BuildMetadata>$ALPHA_NUMERIC+(?:\.$ALPHA_NUMERIC+)*))?"""
).toRegex()
fun tryParse(refInfo: IRefInfo): SemVersion? {
val match = semVersionPattern.find(refInfo.text) ?: return null
fun getInt(group: String) = match.groups[group]?.value?.toInt()
val version = SemVersion(
refInfo.sha,
getInt("Major")!!,
getInt("Minor")!!,
getInt("Patch") ?: 0,
PreRelease.parse(
match.groups["PreRelease"]?.value,
getInt("Revision")
)
)
logger.debug("Found version: {} in: '{}'", version, refInfo.text)
return version
}
fun isRelease(commit: IRefInfo, settings: SemverSettings): Boolean {
return settings.releaseRegex.containsMatchIn(commit.text)
}
}
val isPreRelease
get() = preRelease.isPreRelease
internal fun setPreRelease(value: String?) {
preRelease = PreRelease.parse(value)
}
override fun compareTo(other: SemVersion): Int {
return compareValuesBy(this, other,
{ it.major },
{ it.minor },
{ it.patch },
{ !it.isPreRelease },
{ it.preRelease.prefix },
{ it.preRelease.number },
{ it.commitCount }
)
}
internal fun updateFromCommit(commit: IRefInfo, settings: SemverSettings, preReleaseVersion: SemVersion?) {
sha = commit.sha
if (preReleaseVersion != null) {
if (preReleaseVersion >= this) {
major = preReleaseVersion.major
minor = preReleaseVersion.minor
patch = preReleaseVersion.patch
preRelease = preReleaseVersion.preRelease
commitCount = 0
resetPendingChanges()
logger.debug(
"Version after commit(\"{}\") with pre-release: {}",
commit,
this
)
return
} else {
logger.warn("Ignored given version lower than the current version: {} < {} ", preReleaseVersion, this)
}
}
commitCount += 1
checkCommitText(settings, commit.text)
logger.debug(
"Version after commit(\"{}\"): {} +({}.{}.{}-{})",
commit,
this,
bumpMajor,
bumpMinor,
bumpPatch,
bumpPre
)
}
private fun checkCommitText(
settings: SemverSettings,
text: String
) {
when {
settings.majorRegex.containsMatchIn(text) ->
if (!isPreRelease || major == lastReleaseMajor) {
bumpMajor += 1
bumpMinor = 0
bumpPatch = 0
bumpPre = 0
}
settings.minorRegex.containsMatchIn(text) ->
if (!isPreRelease || major == lastReleaseMajor && minor == lastReleaseMinor) {
bumpMinor += 1
bumpPatch = 0
bumpPre = 0
}
settings.patchRegex.containsMatchIn(text) ->
if (!isPreRelease) {
bumpPatch += 1
bumpPre = 0
} else if (preRelease.number != null) {
bumpPre += 1
}
}
}
internal fun applyPendingChanges(forceBumpIfNoChanges: Boolean, groupChanges: Boolean): Boolean {
if (hasPendingChanges) {
if (groupChanges) {
applyChangesGrouped()
} else {
applyChangesNotGrouped()
}
resetPendingChanges()
return true
}
if (!forceBumpIfNoChanges) {
return false
}
val preReleaseNumber = preRelease.number
if (preReleaseNumber != null) {
preRelease = PreRelease(preRelease.prefix, preReleaseNumber + 1)
} else {
patch += 1
}
return true
}
private fun applyChangesNotGrouped() {
if (bumpMajor > 0) {
updateMajor(bumpMajor)
}
if (bumpMinor > 0) {
updateMinor(bumpMinor)
}
if (bumpPatch > 0) {
updatePatch(bumpPatch)
}
if (bumpPre > 0) {
updatePreReleaseNumber { it + bumpPre }
}
}
private fun applyChangesGrouped() {
when {
bumpMajor > 0 -> {
updateMajor(1)
}
bumpMinor > 0 -> {
updateMinor(1)
}
bumpPatch > 0 -> {
updatePatch(1)
}
else -> { // bumpPre > 0
updatePreReleaseNumber { it + 1 }
}
}
}
private fun updateMajor(i: Int) {
major += i
minor = 0
patch = 0
updatePreReleaseNumber { 1 }
}
private fun updateMinor(i: Int) {
minor += i
patch = 0
updatePreReleaseNumber { 1 }
}
private fun updatePatch(i: Int) {
patch += i
updatePreReleaseNumber { 1 }
}
private fun updatePreReleaseNumber(updateFunction: (Int) -> Int) {
val preReleaseNumber = preRelease.number
if (preReleaseNumber != null) {
preRelease = PreRelease(preRelease.prefix, updateFunction(preReleaseNumber))
}
}
internal fun mergeChanges(versions: List<SemVersion>) {
this.commitCount = versions.sumOf { it.commitCount }
this.bumpPatch = versions.sumOf { it.bumpPatch }
this.bumpMinor = versions.sumOf { it.bumpMinor }
this.bumpMajor = versions.sumOf { it.bumpMajor }
this.bumpPre = versions.sumOf { it.bumpPre }
}
private val hasPendingChanges
get() = bumpMajor + bumpMinor + bumpPatch + bumpPre > 0
private fun resetPendingChanges() {
bumpMajor = 0
bumpMinor = 0
bumpPatch = 0
bumpPre = 0
}
fun toVersionString(v2: Boolean = true): String {
return toInfoVersionString("", 0, v2)
}
fun toInfoVersionString(commitCountStringFormat: String = "%03d", shaLength: Int = 0, v2: Boolean = true, appendPreReleaseLast: Boolean = false): String {
val builder = StringBuilder().append(major).append('.').append(minor).append('.').append(patch)
if (v2) {
if (isPreRelease && !appendPreReleaseLast) {
builder.append('-').append(preRelease)
}
var metaSeparator = '+'
if (this.commitCount > 0 && commitCountStringFormat.isNotEmpty()) {
builder.append(metaSeparator).append(commitCountStringFormat.format(this.commitCount))
metaSeparator = '.'
}
val shaTake = sha.take(shaLength)
if (shaTake.isNotEmpty()) {
builder.append(metaSeparator).append("sha.").append(shaTake)
}
if (isPreRelease && appendPreReleaseLast) {
builder.append('-').append(preRelease)
}
}
else if (isPreRelease) {
builder.append("-")
.append(preRelease.prefix.replace("[^0-9A-Za-z-]".toRegex(), ""))
.append (preRelease.number ?: "")
}
return builder.toString()
}
override fun toString(): String {
return toInfoVersionString(shaLength = 7)
}
class PreRelease(val prefix: String, val number: Int?) {
companion object {
val noPreRelease = PreRelease("", null)
internal fun parse(value: String?, defaultPreReleaseVersion: Int? = null): PreRelease {
if (value == null) {
return noPreRelease
}
val prefix = value.trimEnd { it.isDigit() }
return PreRelease(prefix,
if (prefix.length < value.length)
value.substring(prefix.length).toInt()
else
defaultPreReleaseVersion)
}
}
val isPreRelease
get() = prefix.isNotEmpty() || number != null
override fun toString() = prefix + (number ?: "")
}
} | 3 | Kotlin | 4 | 27 | 2cba7e8fb0cef6ba1d36b6672d64afb50758759e | 9,531 | Git.SemVersioning.Gradle | Apache License 2.0 |
src/main/kotlin/io/maslick/revolutto/BusinessLogic.kt | maslick | 208,226,196 | false | null | package io.maslick.revolutto
import org.slf4j.LoggerFactory
import java.math.BigDecimal
interface ITransaction {
suspend fun transfer(from: String, to: String, amount: BigDecimal): Boolean
}
interface IBalance {
suspend fun getBalance(userId: String): BigDecimal
}
class Transaction(private val repo: IRepo) : ITransaction {
@Synchronized
override suspend fun transfer(from: String, to: String, amount: BigDecimal): Boolean {
if (from == to) return false
if (!repo.withdraw(from, amount)) return false
return repo.deposit(to, amount).also {
log.debug("Sent $amount EUR from $from to $to")
}
}
}
class Balance(private val repo: IRepo) : IBalance {
override suspend fun getBalance(userId: String) = repo.getBalance(userId)
}
val log = LoggerFactory.getLogger("revolutto")!! | 0 | Kotlin | 0 | 2 | 8932690a9445bd33a5104a63defd6a43483f9bed | 845 | revolutto | MIT License |
src/main/kotlin/com/pettcare/message/repository/MessageRepository.kt | antelukic | 810,253,774 | false | {"Kotlin": 75020, "Dockerfile": 300} | package com.pettcare.message.repository
import com.pettcare.core.BaseResponse
import com.pettcare.message.request.SendMessageRequest
import io.ktor.websocket.WebSocketSession
interface MessageRepository {
suspend fun sendMessage(socketSession: WebSocketSession, message: SendMessageRequest): BaseResponse<out Any>
suspend fun getAllMessages(chatId: String): BaseResponse<out Any>
suspend fun tryDisconnect(socketSession: WebSocketSession): BaseResponse<out Any>
} | 0 | Kotlin | 0 | 0 | 7a7f370d3607511fa4dceacfdfd70dbe55fc4841 | 480 | PettCare-Server | Apache License 2.0 |
model-server/src/test/kotlin/org/modelix/model/server/StoreClientWithStatistics.kt | modelix | 533,211,353 | false | {"Kotlin": 2516761, "JetBrains MPS": 274458, "TypeScript": 55129, "Java": 9941, "JavaScript": 6875, "Mustache": 5974, "CSS": 2898, "Shell": 2811, "Dockerfile": 389, "Procfile": 76} | /*
* Copyright (c) 2024.
*
* 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.modelix.model.server
import org.modelix.model.server.store.IsolatingStore
import org.modelix.model.server.store.ObjectInRepository
import java.util.concurrent.atomic.AtomicLong
class StoreClientWithStatistics(val store: IsolatingStore) : IsolatingStore by store {
private val totalRequests = AtomicLong()
fun getTotalRequests() = totalRequests.get()
override fun get(key: ObjectInRepository): String? {
totalRequests.incrementAndGet()
return store.get(key)
}
override fun getAll(keys: List<ObjectInRepository>): List<String?> {
totalRequests.incrementAndGet()
return store.getAll(keys)
}
override fun getAll(keys: Set<ObjectInRepository>): Map<ObjectInRepository, String?> {
totalRequests.incrementAndGet()
return store.getAll(keys)
}
override fun getAll(): Map<ObjectInRepository, String?> {
totalRequests.incrementAndGet()
return store.getAll()
}
}
| 47 | Kotlin | 9 | 6 | 2bbc5b1ed943aa9842cb3d58d4d2a8a6bc8b4bd0 | 1,559 | modelix.core | Apache License 2.0 |
compose/desktop/desktop/samples/src/jvmMain/kotlin/androidx/compose/desktop/examples/popupexample/MenuItems.jvm.kt | RikkaW | 389,105,112 | false | null | /*
* Copyright 2020 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.compose.desktop.examples.popupexample
import androidx.compose.desktop.AppManager
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.window.MenuItem
import androidx.compose.ui.window.KeyStroke
import androidx.compose.ui.window.Notifier
object MenuItems {
val Exit = MenuItem(
name = "Exit",
onClick = { AppManager.exit() },
shortcut = KeyStroke(Key.X)
)
val Notify = MenuItem(
name = "Send tray notification",
onClick = {
Notifier().notify(
title = "New Notification from JB",
message = "JetBrains send you a message!"
)
},
shortcut = KeyStroke(Key.N)
)
val Increment = MenuItem(
name = "Increment amount",
onClick = { AppState.amount.value++ },
shortcut = KeyStroke(Key.A)
)
val About = MenuItem(
name = "About app",
onClick = {
println("This is PopUpExampleApp")
},
shortcut = KeyStroke(Key.I)
)
val Update = MenuItem(
name = "Check updates",
onClick = {
println("Application is up to date.")
},
shortcut = KeyStroke(Key.U)
)
} | 0 | null | 0 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 1,848 | androidx | Apache License 2.0 |
app/src/main/java/com/amitranofinzi/vimata/data/dao/CollectionDao.kt | Ggino11 | 788,949,158 | false | {"Kotlin": 399279} | package com.amitranofinzi.vimata.data.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.amitranofinzi.vimata.data.model.Collection
@Dao
interface CollectionDao {
/**
* Retrieves a list of Collection where the value of a specific field equals a given value.
*
* @param field The name of the field to be compared.
* @param value The value to be compared with the specified field.
* @return A list of Collection objects that meet the equality condition.
*/
@Query("SELECT * FROM collections WHERE :field = :value")
fun getWhereEqual(field: String, value: String): List<Collection>
/**
* Retrieves a list of Collection where the value of a specific field is in a list of values.
*
* @param field The name of the field to be compared.
* @param values The list of values to be compared with the specified field.
* @return A list of Collection objects that meet the inclusion condition.
*/
@Query("SELECT * FROM collections WHERE :field IN (:values)")
fun getWhereIn(field: String, values: List<String>): List<Collection>
/**
* Retrieves a Collection with a specific primary key.
*
* @param id The primary key of the Collection to retrieve.
* @return The Collection object with the specified primary key, or null if not found.
*/
@Query("SELECT * FROM collections WHERE id = :id")
fun getWithPrimaryKey(id: String): Collection?
/**
* Inserts a Collection into the database. If a conflict occurs, the existing entry will be replaced.
*
* @param collection The Collection object to insert.
*/
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(collection: Collection)
/**
* Updates an existing Collection in the database.
*
* @param collection The Collection object to update.
*/
@Update
fun update(collection: Collection)
}
| 0 | Kotlin | 0 | 0 | e864fc070b7343394457425601c7e276968a2ca6 | 2,030 | ProgettoAmitranoFinzi-progMob | MIT License |
library/src/main/java/com/androidbolts/library/LocationManager.kt | nawinkhatiwada | 216,338,736 | false | null | package com.androidbolts.library
import android.app.Activity
import android.content.Context
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.androidbolts.library.gps.GpsManager
import com.androidbolts.library.gps.GpsProvider
import com.androidbolts.library.permissions.PermissionListener
import com.androidbolts.library.permissions.PermissionProvider
import com.androidbolts.library.utils.ContextProcessor
import com.androidbolts.library.utils.ExperimentalSharedPrefs
import com.androidbolts.library.utils.LocationConstants
class LocationManager internal constructor(
private val locationListener: LocationListener?,
contextProcessor: ContextProcessor,
timeOut: Long = LocationConstants.TIME_OUT_NONE,
showLoading: Boolean
) : PermissionListener, LifecycleObserver {
private var permissionManager = PermissionProvider.getPermissionManager()
private var gpsProvider: GpsProvider
private var prefs: PreferenceManager? = null
init {
this.permissionManager.setListener(this)
this.permissionManager.setContextProcessor(contextProcessor)
this.gpsProvider = GpsManager.getGpsManager()
this.gpsProvider.setContextProcessor(contextProcessor)
this.gpsProvider.setLocationListener(locationListener)
this.gpsProvider.setShowLoading(showLoading)
this.gpsProvider.setTimeOut(timeOut)
this.prefs = PreferenceManager.getInstance()
this.prefs?.setContextProcessor(contextProcessor)
this.gpsProvider.setPrefs(this.prefs)
}
class Builder(context: Context) {
private lateinit var locationListener: LocationListener
private var timeOut: Long = LocationConstants.TIME_OUT_NONE
private var contextProcessor: ContextProcessor = ContextProcessor(context)
private var showLoading: Boolean = false
fun setListener(listener: LocationListener): Builder {
this.locationListener = listener
return this
}
fun setActivity(activity: Activity): Builder {
this.contextProcessor.activity = activity
return this
}
fun setFragment(fragment: Fragment): Builder {
this.contextProcessor.fragment = fragment
return this
}
fun setRequestTimeOut(timeOut: Long): Builder {
this.timeOut = timeOut
return this
}
fun showLoading(show: Boolean): Builder {
this.showLoading = show
return this
}
fun build(): LocationManager {
return LocationManager(locationListener, contextProcessor, timeOut, showLoading)
}
}
fun getLocation() {
askForPermission()
}
private fun askForPermission() {
if (permissionManager.hasPermission()) {
permissionGranted(true)
} else {
permissionManager.requestPermissions()
}
}
private fun permissionGranted(alreadyHadPermission: Boolean) {
locationListener?.onPermissionGranted(alreadyHadPermission)
// gpsProvider.get()
}
private fun onPermissionGrantedFailed() {
locationListener?.let {
locationListener.onPermissionDenied()
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {
locationListener?.let {
gpsProvider.onCreate()
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() {
locationListener?.let {
val hasPermission = permissionManager.hasPermission()
Log.i("Has Permission", hasPermission.toString())
val isProviderEnabled = permissionManager.isProviderEnabled()
Log.i("isProviderEnabled", isProviderEnabled.toString())
if (hasPermission) {
if (isProviderEnabled) {
gpsProvider.onResume()
} else {
gpsProvider.enableGps()
}
}
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() {
locationListener?.let {
gpsProvider.onPause()
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
locationListener?.let {
gpsProvider.onDestroy()
}
}
fun setShowLoading(showLoading: Boolean) {
this.gpsProvider.setShowLoading(showLoading)
}
fun isLoadingSet(): Boolean {
return this.gpsProvider.isLoadingSet()
}
@ExperimentalSharedPrefs
/** This is currently is experimental state so it may not work. */
fun getLastUpdatedLocation(): LocationModel? {
return prefs?.getLocationModel()
}
override fun onPermissionGranted() {
permissionGranted(false)
}
override fun onPermissionDenied() {
onPermissionGrantedFailed()
}
fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
permissionManager.onPermissionResult(requestCode, permissions, grantResults)
}
} | 1 | null | 1 | 3 | 8494456aab6331d6ae7df6ed1c46bbb05d20869e | 5,251 | LocationManager | Apache License 2.0 |
domain/src/main/java/com/example/domain/entities/enums/Category.kt | IlyaBorisovDly | 447,408,801 | false | {"Kotlin": 81181} | package com.example.domain.entities.enums
enum class Category {
Creators,
Publishers,
Genres,
Developers,
Platforms
} | 0 | Kotlin | 0 | 0 | 1e08c0d35e9779d67e1b046892a99532a4a936be | 138 | GamePicker | MIT License |
src/main/kotlin/com/autonomousapps/internal/ConfigurationsToDependenciesTransformer.kt | autonomousapps | 217,134,508 | false | null | package com.autonomousapps.internal
import com.autonomousapps.internal.utils.*
import com.autonomousapps.tasks.LocateDependenciesTask
import org.gradle.api.artifacts.ConfigurationContainer
internal class ConfigurationsToDependenciesTransformer(
private val flavorName: String?,
private val buildType: String?,
private val variantName: String,
private val configurations: ConfigurationContainer
) {
private val logger = getLogger<LocateDependenciesTask>()
companion object {
private val DEFAULT_CONFS = listOf(
// Main configurations
"api",
"implementation",
"compileOnly",
//"compileOnlyApi", // TODO
"runtimeOnly",
// Test configurations
"testRuntimeOnly",
"testImplementation",
"testCompileOnly",
)
private val DEFAULT_PROC_CONFS = listOf("kapt", "annotationProcessor")
}
fun locations(): Set<Location> {
val interestingConfigurations = buildConfNames() + buildAPConfNames()
// Partition all configurations into those we care about and those we don't
val (interestingConfs, otherConfs) = configurations.partition { conf ->
interestingConfigurations.contains(conf.name)
}
// TODO combine these into one sink
val warnings = linkedMapOf<String, MutableSet<String>>()
val metadataSink = mutableMapOf<String, Boolean>()
// Get all the interesting confs
val interestingLocations = interestingConfs.flatMapToMutableSet { conf ->
conf.dependencies.toIdentifiers(metadataSink).map { identifier ->
Location(
identifier = identifier,
configurationName = conf.name,
isInteresting = true
).also {
// Looking for dependencies stored on multiple configurations
warnings.merge(it.identifier, mutableSetOf(it.configurationName)) { old, new ->
old.apply { addAll(new) }
}
}
}
}
// Get all the non-interesting confs, too
val boringLocations = otherConfs.flatMapToSet { conf ->
conf.dependencies.toIdentifiers(metadataSink).map { identifier ->
Location(
identifier = identifier,
configurationName = conf.name,
isInteresting = false
)
}
}.filterToSet { boring ->
// if a dependency is in both sets, prefer interestingLocations over boringLocations
interestingLocations.none { interesting ->
boring.identifier == interesting.identifier
}
}
// Warn if dependency is declared on multiple configurations
warnings.forEach { (identifier, configurations) ->
if (configurations.size > 1) {
// Don't emit a warning if it's for a java-platform project. These can be declared on
// multiple configurations.
if (metadataSink[identifier] != true) {
logger.info("Dependency $identifier has been declared multiple times: $configurations")
}
// if one of the declarations is for an api configuration. Prefer that one
if (configurations.any { it.endsWith("api", true) }) {
interestingLocations.removeIf {
it.identifier == identifier && !it.configurationName.endsWith("api", true)
}
}
}
}
return interestingLocations + boringLocations
}
private fun buildConfNames(): Set<String> {
val confNames = (DEFAULT_CONFS + DEFAULT_CONFS.map {
// so, flavorDebugApi, etc.
"${variantName}${it.capitalizeSafely()}"
}).toMutableSet()
if (flavorName != null) {
confNames.addAll(DEFAULT_CONFS.map {
// so, flavorApi, etc.
"${flavorName}${it.capitalizeSafely()}"
})
}
if (buildType != null) {
confNames.addAll(DEFAULT_CONFS.map {
// so, buildTypeApi, etc.
"${buildType}${it.capitalizeSafely()}"
})
}
return confNames
}
private fun buildAPConfNames(): Set<String> {
val procConfNames = (DEFAULT_PROC_CONFS + DEFAULT_PROC_CONFS.map {
// so, kaptFlavorDebug, etc
"${it}${variantName.capitalizeSafely()}"
}).toMutableSet()
if (flavorName != null) {
procConfNames.addAll(DEFAULT_PROC_CONFS.map {
// so, kaptFlavor, etc.
"${it}${flavorName.capitalizeSafely()}"
})
}
return procConfNames
}
}
| 70 | null | 40 | 566 | e390bdbae96804037ec663884e45a57ee2d0f149 | 4,284 | dependency-analysis-android-gradle-plugin | Apache License 2.0 |
kool-editor/src/commonMain/kotlin/de/fabmax/kool/editor/actions/SetCameraAction.kt | fabmax | 81,503,047 | false | {"Kotlin": 5305864, "C++": 3256, "CMake": 1870, "HTML": 1464, "JavaScript": 597} | package de.fabmax.kool.editor.actions
import de.fabmax.kool.editor.components.CameraComponent
import de.fabmax.kool.editor.data.CameraTypeData
class SetCameraAction(
val cameraComponent: CameraComponent,
val setCameraData: CameraTypeData,
val undoCamData: CameraTypeData
) : EditorAction {
override fun doAction() {
cameraComponent.cameraState.set(setCameraData)
}
override fun undoAction() {
cameraComponent.cameraState.set(undoCamData)
}
} | 10 | Kotlin | 15 | 249 | 03251975abdda81dc398d86cc2ffaa545c867033 | 489 | kool | Apache License 2.0 |
expandablehinttext/src/main/java/com/tomlonghurst/expandablehinttext/ViewHelper.kt | thomhurst | 163,102,531 | false | null | package com.ahmedessamedeen.prettyedittext
import android.content.Context
internal object ViewHelper {
internal fun getDp(context: Context, int: Int): Int {
val scale = context.resources.displayMetrics.density
return (int * scale + 0.5f).toInt()
}
} | 5 | null | 20 | 179 | 5891297e568f1ffe028a119df5f46e85ab2b990a | 275 | ExpandableHintText | Apache License 2.0 |
app/src/main/java/io/wookey/wallet/data/dao/WalletDao.kt | WooKeyWallet | 176,637,569 | false | null | package io.wookey.wallet.data.dao
import android.arch.lifecycle.LiveData
import android.arch.persistence.room.*
import io.wookey.wallet.data.entity.Wallet
@Dao
interface WalletDao {
/**
* Insert a wallet in the database. If the wallet already exists, ignore it.
*
* @param wallet the wallet to be inserted.
*/
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun insertWallet(wallet: Wallet)
/**
* Select wallets from the wallets table by symbol.
*
* @return wallets.
*/
@Query("SELECT * FROM wallets WHERE symbol = :symbol ORDER BY _id")
fun loadSymbolWallets(symbol: String): LiveData<List<Wallet>>
/**
* Select all wallets count from the wallets table.
*
* @return wallets count.
*/
@Query("SELECT COUNT(*) FROM wallets")
fun countWallets(): Int
/**
* Select all wallets count from the wallets table.
*
* @return wallets count.
*/
@Query("SELECT COUNT(*) FROM wallets WHERE symbol = :symbol AND name = :name")
fun countWalletsByName(symbol: String, name: String): Int
/**
* Select wallets from the wallets table.
*
* @return wallets.
*/
@Query("SELECT * FROM wallets")
fun getWallets(): List<Wallet>
/**
* Select the active wallet from the wallets table.
*
* @return active wallet.
*/
@Query("SELECT * FROM wallets WHERE isActive = 1")
fun getActiveWallet(): Wallet?
/**
* Select the active wallets from the wallets table.
*
* @return active wallets.
*/
@Query("SELECT * FROM wallets WHERE isActive = 1")
fun getActiveWallets(): List<Wallet>?
/**
* Select wallet from the wallets table by symbol and name.
*
* @return wallet.
*/
@Query("SELECT * FROM wallets WHERE symbol = :symbol AND name = :name")
fun getWalletsByName(symbol: String, name: String): Wallet?
/**
* Select the wallet from the wallets table by id.
*
* @return wallet.
*/
@Query("SELECT * FROM wallets WHERE _id = :id")
fun getWalletById(id: Int): Wallet?
/**
* Select the wallet from the wallets table by id.
*
* @return wallet.
*/
@Query("SELECT * FROM wallets WHERE _id = :id")
fun loadWalletById(id: Int): LiveData<Wallet>
/**
* Select the active wallet from the wallets table.
*
* @return active wallet.
*/
@Query("SELECT * FROM wallets WHERE isActive = 1")
fun loadActiveWallet(): LiveData<Wallet>
/**
* Select symbol from the wallets table group by symbol.
*
* @return symbol group.
*/
@Query("SELECT symbol FROM wallets GROUP BY symbol")
fun loadWalletSymbol(): LiveData<List<String>>
/**
* Update wallets in the database
*
* @param wallets the wallets to be updated.
*/
@Update(onConflict = OnConflictStrategy.REPLACE)
fun updateWallets(vararg wallets: Wallet)
/**
* Delete wallets in the database
*
* @param wallets the wallets to be deleted.
*/
@Delete
fun deleteWallets(vararg wallets: Wallet)
} | 6 | null | 20 | 23 | 93d0d6a4743e95ab2455bb6ae24b2cc6b616bd90 | 3,139 | monero-wallet-android-app | MIT License |
solar/src/main/java/com/chiksmedina/solar/lineduotone/businessstatistic/DiagramUp.kt | CMFerrer | 689,442,321 | false | {"Kotlin": 36591890} | package com.chiksmedina.solar.lineduotone.businessstatistic
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.chiksmedina.solar.lineduotone.BusinessStatisticGroup
val BusinessStatisticGroup.DiagramUp: ImageVector
get() {
if (_diagramUp != null) {
return _diagramUp!!
}
_diagramUp = Builder(
name = "DiagramUp", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
fillAlpha = 0.5f, strokeAlpha = 0.5f, strokeLineWidth = 1.5f, strokeLineCap =
Round, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(22.0f, 22.0f)
horizontalLineTo(12.0f)
curveTo(7.286f, 22.0f, 4.9289f, 22.0f, 3.4645f, 20.5355f)
curveTo(2.0f, 19.0711f, 2.0f, 16.714f, 2.0f, 12.0f)
verticalLineTo(2.0f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(19.0002f, 7.0f)
lineTo(15.8821f, 10.9264f)
curveTo(15.4045f, 11.5278f, 15.1657f, 11.8286f, 14.8916f, 11.9751f)
curveTo(14.47f, 12.2005f, 13.9663f, 12.2114f, 13.5354f, 12.0046f)
curveTo(13.2551f, 11.8701f, 13.0035f, 11.5801f, 12.5002f, 11.0f)
curveTo(11.9968f, 10.4199f, 11.7452f, 10.1299f, 11.4649f, 9.9953f)
curveTo(11.034f, 9.7886f, 10.5303f, 9.7995f, 10.1088f, 10.0248f)
curveTo(9.8346f, 10.1714f, 9.5958f, 10.4721f, 9.1182f, 11.0735f)
lineTo(6.0f, 15.0f)
}
}
.build()
return _diagramUp!!
}
private var _diagramUp: ImageVector? = null
| 0 | Kotlin | 0 | 0 | 3414a20650d644afac2581ad87a8525971222678 | 2,531 | SolarIconSetAndroid | MIT License |
app/src/main/java/com/thekalya/instantnews/network/ApiClient.kt | kalyakiplangat | 270,838,573 | false | null | package com.thekalya.instantnews.network
import Urls
import com.bumptech.glide.BuildConfig
import com.google.gson.GsonBuilder
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
class ApiClient {
companion object {
fun getClient(): ApiService {
val interceptor = Interceptor { chain ->
val request = chain.request().newBuilder()
.addHeader("Accept", "application/json")
.header("X-Api-Key", "67c24956036d4d539197df1573243782")
.addHeader("Content-Type", "application/json")
.build()
chain.proceed(request)
}
val client = OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.addNetworkInterceptor(interceptor)
.addInterceptor(HttpLoggingInterceptor().apply {
level =
if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE
})
.build()
val gson = GsonBuilder()
.setLenient()
.setPrettyPrinting()
.create()
val retrofit = Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.client(client)
.baseUrl(Urls.baseUrl)
.build()
return retrofit.create(ApiService::class.java)
}
}
} | 0 | Kotlin | 0 | 0 | c1f1dc351f69a4e4beec124f312445e5edcd7086 | 1,891 | Instant-News | MIT License |
libraries/stdlib/test/numbers/NumbersTest.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package test.numbers
import test.isFloat32RangeEnforced
import kotlin.random.Random
import kotlin.test.*
object NumbersTestConstants {
public const val byteMinSucc: Byte = (Byte.MIN_VALUE + 1).toByte()
public const val byteMaxPred: Byte = (Byte.MAX_VALUE - 1).toByte()
public const val shortMinSucc: Short = (Short.MIN_VALUE + 1).toShort()
public const val shortMaxPred: Short = (Short.MAX_VALUE - 1).toShort()
public const val intMinSucc: Int = Int.MIN_VALUE + 1
public const val intMaxPred: Int = Int.MAX_VALUE - 1
public const val longMinSucc: Long = Long.MIN_VALUE + 1L
public const val longMaxPred: Long = Long.MAX_VALUE - 1L
public const val doubleMaxHalf: Double = Double.MAX_VALUE / 2
public const val doubleMinTwice: Double = Double.MIN_VALUE * 2
public const val floatMaxHalf: Float = Float.MAX_VALUE / 2
public const val floatMinTwice: Float = Float.MIN_VALUE * 2
}
class NumbersTest {
var one: Int = 1
var oneS: Short = 1
var oneB: Byte = 1
var two: Int = 2
@Test fun intMinMaxValues() {
assertTrue(Int.MIN_VALUE < 0)
assertTrue(Int.MAX_VALUE > 0)
assertEquals(NumbersTestConstants.intMinSucc, Int.MIN_VALUE + one)
assertEquals(NumbersTestConstants.intMaxPred, Int.MAX_VALUE - one)
// overflow behavior
expect(Int.MIN_VALUE) { Int.MAX_VALUE + one }
expect(Int.MAX_VALUE) { Int.MIN_VALUE - one }
expect(Int.MIN_VALUE) { Int.MIN_VALUE / -1 }
expect(0) { (Int.MIN_VALUE % -1) + 0 } // +0 is a workaround for KT-45620
}
@Test fun longMinMaxValues() {
assertTrue(Long.MIN_VALUE < 0)
assertTrue(Long.MAX_VALUE > 0)
assertEquals(NumbersTestConstants.longMinSucc, Long.MIN_VALUE + one)
assertEquals(NumbersTestConstants.longMaxPred, Long.MAX_VALUE - one)
// overflow behavior
expect(Long.MIN_VALUE) { Long.MAX_VALUE + one }
expect(Long.MAX_VALUE) { Long.MIN_VALUE - one }
expect(Long.MIN_VALUE) { Long.MIN_VALUE / -1L }
expect(0L) { Long.MIN_VALUE % -1L }
}
@Test fun shortMinMaxValues() {
assertTrue(Short.MIN_VALUE < 0)
assertTrue(Short.MAX_VALUE > 0)
assertEquals(NumbersTestConstants.shortMinSucc, Short.MIN_VALUE.inc())
assertEquals(NumbersTestConstants.shortMaxPred, Short.MAX_VALUE.dec())
// overflow behavior
expect(Short.MIN_VALUE) { (Short.MAX_VALUE + oneS).toShort() }
expect(Short.MAX_VALUE) { (Short.MIN_VALUE - oneS).toShort() }
expect(Short.MAX_VALUE + oneS) { Short.MIN_VALUE / (-1).toShort() }
expect(0) { (Short.MIN_VALUE % (-1).toShort()) + 0 } // +0 is a workaround for KT-45620
}
@Test fun byteMinMaxValues() {
assertTrue(Byte.MIN_VALUE < 0)
assertTrue(Byte.MAX_VALUE > 0)
assertEquals(NumbersTestConstants.byteMinSucc, Byte.MIN_VALUE.inc())
assertEquals(NumbersTestConstants.byteMaxPred, Byte.MAX_VALUE.dec())
// overflow behavior
expect(Byte.MIN_VALUE) { (Byte.MAX_VALUE + oneB).toByte() }
expect(Byte.MAX_VALUE) { (Byte.MIN_VALUE - oneB).toByte() }
expect(Byte.MAX_VALUE + oneB) { Byte.MIN_VALUE / (-1).toByte() }
expect(0) { (Byte.MIN_VALUE % (-1).toByte()) + 0 } // +0 is a workaround for KT-45620
}
@Test fun doubleMinMaxValues() {
assertTrue(Double.MIN_VALUE > 0)
assertTrue(Double.MAX_VALUE > 0)
assertEquals(NumbersTestConstants.doubleMaxHalf, Double.MAX_VALUE / two)
assertEquals(NumbersTestConstants.doubleMinTwice, Double.MIN_VALUE * two)
// overflow behavior
expect(Double.POSITIVE_INFINITY) { Double.MAX_VALUE * 2 }
expect(Double.NEGATIVE_INFINITY) {-Double.MAX_VALUE * 2 }
expect(0.0) { Double.MIN_VALUE / 2 }
}
@Test fun floatMinMaxValues() {
assertTrue(Float.MIN_VALUE > 0)
assertTrue(Float.MAX_VALUE > 0)
if (isFloat32RangeEnforced) {
assertEquals(NumbersTestConstants.floatMaxHalf, Float.MAX_VALUE / two)
assertEquals(NumbersTestConstants.floatMinTwice, Float.MIN_VALUE * two)
} else {
assertAlmostEquals(NumbersTestConstants.floatMaxHalf, Float.MAX_VALUE / two, 0.0000001 * NumbersTestConstants.floatMaxHalf)
assertAlmostEquals(NumbersTestConstants.floatMinTwice, Float.MIN_VALUE * two, 0.0000001 * NumbersTestConstants.floatMinTwice)
}
// overflow behavior
if (isFloat32RangeEnforced) {
expect(Float.POSITIVE_INFINITY) { Float.MAX_VALUE * 2 }
expect(Float.NEGATIVE_INFINITY) { -Float.MAX_VALUE * 2 }
expect(0.0F) { Float.MIN_VALUE / 2.0F }
}
}
@Test fun charMinMaxValues() {
assertTrue(Char.MIN_VALUE.code == 0)
assertTrue(Char.MAX_VALUE.code > 0)
// overflow behavior
expect(Char.MIN_VALUE) { Char.MAX_VALUE + one }
expect(Char.MAX_VALUE) { Char.MIN_VALUE - one }
}
@Test fun doubleProperties() {
for (value in listOf(1.0, 0.0, Double.MIN_VALUE, Double.MAX_VALUE))
doTestNumber(value)
for (value in listOf(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY))
doTestNumber(value, isInfinite = true)
doTestNumber(Double.NaN, isNaN = true)
}
@Test fun floatProperties() {
for (value in listOf(1.0F, 0.0F, Float.MAX_VALUE, Float.MIN_VALUE))
doTestNumber(value)
for (value in listOf(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY))
doTestNumber(value, isInfinite = true)
doTestNumber(Float.NaN, isNaN = true)
}
@Test fun floatFitsInFloatArray() {
val values = listOf(1.0F, 0.0F, Float.MAX_VALUE, Float.MIN_VALUE, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, Float.NaN)
val valuesArray = values.toFloatArray()
for (index in values.indices) {
val value = values[index]
val tolerance = if (value == Float.MIN_VALUE) 0.001 * value else 0.0000001 * value
assertAlmostEquals(value, valuesArray[index], tolerance)
}
}
private fun doTestNumber(value: Double, isNaN: Boolean = false, isInfinite: Boolean = false) {
assertEquals(isNaN, value.isNaN(), "Expected $value to have isNaN: $isNaN")
assertEquals(isInfinite, value.isInfinite(), "Expected $value to have isInfinite: $isInfinite")
assertEquals(!isNaN && !isInfinite, value.isFinite())
}
private fun doTestNumber(value: Float, isNaN: Boolean = false, isInfinite: Boolean = false) {
assertEquals(isNaN, value.isNaN(), "Expected $value to have isNaN: $isNaN")
assertEquals(isInfinite, value.isInfinite(), "Expected $value to have isInfinite: $isInfinite")
assertEquals(!isNaN && !isInfinite, value.isFinite())
}
@Test fun doubleToBits() {
assertEquals(0x400921fb54442d18L, kotlin.math.PI.toBits())
assertEquals(0x400921fb54442d18L, kotlin.math.PI.toRawBits())
assertEquals(kotlin.math.PI, Double.fromBits(0x400921fb54442d18L))
for (value in listOf(Double.NEGATIVE_INFINITY, -Double.MAX_VALUE, -1.0, -Double.MIN_VALUE, -0.0, 0.0, Double.POSITIVE_INFINITY, Double.MAX_VALUE, 1.0, Double.MIN_VALUE)) {
assertEquals(value, Double.fromBits(value.toBits()))
assertEquals(value, Double.fromBits(value.toRawBits()))
}
assertTrue(Double.NaN.toBits().let(Double.Companion::fromBits).isNaN())
assertTrue(Double.NaN.toRawBits().let { Double.fromBits(it) }.isNaN())
assertEquals(0x7FF00000L shl 32, Double.POSITIVE_INFINITY.toBits())
assertEquals(0xFFF00000L shl 32, Double.NEGATIVE_INFINITY.toBits())
assertEquals(0x7FF80000_00000000L, Double.NaN.toBits())
assertEquals(0x7FF80000_00000000L, Double.NaN.toRawBits())
val bitsNaN = Double.NaN.toBits()
for (bitsDenormNaN in listOf(0xFFF80000L shl 32, bitsNaN or 1)) {
assertTrue(Double.fromBits(bitsDenormNaN).isNaN(), "expected $bitsDenormNaN represent NaN")
assertEquals(bitsNaN, Double.fromBits(bitsDenormNaN).toBits())
}
}
@Test fun floatToBits() {
val PI_F = kotlin.math.PI.toFloat()
assertEquals(0x40490fdb, PI_F.toBits())
if (isFloat32RangeEnforced) {
assertEquals(PI_F, Float.fromBits(0x40490fdb))
} else {
assertAlmostEquals(PI_F, Float.fromBits(0x40490fdb)) // PI_F is actually Double in JS
}
for (value in listOf(Float.NEGATIVE_INFINITY, -1.0F, -0.0F, 0.0F, Float.POSITIVE_INFINITY, 1.0F)) {
assertEquals(value, Float.fromBits(value.toBits()))
assertEquals(value, Float.fromBits(value.toRawBits()))
}
for (value in listOf(-Float.MAX_VALUE, Float.MAX_VALUE, -Float.MIN_VALUE, Float.MIN_VALUE)) {
if (isFloat32RangeEnforced) {
assertEquals(value, Float.fromBits(value.toBits()))
assertEquals(value, Float.fromBits(value.toRawBits()))
} else {
val tolerance = if (kotlin.math.abs(value) == Float.MIN_VALUE) 0.001 * value else 0.0000001 * value
assertAlmostEquals(value, Float.fromBits(value.toBits()), tolerance)
assertAlmostEquals(value, Float.fromBits(value.toRawBits()), tolerance)
}
}
assertTrue(Float.NaN.toBits().let(Float.Companion::fromBits).isNaN())
assertTrue(Float.NaN.toRawBits().let { Float.fromBits(it) }.isNaN())
assertEquals(0xbf800000.toInt(), (-1.0F).toBits())
assertEquals(0x7fc00000, Float.NaN.toBits())
assertEquals(0x7fc00000, Float.NaN.toRawBits())
val bitsNaN = Float.NaN.toBits()
for (bitsDenormNaN in listOf(0xFFFC0000.toInt(), bitsNaN or 1)) {
assertTrue(Float.fromBits(bitsDenormNaN).isNaN(), "expected $bitsDenormNaN represent NaN")
assertEquals(bitsNaN, Float.fromBits(bitsDenormNaN).toBits())
}
}
@Test fun sizeInBitsAndBytes() {
fun testSizes(companion: Any, sizeBytes: Int, sizeBits: Int, expectedSizeBytes: Int) {
assertEquals(expectedSizeBytes, sizeBytes, companion.toString())
assertEquals(expectedSizeBytes * 8, sizeBits, companion.toString())
}
testSizes(Char, Char.SIZE_BYTES, Char.SIZE_BITS, 2)
testSizes(Byte, Byte.SIZE_BYTES, Byte.SIZE_BITS, 1)
testSizes(Short, Short.SIZE_BYTES, Short.SIZE_BITS, 2)
testSizes(Int, Int.SIZE_BYTES, Int.SIZE_BITS, 4)
testSizes(Long, Long.SIZE_BYTES, Long.SIZE_BITS, 8)
testSizes(Float, Float.SIZE_BYTES, Float.SIZE_BITS, 4)
testSizes(Double, Double.SIZE_BYTES, Double.SIZE_BITS, 8)
testSizes(UByte, UByte.SIZE_BYTES, UByte.SIZE_BITS, 1)
testSizes(UShort, UShort.SIZE_BYTES, UShort.SIZE_BITS, 2)
testSizes(UInt, UInt.SIZE_BYTES, UInt.SIZE_BITS, 4)
testSizes(ULong, ULong.SIZE_BYTES, ULong.SIZE_BITS, 8)
}
@Test
fun byteBits() {
fun test(value: Byte, oneBits: Int, leadingZeroes: Int, trailingZeroes: Int) {
assertEquals(oneBits, value.countOneBits())
assertEquals(leadingZeroes, value.countLeadingZeroBits())
assertEquals(trailingZeroes, value.countTrailingZeroBits())
val highestBit = if (leadingZeroes < Byte.SIZE_BITS) 1.shl(Byte.SIZE_BITS - leadingZeroes - 1).toByte() else 0
val lowestBit = if (trailingZeroes < Byte.SIZE_BITS) 1.shl(trailingZeroes).toByte() else 0
assertEquals(highestBit, value.takeHighestOneBit())
assertEquals(lowestBit, value.takeLowestOneBit())
}
test(0, 0, 8, 8)
test(1, 1, 7, 0)
test(2, 1, 6, 1)
test(0x44, 2, 1, 2)
test(0x80.toByte(), 1, 0, 7)
test(0xF0.toByte(), 4, 0, 4)
}
@Test
fun shortBits() {
fun test(value: Short, oneBits: Int, leadingZeroes: Int, trailingZeroes: Int) {
assertEquals(oneBits, value.countOneBits())
assertEquals(leadingZeroes, value.countLeadingZeroBits())
assertEquals(trailingZeroes, value.countTrailingZeroBits())
val highestBit = if (leadingZeroes < Short.SIZE_BITS) 1.shl(Short.SIZE_BITS - leadingZeroes - 1).toShort() else 0
val lowestBit = if (trailingZeroes < Short.SIZE_BITS) 1.shl(trailingZeroes).toShort() else 0
assertEquals(highestBit, value.takeHighestOneBit())
assertEquals(lowestBit, value.takeLowestOneBit())
}
test(0, 0, 16, 16)
test(1, 1, 15, 0)
test(2, 1, 14, 1)
test(0xF2, 5, 8, 1)
test(0x8000.toShort(), 1, 0, 15)
test(0xF200.toShort(), 5, 0, 9)
}
@Test
fun intBits() {
fun test(value: Int, oneBits: Int, leadingZeroes: Int, trailingZeroes: Int) {
assertEquals(oneBits, value.countOneBits())
assertEquals(leadingZeroes, value.countLeadingZeroBits())
assertEquals(trailingZeroes, value.countTrailingZeroBits())
val highestBit = if (leadingZeroes < Int.SIZE_BITS) 1.shl(Int.SIZE_BITS - leadingZeroes - 1) else 0
val lowestBit = if (trailingZeroes < Int.SIZE_BITS) 1.shl(trailingZeroes) else 0
assertEquals(highestBit, value.takeHighestOneBit())
assertEquals(lowestBit, value.takeLowestOneBit())
}
test(0, 0, 32, 32)
test(1, 1, 31, 0)
test(2, 1, 30, 1)
test(0xF002, 5, 16, 1)
test(0xF00F0000.toInt(), 8, 0, 16)
}
@Test
fun longBits() {
fun test(value: Long, oneBits: Int, leadingZeroes: Int, trailingZeroes: Int) {
assertEquals(oneBits, value.countOneBits())
assertEquals(leadingZeroes, value.countLeadingZeroBits())
assertEquals(trailingZeroes, value.countTrailingZeroBits())
val highestBit = if (leadingZeroes < Long.SIZE_BITS) 1L.shl(Long.SIZE_BITS - leadingZeroes - 1).toLong() else 0
val lowestBit = if (trailingZeroes < Long.SIZE_BITS) 1L.shl(trailingZeroes).toLong() else 0
assertEquals(highestBit, value.takeHighestOneBit())
assertEquals(lowestBit, value.takeLowestOneBit())
}
test(0, 0, 64, 64)
test(1, 1, 63, 0)
test(2, 1, 62, 1)
test(0xF002, 5, 48, 1)
test(0xF00F0000L, 8, 32, 16)
test(0x1111_3333_EEEE_0000L, 4 + 8 + 12, 3, 17)
}
@Test
fun intRotate() {
fun test(value: Int, n: Int, expected: Int) {
assertEquals(expected, value.rotateLeft(n))
assertEquals(expected, value.rotateRight(-n))
}
fun testCyclic(value: Int) {
for (n in -2 * Int.SIZE_BITS..2 * Int.SIZE_BITS) {
val rl = value.rotateLeft(n)
val rr = value.rotateRight(-n)
assertEquals(rl, rr)
assertEquals(rl, value.rotateLeft(n % Int.SIZE_BITS))
assertEquals(rr, value.rotateRight((-n) % Int.SIZE_BITS))
assertEquals(value, value.rotateLeft(n).rotateLeft(-n))
assertEquals(value, value.rotateRight(n).rotateRight(-n))
}
}
test(0x7_3422345, 4, 0x3422345_7)
test(0x7342234_5, -4, 0x5_7342234)
test(0x73422345, 1, 0xE684468A.toInt())
repeat(100) {
testCyclic(Random.nextInt())
}
}
@Test
fun byteRotate() {
fun test(value: Byte, n: Int, expected: Byte) {
assertEquals(expected, value.rotateLeft(n))
assertEquals(expected, value.rotateRight(-n))
}
fun testCyclic(value: Byte) {
for (n in -2 * Byte.SIZE_BITS..2 * Byte.SIZE_BITS) {
val rl = value.rotateLeft(n)
val rr = value.rotateRight(-n)
assertEquals(rl, rr)
assertEquals(rl, value.rotateLeft(n % Byte.SIZE_BITS))
assertEquals(rr, value.rotateRight((-n) % Byte.SIZE_BITS))
assertEquals(value, value.rotateLeft(n).rotateLeft(-n))
assertEquals(value, value.rotateRight(n).rotateRight(-n))
}
}
test(0x73, 4, 0x37)
test(0x73, -3, 0x6E)
test(0x73, 1, 0xE6.toByte())
test(0xE6.toByte(), 1, 0xCD.toByte())
repeat(100) {
testCyclic(Random.nextInt().toByte())
}
}
@Test
fun longRotate() {
fun test(value: Long, n: Int, expected: Long) {
assertEquals(expected, value.rotateLeft(n))
assertEquals(expected, value.rotateRight(-n))
}
fun testCyclic(value: Long) {
for (n in -2 * Long.SIZE_BITS..2 * Long.SIZE_BITS) {
val rl = value.rotateLeft(n)
val rr = value.rotateRight(-n)
assertEquals(rl, rr)
assertEquals(rl, value.rotateLeft(n % Long.SIZE_BITS))
assertEquals(rr, value.rotateRight((-n) % Long.SIZE_BITS))
assertEquals(value, value.rotateLeft(n).rotateLeft(-n))
assertEquals(value, value.rotateRight(n).rotateRight(-n))
}
}
test(0x7372ABAC_DEEF0123, 4, 0x372ABAC_DEEF01237)
test(0x88888888_44444444U.toLong(), -3, 0x91111111_08888888u.toLong())
test(0x88888888_44444444U.toLong(), 1, 0x11111110_88888889)
repeat(100) {
testCyclic(Random.nextLong())
}
}
@Test
fun shortRotate() {
fun test(value: Short, n: Int, expected: Short) {
assertEquals(expected, value.rotateLeft(n))
assertEquals(expected, value.rotateRight(-n))
}
fun testCyclic(value: Short) {
for (n in -2 * Short.SIZE_BITS..2 * Short.SIZE_BITS) {
val rl = value.rotateLeft(n)
val rr = value.rotateRight(-n)
assertEquals(rl, rr)
assertEquals(rl, value.rotateLeft(n % Short.SIZE_BITS))
assertEquals(rr, value.rotateRight((-n) % Short.SIZE_BITS))
assertEquals(value, value.rotateLeft(n).rotateLeft(-n))
assertEquals(value, value.rotateRight(n).rotateRight(-n))
}
}
test(0x7361, 4, 0x3617)
test(0x7361, -3, 0b001_0111_0011_0110_0)
test(0x7361, 1, 0b111_0011_0110_0001_0.toShort())
test(0xE6C2.toShort(), 1, 0b11_0011_0110_0001_01.toShort())
repeat(100) {
testCyclic(Random.nextInt().toShort())
}
}
} | 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 18,770 | kotlin | Apache License 2.0 |
kaptain/src/main/java/cafe/adriel/kaptain/KaptainException.kt | adrielcafe | 250,125,515 | false | {"Kotlin": 8322} | package cafe.adriel.kaptain
import java.lang.RuntimeException
class KaptainException(message: String) : RuntimeException(message) | 0 | Kotlin | 3 | 27 | f03d8527d624f5c54add941c1247583317bb3b2e | 131 | kaptain | MIT License |
app/src/main/java/com/android/core/arch/utils/app/CommonUtils.kt | sameerb-webonise | 205,486,810 | false | {"Gradle": 3, "INI": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Java Properties": 1, "Proguard": 1, "Java": 4, "XML": 14, "Kotlin": 45} | package com.android.core.arch.utils.app
import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.content.Context
import android.content.res.AssetManager
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.provider.Settings
import android.telephony.TelephonyManager
import java.io.IOException
import java.io.InputStream
import java.nio.charset.Charset
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.regex.Matcher
import java.util.regex.Pattern
/**
* Common Utils Class
* @author <NAME>
* @since 2019-02-14
*/
object CommonUtils {
val timeStamp: String
get() = SimpleDateFormat(AppConstants.TIMESTAMP_FORMAT, Locale.US).format(Date())
fun showLoadingDialog(context: Context): ProgressDialog {
val progressDialog = ProgressDialog(context)
progressDialog.show()
if (progressDialog.window != null) {
progressDialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
}
//progressDialog.setContentView(R.layout.progress_dialog);
progressDialog.isIndeterminate = true
progressDialog.setCancelable(false)
progressDialog.setCanceledOnTouchOutside(false)
return progressDialog
}
/**
* get unique device id from phone.
* @return
*/
@SuppressLint("MissingPermission")
fun getUniqueDeviceID(context: Context): String {
val deviceId: String
val mTelephony = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
if (mTelephony != null && mTelephony.deviceId != null) {
deviceId = mTelephony.deviceId
} else {
deviceId = Settings.Secure.getString(
context.contentResolver,
Settings.Secure.ANDROID_ID)
}
return deviceId
}
@SuppressLint("all")
fun getDeviceId(context: Context): String {
return Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
}
fun isEmailValid(email: String): Boolean {
val pattern: Pattern
val matcher: Matcher
val EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"
pattern = Pattern.compile(EMAIL_PATTERN)
matcher = pattern.matcher(email)
return matcher.matches()
}
@Throws(IOException::class)
fun loadJSONFromAsset(context: Context, jsonFileName: String): String {
val manager = context.assets
val `is` = manager.open(jsonFileName)
val size = `is`.available()
val buffer = ByteArray(size)
`is`.read(buffer)
`is`.close()
return String(buffer, Charsets.UTF_8)
//return Charset.forName("UTF-8").toString()
}
}// This utility class is not publicly instantiable
| 0 | Kotlin | 0 | 0 | 988504bfef846a7b7cc4fcdfa3fcd5f6a96b0faf | 2,924 | new_android_app_architecture_kotlin | Apache License 2.0 |
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/DocumentGeneratorInformation.kt | Danilo-Araujo-Silva | 271,904,885 | false | null | package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: DocumentGeneratorInformation
*
* Full name: System`DocumentGeneratorInformation
*
* DocumentGeneratorInformation[CloudObject] returns information about a generator.
* Usage: DocumentGeneratorInformation[CloudObject, property] returns the value of the specified property.
*
* Options: None
*
* Protected
* Attributes: ReadProtected
*
* local: paclet:ref/DocumentGeneratorInformation
* Documentation: web: http://reference.wolfram.com/language/ref/DocumentGeneratorInformation.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun documentGeneratorInformation(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("DocumentGeneratorInformation", arguments.toMutableList(), options)
}
| 2 | Kotlin | 0 | 3 | 4fcf68af14f55b8634132d34f61dae8bb2ee2942 | 1,224 | mathemagika | Apache License 2.0 |
features/times/src/main/java/com/metinkale/prayer/times/utils/ExportController.kt | metinkale38 | 48,848,634 | false | {"Kotlin": 616528, "HTML": 242192, "Java": 233206, "Shell": 1622, "CSS": 382} | /*
* Copyright (c) 2013-2023 Metin Kale
*
* 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.metinkale.prayer.times.utils
import android.app.DatePickerDialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.Drawable
import android.graphics.pdf.PdfDocument
import android.graphics.pdf.PdfDocument.*
import android.net.Uri
import android.widget.DatePicker
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import com.metinkale.prayer.CrashReporter
import com.metinkale.prayer.date.HijriDate
import com.metinkale.prayer.date.HijriDay
import com.metinkale.prayer.times.R
import com.metinkale.prayer.times.drawableId
import com.metinkale.prayer.times.times.DayTimesWebProvider
import com.metinkale.prayer.times.times.Times
import com.metinkale.prayer.times.times.Vakit
import com.metinkale.prayer.times.times.getDayTimes
import com.metinkale.prayer.times.times.getTime
import com.metinkale.prayer.utils.LocaleUtils
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
private fun LocalDate.toString(pattern: String) = format(DateTimeFormatter.ofPattern(pattern))
private fun LocalTime.toString(pattern: String) = format(DateTimeFormatter.ofPattern(pattern))
object ExportController {
@Throws(IOException::class)
fun exportPDF(ctx: Context, times: Times, from: LocalDate, to: LocalDate) {
var date = from
val document = PdfDocument()
val pageInfo: PageInfo
val pw = 595
val ph = 842
pageInfo = PageInfo.Builder(pw, ph, 1).create()
val page: Page = document.startPage(pageInfo)
val canvas: Canvas = page.canvas
val paint = Paint()
paint.setARGB(255, 0, 0, 0)
paint.textSize = 10f
paint.textAlign = Paint.Align.CENTER
canvas.translate(0.0f, -15.0f)
Drawable.createFromStream(ctx.assets.open("pdf/launcher.png"), null)?.let { launcher ->
launcher.setBounds(30, 30, 30 + 65, 30 + 65)
launcher.draw(canvas)
}
Drawable.createFromStream(ctx.assets.open("pdf/qrcode.png"), null)?.let { qr ->
qr.setBounds(pw - 30 - 65, 40 + 65 + 5, pw - 30, 40 + 65 + 5 + 65)
qr.draw(canvas)
}
Drawable.createFromStream(
ctx.assets.open(
"pdf/badge_" + LocaleUtils.getLanguage("en", "de", "tr", "fr", "ar") + ".png"
), null
)?.let { badge ->
val w = 100
val h: Int = w * badge.intrinsicHeight / badge.intrinsicWidth
badge.setBounds(pw - 30 - w, 30 + (60 / 2 - h / 2), pw - 30, 30 + (60 / 2 - h / 2) + h)
badge.draw(canvas)
canvas.drawText(
"com.metinkale.prayer", pw - 30 - w / 2f, 30 + (60 / 2f - h / 2f) + h + 10, paint
)
}
paint.setARGB(255, 61, 184, 230)
canvas.drawRect(
0f, (30 + 60).toFloat(), pw.toFloat(), (30 + 60 + 5).toFloat(), paint
)
times.source.drawableId?.let {
ContextCompat.getDrawable(ctx, it)?.let { source ->
val h = 65
val w = h * source.intrinsicWidth / source.intrinsicHeight
source.setBounds(30, 40 + 65 + 5, 30 + w, 40 + 65 + 5 + h)
source.draw(canvas)
}
}
paint.setARGB(255, 0, 0, 0)
paint.textSize = 30f
paint.textAlign = Paint.Align.LEFT
canvas.drawText(
ctx.getText(R.string.appName).toString(),
(30 + 65 + 5).toFloat(),
(30 + 50).toFloat(),
paint
)
val p = 30
paint.textSize = 40f
paint.textAlign = Paint.Align.CENTER
paint.isFakeBoldText = true
canvas.drawText(times.name, pw / 2.0f, (40 + 65 + 50).toFloat(), paint)
paint.textSize = 12f
var y = 40 + 65 + 5 + 65 + 30
paint.isFakeBoldText = false
val dateWidth = paint.measureText("00.00.0000")
val timeWidth = paint.measureText("00:00")
val width = pw - p - p
val alignWidth = width - dateWidth - timeWidth
val xPos: List<Pair<Paint.Align, Float>> =
listOf(Paint.Align.LEFT to 0f) +
(1..5).map {
Paint.Align.CENTER to (dateWidth - timeWidth / 2) + it.toFloat() * ((alignWidth + timeWidth) / 6)
} +
listOf(Paint.Align.RIGHT to width.toFloat())
paint.isFakeBoldText = true
paint.setARGB(255, 61, 184, 230)
canvas.drawRect(0f, -15f + y.toFloat(), pw.toFloat(), -15f + y + 20f, paint)
paint.color = Color.WHITE
xPos.forEachIndexed { index, (align, x) ->
paint.textAlign = align
val text = when (index) {
0 -> ctx.getString(R.string.date)
1 -> Vakit.FAJR.string
2 -> Vakit.SUN.string
3 -> Vakit.DHUHR.string
4 -> Vakit.ASR.string
5 -> Vakit.MAGHRIB.string
6 -> Vakit.ISHAA.string
else -> ""
}
canvas.drawText(text, p + x, y.toFloat(), paint)
}
paint.isFakeBoldText = false
var i = 0
do {
y += 20
if (++i % 2 == 0) {
paint.setARGB(100, 61, 184, 230)
canvas.drawRect(0f, -15f + y.toFloat(), pw.toFloat(), -15f + y + 20f, paint)
}
paint.color = Color.BLACK
xPos.forEachIndexed { index, (align, x) ->
paint.textAlign = align
val text = when (index) {
0 -> date.toString("dd.MM.yyyy")
1 -> times.getTime(date, Vakit.FAJR.ordinal).toLocalTime().toString("HH:mm")
2 -> times.getTime(date, Vakit.SUN.ordinal).toLocalTime().toString("HH:mm")
3 -> times.getTime(date, Vakit.DHUHR.ordinal).toLocalTime().toString("HH:mm")
4 -> times.getTime(date, Vakit.ASR.ordinal).toLocalTime().toString("HH:mm")
5 -> times.getTime(date, Vakit.MAGHRIB.ordinal).toLocalTime().toString("HH:mm")
6 -> times.getTime(date, Vakit.ISHAA.ordinal).toLocalTime().toString("HH:mm")
else -> ""
}
canvas.drawText(text, p + x, y.toFloat(), paint)
}
} while (!date.plusDays(1).also { date = it }.isAfter(to))
document.finishPage(page)
val outputDir = ctx.cacheDir
if (!outputDir.exists()) outputDir.mkdirs()
val outputFile = File(outputDir, times.name.replace(" ", "_") + ".pdf")
if (outputFile.exists()) outputFile.delete()
val outputStream = FileOutputStream(outputFile)
document.writeTo(outputStream)
document.close()
val shareIntent = Intent()
shareIntent.action = Intent.ACTION_SEND
shareIntent.type = "application/pdf"
val uri: Uri = FileProvider.getUriForFile(
ctx, ctx.getString(R.string.FILE_PROVIDER_AUTHORITIES), outputFile
)
shareIntent.putExtra(Intent.EXTRA_STREAM, uri)
ctx.startActivity(Intent.createChooser(shareIntent, ctx.resources.getText(R.string.export)))
}
@Throws(IOException::class)
fun exportCSV(ctx: Context, times: Times, from: LocalDate, to: LocalDate) {
var date = from
val outputDir = ctx.cacheDir
if (!outputDir.exists()) outputDir.mkdirs()
val outputFile = File(outputDir, times.name.replace(" ", "_") + ".csv")
if (outputFile.exists()) outputFile.delete()
val outputStream = FileOutputStream(outputFile)
outputStream.write("HijriDate;Fajr;Shuruq;Dhuhr;Asr;Maghrib;Ishaa\n".toByteArray())
do {
outputStream.write((date.toString("yyyy-MM-dd") + ";").toByteArray())
outputStream.write(
(times.getTime(date, Vakit.FAJR.ordinal).toLocalTime()
.toString("HH:mm") + ";").toByteArray()
)
outputStream.write(
(times.getTime(date, Vakit.SUN.ordinal).toLocalTime()
.toString("HH:mm") + ";").toByteArray()
)
outputStream.write(
(times.getTime(date, Vakit.DHUHR.ordinal).toLocalTime()
.toString("HH:mm") + ";").toByteArray()
)
outputStream.write(
(times.getTime(date, Vakit.ASR.ordinal).toLocalTime()
.toString("HH:mm") + ";").toByteArray()
)
outputStream.write(
(times.getTime(date, Vakit.MAGHRIB.ordinal).toLocalTime()
.toString("HH:mm") + ";").toByteArray()
)
outputStream.write(
"""${times.getTime(date, Vakit.ISHAA.ordinal).toLocalTime().toString("HH:mm")}
""".toByteArray()
)
} while (!date.plusDays(1).also { date = it }.isAfter(to))
outputStream.close()
val shareIntent = Intent()
shareIntent.action = Intent.ACTION_SEND
shareIntent.type = "name/csv"
val uri: Uri = FileProvider.getUriForFile(
ctx, ctx.getString(R.string.FILE_PROVIDER_AUTHORITIES), outputFile
)
shareIntent.putExtra(Intent.EXTRA_STREAM, uri)
ctx.startActivity(Intent.createChooser(shareIntent, ctx.resources.getText(R.string.export)))
}
fun exportICS(ctx: Context, times: Times, from: LocalDate, to: LocalDate) {
val prodId = "prayer-times-android/${ctx.packageName}"
val now = LocalDateTime.now()
val output = StringBuilder().apply {
appendLine("BEGIN:VCALENDAR")
appendLine("VERSION:2.0")
appendLine("PRODID:-//$prodId")
appendLine("METHOD:PUBLISH")
var date = from
do {
times.getDayTimes(date)?.let { daytimes ->
Vakit.values().forEach { v ->
appendLine("BEGIN:VEVENT")
appendLine("TRANSP:TRANSPARENT")
appendLine("SUMMARY:" + v.string)
appendLine(
"DTSTAMP:${
now.withSecond(0).withNano(0).toString().replace("-", "").replace(":", "") + "00"
}"
)
appendLine(
"DTSTART:${
daytimes.by(v).atDate(date).withSecond(0).withNano(0).toString().replace("-", "")
.replace(":", "") + "00"
}"
)
appendLine(
"DTEND:${
daytimes.by(v).atDate(date).withSecond(0).withNano(0).toString()
.replace("-", "").replace(":", "") + "00"
}"
)
appendLine("UID:${date.hashCode() + v.hashCode()}@${ctx.packageName}")
appendLine(
"DESCRIPTION:" + LocaleUtils.formatDate(
HijriDate.fromLocalDate(
date
)
)
)
appendLine("LOCATION:" + times.name)
appendLine("URL;VALUE=URI:https://play.google.com/store/apps/details?id=com.metinkale.prayer")
appendLine("BEGIN:VALARM")
appendLine("TRIGGER:PT0S")
appendLine("DESCRIPTION:")
appendLine("ACTION:DISPLAY")
appendLine("END:VALARM")
appendLine("END:VEVENT")
}
}
date = date.plusDays(1)
} while (date <= to)
appendLine("END:VCALENDAR")
}.toString()
val outputDir = ctx.cacheDir
if (!outputDir.exists()) outputDir.mkdirs()
val outputFile = File(outputDir, "times.ics")
if (outputFile.exists()) outputFile.delete()
FileOutputStream(outputFile).bufferedWriter().use { it.write(output) }
val intent = Intent()
intent.action = Intent.ACTION_VIEW
val uri: Uri = FileProvider.getUriForFile(
ctx,
ctx.getString(com.metinkale.prayer.base.R.string.FILE_PROVIDER_AUTHORITIES),
outputFile
)
intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION;
intent.setDataAndType(uri, "text/calendar")
ctx.startActivity(intent)
}
fun export(ctx: Context, times: Times) {
val builder = AlertDialog.Builder(ctx)
builder.setTitle(R.string.export).setItems(
arrayOf<CharSequence>("CSV", "PDF", "ICS")
) { _: DialogInterface?, which: Int ->
var minDate: Long = 0
var maxDate = Long.MAX_VALUE
(times.dayTimes as? DayTimesWebProvider)?.let {
minDate = it.firstSyncedDay?.atStartOfDay(ZoneId.systemDefault())?.toInstant()
?.toEpochMilli() ?: 0
maxDate = it.lastSyncedDay?.atStartOfDay(ZoneId.systemDefault())?.toInstant()
?.toEpochMilli() ?: 0
}
val ld = LocalDate.now()
val finalMaxDate = maxDate
val dlg = DatePickerDialog(
ctx, { _: DatePicker?, y: Int, m: Int, d: Int ->
val from = LocalDate.of(y, m + 1, d)
val dlg1 = DatePickerDialog(
ctx, { _: DatePicker?, y1: Int, m1: Int, d1: Int ->
val to = LocalDate.of(y1, m1 + 1, d1)
try {
if (which == 0) {
exportCSV(ctx, times, from, to)
} else if (which == 1) {
exportPDF(ctx, times, from, to)
} else {
exportICS(ctx, times, from, to)
}
} catch (e: IOException) {
e.printStackTrace()
CrashReporter.recordException(e)
Toast.makeText(ctx, R.string.error, Toast.LENGTH_SHORT).show()
}
}, ld.year, ld.monthValue - 1, ld.dayOfMonth
)
val startDate = LocalDate.of(y, m + 1, d).atTime(LocalTime.now())
val start = startDate.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
if (which == 1) dlg1.datePicker.maxDate = Math.min(
finalMaxDate,
startDate.plusDays(31).atZone(ZoneId.systemDefault()).toInstant()
.toEpochMilli()
) else dlg1.datePicker.maxDate = finalMaxDate
dlg1.datePicker.minDate = Math.min(
start, dlg1.datePicker.maxDate - 1000 * 60 * 60 * 24
)
dlg1.setTitle(R.string.to)
dlg1.show()
}, ld.year, ld.monthValue - 1, ld.dayOfMonth
)
dlg.datePicker.minDate = minDate
dlg.datePicker.maxDate = maxDate.coerceAtLeast(minDate)
dlg.setTitle(R.string.from)
dlg.show()
}
builder.show()
}
} | 24 | Kotlin | 108 | 232 | f16a719edab1d3d516accb42d6eee15743d78269 | 16,602 | prayer-times-android | Apache License 2.0 |
foundation-shared/src/main/kotlin/gay/pizza/foundation/shared/PluginPersistence.kt | GayPizzaSpecifications | 447,482,867 | false | null | package gay.pizza.foundation.shared
import java.util.concurrent.ConcurrentHashMap
class PluginPersistence(val core: IFoundationCore) {
val stores = ConcurrentHashMap<String, PersistentStore>()
/**
* Fetch a persistent store by name. Make sure the name is path-safe, descriptive and consistent across server runs.
*/
fun store(name: String): PersistentStore =
stores.getOrPut(name) { PersistentStore(core, name) }
fun unload() {
stores.values.forEach { store -> store.close() }
stores.clear()
}
}
| 1 | Kotlin | 0 | 0 | 4b1af52ef0190ee753c965bdf7af0031bb4ec744 | 528 | foundation | MIT License |
app/src/main/java/de/stefanmedack/ccctv/ui/main/home/uiModel/HomeUiModel.kt | stefanmedack | 96,631,852 | false | null | package de.stefanmedack.ccctv.ui.main.home.uiModel
import de.stefanmedack.ccctv.persistence.entities.Event
data class HomeUiModel(
val bookmarkedEvents: List<Event>,
val playedEvents: List<Event>,
val promotedEvents: List<Event>,
val trendingEvents: List<Event>,
val popularEvents: List<Event>,
val recentEvents: List<Event>
) | 4 | Kotlin | 9 | 34 | b96d15c64b66af5c9f4ca08a2df961b47f1df70d | 376 | cccTV | Apache License 2.0 |
experimental/corda-utils/src/main/kotlin/io/cryptoblk/core/StatusTransitions.kt | corda | 70,137,417 | false | null | package io.cryptoblk.core
import net.corda.core.contracts.CommandData
import net.corda.core.contracts.ContractState
import net.corda.core.identity.Party
import net.corda.core.transactions.LedgerTransaction
import kotlin.reflect.KClass
/**
* Contract state that records changes of some [status] on the ledger and roles of parties that are participants
* in that state using [roleToParty].
*/
interface StatusTrackingContractState<out S, in R> : ContractState {
val status: S
fun roleToParty(role: R): Party
}
/**
* Definition of finite state transition: for a particular command in a TX, it defines what transitions can be done
* [from] what status [to] what statuses, and who needs to sign them ([signer]).
* If [from] is null, it means there doesn't need to be any input; if [to] is null, it mean there doesn't need to be any output.
* If [signer] is null, it means anyone can sign it.
*/
data class TransitionDef<out S, out R>(val cmd: Class<*>, val signer: R?, val from: S?, val to: List<S?>)
/**
* Holds visualized PUML graph in [printedPUML] and the relevant state class name in [stateClassName].
*/
data class PrintedTransitionGraph(val stateClassName: String, val printedPUML: String)
/**
* Shorthand for defining transitions directly from the command class
*/
fun <S, R> CommandData.txDef(signer: R? = null, from: S?, to: List<S?>):
TransitionDef<S, R> = TransitionDef(this::class.java, signer, from, to)
/**
* For a given [stateClass] that tracks a status, it holds all possible transitions in [ts].
* This can be used for generic [verify] in contract code as well as for visualizing the state transition graph in PUML ([printGraph]).
*/
class StatusTransitions<out S, in R, T : StatusTrackingContractState<S, R>>(private val stateClass: KClass<T>,
private vararg val ts: TransitionDef<S, R>) {
private val allowedCmds = ts.map { it.cmd }.toSet()
private fun matchingTransitions(input: S?, output: S?, command: CommandData): List<TransitionDef<S, R>> {
val options = ts.filter {
(it.from == input) && (output in it.to) && (it.cmd == command.javaClass)
}
if (options.isEmpty()) throw IllegalStateException("Transition [$input -(${command.javaClass.simpleName})-> $output] not allowed")
return options
}
/**
* Generic verification based on provided [TransitionDef]s
*/
fun verify(tx: LedgerTransaction) {
val relevantCmds = tx.commands.filter { allowedCmds.contains(it.value.javaClass) }
require(relevantCmds.isNotEmpty()) { "Transaction must have at least one Command relevant to its defined transitions" }
relevantCmds.forEach { cmd ->
val ins = tx.inputsOfType(stateClass.java)
val inputStates = if (ins.isEmpty()) listOf(null) else ins
val outs = tx.outputsOfType(stateClass.java)
val outputStates = if (outs.isEmpty()) listOf(null) else outs
// for each combination of in x out which should normally be at most 1...
inputStates.forEach { inp ->
outputStates.forEach { outp ->
require(inp != null || outp != null)
val options = matchingTransitions(inp?.status, outp?.status, cmd.value)
val signerGroup = options.groupBy { it.signer }.entries.singleOrNull()
?: throw IllegalStateException("Cannot have different signers in StatusTransitions for the same command.")
val signer = signerGroup.key
if (signer != null) {
// which state determines who is the signer? by default the input, unless it's the initial transition
val state = (inp ?: outp)!!
val signerParty = state.roleToParty(signer)
if (!cmd.signers.contains(signerParty.owningKey))
throw IllegalStateException("Command ${cmd.value.javaClass} must be signed by $signer")
}
}
}
}
}
fun printGraph(): PrintedTransitionGraph {
val sb = StringBuilder()
sb.append("@startuml\n")
if (stateClass.simpleName != null) sb.append("title ${stateClass.simpleName}\n")
ts.forEach { txDef ->
val fromStatus = txDef.from?.toString() ?: "[*]"
txDef.to.forEach { to ->
val toStatus = (to ?: "[*]").toString()
val cmd = txDef.cmd.simpleName
val signer = txDef.signer?.toString() ?: "anyone involved"
sb.append("$fromStatus --> $toStatus : $cmd (by $signer)\n")
}
}
sb.append("@enduml")
return PrintedTransitionGraph(stateClass.simpleName ?: "", sb.toString())
}
} | 62 | null | 1077 | 3,989 | d27aa0e6850d3804d0982024054376d452e7073a | 4,814 | corda | Apache License 2.0 |
app/src/main/java/com/example/homepage/utils/models/GroupNoticeData.kt | piru72 | 516,901,454 | false | null | package com.example.homepage.groupNoticePage.groupNoticeModel
data class GroupNoticeData(
var uid: String? = "",
var taskname: String? = "",
var taskdescription: String? = "",
var taskdate: String? = "",
var path: String? = "",
var groupId: String? = ""
) {
fun toMap(): Map<String, Any?> {
return mapOf(
"uid" to uid,
"taskname" to taskname,
"taskdescription" to taskdescription,
"taskdate" to taskdate,
"path" to path,
"groupId" to groupId
)
}
} | 10 | null | 3 | 9 | 47f4ab162fdf79d203e3643dbe8527a52f9f62cd | 571 | AUST_BUDDY | MIT License |
multiplatform-locale/src/commonTest/kotlin/com/vanniktech/locale/LanguagesTest.kt | vanniktech | 562,822,028 | false | null | package com.vanniktech.locale
import kotlin.test.Test
import kotlin.test.assertEquals
class LanguagesTest {
@Test fun currentLanguageCode() {
assertEquals(expected = "en", actual = Languages.currentLanguageCode())
}
}
| 0 | Kotlin | 0 | 7 | 22d30f0fbd5c5d2e5d70e3cb152cf804ba87304f | 228 | multiplatform-locale | Apache License 2.0 |
comet-utils/src/main/kotlin/ren/natsuyuk1/comet/utils/skiko/SkikoHelper.kt | StarWishsama | 173,288,057 | false | null | package ren.natsuyuk1.comet.utils.skiko
import io.ktor.client.plugins.*
import io.ktor.http.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runInterruptible
import mu.KotlinLogging
import org.jetbrains.skiko.Library
import org.jetbrains.skiko.hostId
import ren.natsuyuk1.comet.utils.file.absPath
import ren.natsuyuk1.comet.utils.file.resolveDirectory
import ren.natsuyuk1.comet.utils.ktor.defaultClient
import ren.natsuyuk1.comet.utils.ktor.downloadFile
import ren.natsuyuk1.comet.utils.system.OsArch
import ren.natsuyuk1.comet.utils.system.OsType
import ren.natsuyuk1.comet.utils.system.RuntimeUtil
import java.io.File
import java.nio.file.Path
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
import kotlin.io.path.outputStream
private val logger = KotlinLogging.logger {}
object SkikoHelper {
private const val SKIKO_LIBRARY_PATH_PROPERTY = "skiko.library.path"
private const val SKIKO_VERSION = "0.7.45"
private var isLoaded = false
private val skikoLibraryPath = System.getProperty(SKIKO_LIBRARY_PATH_PROPERTY)
private val skikoLibFolder = File(resolveDirectory("/modules"), "/skiko")
private val skikoLib = skikoLibFolder.resolve(System.mapLibraryName("skiko-$hostId"))
suspend fun loadSkiko() {
if (skikoLibraryPath != null) {
return
}
skikoLibFolder.mkdirs()
val skikoOsName = when (RuntimeUtil.getOsType()) {
OsType.MACOS -> "macos"
OsType.WINDOWS -> "windows"
OsType.LINUX -> "linux"
else -> return
}
val skikoArchName = when (RuntimeUtil.getOsArch()) {
OsArch.X86_64 -> "x64"
OsArch.ARM64 -> "arm64"
else -> return
}
if (skikoLibFolder.listFiles()?.isEmpty() == true) {
logger.info { "开始下载 Skiko $SKIKO_VERSION 依赖库." }
/* ktlint-disable max-line-length */
val downloadURL = "https://maven.pkg.jetbrains.space/public/p/compose/dev/org/jetbrains/skiko/skiko-awt-runtime-$skikoOsName-$skikoArchName/$SKIKO_VERSION/skiko-awt-runtime-$skikoOsName-$skikoArchName-$SKIKO_VERSION.jar"
/* ktlint-enable max-line-length */
kotlin.runCatching {
val tmpDownloadFile =
skikoLibFolder.resolve("skiko-awt-runtime-$skikoOsName-$skikoArchName-$SKIKO_VERSION.jar")
defaultClient.downloadFile(downloadURL, tmpDownloadFile)
val zip = runInterruptible {
ZipFile(tmpDownloadFile)
}
suspend fun copyEntryTo(entry: ZipEntry, output: Path) {
runInterruptible(Dispatchers.IO) {
zip.getInputStream(entry).use { input ->
output.outputStream().use(input::copyTo)
}
}
}
copyEntryTo(
zip.getEntry(skikoLib.name) ?: kotlin.run {
logger.warn { "下载的 Skiko 文件缺失, 请自行下载." }
return
},
skikoLib.toPath()
)
if (skikoOsName == "windows") {
val extraEntry = zip.getEntry("icudtl.dat") ?: kotlin.run {
logger.warn { "下载的 Skiko 文件缺失, 请自行下载." }
return
}
copyEntryTo(extraEntry, skikoLibFolder.resolve("icudtl.dat").toPath())
}
try {
zip.close()
tmpDownloadFile.delete()
} catch (e: FileSystemException) {
logger.warn("删除缓存 ${tmpDownloadFile.absPath} 失败, 请自行删除.")
}
}.onSuccess {
loadSkikoLibrary()
FontUtil.loadDefaultFont()
}.onFailure {
if (it is ResponseException) {
if (it.response.status == HttpStatusCode.NotFound) {
logger.warn { "找不到版本为 $SKIKO_VERSION 的 Skiko, 请手动下载." }
} else {
logger.warn(it) { "在下载 Skiko 库时出现异常, 版本 $SKIKO_VERSION, 如为下载失败请手动下载." }
}
} else {
logger.warn(it) { "在下载 Skiko 库时出现异常, 版本 $SKIKO_VERSION, 如为下载失败请手动下载." }
}
}
} else {
loadSkikoLibrary()
FontUtil.loadDefaultFont()
}
}
private fun loadSkikoLibrary() {
try {
System.setProperty(SKIKO_LIBRARY_PATH_PROPERTY, skikoLibFolder.absPath)
Library.load()
isLoaded = true
logger.info { "成功加载 Skiko $SKIKO_VERSION, Skiko 存放在 ${skikoLibFolder.absPath}" }
} catch (t: Throwable) {
logger.warn(t) { "在加载 Skiko 库时出现异常, 版本 $SKIKO_VERSION" }
}
}
fun isSkikoLoaded() = isLoaded
}
| 19 | null | 20 | 193 | 19ed20ec4003a37be3bc2dfc6b55a9e2548f0542 | 4,934 | Comet-Bot | MIT License |
comet-utils/src/main/kotlin/ren/natsuyuk1/comet/utils/skiko/SkikoHelper.kt | StarWishsama | 173,288,057 | false | null | package ren.natsuyuk1.comet.utils.skiko
import io.ktor.client.plugins.*
import io.ktor.http.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runInterruptible
import mu.KotlinLogging
import org.jetbrains.skiko.Library
import org.jetbrains.skiko.hostId
import ren.natsuyuk1.comet.utils.file.absPath
import ren.natsuyuk1.comet.utils.file.resolveDirectory
import ren.natsuyuk1.comet.utils.ktor.defaultClient
import ren.natsuyuk1.comet.utils.ktor.downloadFile
import ren.natsuyuk1.comet.utils.system.OsArch
import ren.natsuyuk1.comet.utils.system.OsType
import ren.natsuyuk1.comet.utils.system.RuntimeUtil
import java.io.File
import java.nio.file.Path
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
import kotlin.io.path.outputStream
private val logger = KotlinLogging.logger {}
object SkikoHelper {
private const val SKIKO_LIBRARY_PATH_PROPERTY = "skiko.library.path"
private const val SKIKO_VERSION = "0.7.45"
private var isLoaded = false
private val skikoLibraryPath = System.getProperty(SKIKO_LIBRARY_PATH_PROPERTY)
private val skikoLibFolder = File(resolveDirectory("/modules"), "/skiko")
private val skikoLib = skikoLibFolder.resolve(System.mapLibraryName("skiko-$hostId"))
suspend fun loadSkiko() {
if (skikoLibraryPath != null) {
return
}
skikoLibFolder.mkdirs()
val skikoOsName = when (RuntimeUtil.getOsType()) {
OsType.MACOS -> "macos"
OsType.WINDOWS -> "windows"
OsType.LINUX -> "linux"
else -> return
}
val skikoArchName = when (RuntimeUtil.getOsArch()) {
OsArch.X86_64 -> "x64"
OsArch.ARM64 -> "arm64"
else -> return
}
if (skikoLibFolder.listFiles()?.isEmpty() == true) {
logger.info { "开始下载 Skiko $SKIKO_VERSION 依赖库." }
/* ktlint-disable max-line-length */
val downloadURL = "https://maven.pkg.jetbrains.space/public/p/compose/dev/org/jetbrains/skiko/skiko-awt-runtime-$skikoOsName-$skikoArchName/$SKIKO_VERSION/skiko-awt-runtime-$skikoOsName-$skikoArchName-$SKIKO_VERSION.jar"
/* ktlint-enable max-line-length */
kotlin.runCatching {
val tmpDownloadFile =
skikoLibFolder.resolve("skiko-awt-runtime-$skikoOsName-$skikoArchName-$SKIKO_VERSION.jar")
defaultClient.downloadFile(downloadURL, tmpDownloadFile)
val zip = runInterruptible {
ZipFile(tmpDownloadFile)
}
suspend fun copyEntryTo(entry: ZipEntry, output: Path) {
runInterruptible(Dispatchers.IO) {
zip.getInputStream(entry).use { input ->
output.outputStream().use(input::copyTo)
}
}
}
copyEntryTo(
zip.getEntry(skikoLib.name) ?: kotlin.run {
logger.warn { "下载的 Skiko 文件缺失, 请自行下载." }
return
},
skikoLib.toPath()
)
if (skikoOsName == "windows") {
val extraEntry = zip.getEntry("icudtl.dat") ?: kotlin.run {
logger.warn { "下载的 Skiko 文件缺失, 请自行下载." }
return
}
copyEntryTo(extraEntry, skikoLibFolder.resolve("icudtl.dat").toPath())
}
try {
zip.close()
tmpDownloadFile.delete()
} catch (e: FileSystemException) {
logger.warn("删除缓存 ${tmpDownloadFile.absPath} 失败, 请自行删除.")
}
}.onSuccess {
loadSkikoLibrary()
FontUtil.loadDefaultFont()
}.onFailure {
if (it is ResponseException) {
if (it.response.status == HttpStatusCode.NotFound) {
logger.warn { "找不到版本为 $SKIKO_VERSION 的 Skiko, 请手动下载." }
} else {
logger.warn(it) { "在下载 Skiko 库时出现异常, 版本 $SKIKO_VERSION, 如为下载失败请手动下载." }
}
} else {
logger.warn(it) { "在下载 Skiko 库时出现异常, 版本 $SKIKO_VERSION, 如为下载失败请手动下载." }
}
}
} else {
loadSkikoLibrary()
FontUtil.loadDefaultFont()
}
}
private fun loadSkikoLibrary() {
try {
System.setProperty(SKIKO_LIBRARY_PATH_PROPERTY, skikoLibFolder.absPath)
Library.load()
isLoaded = true
logger.info { "成功加载 Skiko $SKIKO_VERSION, Skiko 存放在 ${skikoLibFolder.absPath}" }
} catch (t: Throwable) {
logger.warn(t) { "在加载 Skiko 库时出现异常, 版本 $SKIKO_VERSION" }
}
}
fun isSkikoLoaded() = isLoaded
}
| 19 | null | 20 | 193 | 19ed20ec4003a37be3bc2dfc6b55a9e2548f0542 | 4,934 | Comet-Bot | MIT License |
app/src/main/java/dev/braian/goalbit/view/activities/MainActivity.kt | BraianS | 745,135,660 | false | {"Kotlin": 105726} | package dev.braian.goalbit.view.activities
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.fragment.app.Fragment
import com.google.firebase.auth.FirebaseAuth
import dev.braian.goalbit.R
import dev.braian.goalbit.databinding.ActivityMainBinding
import dev.braian.goalbit.utils.NotificationHelper
import dev.braian.goalbit.view.fragment.HistoricFragment
import dev.braian.goalbit.view.fragment.HomeFragment
import dev.braian.goalbit.view.fragment.MeFragment
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private var selectedItemId: Int = R.id.item_home
private lateinit var notificationHelper: NotificationHelper
private lateinit var auth: FirebaseAuth
override fun onStart() {
super.onStart()
navigationView()
displayFragment(HomeFragment())
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
auth = FirebaseAuth.getInstance()
Thread.sleep(2000)
installSplashScreen()
notificationHelper = NotificationHelper(applicationContext)
notificationHelper.createNotificationChannel()
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
window.statusBarColor = ContextCompat.getColor(this,R.color.secondary_color_alt)
}
private fun displayFragment(fragment: Fragment) {
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.frame_layout, fragment)
fragmentTransaction.commit()
}
private fun navigationView() {
binding.bottomNavigationView.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.item_home -> {
displayFragment(HomeFragment())
selectedItemId = R.id.item_home
true
}
R.id.item_add -> {
startActivity(Intent(this, AddHabitFormActivity::class.java))
false
}
R.id.item_hystory -> {
displayFragment(HistoricFragment())
selectedItemId = R.id.item_hystory
true
}
R.id.item_me -> {
displayFragment(MeFragment())
selectedItemId = R.id.item_me
true
}
else -> false
}
}
}
}
| 0 | Kotlin | 0 | 0 | 400644bf3425cdd2d589f086bfab55b41076fdee | 2,765 | goalbit-android | Apache License 2.0 |
app/src/main/java/com/nora/covdecem/data/database/dao/CaseDao.kt | NoraHeithur | 499,868,323 | false | null | package com.nora.covdecem.data.database.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.nora.covdecem.data.database.entity.CaseEntity
@Dao
interface CaseDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertDailyData(case: CaseEntity)
@Query("SELECT * FROM DAILY_CASE_DATABASE")
suspend fun queryDailyData(): CaseEntity
} | 0 | Kotlin | 0 | 0 | 0138f2ef1804b98571c68c4c0ef26244aa99178d | 447 | CovDecem | MIT License |
test_runner/src/test/kotlin/ftl/environment/android/AndroidModelDescriptionTest.kt | Flank | 84,221,974 | false | {"Kotlin": 1748173, "Java": 101254, "Swift": 41229, "Shell": 10674, "Objective-C": 10006, "Dart": 9705, "HTML": 7235, "Gherkin": 4210, "TypeScript": 2717, "Ruby": 2272, "JavaScript": 1764, "SCSS": 1365, "Batchfile": 1183, "EJS": 1061, "Go": 159} | package ftl.environment.android
import ftl.api.DeviceModel
import ftl.presentation.cli.firebase.test.android.models.describe.prepareDescription
import org.junit.Assert.assertEquals
import org.junit.Test
class AndroidModelDescriptionTest {
@Test
fun `should return model with tag if any tag exists`() {
val models = listOf(
DeviceModel.Android(
id = "walleye",
codename = "walleye",
brand = "Google",
form = "PHYSICAL",
formFactor = "PHONE",
manufacturer = "Google",
name = "Pixel 2",
screenDensity = 420,
screenX = 1080,
screenY = 1920,
supportedAbis = listOf("arm64-v8a", "armeabi-v7a", "armeabi"),
supportedVersionIds = listOf("26", "27", "28"),
thumbnailUrl =
"https://lh3.googleusercontent.com/j4urvb3lXTaFGZI6IzHmAjum2HQVID1OHPhDB7dOzRvXb2WscSX2RFwEEFFSYhajqRO5Yu0e6FYQ",
tags = listOf("default"),
lowFpsVideoRecording = true
)
)
val modelDescription = models.find { it.id == "walleye" }?.prepareDescription()
val expected = """
brand: Google
codename: walleye
form: PHYSICAL
formFactor: PHONE
id: walleye
manufacturer: Google
name: Pixel 2
screenDensity: 420
screenX: 1080
screenY: 1920
supportedAbis:
- arm64-v8a
- armeabi-v7a
- armeabi
supportedVersionIds:
- 26
- 27
- 28
tags:
- default
thumbnailUrl: https://lh3.googleusercontent.com/j4urvb3lXTaFGZI6IzHmAjum2HQVID1OHPhDB7dOzRvXb2WscSX2RFwEEFFSYhajqRO5Yu0e6FYQ
""".trimIndent()
assertEquals(expected, modelDescription)
}
@Test
fun `should return model without tag if no tags`() {
val models = listOf(
DeviceModel.Android(
id = "walleye",
codename = "walleye",
brand = "Google",
form = "PHYSICAL",
formFactor = "PHONE",
manufacturer = "Google",
name = "Pixel 2",
screenDensity = 420,
screenX = 1080,
screenY = 1920,
supportedAbis = listOf("arm64-v8a", "armeabi-v7a", "armeabi"),
supportedVersionIds = listOf("26", "27", "28"),
thumbnailUrl =
"https://lh3.googleusercontent.com/j4urvb3lXTaFGZI6IzHmAjum2HQVID1OHPhDB7dOzRvXb2WscSX2RFwEEFFSYhajqRO5Yu0e6FYQ",
tags = emptyList(),
lowFpsVideoRecording = true
)
)
val modelDescription = models.find { it.id == "walleye" }?.prepareDescription()
val expected = """
brand: Google
codename: walleye
form: PHYSICAL
formFactor: PHONE
id: walleye
manufacturer: Google
name: Pixel 2
screenDensity: 420
screenX: 1080
screenY: 1920
supportedAbis:
- arm64-v8a
- armeabi-v7a
- armeabi
supportedVersionIds:
- 26
- 27
- 28
thumbnailUrl: https://lh3.googleusercontent.com/j4urvb3lXTaFGZI6IzHmAjum2HQVID1OHPhDB7dOzRvXb2WscSX2RFwEEFFSYhajqRO5Yu0e6FYQ
""".trimIndent()
assertEquals(expected, modelDescription)
}
}
| 64 | Kotlin | 115 | 676 | b40904b4e74a670cf72ee53dc666fc3a801e7a95 | 3,504 | flank | Apache License 2.0 |
app/src/main/java/dev/shorthouse/coinwatch/ui/screen/search/SearchViewModel.kt | shorthouse | 655,260,745 | false | null | package dev.shorthouse.coinwatch.ui.screen.search
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import dev.shorthouse.coinwatch.common.Result
import dev.shorthouse.coinwatch.domain.GetCoinSearchResultsUseCase
import javax.inject.Inject
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.toPersistentList
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.update
@OptIn(FlowPreview::class)
@HiltViewModel
class CoinSearchViewModel @Inject constructor(
private val getCoinSearchResultsUseCase: GetCoinSearchResultsUseCase
) : ViewModel() {
private val _uiState = MutableStateFlow<CoinSearchUiState>(CoinSearchUiState.Loading)
val uiState = _uiState.asStateFlow()
var searchQuery by mutableStateOf("")
private set
init {
initialiseUiState()
}
fun initialiseUiState() {
snapshotFlow { searchQuery }
.debounce(350L)
.onEach { query ->
if (query.isNotBlank()) {
val result = getCoinSearchResultsUseCase(query)
when (result) {
is Result.Error -> {
_uiState.update {
CoinSearchUiState.Error(
message = result.message
)
}
}
is Result.Success -> {
val searchResults = result.data.toPersistentList()
_uiState.update {
CoinSearchUiState.Success(
searchResults = searchResults,
queryHasNoResults = searchResults.isEmpty()
)
}
}
}
} else {
_uiState.update {
CoinSearchUiState.Success(
searchResults = persistentListOf(),
queryHasNoResults = false
)
}
}
}.launchIn(viewModelScope)
}
fun updateSearchQuery(newQuery: String) {
searchQuery = newQuery
}
}
| 5 | null | 7 | 9 | ec946062b37a8c675798db0af440394a3c253d1d | 2,800 | CoinWatch | Apache License 2.0 |
app/src/main/java/my/app/canvas/DrawPencil.kt | gerasymenkoke | 637,945,680 | false | {"Kotlin": 52735} | package com.ferodev.simplepaint.canvas
import android.graphics.Color
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.graphics.Path
import com.ferodev.simplepaint.MainActivity.Companion.currentBrush
import com.ferodev.simplepaint.MainActivity.Companion.path
import com.ferodev.simplepaint.MainActivity.Companion.shift
import com.ferodev.simplepaint.cons.Pencil
import com.ferodev.simplepaint.databinding.ActivityMainBinding
import kotlin.math.roundToInt
import kotlin.math.abs
import kotlin.math.atan
import kotlin.math.PI
class DrawPencil @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private val TOUCH_TOLERANCE = 4f
private var mX = 0f
private var mY = 0f
private val dataPencil = mutableListOf<Pencil>()
private val colorList = mutableListOf<Int>()
private var i = -1
private var arr = Array<Float>(10){0.0F}
private var x1 = 0f
private var y1 = 0f
private var x = 0f
private var y = 0f
private var rx1 = 1f
private var ry1 = 1f
private var N = 1
companion object {
var xxx = "99"
var yyy = "99"
var aaa = Array<String>(10){"0"}
var zzz = 0
var rxx = "1"
var ryy = "1"
var crx_ = Array<Float>(800){0.0f}
var cry_ = Array<Float>(800){0.0f}
var crxdy_ = Array<Float>(800){1000.0f}
var cangle_ =Array<Float>(800){0.0f}
var cangle = 0.0f
var cangle1 = 0.0f
var ci = 0
var rx = 0.0f
var ry = 0.0f
// var shift = 0 // user's a new symbol is beging draw on the screen
var iii = 0
var j = 0
}
private val paintBrush = Paint().apply {
isAntiAlias = true
isDither = true
color = currentBrush
style = Paint.Style.STROKE
strokeJoin = Paint.Join.ROUND
strokeCap = Paint.Cap.ROUND
strokeWidth = 16f
alpha = 0xff
}
fun updateColor(newColor: Int) {
paintBrush.color = newColor
}
private fun touchStart(x: Float, y: Float) {
val p = Pencil(currentBrush, path)
dataPencil.add(p)
colorList.add(currentBrush)
path.moveTo(x, y)
mX = x
mY = y
}
private fun touchMove(x: Float, y: Float) {
val dx = Math.abs(x - mX)
val dy = Math.abs(y - mY)
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
path.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2)
mX = x
mY = y
}
}
private fun touchUp() {
path.lineTo(mX, mY)
}
override fun onTouchEvent(event1: MotionEvent): Boolean {
x = event1.x
y = event1.y
xxx = x.toString()
yyy = y.toString()
if(shift==1) { j=0; ci=0; shift=0 }
if ( j<=799 )
{
// if (x==0.0f) x=0.001f; if (y==0.0f) y=0.001f
rx=(((x) * 1000.0).roundToInt() / 1000.0).toFloat()
ry=(((y) * 1000.0).roundToInt() / 1000.0).toFloat()
// if (rx==0.0f) rx=0.001f; if (ry==0.0f) ry=0.001f
if ( ry==0.0f) { ry=0.00001f }
cangle= (atan(rx/ry)*(180/PI)).toFloat()
if ( Math.abs ( cangle - cangle1) > 10 )
{
cangle_[ci] = cangle
crx_[ci] = rx
cry_[ci] = ry
ci=ci+1
}
cangle1 = cangle
x1=x
y1=y
j = j + 1
}
when (event1.action) {
MotionEvent.ACTION_DOWN -> {
touchStart(x, y)
invalidate()
}
MotionEvent.ACTION_MOVE -> {
touchMove(x, y)
invalidate()
}
MotionEvent.ACTION_UP -> {
touchUp()
invalidate()
}
}
return true
}
override fun onDraw(canvas: Canvas) {
for (p in dataPencil) {
paintBrush.color = p.color
canvas.drawPath(p.path!!, paintBrush)
invalidate()
}
}
fun undo() {
if (dataPencil.size != 0) {
dataPencil.removeAt(dataPencil.size - 1)
invalidate()
}
}
}
| 0 | Kotlin | 0 | 0 | e1d26c47763b46650a50003681ea89f5038ef6b5 | 5,114 | paint | Apache License 2.0 |
app/src/main/java/my/app/canvas/DrawPencil.kt | gerasymenkoke | 637,945,680 | false | {"Kotlin": 52735} | package com.ferodev.simplepaint.canvas
import android.graphics.Color
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.graphics.Path
import com.ferodev.simplepaint.MainActivity.Companion.currentBrush
import com.ferodev.simplepaint.MainActivity.Companion.path
import com.ferodev.simplepaint.MainActivity.Companion.shift
import com.ferodev.simplepaint.cons.Pencil
import com.ferodev.simplepaint.databinding.ActivityMainBinding
import kotlin.math.roundToInt
import kotlin.math.abs
import kotlin.math.atan
import kotlin.math.PI
class DrawPencil @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private val TOUCH_TOLERANCE = 4f
private var mX = 0f
private var mY = 0f
private val dataPencil = mutableListOf<Pencil>()
private val colorList = mutableListOf<Int>()
private var i = -1
private var arr = Array<Float>(10){0.0F}
private var x1 = 0f
private var y1 = 0f
private var x = 0f
private var y = 0f
private var rx1 = 1f
private var ry1 = 1f
private var N = 1
companion object {
var xxx = "99"
var yyy = "99"
var aaa = Array<String>(10){"0"}
var zzz = 0
var rxx = "1"
var ryy = "1"
var crx_ = Array<Float>(800){0.0f}
var cry_ = Array<Float>(800){0.0f}
var crxdy_ = Array<Float>(800){1000.0f}
var cangle_ =Array<Float>(800){0.0f}
var cangle = 0.0f
var cangle1 = 0.0f
var ci = 0
var rx = 0.0f
var ry = 0.0f
// var shift = 0 // user's a new symbol is beging draw on the screen
var iii = 0
var j = 0
}
private val paintBrush = Paint().apply {
isAntiAlias = true
isDither = true
color = currentBrush
style = Paint.Style.STROKE
strokeJoin = Paint.Join.ROUND
strokeCap = Paint.Cap.ROUND
strokeWidth = 16f
alpha = 0xff
}
fun updateColor(newColor: Int) {
paintBrush.color = newColor
}
private fun touchStart(x: Float, y: Float) {
val p = Pencil(currentBrush, path)
dataPencil.add(p)
colorList.add(currentBrush)
path.moveTo(x, y)
mX = x
mY = y
}
private fun touchMove(x: Float, y: Float) {
val dx = Math.abs(x - mX)
val dy = Math.abs(y - mY)
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
path.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2)
mX = x
mY = y
}
}
private fun touchUp() {
path.lineTo(mX, mY)
}
override fun onTouchEvent(event1: MotionEvent): Boolean {
x = event1.x
y = event1.y
xxx = x.toString()
yyy = y.toString()
if(shift==1) { j=0; ci=0; shift=0 }
if ( j<=799 )
{
// if (x==0.0f) x=0.001f; if (y==0.0f) y=0.001f
rx=(((x) * 1000.0).roundToInt() / 1000.0).toFloat()
ry=(((y) * 1000.0).roundToInt() / 1000.0).toFloat()
// if (rx==0.0f) rx=0.001f; if (ry==0.0f) ry=0.001f
if ( ry==0.0f) { ry=0.00001f }
cangle= (atan(rx/ry)*(180/PI)).toFloat()
if ( Math.abs ( cangle - cangle1) > 10 )
{
cangle_[ci] = cangle
crx_[ci] = rx
cry_[ci] = ry
ci=ci+1
}
cangle1 = cangle
x1=x
y1=y
j = j + 1
}
when (event1.action) {
MotionEvent.ACTION_DOWN -> {
touchStart(x, y)
invalidate()
}
MotionEvent.ACTION_MOVE -> {
touchMove(x, y)
invalidate()
}
MotionEvent.ACTION_UP -> {
touchUp()
invalidate()
}
}
return true
}
override fun onDraw(canvas: Canvas) {
for (p in dataPencil) {
paintBrush.color = p.color
canvas.drawPath(p.path!!, paintBrush)
invalidate()
}
}
fun undo() {
if (dataPencil.size != 0) {
dataPencil.removeAt(dataPencil.size - 1)
invalidate()
}
}
}
| 0 | Kotlin | 0 | 0 | e1d26c47763b46650a50003681ea89f5038ef6b5 | 5,114 | paint | Apache License 2.0 |
test/fixtures/gradle/multi_project/lib/src/test/kotlin/multi_project/AppTest.kt | github | 120,039,636 | false | null | /*
* This Kotlin source file was generated by the Gradle 'init' task.
*/
package cubeconundrum
import kotlin.test.Test
import kotlin.test.assertNotNull
class AppTest {
@Test fun appHasAGreeting() {
// val classUnderTest = App()
// assertNotNull(classUnderTest.greeting, "app should have a greeting")
}
}
| 6 | null | 3 | 979 | 20ccab13f3e8738cf12543ef78da3469bf63c249 | 332 | licensed | MIT License |
jvm/src/main/kotlin/io/github/shyamz/openidconnect/configuration/model/TokenEndPointAuthMethod.kt | shyamz-22 | 117,333,520 | false | null | package io.github.shyamz.openidconnect.configuration.model
/**
* Other methods client_secret_jwt, and private_key_jwt are unsupported by the library
*/
enum class TokenEndPointAuthMethod(val supportedMethod: String) {
Post("client_secret_post"),
Basic("client_secret_basic"),
None("none")
} | 0 | Kotlin | 2 | 11 | 421a680d5bee2a1d88c6890d2d71ac847af30fe7 | 305 | openid-connect-client | Apache License 2.0 |
plot-api/src/commonMain/kotlin/org/jetbrains/letsPlot/geom/geom_boxplot.kt | JetBrains | 172,682,391 | false | null | /*
* Copyright (c) 2021. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package org.jetbrains.letsPlot.geom
import org.jetbrains.letsPlot.Geom.boxplot
import org.jetbrains.letsPlot.Stat
import org.jetbrains.letsPlot.intern.*
import org.jetbrains.letsPlot.intern.layer.PosOptions
import org.jetbrains.letsPlot.intern.layer.StatOptions
import org.jetbrains.letsPlot.intern.layer.WithColorOption
import org.jetbrains.letsPlot.intern.layer.WithFillOption
import org.jetbrains.letsPlot.intern.layer.geom.BoxplotAesthetics
import org.jetbrains.letsPlot.intern.layer.geom.BoxplotMapping
import org.jetbrains.letsPlot.intern.layer.geom.BoxplotParameters
import org.jetbrains.letsPlot.intern.layer.geom.PointMapping
import org.jetbrains.letsPlot.intern.layer.stat.BoxplotStatAesthetics
import org.jetbrains.letsPlot.intern.layer.stat.BoxplotStatParameters
import org.jetbrains.letsPlot.pos.positionDodge
import org.jetbrains.letsPlot.tooltips.TooltipOptions
/**
* Displays the distribution of data based on a five number summary ("minimum", first quartile (Q1),
* median, third quartile (Q3), and "maximum"), and "outlying" points individually.
*
* ## Examples
*
* - [distributions.ipynb](https://nbviewer.jupyter.org/github/JetBrains/lets-plot-kotlin/blob/master/docs/examples/jupyter-notebooks/distributions.ipynb)
*
* - [stat_boxplot_outlier.ipynb](https://nbviewer.jupyter.org/github/JetBrains/lets-plot-kotlin/blob/master/docs/examples/jupyter-notebooks/f-4.4.2/stat_boxplot_outlier.ipynb).
*
* @param data The data to be displayed. If null, the default, the data is inherited
* from the plot data as specified in the call to [letsPlot][org.jetbrains.letsPlot.letsPlot].
* @param stat default = `Stat.boxplot()`. The statistical transformation to use on the data for this layer.
* Supported transformations: `Stat.identity`, `Stat.bin()`, `Stat.count()`, etc. see [Stat][org.jetbrains.letsPlot.Stat].
* @param position default = `positionDodge()`. Position adjustment: `positionIdentity`,
* `positionStack()`, `positionDodge()`, etc. see [Position](https://lets-plot.org/kotlin/-lets--plot--kotlin/org.jetbrains.letsPlot.pos/).
* @param showLegend default = true.
* If false - do not show legend for this layer.
* @param tooltips Result of the call to the `layerTooltips()` function.
* Specifies appearance, style and content.
* @param orientation Specifies the axis that the layer's stat and geom should run along, default = "x".
* Possible values: "x", "y".
* @param outlierAlpha Default transparency aesthetic for outliers.
* @param outlierColor Color aesthetic for outliers.
* @param outlierFill Fill aesthetic for outliers.
* @param outlierShape Shape aesthetic for outliers.
* @param outlierSize Size aesthetic for outliers.
* @param outlierStroke Default width of the border for outliers.
* @param varWidth default = false. If false make a standard box plot.
* If true, boxes are drawn with widths proportional to the square-roots of the number of
* observations in the groups.
* @param fatten default = 1.0.
* A multiplicative factor applied to size of the middle bar.
* @param whiskerWidth default = 0.0.
* A multiplicative factor applied to the box width to draw horizontal segments on whiskers.
* @param coef default = 1.5.
* Length of the whiskers as multiple of IQR.
* @param colorBy default = "color" ("fill", "color", "paint_a", "paint_b", "paint_c").
* Defines the color aesthetic for the geometry.
* @param fillBy default = "fill" ("fill", "color", "paint_a", "paint_b", "paint_c").
* Defines the fill aesthetic for the geometry.
* @param lower Lower hinge, 25% quantile.
* @param middle Median, 50% quantile.
* @param upper Upper hinge, 75% quantile.
* @param ymin Lower whisker - the smallest observation greater than or equal to the lower hinge - 1.5 * IQR
* @param ymax Upper whisker - the largest observation less than or equal to the upper hinge + 1.5 * IQR
* @param width Width of boxplot. Typically ranges between 0 and 1. Values that are greater than 1 lead to overlapping of the boxes.
* @param alpha Transparency level of a layer.
* Understands numbers between 0 and 1.
* @param color Color of the geometry.
* String in the following formats:
* - RGB/RGBA (e.g. "rgb(0, 0, 255)")
* - HEX (e.g. "#0000FF")
* - color name (e.g. "red")
* - role name ("pen", "paper" or "brush")
*
* Or an instance of the `java.awt.Color` class.
* @param fill Fill color.
* String in the following formats:
* - RGB/RGBA (e.g. "rgb(0, 0, 255)")
* - HEX (e.g. "#0000FF")
* - color name (e.g. "red")
* - role name ("pen", "paper" or "brush")
*
* Or an instance of the `java.awt.Color` class.
* @param size Lines width.
* @param linetype Type of the line of border.
* Codes and names: 0 = "blank", 1 = "solid", 2 = "dashed", 3 = "dotted", 4 = "dotdash",
* 5 = "longdash", 6 = "twodash".
* @param mapping Set of aesthetic mappings.
* Aesthetic mappings describe the way that variables in the data are
* mapped to plot "aesthetics".
*/
fun geomBoxplot(
data: Map<*, *>? = null,
stat: StatOptions = Stat.boxplot(),
position: PosOptions = positionDodge(),
showLegend: Boolean = true,
tooltips: TooltipOptions? = null,
orientation: String? = null,
x: Number? = null,
y: Number? = null,
lower: Number? = null,
middle: Number? = null,
upper: Number? = null,
ymin: Number? = null,
ymax: Number? = null,
alpha: Number? = null,
color: Any? = null,
fill: Any? = null,
size: Number? = null,
stroke: Number? = null,
linetype: Any? = null,
shape: Any? = null,
width: Any? = null,
weight: Any? = null,
outlierAlpha: Number? = null,
outlierColor: Any? = null,
outlierFill: Any? = null,
outlierShape: Any? = null,
outlierSize: Number? = null,
outlierStroke: Number? = null,
fatten: Number? = null,
whiskerWidth: Number? = null,
varWidth: Boolean? = null,
@Suppress("SpellCheckingInspection")
coef: Number? = null,
colorBy: String? = null,
fillBy: String? = null,
mapping: BoxplotMapping .() -> Unit = {}
): FeatureList {
val layers = mutableListOf<Layer>()
layers += geomBoxplotInternal(
data,
stat,
position,
showLegend,
tooltips,
orientation,
x, y, lower, middle, upper, ymin, ymax, alpha, color, fill, size, linetype, shape, width, weight, fatten,
whiskerWidth, varWidth, coef,
colorBy, fillBy,
mapping
)
if (stat.kind == StatKind.BOXPLOT) {
val outlierFatten = 4.0
val boxplotMapping = BoxplotMapping().apply(mapping)
val pointMapping: PointMapping.() -> Unit = {
this.x = boxplotMapping.x
this.y = boxplotMapping.y
this.alpha = boxplotMapping.alpha
this.color = boxplotMapping.color
this.fill = boxplotMapping.fill
this.shape = boxplotMapping.shape
this.size = boxplotMapping.size
// stroke
this.group = boxplotMapping.group
this.paint_a = boxplotMapping.paint_a
this.paint_b = boxplotMapping.paint_b
this.paint_c = boxplotMapping.paint_c
}
layers += geomPoint(
data = data,
stat = Stat.boxplotOutlier(),
position = position,
showLegend = false,
sampling = null,
orientation = orientation,
x = x, y = y,
alpha = outlierAlpha ?: alpha,
color = outlierColor ?: color,
fill = outlierFill ?: fill,
shape = outlierShape ?: shape,
size = (outlierSize ?: size)?.let { it.toDouble() * outlierFatten },
stroke = outlierStroke ?: stroke,
colorBy = colorBy, fillBy = fillBy,
mapping = pointMapping
)
}
return FeatureList(layers)
}
@Suppress("ClassName")
private class geomBoxplotInternal(
data: Map<*, *>? = null,
stat: StatOptions = Stat.boxplot(),
position: PosOptions = positionDodge(),
showLegend: Boolean = true,
tooltips: TooltipOptions? = null,
orientation: String? = null,
override val x: Number? = null,
override val y: Number? = null,
override val lower: Number? = null,
override val middle: Number? = null,
override val upper: Number? = null,
override val ymin: Number? = null,
override val ymax: Number? = null,
override val alpha: Number? = null,
override val color: Any? = null,
override val fill: Any? = null,
override val size: Number? = null,
override val linetype: Any? = null,
override val shape: Any? = null,
override val width: Any? = null,
override val weight: Any? = null,
override val fatten: Number? = null,
override val whiskerWidth: Number? = null,
override val varWidth: Boolean? = null,
@Suppress("SpellCheckingInspection")
override val coef: Number? = null,
override val colorBy: String? = null,
override val fillBy: String? = null,
mapping: BoxplotMapping .() -> Unit = {}
) : BoxplotAesthetics,
BoxplotParameters,
BoxplotStatAesthetics,
BoxplotStatParameters,
WithColorOption,
WithFillOption,
Layer(
mapping = BoxplotMapping().apply(mapping).seal(),
data = data,
geom = boxplot(),
stat = stat,
position = position,
showLegend = showLegend,
sampling = null,
tooltips = tooltips,
orientation = orientation
) {
override fun seal(): Options {
return super<BoxplotAesthetics>.seal() +
super<BoxplotParameters>.seal() +
super<BoxplotStatAesthetics>.seal() +
super<BoxplotStatParameters>.seal() +
super<WithColorOption>.seal() +
super<WithFillOption>.seal()
}
}
| 19 | null | 37 | 433 | f6edab1a67783d14e2378675f065ef7111bdc1a0 | 9,979 | lets-plot-kotlin | MIT License |
src/test/kotlin/dev/shtanko/algorithms/leetcode/ThreeSumSmallerTest.kt | ashtanko | 203,993,092 | false | {"Kotlin": 6042782, "Shell": 1168, "Makefile": 961} | /*
* 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 dev.shtanko.algorithms.leetcode
import java.util.stream.Stream
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.ArgumentsProvider
import org.junit.jupiter.params.provider.ArgumentsSource
abstract class ThreeSumSmallerTest<out T : ThreeSumSmallerStrategy>(val strategy: T) {
private class InputArgumentsProvider : ArgumentsProvider {
override fun provideArguments(context: ExtensionContext?): Stream<out Arguments> = Stream.of(
Arguments.of(
intArrayOf(-2, 0, 1, 3),
2,
2,
),
Arguments.of(
intArrayOf(),
0,
0,
),
Arguments.of(
intArrayOf(0),
0,
0,
),
Arguments.of(
intArrayOf(0, 0, 0),
0,
0,
),
Arguments.of(
intArrayOf(1, 1, 1, 1),
4,
4,
),
)
}
@ParameterizedTest
@ArgumentsSource(InputArgumentsProvider::class)
fun `3 sum test`(nums: IntArray, target: Int, expected: Int) {
val actual = strategy.invoke(nums, target)
assertEquals(expected, actual)
}
}
class ThreeSumSmallerBinarySearchTest :
ThreeSumSmallerTest<ThreeSumSmallerBinarySearch>(ThreeSumSmallerBinarySearch())
class ThreeSumSmallerTwoPointersTest :
ThreeSumSmallerTest<ThreeSumSmallerTwoPointers>(ThreeSumSmallerTwoPointers())
| 6 | Kotlin | 0 | 19 | e7063905fd9b543055a7d8c2826db73cc65715db | 2,322 | kotlab | Apache License 2.0 |
src/test/kotlin/dev/shtanko/algorithms/leetcode/ThreeSumSmallerTest.kt | ashtanko | 203,993,092 | false | {"Kotlin": 6042782, "Shell": 1168, "Makefile": 961} | /*
* Copyright 2020 Oleksii Shtanko
*
* 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 dev.shtanko.algorithms.leetcode
import java.util.stream.Stream
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.ArgumentsProvider
import org.junit.jupiter.params.provider.ArgumentsSource
abstract class ThreeSumSmallerTest<out T : ThreeSumSmallerStrategy>(val strategy: T) {
private class InputArgumentsProvider : ArgumentsProvider {
override fun provideArguments(context: ExtensionContext?): Stream<out Arguments> = Stream.of(
Arguments.of(
intArrayOf(-2, 0, 1, 3),
2,
2,
),
Arguments.of(
intArrayOf(),
0,
0,
),
Arguments.of(
intArrayOf(0),
0,
0,
),
Arguments.of(
intArrayOf(0, 0, 0),
0,
0,
),
Arguments.of(
intArrayOf(1, 1, 1, 1),
4,
4,
),
)
}
@ParameterizedTest
@ArgumentsSource(InputArgumentsProvider::class)
fun `3 sum test`(nums: IntArray, target: Int, expected: Int) {
val actual = strategy.invoke(nums, target)
assertEquals(expected, actual)
}
}
class ThreeSumSmallerBinarySearchTest :
ThreeSumSmallerTest<ThreeSumSmallerBinarySearch>(ThreeSumSmallerBinarySearch())
class ThreeSumSmallerTwoPointersTest :
ThreeSumSmallerTest<ThreeSumSmallerTwoPointers>(ThreeSumSmallerTwoPointers())
| 6 | Kotlin | 0 | 19 | e7063905fd9b543055a7d8c2826db73cc65715db | 2,331 | kotlab | Apache License 2.0 |
sample/common/src/iosMain/kotlin/com/example/sqldelight/hockey/ui/TeamData.kt | sqldelight | 44,677,680 | false | null | package com.example.sqldelight.hockey.ui
import com.example.sqldelight.hockey.data.Db
// For Swift
object TeamData {
fun teams() = Db.instance.teamQueries.selectAll().executeAsList()
}
| 606 | null | 516 | 6,152 | f79bd8ae2cf991de6dccdb643376253402f665e1 | 189 | sqldelight | Apache License 2.0 |
android-kotlin-notifications-start/app/src/main/java/com/example/android/eggtimernotifications/receiver/AlarmReceiver.kt | hieuwu | 290,215,458 | false | null | /*
* Copyright (C) 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.eggtimernotifications.receiver
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.core.content.ContextCompat
import com.example.android.eggtimernotifications.R
import com.example.android.eggtimernotifications.util.sendNotification
class AlarmReceiver: BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
// TODO: Step 1.9 add call to sendNotification
val notificationManager = ContextCompat.getSystemService(
context,
NotificationManager::class.java
) as NotificationManager
notificationManager.sendNotification(
context.getText(R.string.eggs_ready).toString(),
context
)
}
} | 1 | null | 5 | 37 | 8d0720ea18465f978e8e77748311609f0807c6fc | 1,440 | kotlin-android-practice | Creative Commons Attribution 4.0 International |
src/jsMain/kotlin/baaahs/gl/render/WebGL2ResultDeliveryStrategy.kt | baaahs | 174,897,412 | false | null | package baaahs.gl.render
import baaahs.document
import baaahs.gl.GlBase
import baaahs.gl.GlContext
import baaahs.gl.WebGL2RenderingContext
import baaahs.gl.WebGL2RenderingContext.Companion.PIXEL_PACK_BUFFER
import baaahs.gl.WebGL2RenderingContext.Companion.STREAM_READ
import baaahs.gl.WebGL2RenderingContext.Companion.SYNC_GPU_COMMANDS_COMPLETE
import baaahs.gl.WebGLSync
import baaahs.gl.result.ResultStorage
import baaahs.internalTimerClock
import com.danielgergely.kgl.Buffer
import com.danielgergely.kgl.GlBuffer
import kotlinx.coroutines.delay
actual fun pickResultDeliveryStrategy(gl: GlContext): ResultDeliveryStrategy {
return SwitchingResultDeliveryStrategy(gl as GlBase.JsGlContext)
// return WebGl2ResultDeliveryStrategy(gl as GlBase.JsGlContext)
}
class SwitchingResultDeliveryStrategy(private val gl: GlBase.JsGlContext): ResultDeliveryStrategy {
val sync = SyncResultDeliveryStrategy()
val async = WebGl2ResultDeliveryStrategy(gl)
private fun pickStrategy() =
if (document.asDynamic()["strategy"] != "sync") async else sync
override fun beforeRender() {
pickStrategy().beforeRender()
}
override fun afterRender(frameBuffer: GlContext.FrameBuffer, resultStorage: ResultStorage) {
pickStrategy().afterRender(frameBuffer, resultStorage)
}
override suspend fun awaitResults(frameBuffer: GlContext.FrameBuffer, resultStorage: ResultStorage) {
pickStrategy().awaitResults(frameBuffer, resultStorage)
}
}
// See https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/WebGL_best_practices#use_non-blocking_async_data_readback
class WebGl2ResultDeliveryStrategy(private val gl: GlBase.JsGlContext) : ResultDeliveryStrategy {
private val webgl2 = gl.webgl
val bufs: MutableList<Pair<Buffer, GlBuffer>> = arrayListOf()
override fun afterRender(frameBuffer: GlContext.FrameBuffer, resultStorage: ResultStorage) {
resultStorage.resultBuffers.forEach {
val gpuBuffer = it.gpuBuffer
val resultType = it.type
val cpuBuffer: Buffer = it.cpuBuffer
frameBuffer.withRenderBufferAsAttachment0(gpuBuffer) {
val glBuf = gl.check { createBuffer() }
gl.check { bindBuffer(PIXEL_PACK_BUFFER, glBuf) }
gl.check { webgl2.bufferData(PIXEL_PACK_BUFFER, it.cpuBufferSizeInBytes, STREAM_READ) }
gl.check {
webgl2.readPixels(
0, 0, gpuBuffer.curWidth, gpuBuffer.curHeight,
resultType.readFormat, resultType.readType, 0
)
}
gl.check { bindBuffer(PIXEL_PACK_BUFFER, null) }
bufs.add(cpuBuffer to glBuf)
}
}
}
override suspend fun awaitResults(frameBuffer: GlContext.FrameBuffer, resultStorage: ResultStorage) {
FenceSync(gl).await()
bufs.forEach { (cpuBuffer, glBuf) ->
gl.check { bindBuffer(PIXEL_PACK_BUFFER, glBuf) }
gl.check {
webgl2.getBufferSubData(
PIXEL_PACK_BUFFER, 0, cpuBuffer.getJsBufferWithOffset(), 0, 0
)
}
gl.check { bindBuffer(PIXEL_PACK_BUFFER, null) }
gl.check { deleteBuffer(glBuf) }
}
bufs.clear()
}
}
class FenceSync(private val gl: GlBase.JsGlContext) {
private val webgl2 = gl.webgl
private val fenceSync = gl.check { webgl2.fenceSync(SYNC_GPU_COMMANDS_COMPLETE, 0) }
suspend fun await() {
gl.check { webgl2.flush() }
val startTime = internalTimerClock.now()
val maxTries = fenceTimeoutMs / delayBetweenSyncChecksMs
var tries = 0
while (tries ++ < maxTries) {
val result = clientWaitSync(fenceSync, timeout = 0)
if (result) {
gl.check { webgl2.deleteSync(fenceSync) }
return
}
delay(delayBetweenSyncChecksMs)
}
gl.check { webgl2.deleteSync(fenceSync) }
error("Fence sync failed after ${internalTimerClock.now() - startTime}ms, $tries tries!")
}
private fun clientWaitSync(fence: WebGLSync, timeout: Int): Boolean {
return when (
val result = gl.check { gl.webgl.clientWaitSync(fence, 0, timeout) }
) {
WebGL2RenderingContext.ALREADY_SIGNALED -> true
WebGL2RenderingContext.TIMEOUT_EXPIRED -> false
WebGL2RenderingContext.CONDITION_SATISFIED -> true
WebGL2RenderingContext.WAIT_FAILED -> false
else -> error("Unknown result $result.")
}
}
companion object {
private const val fenceTimeoutMs = 5000
private const val delayBetweenSyncChecksMs = 3L
}
} | 88 | null | 6 | 40 | acdd13a4d34ebdcea0b7452bee6e187954db3fd0 | 4,786 | sparklemotion | MIT License |
android-app/src/main/java/com/github/aivanovski/testswithme/android/presentation/screens/flow/model/FlowState.kt | aivanovski | 815,197,496 | false | {"Kotlin": 800559, "Clojure": 13655, "Shell": 1883, "Scala": 850, "Dockerfile": 375} | package com.github.aivanovski.testswithme.android.presentation.screens.flow.model
import androidx.compose.runtime.Immutable
import com.github.aivanovski.testswithme.android.entity.ErrorMessage
import com.github.aivanovski.testswithme.android.presentation.core.cells.BaseCellViewModel
import com.github.aivanovski.testswithme.android.presentation.core.cells.screen.CellsScreenState
import com.github.aivanovski.testswithme.android.presentation.core.cells.screen.TerminalState
import com.github.aivanovski.testswithme.android.presentation.core.compose.dialogs.model.MessageDialogState
@Immutable
data class FlowState(
override val terminalState: TerminalState? = null,
override val viewModels: List<BaseCellViewModel> = emptyList(),
val errorDialogMessage: ErrorMessage? = null,
val flowDialogState: MessageDialogState? = null
) : CellsScreenState | 0 | Kotlin | 0 | 0 | 0366b4dc9afc396dcb782c2bf1cb8ad230895a18 | 863 | tests-with-me | Apache License 2.0 |
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinUSuperExpression.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.kotlin
import org.jetbrains.kotlin.psi.KtSuperExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UIdentifier
import org.jetbrains.uast.USuperExpression
import org.jetbrains.uast.kotlin.declarations.KotlinUIdentifier
import org.jetbrains.uast.kotlin.internal.DelegatedMultiResolve
class KotlinUSuperExpression(
override val sourcePsi: KtSuperExpression,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent), USuperExpression, DelegatedMultiResolve, KotlinUElementWithType, KotlinEvaluatableUElement {
override val label: String?
get() = sourcePsi.getLabelName()
override val labelIdentifier: UIdentifier?
get() = sourcePsi.getTargetLabel()?.let { KotlinUIdentifier(it, this) }
override fun resolve() = sourcePsi.analyze()[BindingContext.LABEL_TARGET, sourcePsi.getTargetLabel()]
} | 191 | null | 4372 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 1,099 | intellij-community | Apache License 2.0 |
app/src/main/java/ws/idroid/worldstatus/data/model/CovidOverview.kt | mabualzait | 250,814,252 | false | null | package ws.idroid.worldstatus.data.model
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
/**
* <NAME> 04/03/20.
*/
data class CovidOverview(
@Expose @SerializedName("confirmed") val confirmed: CovidOverviewItem? = null,
@Expose @SerializedName("recovered") val recovered: CovidOverviewItem? = null,
@Expose @SerializedName("deaths") val deaths: CovidOverviewItem? = null
) | 0 | Kotlin | 0 | 3 | 958751c4a09664402317630142733f3c97bd4de9 | 436 | Covid-19-Android | Apache License 2.0 |
compiler/cli/cli-common/src/org/jetbrains/kotlin/cli/common/messages/CompilerMessageLocation.kt | AlexeyTsvetkov | 17,321,988 | false | null | /*
* Copyright 2010-2015 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.cli.common.messages
import java.io.Serializable
data class CompilerMessageLocation private constructor(
val path: String?,
val line: Int,
val column: Int,
val lineContent: String?
) : Serializable {
override fun toString(): String =
path + (if (line != -1 || column != -1) " ($line:$column)" else "")
companion object {
@JvmField val NO_LOCATION: CompilerMessageLocation = CompilerMessageLocation(null, -1, -1, null)
@JvmStatic fun create(
path: String?,
line: Int,
column: Int,
lineContent: String?
): CompilerMessageLocation =
if (path == null) NO_LOCATION else CompilerMessageLocation(path, line, column, lineContent)
private val serialVersionUID: Long = 8228357578L
}
}
| 1 | null | 0 | 2 | 72a84083fbe50d3d12226925b94ed0fe86c9d794 | 1,478 | kotlin | Apache License 2.0 |
ui/ui-core/integration-tests/ui-core-demos/src/main/java/androidx/ui/core/demos/focus/FocusableDemo.kt | arkivanov | 288,587,741 | false | null | /*
* Copyright 2019 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.ui.core.demos.focus
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.state
import androidx.ui.core.Modifier
import androidx.ui.core.focus.ExperimentalFocus
import androidx.ui.core.gesture.tapGestureFilter
import androidx.ui.core.focus.FocusRequester
import androidx.ui.core.focus.focus
import androidx.ui.core.focus.focusObserver
import androidx.ui.core.focus.focusRequester
import androidx.ui.core.focus.isFocused
import androidx.compose.foundation.Text
import androidx.compose.ui.graphics.Color.Companion.Black
import androidx.compose.ui.graphics.Color.Companion.Green
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxWidth
@Composable
fun FocusableDemo() {
Column(
verticalArrangement = Arrangement.SpaceEvenly
) {
CenteredRow {
Text("Click on any focusable to bring it into focus:")
}
CenteredRow {
FocusableText("Focusable 1")
}
CenteredRow {
FocusableText("Focusable 2")
}
CenteredRow {
FocusableText("Focusable 3")
}
}
}
@Composable
@OptIn(ExperimentalFocus::class)
private fun FocusableText(text: String) {
var color by state { Black }
val focusRequester = FocusRequester()
Text(
modifier = Modifier
.focusRequester(focusRequester)
.focusObserver { color = if (it.isFocused) Green else Black }
.focus()
.tapGestureFilter { focusRequester.requestFocus() },
text = text,
color = color
)
}
@Composable
private fun CenteredRow(children: @Composable RowScope.() -> Unit) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
children = children
)
} | 0 | null | 0 | 1 | 549e3e3003cd308939ff31799cf1250e86d3e63e | 2,681 | androidx | MIT License |
data/episodes/implementation/src/commonMain/kotlin/com/thomaskioko/tvmaniac/episodes/implementation/EpisodeRepositoryImpl.kt | c0de-wizard | 361,393,353 | false | null | package com.thomaskioko.tvmaniac.episodes.implementation
import com.thomaskioko.tvmaniac.episodes.api.EpisodeRepository
import me.tatarka.inject.annotations.Inject
@Inject class EpisodeRepositoryImpl : EpisodeRepository
| 9 | Kotlin | 28 | 98 | 8bc3853d84c58520dffe26ddb260a2e7b6482ae9 | 222 | tv-maniac | Apache License 2.0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.