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
watari-codec-pmp/src/main/kotlin/tv/dotstart/watari/protocol/pmp/message/request/v0/reader/AbstractPortMappingRequestReader.kt
dotStart
517,175,816
false
null
/* * Copyright 2022 Johannes Donath <[email protected]> * and other copyright owners as documented in the project's IP log. * * 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 tv.dotstart.watari.protocol.pmp.message.request.v0.reader import tv.dotstart.watari.protocol.pmp.message.request.reader.RequestReader import tv.dotstart.watari.protocol.pmp.message.request.v0.PortMappingRequest import tv.dotstart.watari.protocol.pmp.message.wire.WireRequest import java.net.InetSocketAddress import java.time.Duration /** * Provides a basis for request readers which decode the POKO representations of port mapping * requests. * * @author Johannes Donath * @date 08/07/2022 */ abstract class AbstractPortMappingRequestReader<out DM : PortMappingRequest> : RequestReader<DM> { companion object { /** * Defines the minimum amount of bytes required within a valid wire representation for a port * mapping request. * * Port mapping requests (regardless of protocol type) always contain the following 3 fields: * * - Internal Port * - Suggested External Port * - Time To Live (in Seconds) */ private const val MIN_BYTES = 2 + 2 + 4 } override fun decode(msg: WireRequest): DM { require(msg.version == 0u.toUByte()) { "Expected v1 request but got v${msg.version}" } with(msg.content()) { require( isReadable( MIN_BYTES ) ) { "Expected at least $MIN_BYTES bytes within mapping request but got ${readableBytes()}" } val internalPort = readShort().toUShort() val suggestedExternalPort = readShort().toUShort() .takeIf { it != 0u.toUShort() } val timeToLive = Duration.ofSeconds(readUnsignedInt()) return create(msg.sender(), msg.recipient(), internalPort, suggestedExternalPort, timeToLive) } } protected abstract fun create( sender: InetSocketAddress, recipient: InetSocketAddress, internalPort: UShort, suggestedExternalPort: UShort?, timeToLive: Duration ): DM }
0
Kotlin
0
0
13214a53df9d144c6e0c81e543b4f2a0326bc6c8
2,561
watari
Apache License 2.0
shared/ui-widget/src/main/java/ru/maksonic/rdcompose/shared/ui_widget/viewstate/LoadingViewState.kt
maksonic
495,363,119
false
{"Kotlin": 352101}
package ru.maksonic.rdcompose.shared.ui_widget.viewstate import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.Icon import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import ru.maksonic.rdcompose.shared.theme.theme.RDTheme import ru.maksonic.rdcompose.shared.ui_widget.R /** * @Author maksonic on 26.05.2022 */ @Composable fun LoadingViewState(modifier: Modifier = Modifier) { val innerModifier = Modifier Box( modifier.fillMaxSize().background(RDTheme.color.background), contentAlignment = Alignment.Center ) { CircularProgressIndicator( innerModifier.size(RDTheme.componentSize.circularProgressIndicatorSize), color = RDTheme.color.primary, strokeWidth = RDTheme.componentSize.circularProgressIndicatorStrokeWidth ) Icon( painterResource(R.drawable.ic_rd_filled), tint = RDTheme.color.primary, modifier = innerModifier.size(50.dp), contentDescription = "" ) } }
0
Kotlin
1
1
97e59162c3a6ea94c69f8c337666edbe22f53c7c
1,394
RDCompose
MIT License
plugins/analysis/common/src/main/kotlin/arrow/meta/plugins/analysis/smt/utils/FormulaToKotlin.kt
arrow-kt
217,378,939
false
null
package arrow.meta.plugins.analysis.smt.utils import arrow.meta.plugins.analysis.smt.Solver import org.sosy_lab.java_smt.api.Formula import org.sosy_lab.java_smt.api.FormulaManager import org.sosy_lab.java_smt.api.FunctionDeclaration import org.sosy_lab.java_smt.api.FunctionDeclarationKind import org.sosy_lab.java_smt.api.visitors.DefaultFormulaVisitor interface KotlinPrinter { fun Formula.dumpKotlinLike(): String fun mirroredElement(name: String): ReferencedElement? } internal class DefaultKotlinPrinter( private val fmgr: FormulaManager, private val nameProvider: NameProvider ) : KotlinPrinter { override fun mirroredElement(name: String): ReferencedElement? = nameProvider.mirroredElement(name) override fun Formula.dumpKotlinLike(): String { val str = StringBuilder() fmgr.visit(this, KotlinPrintVisitor(fmgr, str, nameProvider, false, false)) return str.toString() } private data class KotlinPrintVisitor( private val fmgr: FormulaManager, private val out: StringBuilder, private val nameProvider: NameProvider, private val parensContext: Boolean, private val negatedContext: Boolean ) : DefaultFormulaVisitor<Void?>() { override fun visitDefault(pF: Formula): Void? { if (negatedContext) out.append('!') val text = nameProvider.mirroredElement(pF.toString())?.element?.text ?: pF.toString() val needsParens = (parensContext || negatedContext) && text.contains(' ') if (needsParens) out.append('(') out.append(text) if (needsParens) out.append(')') return null } private enum class Render { Negation, Postfix, Binary, Hidden, Field, Unsupported } private fun FunctionDeclaration<*>.toKotlin(): Triple<Render, String, String?> = when (kind) { FunctionDeclarationKind.NOT -> Triple(Render.Negation, "!", null) FunctionDeclarationKind.AND -> Triple(Render.Binary, "&&", null) FunctionDeclarationKind.OR -> Triple(Render.Binary, "||", null) FunctionDeclarationKind.SUB -> Triple(Render.Binary, "-", null) FunctionDeclarationKind.ADD -> Triple(Render.Binary, "+", null) FunctionDeclarationKind.DIV -> Triple(Render.Binary, "/", null) FunctionDeclarationKind.MUL -> Triple(Render.Binary, "*", null) FunctionDeclarationKind.LT -> Triple(Render.Binary, "<", ">=") FunctionDeclarationKind.LTE -> Triple(Render.Binary, "<=", ">") FunctionDeclarationKind.GT -> Triple(Render.Binary, ">", "<=") FunctionDeclarationKind.GTE -> Triple(Render.Binary, ">=", "<") FunctionDeclarationKind.EQ -> Triple(Render.Binary, "==", "!=") FunctionDeclarationKind.UF -> when (name) { Solver.INT_VALUE_NAME -> Triple(Render.Hidden, "", null) Solver.BOOL_VALUE_NAME -> Triple(Render.Hidden, "", null) Solver.DECIMAL_VALUE_NAME -> Triple(Render.Hidden, "", null) Solver.FIELD_FUNCTION_NAME -> Triple(Render.Field, name, null) Solver.IS_NULL_FUNCTION_NAME -> Triple(Render.Postfix, " == null", " != null") else -> Triple(Render.Unsupported, "[unsupported UF: $name]", null) } else -> Triple(Render.Unsupported, "[unsupported: $this]", null) } override fun visitFunction( pF: Formula, pArgs: List<Formula>, pFunctionDeclaration: FunctionDeclaration<*> ): Void? { val (render, name, negatedName) = pFunctionDeclaration.toKotlin() when (render) { Render.Hidden, Render.Unsupported -> { pArgs.forEach { arg -> fmgr.visit(arg, this) } } Render.Negation -> { fmgr.visit(pArgs[0], this.copy(negatedContext = !negatedContext)) } else -> { val mustBeNegated = negatedContext && negatedName == null val needsParens = parensContext || mustBeNegated val nameToShow = if (negatedContext && negatedName != null) negatedName else name if (mustBeNegated) out.append('!') if (needsParens) out.append('(') when (render) { Render.Postfix -> { fmgr.visit(pArgs[0], this.copy(parensContext = false, negatedContext = false)) out.append(nameToShow) } Render.Binary -> { fmgr.visit(pArgs[0], this.copy(parensContext = true, negatedContext = false)) out.append(' ') out.append(nameToShow) out.append(' ') fmgr.visit(pArgs[1], this.copy(parensContext = true, negatedContext = false)) } Render.Field -> { fmgr.visit(pArgs[1], this.copy(parensContext = false, negatedContext = false)) out.append(".") out.append(pArgs[0].toString().substringAfterLast(".")) } else -> {} // taken care of above } if (needsParens) out.append(')') } } return null } } }
99
Kotlin
40
316
8d2a80cf3a1275a752c18baceed74cb61aa13b4d
5,009
arrow-meta
Apache License 2.0
server/world/src/main/kotlin/event/GameEvent.kt
Guthix
270,323,476
false
null
/* * Copyright 2018-2021 Guthix * * 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.guthix.oldscape.server.event import io.guthix.oldscape.server.world.World import io.guthix.oldscape.server.world.entity.Character import io.guthix.oldscape.server.world.entity.Npc import io.guthix.oldscape.server.world.entity.Player interface Event abstract class GameEvent(open val world: World) : Event abstract class PlayerGameEvent(open val player: Player, world: World) : GameEvent(world) abstract class NpcGameEvent(open val npc: Npc, world: World) : GameEvent(world) abstract class CharacterGameEvent(open val character: Character, world: World) : GameEvent(world)
2
null
9
43
bbf40d18940a12155a33341a1c99ba47289b8e2a
1,180
OldScape
Apache License 2.0
ktor-client/ktor-client-tests/jvm/test/io/ktor/client/tests/MultithreadedTest.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.tests import io.ktor.client.call.* import io.ktor.client.request.* import io.ktor.client.tests.utils.* import kotlinx.coroutines.* import java.util.concurrent.* import kotlin.test.* private const val TEST_SIZE = 100_000 private const val DEFAULT_THREADS_COUNT = 32 class MultithreadedTest : ClientLoader() { @Test fun numberTest() = clientTests { config { engine { pipelining = true } } test { client -> val result = withPool { client.get("$TEST_SERVER/multithreaded").body<Int>() }.toSet().size assertEquals(TEST_SIZE, result) } } } private fun <T> withPool( threads: Int = DEFAULT_THREADS_COUNT, testSize: Int = TEST_SIZE, block: suspend () -> T ): List<T> { val pool = Executors.newFixedThreadPool(threads) val result = List(testSize) { pool.submit( Callable<T> { runBlocking { block() } } ) }.map { it.get() } pool.shutdown() assertTrue(pool.awaitTermination(1, TimeUnit.SECONDS)) return result }
303
null
806
9,709
9e0eb99aa2a0a6bc095f162328525be1a76edb21
1,284
ktor
Apache License 2.0
build-attribution/testSrc/com/android/build/attribution/ui/BuildAttributionUiManagerTest.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 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 com.android.build.attribution.ui import com.android.build.attribution.ui.analytics.BuildAttributionUiAnalytics import com.android.build.attribution.ui.data.BuildAttributionReportUiData import com.android.build.attribution.ui.data.builder.AbstractBuildAttributionReportBuilderTest import com.android.build.attribution.ui.data.builder.BuildAttributionReportBuilder import com.android.testutils.VirtualTimeScheduler import com.android.tools.analytics.TestUsageTracker import com.android.tools.analytics.UsageTracker import com.google.common.truth.Truth import com.google.wireless.android.sdk.stats.AndroidStudioEvent import com.google.wireless.android.sdk.stats.BuildAttributionUiEvent import com.intellij.build.BuildContentManager import com.intellij.build.BuildContentManagerImpl import com.intellij.openapi.util.Disposer import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.impl.ToolWindowHeadlessManagerImpl import com.intellij.testFramework.PlatformTestUtil import com.intellij.ui.content.impl.ContentImpl import org.jetbrains.android.AndroidTestCase import java.util.* import javax.swing.JPanel class BuildAttributionUiManagerTest : AndroidTestCase() { private lateinit var windowManager: ToolWindowManager private val tracker = TestUsageTracker(VirtualTimeScheduler()) private lateinit var buildAttributionUiManager: BuildAttributionUiManagerImpl private lateinit var reportUiData: BuildAttributionReportUiData private lateinit var buildSessionId: String override fun setUp() { super.setUp() UsageTracker.setWriterForTest(tracker) windowManager = ToolWindowHeadlessManagerImpl(project) registerProjectService(ToolWindowManager::class.java, windowManager) registerProjectService(BuildContentManager::class.java, BuildContentManagerImpl(project)) // Add a fake build tab project.getService(BuildContentManager::class.java).addContent( ContentImpl(JPanel(), BuildContentManagerImpl.Build_Tab_Title_Supplier.get(), true) ) buildAttributionUiManager = BuildAttributionUiManagerImpl(project) reportUiData = BuildAttributionReportBuilder(AbstractBuildAttributionReportBuilderTest.MockResultsProvider(), 0).build() buildSessionId = UUID.randomUUID().toString() } override fun tearDown() { UsageTracker.cleanAfterTesting() super.tearDown() } fun testShowNewReport() { setNewReportData(reportUiData, buildSessionId) verifyBuildAnalyzerTabExist() verifyBuildAnalyzerTabNotSelected() // Verify state Truth.assertThat(buildAttributionUiManager.buildAttributionView).isNotNull() Truth.assertThat(buildAttributionUiManager.buildContent).isNotNull() // Verify metrics sent val buildAttributionEvents = tracker.usages.filter { use -> use.studioEvent.kind == AndroidStudioEvent.EventKind.BUILD_ATTRIBUTION_UI_EVENT } Truth.assertThat(buildAttributionEvents).hasSize(1) val buildAttributionUiEvent = buildAttributionEvents.first().studioEvent.buildAttributionUiEvent Truth.assertThat(buildAttributionUiEvent.buildAttributionReportSessionId).isEqualTo(buildSessionId) Truth.assertThat(buildAttributionUiEvent.eventType).isEqualTo(BuildAttributionUiEvent.EventType.TAB_CREATED) } fun testOnBuildFailureWhenTabClosed() { sendOnBuildFailure(buildSessionId) verifyBuildAnalyzerTabNotExist() // Verify state Truth.assertThat(buildAttributionUiManager.buildAttributionView).isNull() Truth.assertThat(buildAttributionUiManager.buildContent).isNull() // Verify no metrics sent val buildAttributionEvents = tracker.usages.filter { use -> use.studioEvent.kind == AndroidStudioEvent.EventKind.BUILD_ATTRIBUTION_UI_EVENT } Truth.assertThat(buildAttributionEvents).isEmpty() } fun testShowNewReportAndOpenWithLink() { setNewReportData(reportUiData, buildSessionId) openBuildAnalyzerTabFromAction() verifyBuildAnalyzerTabExist() verifyBuildAnalyzerTabSelected() // Verify metrics sent val buildAttributionEvents = tracker.usages.filter { use -> use.studioEvent.kind == AndroidStudioEvent.EventKind.BUILD_ATTRIBUTION_UI_EVENT } Truth.assertThat(buildAttributionEvents).hasSize(2) buildAttributionEvents[1].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.TAB_OPENED_WITH_BUILD_OUTPUT_LINK) } } fun testShowNewReportAndOpenWithTabClick() { setNewReportData(reportUiData, buildSessionId) selectBuildAnalyzerTab() verifyBuildAnalyzerTabExist() verifyBuildAnalyzerTabSelected() // Verify metrics sent val buildAttributionEvents = tracker.usages.filter { use -> use.studioEvent.kind == AndroidStudioEvent.EventKind.BUILD_ATTRIBUTION_UI_EVENT } Truth.assertThat(buildAttributionEvents).hasSize(2) buildAttributionEvents[1].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.TAB_OPENED_WITH_TAB_CLICK) } } fun testContentTabClosed() { setNewReportData(reportUiData, buildSessionId) // Get the reference to check the state later val buildAttributionTreeView = buildAttributionUiManager.buildAttributionView!! closeBuildAnalyzerTab() verifyBuildAnalyzerTabNotExist() // Verify metrics sent val buildAttributionEvents = tracker.usages.filter { use -> use.studioEvent.kind == AndroidStudioEvent.EventKind.BUILD_ATTRIBUTION_UI_EVENT } Truth.assertThat(buildAttributionEvents).hasSize(2) buildAttributionEvents[1].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.TAB_CLOSED) } // Verify state cleaned up Truth.assertThat(Disposer.isDisposed(buildAttributionTreeView)).isTrue() Truth.assertThat(buildAttributionUiManager.buildAttributionView).isNull() Truth.assertThat(buildAttributionUiManager.buildContent).isNull() } fun testReplaceReportWithSecondOne() { val buildSessionId1 = UUID.randomUUID().toString() val buildSessionId2 = UUID.randomUUID().toString() val buildSessionId3 = UUID.randomUUID().toString() setNewReportData(reportUiData, buildSessionId1) setNewReportData(reportUiData, buildSessionId2) closeBuildAnalyzerTab() setNewReportData(reportUiData, buildSessionId3) verifyBuildAnalyzerTabExist() // Verify metrics sent val buildAttributionEvents = tracker.usages.filter { use -> use.studioEvent.kind == AndroidStudioEvent.EventKind.BUILD_ATTRIBUTION_UI_EVENT } Truth.assertThat(buildAttributionEvents).hasSize(6) buildAttributionEvents[0].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId1) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.TAB_CREATED) } buildAttributionEvents[1].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId1) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.USAGE_SESSION_OVER) } buildAttributionEvents[2].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId2) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.CONTENT_REPLACED) } buildAttributionEvents[3].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId2) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.TAB_CLOSED) } buildAttributionEvents[4].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId2) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.USAGE_SESSION_OVER) } buildAttributionEvents[5].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId3) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.TAB_CREATED) } } fun testOnBuildFailureWhenOpened() { val buildSessionId1 = UUID.randomUUID().toString() val buildSessionId2 = UUID.randomUUID().toString() setNewReportData(reportUiData, buildSessionId1) sendOnBuildFailure(buildSessionId2) verifyBuildAnalyzerTabExist() // Verify state Truth.assertThat(buildAttributionUiManager.buildAttributionView).isNotNull() Truth.assertThat(buildAttributionUiManager.buildAttributionView?.component?.name).isEqualTo("Build failure empty view") Truth.assertThat(buildAttributionUiManager.buildContent).isNotNull() // Verify metrics sent val buildAttributionEvents = tracker.usages.filter { use -> use.studioEvent.kind == AndroidStudioEvent.EventKind.BUILD_ATTRIBUTION_UI_EVENT } Truth.assertThat(buildAttributionEvents).hasSize(3) buildAttributionEvents[0].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId1) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.TAB_CREATED) } buildAttributionEvents[1].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId1) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.USAGE_SESSION_OVER) } buildAttributionEvents[2].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId2) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.CONTENT_REPLACED) } } fun testReportTabSelectedAndUnselected() { setNewReportData(reportUiData, buildSessionId) verifyBuildAnalyzerTabExist() selectBuildAnalyzerTab() selectBuildTab() selectBuildAnalyzerTab() verifyBuildAnalyzerTabSelected() // Verify metrics sent val buildAttributionEvents = tracker.usages.filter { use -> use.studioEvent.kind == AndroidStudioEvent.EventKind.BUILD_ATTRIBUTION_UI_EVENT } Truth.assertThat(buildAttributionEvents).hasSize(4) buildAttributionEvents[1].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.TAB_OPENED_WITH_TAB_CLICK) } buildAttributionEvents[2].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.TAB_HIDDEN) } buildAttributionEvents[3].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.TAB_OPENED_WITH_TAB_CLICK) } } fun testBuildOutputLinkClickAfterTabUnselected() { setNewReportData(reportUiData, buildSessionId) verifyBuildAnalyzerTabExist() selectBuildAnalyzerTab() selectBuildTab() openBuildAnalyzerTabFromAction() verifyBuildAnalyzerTabSelected() // Verify metrics sent val buildAttributionEvents = tracker.usages.filter { use -> use.studioEvent.kind == AndroidStudioEvent.EventKind.BUILD_ATTRIBUTION_UI_EVENT } Truth.assertThat(buildAttributionEvents).hasSize(4) buildAttributionEvents[1].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.TAB_OPENED_WITH_TAB_CLICK) } buildAttributionEvents[2].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.TAB_HIDDEN) } buildAttributionEvents[3].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.TAB_OPENED_WITH_BUILD_OUTPUT_LINK) } } fun testBuildOutputLinkClickAfterTabClosed() { setNewReportData(reportUiData, buildSessionId) closeBuildAnalyzerTab() openBuildAnalyzerTabFromAction() verifyBuildAnalyzerTabExist() // Verify metrics sent val buildAttributionEvents = tracker.usages.filter { use -> use.studioEvent.kind == AndroidStudioEvent.EventKind.BUILD_ATTRIBUTION_UI_EVENT } Truth.assertThat(buildAttributionEvents).hasSize(4) buildAttributionEvents[1].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.TAB_CLOSED) } buildAttributionEvents[2].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.TAB_CREATED) } buildAttributionEvents[3].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.TAB_OPENED_WITH_BUILD_OUTPUT_LINK) } // Verify manager state Truth.assertThat(buildAttributionUiManager.buildAttributionView).isNotNull() Truth.assertThat(Disposer.isDisposed(buildAttributionUiManager.buildAttributionView!!)).isFalse() Truth.assertThat(buildAttributionUiManager.buildContent).isNotNull() } fun testRequestShowWhenReadyBeforeDataExist() { requestOpenWhenDataReady() verifyBuildAnalyzerTabNotExist() setNewReportData(reportUiData, buildSessionId) verifyBuildAnalyzerTabExist() // Since we requested to open earlier tab should be opened now. verifyBuildAnalyzerTabSelected() // Verify metrics sent val buildAttributionEvents = tracker.usages.filter { use -> use.studioEvent.kind == AndroidStudioEvent.EventKind.BUILD_ATTRIBUTION_UI_EVENT } Truth.assertThat(buildAttributionEvents).hasSize(2) buildAttributionEvents[1].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.TAB_OPENED_WITH_WNA_BUTTON) } } fun testRequestShowWhenReadyAfterDataExist() { setNewReportData(reportUiData, buildSessionId) requestOpenWhenDataReady() verifyBuildAnalyzerTabExist() verifyBuildAnalyzerTabSelected() // Verify metrics sent val buildAttributionEvents = tracker.usages.filter { use -> use.studioEvent.kind == AndroidStudioEvent.EventKind.BUILD_ATTRIBUTION_UI_EVENT } Truth.assertThat(buildAttributionEvents).hasSize(2) buildAttributionEvents[1].studioEvent.buildAttributionUiEvent.let { Truth.assertThat(it.buildAttributionReportSessionId).isEqualTo(buildSessionId) Truth.assertThat(it.eventType).isEqualTo(BuildAttributionUiEvent.EventType.TAB_OPENED_WITH_WNA_BUTTON) } } fun testProjectCloseBeforeAnyBuildFinished() { // Regression test for b/147449711. // Calling disposeRootDisposable() before would result in an NullPointerException exception being thrown in metrics sending logic // because it tried to send a session end event even though no data have been shown yet (thus no session exist to be ended). disposeRootDisposable() } private fun openBuildAnalyzerTabFromAction() { buildAttributionUiManager.openTab(BuildAttributionUiAnalytics.TabOpenEventSource.BUILD_OUTPUT_LINK) PlatformTestUtil.dispatchAllInvocationEventsInIdeEventQueue() } private fun setNewReportData(reportUiData: BuildAttributionReportUiData, buildSessionId: String) { buildAttributionUiManager.showNewReport(reportUiData, buildSessionId) PlatformTestUtil.dispatchAllInvocationEventsInIdeEventQueue() } private fun sendOnBuildFailure(buildSessionId: String) { buildAttributionUiManager.onBuildFailure(buildSessionId) PlatformTestUtil.dispatchAllInvocationEventsInIdeEventQueue() } private fun requestOpenWhenDataReady() { buildAttributionUiManager.requestOpenTabWhenDataReady(BuildAttributionUiAnalytics.TabOpenEventSource.WNA_BUTTON) PlatformTestUtil.dispatchAllInvocationEventsInIdeEventQueue() } private fun selectBuildTab() { contentManager().let { it.setSelectedContent(it.findContent(BuildContentManagerImpl.Build_Tab_Title_Supplier.get())) } } private fun selectBuildAnalyzerTab() = contentManager().let { it.setSelectedContent(it.findContent("Build Analyzer")) } private fun closeBuildAnalyzerTab() { contentManager().removeContent(contentManager().findContent("Build Analyzer"), true) } private fun verifyBuildAnalyzerTabExist() = Truth.assertThat(contentManager().findContent("Build Analyzer")).isNotNull() private fun verifyBuildAnalyzerTabNotExist() = Truth.assertThat(contentManager().findContent("Build Analyzer")).isNull() private fun verifyBuildAnalyzerTabSelected() = Truth.assertThat(contentManager().findContent("Build Analyzer").isSelected).isTrue() private fun verifyBuildAnalyzerTabNotSelected() = Truth.assertThat(contentManager().findContent("Build Analyzer").isSelected).isFalse() private fun contentManager() = windowManager.getToolWindow(BuildContentManagerImpl.Build_Tab_Title_Supplier.get())!!.contentManager }
0
null
187
751
16d17317f2c44ec46e8cd2180faf9c349d381a06
18,669
android
Apache License 2.0
android-sdk/src/main/java/webtrekk/android/sdk/Webtrekk.kt
mapp-digital
166,987,236
false
null
/* * MIT License * * Copyright (c) 2019 Webtrekk GmbH * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package webtrekk.android.sdk import android.content.Context import android.net.Uri import android.view.View import java.io.File import webtrekk.android.sdk.core.WebtrekkImpl import webtrekk.android.sdk.events.ActionEvent import webtrekk.android.sdk.events.MediaEvent import webtrekk.android.sdk.events.PageViewEvent /** * Webtrekk is a library used to collect your app usage, how your customers interacting with your app, * tracking specific pages and custom events. And send those data to Webtrekk analytics to be used * for further analysis. * * Abstract class and the entry point to start using [Webtrekk] trackers. * * Webtrekk internally, collects and caches the data that you specify for tracking, and later, it sends * those data to Webtrekk analytics in periodic time. * * As a matter of performance, Webtrekk uses [kotlinx.coroutines] for caching, collecting and sending * the data in the background (pool of threads). Hence, Webtrekk doesn't block the main thread. * * Webtrekk uses [androidx.work.WorkManager] for enqueueing the requests (cached data) and sending them in [Config.requestsInterval] * time in the background in order. It guarantees to send those data requests in periodic time even if your app is not in the background, * and that's for enhancing your app's usage battery and that you don't have to worry about the performance. * * You can configure the work manager constraints [Config.workManagerConstraints] like sending the requests if * the device is charging or when battery is not low. Check [DefaultConfiguration.WORK_MANAGER_CONSTRAINTS] * for the default constraints in case of you not adding your own constraints. * * To start using [Webtrekk], you must retrieve an instance first and then initialize the context [Context] * and the configurations [Config]. Without specifying the context nor the configurations first, webtrekk * will throw [IllegalStateException] upon invoking any method. * * A sample usage: * * val webtrekkConfigurations = WebtrekkConfiguration.Builder(trackIds = listOf("1234567"), trackDomain = "https://www.webtrekk.com") * .logLevel(Logger.Level.BASIC) * .requestsInterval(TimeUnit.MINUTES, 15) * .build() * * val webtrekk = Webtrekk.getInstance() * webtrekk.init(this, webtrekkConfigurations) * * *NOTE* auto tracking is enabled by default, so once you put this code in your [android.app.Application] class, * you will start receiving your app activities and fragments tracking data, getting cached, and will be sent to * Webtrekk analytics in [Config.requestsInterval] time. * * Since webtrekk internally uses [okhttp3.OkHttpClient] for networking, you could configure [okhttp3.OkHttpClient] * through the configurations. Hence, you could add your own certificate, interceptor and so on. * @see [DefaultConfiguration.OKHTTP_CLIENT] for the default OkHttpClient that is used by Webtrekk. * * A sample usage: * * val okHttpClientConfig = OkHttpClient.Builder() * .readTimeout(15, TimeUnit.SECONDS) * .addNetworkInterceptor(StethoInterceptor()) * .build() * * val webtrekkConfigurations = WebtrekkConfiguration.Builder(trackIds = listOf("1234567"), trackDomain = "https://www.webtrekk.com") * .logLevel(Logger.Level.BASIC) * .requestsInterval(TimeUnit.MINUTES, 15) * .okHttpClient(okHttpClient = okHttpClientConfig) * .build() * * *NOTE* make sure your app's manifest has the network permission * <uses-permission android:name="android.permission.INTERNET"/> * */ abstract class Webtrekk protected constructor() { /** * Initializes the [Context.getApplicationContext] context and [Config] Webtrekk's configurations * that will be used through the entire life of [Webtrekk] object. * * *NOTE* this method must be called once and first before invoking any other method. Invoking any other method * without initializing the context nor the configurations, will throw [IllegalStateException]. * * It's preferred to initialize in the [android.app.Application]. * * @param context object for the configurations. This class will call [Context.getApplicationContext] * so it's safely to pass any [Context] without risking a memory leak. * @param config an interface that is used to set up Webtrekk configurations. Use [WebtrekkConfiguration] * which is a concrete implementation of [Config] where you can set up all your configurations. */ abstract fun init(context: Context, config: Config) /** * Used as a manual tracking in case of disabling the auto tracking in [Config.autoTracking]. * Use this method to track a specific page [android.app.Activity] with optional overriding * the local class name and optional some extra tracking params. * * If auto tracking [Config.autoTracking] is enabled, then this function will return * immediately without sending its tracking data, alongside with a warning indicating that * auto tracking is enabled. * * @param context context of the current activity. * @param customPageName *optional* overrides the local class name of the activity. If set to null, then * the local class name of the activity in [context] will be used instead. * @param trackingParams *optional* the custom tracking params that are associated with the current page. * @see [Param] and [TrackingParams] for defining the custom params. * * @throws [IllegalStateException] if [Config] config is not initialized. */ abstract fun trackPage( context: Context, customPageName: String? = null, trackingParams: Map<String, String> = emptyMap() ) /** * Tracks a custom tracking page, with a custom tracking params. * Could be used alongside the auto tracking. * * @param pageName the custom page name that will be used for tracking. * @param trackingParams the custom tracking params that are associated with the custom tracking * page. @see [Param] and [TrackingParams] for setting up the custom params. * * @throws [IllegalStateException] if [Config] config is not initialized. */ abstract fun trackCustomPage(pageName: String, trackingParams: Map<String, String> = emptyMap()) /** * Tracks a specific custom event, with a custom tracking params. * * @param eventName the event name that will be used for tracking that specific event. * @param trackingParams the custom tracking params that are associated with this tracking event. * @see [Param] and [TrackingParams] for setting up the custom params. * * @throws [IllegalStateException] if [Config] config is not initialized. */ abstract fun trackCustomEvent( eventName: String, trackingParams: Map<String, String> = emptyMap() ) /** * Tracks a specific media event, witch custom media param and all other params. * @param mediaName the media name is name of the media file. * @param trackingParams the custom tracking params that are associated with media event and tracking event. * @see [MediaParam], [Param] and [TrackingParams] for setting up the custom params. * * @throws [IllegalStateException] if [Config] config is not initialized. */ abstract fun trackMedia( mediaName: String, trackingParams: Map<String, String> = emptyMap() ) abstract fun trackMedia( pageName: String, mediaName: String, trackingParams: Map<String, String> = emptyMap() ) /** * Tracks specific exception event. * @param exception the exception object that caused crash * @param exceptionType to internally decide if exception is of type [ExceptionType.CAUGHT] or [ExceptionType.CUSTOM] * @throws [IllegalStateException] if [Config] config is not initialized. */ internal abstract fun trackException( exception: Exception, exceptionType: ExceptionType ) /** * Tracks a specific exception event, can be used for all types of the exceptions. * @param exception is used for handled exception. * @throws [IllegalStateException] if [Config] config is not initialized. */ abstract fun trackException( exception: Exception ) /** * Tracks a custom exception can be used for testing or send some critical exception. * @param name custom name of the exception. * @param message custom message can be exception stacktrace or message. * @throws [IllegalStateException] if [Config] config is not initialized. */ abstract fun trackException( name: String, message: String ) /** * Tracks uncaught exception. * @param file file where uncaught exception handler saved throwable that caused app to crash * @throws [IllegalStateException] if [Config] config is not initialized. */ internal abstract fun trackException( file: File ) /** * Tracks a specific form events, in background we will take all import value from the view. * @param context context of the current activity. * @param view *optional* overrides the local view used in activity * @param formTrackingSettings *optional* contain additional settings for the form tracking * */ abstract fun formTracking( context: Context, view: View? = null, formTrackingSettings: FormTrackingSettings = FormTrackingSettings() ) /** * Method which will track campaign parameters from url * @param url url object with campaign parameters * @param mediaCode *optional* mediaCode - custom media code, if nil "wt_mc" is used as default */ abstract fun trackUrl( url: Uri, mediaCode: String? = null ) abstract fun trackPage( page: PageViewEvent ) abstract fun trackAction( action: ActionEvent ) abstract fun trackMedia( media: MediaEvent ) /** * Allows to opt out entirely from tracking. Internally, calling this method will cause to delete * all the current tracking data that are cached in the database (if sendCurrentData is false), * canceling sending requests, shutting down work manager's worker and disabling all incoming tracking requests. * * To stop opting out, you have to set [optOut(false)]. * * In case there are some data already in the cache, and it's desirable to send them before * deleting all the data, set sendCurrentData to true, this allows to send first all current * requests in the cache, then delete everything. * * @param value set it to true to opt out, false to cancel. * @param sendCurrentData set it to true, to send current data in cache before deleting them. * * @throws [IllegalStateException] if [Context] context is not initialized. */ abstract fun optOut(value: Boolean, sendCurrentData: Boolean = false) /** * Returns [Boolean] true if the user is opt'd-out, false otherwise. * * @throws [IllegalStateException] if [Context] context is not initialized. */ abstract fun hasOptOut(): Boolean /** * Returns [String] the user ever id which is associated per each unique user. * * @throws [IllegalStateException] if [Context] context is not initialized. */ abstract fun getEverId(): String /** * This function can be used to change trackingId and Domain in one session * If need to keep same settings engage function must be changed * * @param * The [trackIds] that you get in your Webtrekk's account. [trackIds] must be set in the configuration, * otherwise webtrekk won't send any tracking data. * @param [trackDomain] domain that all the analytics data will be sent to. Make sure it's a valid domain. * @throws [IllegalStateException] if [Context] context is not initialized. */ abstract fun setIdsAndDomain(trackIds: List<String>, trackDomain: String) abstract fun getTrackIds():List<String> abstract fun getTrackDomain():String /** * Returns [String] the user Agent which is associated per each unique device. * * @throws [IllegalStateException] if [Context] context is not initialized. */ abstract fun getUserAgent(): String /** * Due to GDPR and other privacy regulations, someone might want to track without user recognition. * Limitations: Enabling this option will significantly decrease data quality! It is only recommended if no other option exists to comply to data privacy regulations * * @param enabled set it to true we will disable user recognition, and to false it will enable. * @param suppressParams this can disable any other parameter alongside the everID. * @param generateNewEverId true is by default. If you like to keep previous id then change it to false * * @throws [IllegalStateException] if [Context] context is not initialized. */ abstract fun anonymousTracking( enabled: Boolean = true, suppressParams: Set<String> = emptySet(), generateNewEverId: Boolean = true ) /** * Start immediate request sending and cleaning after requests are successfully sent */ abstract fun sendRequestsNowAndClean() /** * Check if batch is enabled in the Webtrekk configuration */ abstract fun isBatchEnabled(): Boolean /** * Set batch enabled or disabled after initialization */ abstract fun setBatchEnabled(enabled: Boolean) /** * Get number of track records sent in one batch */ abstract fun getRequestsPerBatch():Int /** * Set count of track records to be sent in one batch */ abstract fun setRequestPerBatch(requestsCount:Int) /** * Get exception tracking mode */ abstract fun getExceptionLogLevel():ExceptionType /** * Set exception tracking mode */ abstract fun setExceptionLogLevel(exceptionType: ExceptionType) /** * Reset SDK configuration, clean all saved settings */ internal abstract fun clearSdkConfig() /** * Reset everId in runtime, after initialization. * * If null or empty string provided, new everId will be generated and set */ abstract fun setEverId(everId:String?) /** * Enable or disable sending app version in every request */ abstract fun setVersionInEachRequest(enabled: Boolean) /** * Check if app version is set to be sent in every request or not */ abstract fun getVersionInEachRequest():Boolean /** * Chck if SDK is initialized */ abstract fun isInitialized():Boolean companion object { /** * Retrieves a singleton instance of [Webtrekk]. * * To start integrating with [Webtrekk] you must get instance of Webtrekk first. */ @JvmStatic fun getInstance(): Webtrekk { return WebtrekkImpl.getInstance() } /** * Resets all configuration for SDK. After this call client must initialize SDK with new configuration. */ @JvmStatic fun reset(context: Context) { WebtrekkImpl.reset(context) } } }
2
null
2
13
f493dfe7e85591e6806fa3a94c50e394eda3cb60
16,494
webtrekk-android-sdk-v5
MIT License
app/src/main/java/org/bxkr/octodiary/screens/navsections/daybook/CalendarRow.kt
OctoDiary
474,135,407
false
{"Kotlin": 608205}
package org.bxkr.octodiary.screens.navsections.daybook import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.onPlaced import androidx.compose.ui.layout.positionInParent import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.toSize import org.bxkr.octodiary.formatToDay import java.util.Calendar import java.util.Collections import java.util.Date import kotlin.math.roundToInt @Composable fun CalendarRow( date: Calendar, daySelected: State<Date>, onDaySelect: (Date) -> Unit, modifier: Modifier = Modifier, ) { val weekdays = remember { (1..7).toList().also { Collections.rotate(it, -1) } } var selectedPositionX: Float by remember { mutableFloatStateOf(0f) } val selectedPosition = animateFloatAsState(selectedPositionX) var cellSize by remember { mutableStateOf<IntSize?>(null) } Box(modifier.padding(horizontal = 8.dp)) { val density = LocalDensity.current Box( Modifier .offset { IntOffset(selectedPosition.value.roundToInt(), 0) } .size(with(density) { (cellSize ?: IntSize(0, 0)) .toSize() .toDpSize() }) .border( 2.dp, MaterialTheme.colorScheme.secondary, MaterialTheme.shapes.medium, ) ) Row { weekdays.forEach { weekday -> val cellDate = (date.clone() as Calendar).apply { set(Calendar.DAY_OF_WEEK, weekday) } val isSelected = daySelected.value.formatToDay() == cellDate.time.formatToDay() var cellPosition: Float by remember { mutableFloatStateOf(0f) } if (isSelected) { selectedPositionX = cellPosition } CalendarCell(cellDate, Modifier .clip(MaterialTheme.shapes.medium) .clickable { onDaySelect(cellDate.time) } .weight(1f) .onPlaced { coordinates -> cellPosition = coordinates.positionInParent().x val size = coordinates.size if (cellSize == null) cellSize = size if (isSelected) selectedPositionX = cellPosition }) } } } }
10
Kotlin
3
11
c6ba6ec282c6d91e651327d2df0295d100c8ade1
3,515
OctoDiary-kt
MIT License
src/main/kotlin/org/jetbrains/academy/test/system/models/method/TestMethod.kt
jetbrains-academy
632,174,674
false
{"Kotlin": 96901}
package org.jetbrains.academy.test.system.core.models.method import org.jetbrains.academy.test.system.core.checkType import org.jetbrains.academy.test.system.core.models.TestKotlinType import org.jetbrains.academy.test.system.core.models.Visibility import org.jetbrains.academy.test.system.core.models.variable.TestVariable import java.lang.reflect.Method import kotlin.reflect.jvm.kotlinFunction /** * Represents any function in the code, e.g. a member function, a top level function, etc. * * @param name represents a method name. * @param returnType represents a Kotlin return type, see [TestKotlinType]. * @param arguments represents a list of arguments, see [TestVariable]. * @param returnTypeJava represents the short name of a Java return type. * @param visibility represents [Visibility] of the method. * @param hasGeneratedPartInName indicates if the method's name contains a generated by the Kotlin compiler part. */ data class TestMethod( val name: String, val returnType: TestKotlinType, val arguments: List<TestVariable> = emptyList(), val returnTypeJava: String? = null, val visibility: Visibility = Visibility.PUBLIC, val hasGeneratedPartInName: Boolean = false, ) { fun prettyString(withToDo: Boolean = true): String { val args = arguments.joinToString(", ") { it.paramPrettyString() } val body = if (withToDo) { "TODO(\"Not implemented yet\")" } else { "// Some code" } return "${visibility.key} fun $name($args): ${returnType.getTypePrettyString()} = $body" } private fun TestVariable.paramPrettyString() = "$name: $javaType" fun checkMethod(method: Method) { val kotlinFunction = method.kotlinFunction ?: error("Can not find Kotlin method for the method ${this.prettyString()}") assert(kotlinFunction.name == name) { "The function name must be: $name" } val visibility = kotlinFunction.visibility?.name?.lowercase() assert(visibility == this.visibility.key) { "The visibility of the method $name must be ${this.visibility.key}" } kotlinFunction.returnType.checkType(returnType, returnTypeJava ?: returnType.type, "the function $name") } }
2
Kotlin
0
0
efaf033e1274c33e218c48a9640423fedc967183
2,231
kotlin-test-framework
MIT License
kompendium-auth/src/main/kotlin/io/bkbn/kompendium/auth/Notarized.kt
bkbnio
356,919,425
false
null
package io.bkbn.kompendium.auth import io.bkbn.kompendium.auth.configuration.ApiKeyConfiguration import io.bkbn.kompendium.auth.configuration.BasicAuthConfiguration import io.bkbn.kompendium.auth.configuration.JwtAuthConfiguration import io.bkbn.kompendium.auth.configuration.OAuthConfiguration import io.bkbn.kompendium.auth.configuration.SecurityConfiguration import io.bkbn.kompendium.core.Kompendium import io.bkbn.kompendium.oas.security.ApiKeyAuth import io.bkbn.kompendium.oas.security.BasicAuth import io.bkbn.kompendium.oas.security.BearerAuth import io.bkbn.kompendium.oas.security.OAuth import io.ktor.application.feature import io.ktor.auth.authenticate import io.ktor.routing.Route import io.ktor.routing.application object Notarized { fun Route.notarizedAuthenticate( vararg configurations: SecurityConfiguration, optional: Boolean = false, build: Route.() -> Unit ): Route { val configurationNames = configurations.map { it.name }.toTypedArray() val feature = application.feature(Kompendium) configurations.forEach { config -> feature.config.spec.components.securitySchemes[config.name] = when (config) { is ApiKeyConfiguration -> ApiKeyAuth(config.location, config.keyName) is BasicAuthConfiguration -> BasicAuth() is JwtAuthConfiguration -> BearerAuth(config.bearerFormat) is OAuthConfiguration -> OAuth(config.description, config.flows) } } return authenticate(*configurationNames, optional = optional, build = build) } }
19
Kotlin
14
54
22dc0b8eea60916ae0114843b251153e531df499
1,528
kompendium
MIT License
core/acp-core/src/main/kotlin/io/github/zhangbinhub/acp/core/task/timer/rule/ExecuteType.kt
zhangbinhub
279,298,314
false
{"Gradle": 22, "Shell": 2, "Text": 2, "Ignore List": 1, "Batchfile": 2, "INI": 4, "Markdown": 6, "Java": 80, "YAML": 25, "XML": 16, "Kotlin": 201, "Java Properties": 3, "JSON": 2, "HTML": 1}
package io.github.zhangbinhub.acp.core.task.timer.rule import io.github.zhangbinhub.acp.core.exceptions.EnumValueUndefinedException /** * @author zhang by 10/07/2019 * @since JDK 11 */ enum class ExecuteType { WeekDay, Weekend, All; companion object { private var nameMap: MutableMap<String, ExecuteType> = mutableMapOf() init { for (type in values()) { nameMap[type.name.uppercase()] = type } } @JvmStatic @Throws(EnumValueUndefinedException::class) fun getEnum(name: String): ExecuteType { if (nameMap.containsKey(name.lowercase())) { return nameMap.getValue(name.lowercase()) } throw EnumValueUndefinedException(ExecuteType::class.java, name) } } }
0
Kotlin
4
8
3d63305f56fed8302fc63fa45d6ebd30cbbd8c3e
830
acp
Apache License 2.0
enslig-forsorger/src/main/kotlin/no/nav/familie/kontrakter/ef/sรธknad/Samvรฆr.kt
navikt
206,793,193
false
null
package no.nav.familie.kontrakter.ef.sรธknad import java.time.LocalDate data class Samvรฆr( val spรธrsmรฅlAvtaleOmDeltBosted: Sรธknadsfelt<Boolean>? = null, val avtaleOmDeltBosted: Sรธknadsfelt<Dokumentasjon>? = null, val skalAnnenForelderHaSamvรฆr: Sรธknadsfelt<String>? = null, val harDereSkriftligAvtaleOmSamvรฆr: Sรธknadsfelt<String>? = null, val samvรฆrsavtale: Sรธknadsfelt<Dokumentasjon>? = null, val skalBarnetBoHosSรธkerMenAnnenForelderSamarbeiderIkke: Sรธknadsfelt<Dokumentasjon>? = null, val hvordanPraktiseresSamvรฆret: Sรธknadsfelt<String>? = null, val borAnnenForelderISammeHus: Sรธknadsfelt<String>? = null, val borAnnenForelderISammeHusBeskrivelse: Sรธknadsfelt<String>? = null, val harDereTidligereBoddSammen: Sรธknadsfelt<Boolean>? = null, val nรฅrFlyttetDereFraHverandre: Sรธknadsfelt<LocalDate>? = null, val erklรฆringOmSamlivsbrudd: Sรธknadsfelt<Dokumentasjon>? = null, val hvorMyeErDuSammenMedAnnenForelder: Sรธknadsfelt<String>? = null, val beskrivSamvรฆrUtenBarn: Sรธknadsfelt<String>? = null )
16
null
0
2
fd2cae7cc0d8617384440a78bab948e558fcc69b
1,051
familie-kontrakter
MIT License
app/src/main/java/com/example/diapplication/domain/entity/Forecast.kt
rendivy
661,304,960
false
{"Kotlin": 93010}
package com.example.diapplication.domain.entity import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Forecast( @SerialName("forecastday") val forecastDayList: List<Forecastday> )
0
Kotlin
0
0
da2a3e4f13d0064699a2073bdce55fd8d9f9da21
239
MonoWeather
MIT License
features/characters_favorites/src/test/kotlin/com/vmadalin/dynamicfeatures/caractersfavorites/ui/favorite/adapter/CharactersFavoriteTouchHelperTest.kt
vmadalin
192,786,158
false
null
/* * Copyright 2021 vyshas * * 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.vyshas.dynamicfeatures.caractersfavorites.ui.favorite.adapter import androidx.recyclerview.widget.ItemTouchHelper.ACTION_STATE_IDLE import androidx.recyclerview.widget.ItemTouchHelper.LEFT import androidx.recyclerview.widget.ItemTouchHelper.RIGHT import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.NO_POSITION import com.vyshas.dynamicfeatures.charactersfavorites.ui.favorite.adapter.CharactersFavoriteTouchHelper import io.mockk.Called import io.mockk.MockKAnnotations import io.mockk.every import io.mockk.impl.annotations.MockK import io.mockk.mockk import io.mockk.verify import io.mockk.verifyAll import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test class CharactersFavoriteTouchHelperTest { @MockK(relaxed = true) lateinit var onSwiped: (Int) -> Unit lateinit var touchHelper: CharactersFavoriteTouchHelper @Before fun setUp() { MockKAnnotations.init(this) touchHelper = CharactersFavoriteTouchHelper(onSwiped) } @Test fun createTouchHelper_ShouldInitializeCorrectly() { val recycleView = mockk<RecyclerView>() val viewHolder = mockk<RecyclerView.ViewHolder>() touchHelper.getDragDirs(recycleView, viewHolder).run { assertEquals(ACTION_STATE_IDLE, this) } touchHelper.getSwipeDirs(recycleView, viewHolder).run { assertEquals(LEFT or RIGHT, this) } } @Test fun moveTouchEvent_ShouldIgnoreIt() { val recycleView = mockk<RecyclerView>() val viewHolder = mockk<RecyclerView.ViewHolder>() val target = mockk<RecyclerView.ViewHolder>() touchHelper.onMove(recycleView, viewHolder, target).run { assertTrue(this) } verifyAll { recycleView wasNot Called viewHolder wasNot Called target wasNot Called } } @Test fun swipeTouchEvent_OnAlreadyRemovedItem_ShouldInvokeWithNoPosition() { val viewHolder = mockk<RecyclerView.ViewHolder>() val direction = LEFT every { viewHolder.adapterPosition } returns NO_POSITION touchHelper.onSwiped(viewHolder, direction) verify { onSwiped.invoke(NO_POSITION) } } @Test fun swipeTouchEvent_OnExistItem_ShouldInvokeWithPosition() { val viewHolder = mockk<RecyclerView.ViewHolder>() val direction = LEFT val swipePosition = 2 every { viewHolder.adapterPosition } returns swipePosition touchHelper.onSwiped(viewHolder, direction) verify { onSwiped.invoke(swipePosition) } } }
3
null
379
2,347
9fe0723a3bd515337df0837e528968785772e994
3,327
android-modular-architecture
Apache License 2.0
android/src/main/java/com/zondy/mapgis/mobile/geodatabase/JSLogEventReceiver.kt
MapGIS
463,426,830
false
{"TypeScript": 1360825, "Kotlin": 197019, "JavaScript": 2750, "Java": 1126, "Objective-C": 341, "Swift": 253}
package com.zondy.mapgis.mobile.geodatabase import com.facebook.react.bridge.* import com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter import com.zondy.mapgis.geodatabase.LogEventReceiver import com.zondy.mapgis.geodatabase.event.IStepEndListener import com.zondy.mapgis.geodatabase.event.IStepMessageListener import com.zondy.mapgis.geodatabase.event.IStepStartListener import com.zondy.mapgis.mobile.manager.MGObjManager.getObjByID /** * @author fangqi 2021-11-18 * @content ่ฟ‡็จ‹ๅ›ž่ฐƒไฟกๆฏ็ฑป */ class JSLogEventReceiver(private val mReactContext: ReactApplicationContext) : ReactContextBaseJavaModule(mReactContext) { private var mStepStartListener: IStepStartListener? = null private var mStepMessageListener: IStepMessageListener? = null private var mStepEndListener: IStepEndListener? = null override fun getName(): String { return REACT_CLASS } private fun sendEvent(eventName: String, writableMap: WritableMap) { mReactContext.getJSModule(RCTDeviceEventEmitter::class.java) .emit(eventName, writableMap) } @ReactMethod fun addStepStartListener(objId: String?, promise: Promise) { try { mStepStartListener = IStepStartListener { stepName -> val writableMap = Arguments.createMap() writableMap.putString("stepName", stepName) sendEvent(STEPSTART, writableMap) } val logEventReceiver = getObjByID(objId!!) as LogEventReceiver? logEventReceiver!!.addStepStartListener(mStepStartListener) promise.resolve(true) } catch (e: Exception) { promise.reject(e) } } @ReactMethod fun removeStepStartListener(objId: String?, promise: Promise) { try { val logEventReceiver = getObjByID(objId!!) as LogEventReceiver? logEventReceiver!!.removeStepStartListener(mStepStartListener) promise.resolve(true) } catch (e: Exception) { promise.reject(e) } } @ReactMethod fun addStepMessageListener(objId: String?, promise: Promise) { try { mStepMessageListener = IStepMessageListener { message -> val writableMap = Arguments.createMap() writableMap.putString("message", message) sendEvent(STEPMESSAGE, writableMap) } val logEventReceiver = getObjByID(objId!!) as LogEventReceiver? logEventReceiver!!.addStepMessageListener(mStepMessageListener) promise.resolve(true) } catch (e: Exception) { promise.reject(e) } } @ReactMethod fun removeStepMessageListener(objId: String?, promise: Promise) { try { val logEventReceiver = getObjByID(objId!!) as LogEventReceiver? logEventReceiver!!.removeStepMessageListener(mStepMessageListener) promise.resolve(true) } catch (e: Exception) { promise.reject(e) } } @ReactMethod fun addStepEndListener(objId: String?, promise: Promise) { try { mStepEndListener = IStepEndListener { progressStatus, progress, stepName, isAppendLog -> val writableMap = Arguments.createMap() writableMap.putString("status", progressStatus.name) writableMap.putDouble("progress", progress) writableMap.putString("stepName", stepName) writableMap.putBoolean("isAppendLog", isAppendLog) sendEvent(STEPEND, writableMap) } val logEventReceiver = getObjByID(objId!!) as LogEventReceiver? logEventReceiver!!.addStepEndListener(mStepEndListener) promise.resolve(true) } catch (e: Exception) { promise.reject(e) } } @ReactMethod fun removeStepEndListener(objId: String?, promise: Promise) { try { val logEventReceiver = getObjByID(objId!!) as LogEventReceiver? logEventReceiver!!.removeStepEndListener(mStepEndListener) promise.resolve(true) } catch (e: Exception) { promise.reject(e) } } companion object { private const val REACT_CLASS = "JSLogEventReceiver" private const val STEPSTART = "com.mapgis.RN.LogEventReceiver.step_start" private const val STEPMESSAGE = "com.mapgis.RN.SketchEditor.step_message" private const val STEPEND = "com.mapgis.RN.SketchEditor.step_end" } }
0
TypeScript
0
0
156db7d18afd91bcf720c6429dbcd359364abaf2
4,132
MapGIS-Mobile-React-Native
MIT License
ui/src/main/kotlin/com/aptopayments/sdk/features/maintenance/MaintenanceFragment.kt
AptoPayments
197,800,853
false
null
package com.aptopayments.sdk.features.maintenance import android.os.Bundle import com.aptopayments.mobile.data.config.UIConfig import com.aptopayments.mobile.network.NetworkHandler import com.aptopayments.sdk.R import com.aptopayments.sdk.core.platform.BaseFragment import com.aptopayments.sdk.core.platform.theme.themeManager import com.aptopayments.sdk.core.ui.StatusBarUtil import com.aptopayments.sdk.utils.extensions.setOnClickListenerSafe import kotlinx.android.synthetic.main.fragment_maintenance.* import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.android.ext.android.inject internal class MaintenanceFragment : BaseFragment(), MaintenanceContract.View { private val networkHandler: NetworkHandler by inject() private val viewModel: MaintenanceViewModel by viewModel() override fun layoutId() = R.layout.fragment_maintenance override fun backgroundColor(): Int = UIConfig.uiNavigationSecondaryColor override fun setupViewModel() { } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) hideLoading() } override fun setupUI() { setupTheme() } private fun setupTheme() { activity?.window?.let { StatusBarUtil.setStatusBarColor(it, UIConfig.uiNavigationSecondaryColor) } iv_maintenance.setColorFilter(UIConfig.uiTertiaryColor) themeManager().apply { customizeContentPlainInvertedText(tv_description_text) customizeSubmitButton(continue_button) } } override fun setupListeners() = continue_button.setOnClickListenerSafe { networkHandler.checkMaintenanceMode() } companion object { fun newInstance() = MaintenanceFragment() } }
1
Kotlin
0
0
257af71aa439b3e90c150ae258c78eaa1a6ae817
1,747
apto-ui-sdk-android
MIT License
app/src/main/java/com/pr0gramm/app/ui/FancyExifThumbnailGenerator.kt
chrosey
95,877,863
false
null
package com.pr0gramm.app.ui import android.app.Application import android.graphics.* import android.net.Uri import com.pr0gramm.app.R import com.pr0gramm.app.util.time import com.squareup.picasso.Downloader import it.sephiroth.android.library.exif2.ExifInterface import okhttp3.Request import org.slf4j.LoggerFactory import java.io.ByteArrayInputStream /** */ class FancyExifThumbnailGenerator(context: Application, private val downloader: Downloader) { private val logger = LoggerFactory.getLogger("FancyExifThumbnailGenerator") private val maskV = BitmapFactory.decodeResource(context.resources, R.raw.mask_v) private val maskH = BitmapFactory.decodeResource(context.resources, R.raw.mask_h) fun fancyThumbnail(uri: Uri, aspect: Float): Bitmap = logger.time("Building fancy thumbnail") { val bytes = fetch(uri) // almost square? fall back on non fancy normal image if (1 / 1.05 < aspect && aspect < 1.05) { return decode565(bytes) } // load exif thumbnail or fall back to square image, if loading fails val low = exifThumbnail(bytes) ?: return decode565(bytes) // decode image as a mutable bitmap val normal = decodeMutableBitmap(bytes) // add the alpha mask applyAlphaMask(aspect, normal) normal.setHasAlpha(true) try { return compose(aspect, low, normal) } finally { normal.recycle() low.recycle() } } private fun applyAlphaMask(aspect: Float, bitmap: Bitmap) { val baseSquare = Rect(0, 0, bitmap.width, bitmap.height) val canvas = Canvas(bitmap) // draw the alpha mask val paint = Paint() paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_IN) canvas.drawBitmap(if (aspect > 1) maskH else maskV, null, baseSquare, paint) } private fun compose(aspect: Float, low: Bitmap, normal: Bitmap): Bitmap { val centered = Rect(0, 0, normal.width, normal.height) var width = centered.width() var height = centered.height() if (aspect > 1.0) { width = (aspect * height).toInt() centered.left = (width - height) / 2 centered.right = centered.left + height } else { height = (width / aspect).toInt() centered.top = (height - width) / 2 centered.bottom = centered.top + width } // now generate the result val result = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565) val paint = Paint() val canvas = Canvas(result) paint.flags = Paint.FILTER_BITMAP_FLAG canvas.drawBitmap(low, null, Rect(0, 0, width, height), paint) paint.flags = paint.flags and Paint.FILTER_BITMAP_FLAG.inv() canvas.drawBitmap(normal, null, centered, null) return result } private fun decodeMutableBitmap(bytes: ByteArray): Bitmap { val options = BitmapFactory.Options() options.inPreferredConfig = Bitmap.Config.ARGB_8888 options.inMutable = true return BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options) } private fun exifThumbnail(bytes: ByteArray): Bitmap? { ByteArrayInputStream(bytes).use { inputStream -> val ei = ExifInterface() ei.readExif(inputStream, ExifInterface.Options.OPTION_ALL) return ei.thumbnailBitmap } } private fun fetch(uri: Uri): ByteArray { val response = downloader.load(Request.Builder().url(uri.toString()).build()) return response.body()?.bytes() ?: byteArrayOf() } private fun decode565(bytes: ByteArray): Bitmap { val options = BitmapFactory.Options() options.inPreferredConfig = Bitmap.Config.RGB_565 return BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options) } }
1
null
1
1
b6a7b846bcae573545da824cb716a07a334adedb
3,903
Pr0
MIT License
listings/plp-probexplanation.kt
pikalab-unibo
433,442,430
false
{"TeX": 39029, "Kotlin": 2914, "Prolog": 1296, "Java": 760, "JavaScript": 671, "Python": 381, "Raku": 83, "Perl": 56}
internal interface ProbExplanation { val probability: Double val containsAnyNotGroundTerm: Boolean fun not(): ProbExplanation infix fun and( that: ProbExplanation ): ProbExplanation infix fun or( that: ProbExplanation ): ProbExplanation fun apply( transformation: (ProbTerm) -> ProbTerm ): ProbExplanation }
1
TeX
0
0
031ff67a8528465bc6da7338f35441d818c314ab
368
plp-aixia-2021-talk
LaTeX Project Public License v1.3c
src/test/kotlin/io/github/emikaelsilveira/utils/builders/UserDTOBuilder.kt
Emikael
205,024,998
false
null
package io.github.emikaelsilveira.utils.builders import io.github.emikaelsilveira.domain.entities.Address import io.github.emikaelsilveira.domain.entities.User import org.joda.time.LocalDateTime class UserDTOBuilder { var id = 1L var name = "<NAME>" var email = "<EMAIL>" var phone = "(99) 99999-9999" var address: Address? = AddressDTOBuilder.build() private var createAt: LocalDateTime = LocalDateTime.now() private var updateAt: LocalDateTime = LocalDateTime.now() private fun build() = User( id = id, name = name, email = email, phone = phone, address = address, updateAt = updateAt, createAt = createAt ) companion object { fun build(block: (UserDTOBuilder.() -> Unit)? = null) = when (block) { null -> UserDTOBuilder().build() else -> UserDTOBuilder().apply(block).build() } } }
0
Kotlin
0
0
02aa43adb7fa1617541ff946fd4f0687c91bf978
930
kotlin-full-sample
The Unlicense
paymentsheet/src/main/java/com/stripe/android/paymentsheet/PaymentOptionsAdapter.kt
stripe
6,926,049
false
null
package com.stripe.android.paymentsheet import android.annotation.SuppressLint import android.content.res.Resources import android.view.LayoutInflater import android.view.View import android.view.View.IMPORTANT_FOR_ACCESSIBILITY_YES import android.view.ViewGroup import androidx.annotation.VisibleForTesting import androidx.core.view.isVisible import androidx.core.view.marginEnd import androidx.core.view.marginStart import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.IMPORTANT_FOR_ACCESSIBILITY_NO import androidx.recyclerview.widget.RecyclerView.NO_POSITION import com.stripe.android.model.PaymentMethod import com.stripe.android.paymentsheet.databinding.LayoutPaymentsheetAddNewPaymentMethodItemBinding import com.stripe.android.paymentsheet.databinding.LayoutPaymentsheetGooglePayItemBinding import com.stripe.android.paymentsheet.databinding.LayoutPaymentsheetPaymentMethodItemBinding import com.stripe.android.paymentsheet.model.FragmentConfig import com.stripe.android.paymentsheet.model.PaymentSelection import com.stripe.android.paymentsheet.model.SavedSelection import com.stripe.android.paymentsheet.ui.getLabel import com.stripe.android.paymentsheet.ui.getSavedPaymentMethodIcon import kotlin.math.roundToInt import kotlin.properties.Delegates @SuppressLint("NotifyDataSetChanged") internal class PaymentOptionsAdapter( private val canClickSelectedItem: Boolean, val paymentOptionSelectedListener: (paymentSelection: PaymentSelection, isClick: Boolean) -> Unit, val paymentMethodDeleteListener: (paymentMethod: Item.SavedPaymentMethod) -> Unit, val addCardClickListener: View.OnClickListener ) : RecyclerView.Adapter<PaymentOptionsAdapter.PaymentOptionViewHolder>() { @VisibleForTesting internal var items: List<Item> = emptyList() private var selectedItemPosition: Int = NO_POSITION private var isEditing = false internal val selectedItem: Item? get() = items.getOrNull(selectedItemPosition) internal var isEnabled: Boolean by Delegates.observable(true) { _, oldValue, newValue -> if (oldValue != newValue) { notifyDataSetChanged() } } init { setHasStableIds(true) } fun setEditing(editing: Boolean) { if (editing != isEditing) { isEditing = editing notifyDataSetChanged() } } fun setItems( config: FragmentConfig, paymentMethods: List<PaymentMethod>, paymentSelection: PaymentSelection? = null ) { val items = listOfNotNull( Item.AddCard, Item.GooglePay.takeIf { config.isGooglePayReady } ) + sortedPaymentMethods(paymentMethods, config.savedSelection).map { Item.SavedPaymentMethod(it) } this.items = items onItemSelected( position = paymentSelection?.let { findSelectedPosition(it) }.takeIf { it != -1 } ?: findInitialSelectedPosition(config.savedSelection), isClick = false ) notifyDataSetChanged() } fun removeItem(item: Item) { val itemIndex = items.indexOf(item) items = items.toMutableList().apply { removeAt(itemIndex) } notifyItemRemoved(itemIndex) } /** * The initial selection position follows this prioritization: * 1. The index of [Item.SavedPaymentMethod] if it matches the [SavedSelection] * 2. The index of [Item.GooglePay] if it exists * 3. The index of the first [Item.SavedPaymentMethod] * 4. None (-1) */ private fun findInitialSelectedPosition( savedSelection: SavedSelection ): Int { return listOfNotNull( // saved selection items.indexOfFirst { item -> val b = when (savedSelection) { SavedSelection.GooglePay -> item is Item.GooglePay is SavedSelection.PaymentMethod -> { when (item) { is Item.SavedPaymentMethod -> { savedSelection.id == item.paymentMethod.id } else -> false } } SavedSelection.None -> false } b }.takeIf { it != -1 }, // Google Pay items.indexOfFirst { it is Item.GooglePay }.takeIf { it != -1 }, // the first payment method items.indexOfFirst { it is Item.SavedPaymentMethod }.takeIf { it != -1 } ).firstOrNull() ?: NO_POSITION } /** * Find the index of [paymentSelection] in the current items. Return -1 if not found. */ private fun findSelectedPosition(paymentSelection: PaymentSelection): Int { return items.indexOfFirst { item -> when (paymentSelection) { PaymentSelection.GooglePay -> item is Item.GooglePay is PaymentSelection.Saved -> { when (item) { is Item.SavedPaymentMethod -> { paymentSelection.paymentMethod.id == item.paymentMethod.id } else -> false } } else -> false } } } private fun sortedPaymentMethods( paymentMethods: List<PaymentMethod>, savedSelection: SavedSelection ): List<PaymentMethod> { val primaryPaymentMethodIndex = when (savedSelection) { is SavedSelection.PaymentMethod -> { paymentMethods.indexOfFirst { it.id == savedSelection.id } } else -> -1 } return if (primaryPaymentMethodIndex != -1) { val mutablePaymentMethods = paymentMethods.toMutableList() mutablePaymentMethods.removeAt(primaryPaymentMethodIndex) .also { primaryPaymentMethod -> mutablePaymentMethods.add(0, primaryPaymentMethod) } mutablePaymentMethods } else { paymentMethods } } @VisibleForTesting internal fun onItemSelected( position: Int, isClick: Boolean ) { if (position != NO_POSITION && (canClickSelectedItem || position != selectedItemPosition) && !isEditing ) { val previousSelectedIndex = selectedItemPosition selectedItemPosition = position notifyItemChanged(previousSelectedIndex) notifyItemChanged(position) val newSelectedItem = items[position] when (newSelectedItem) { Item.AddCard -> null Item.GooglePay -> PaymentSelection.GooglePay is Item.SavedPaymentMethod -> PaymentSelection.Saved(newSelectedItem.paymentMethod) }?.let { paymentSelection -> paymentOptionSelectedListener( paymentSelection, isClick ) } } } override fun getItemId(position: Int): Long = items[position].hashCode().toLong() override fun getItemCount(): Int = items.size override fun getItemViewType(position: Int): Int = items[position].viewType.ordinal override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): PaymentOptionViewHolder { return when (ViewType.values()[viewType]) { ViewType.AddCard -> AddNewPaymentMethodViewHolder(parent).apply { itemView.setOnClickListener(addCardClickListener) } ViewType.GooglePay -> GooglePayViewHolder(parent).apply { itemView.setOnClickListener { onItemSelected(bindingAdapterPosition, isClick = true) } } ViewType.SavedPaymentMethod -> SavedPaymentMethodViewHolder(parent) { position -> paymentMethodDeleteListener(items[position] as Item.SavedPaymentMethod) }.apply { itemView.setOnClickListener { onItemSelected(bindingAdapterPosition, isClick = true) } } }.apply { val targetWidth = parent.measuredWidth - parent.paddingStart - parent.paddingEnd // minimum width for each item, accounting for the CardView margin so that the CardView // is at least 100dp wide val minItemWidth = 179 * parent.context.resources.displayMetrics.density + cardView.marginEnd + cardView.marginStart // numVisibleItems is incremented in steps of 0.5 items (1, 1.5, 2, 2.5, 3, ...) val numVisibleItems = (targetWidth * 2 / minItemWidth).toInt() / 2f val viewWidth = targetWidth / numVisibleItems itemView.layoutParams.width = viewWidth.toInt() } } override fun onBindViewHolder( holder: PaymentOptionViewHolder, position: Int ) { val item = items[position] when (holder) { is SavedPaymentMethodViewHolder -> { holder.bindSavedPaymentMethod(item as Item.SavedPaymentMethod) holder.setSelected(position == selectedItemPosition && !isEditing) holder.setEnabled(isEnabled) holder.setEditing(isEditing) } is GooglePayViewHolder -> { holder.setSelected(position == selectedItemPosition && !isEditing) holder.setEnabled(isEnabled && !isEditing) } else -> { holder.setEnabled(isEnabled && !isEditing) } } } private class SavedPaymentMethodViewHolder( private val binding: LayoutPaymentsheetPaymentMethodItemBinding, private val onRemoveListener: (Int) -> Unit ) : PaymentOptionViewHolder(binding.root) { constructor(parent: ViewGroup, onRemoveListener: (Int) -> Unit) : this( LayoutPaymentsheetPaymentMethodItemBinding.inflate( LayoutInflater.from(parent.context), parent, false ), onRemoveListener ) override val cardView: View get() = binding.card init { // ensure that the icons are above the card binding.checkIcon.elevation = binding.card.elevation + 1 binding.deleteIcon.elevation = binding.card.elevation + 1 binding.deleteIcon.setOnClickListener { onRemoveListener(absoluteAdapterPosition) } } fun bindSavedPaymentMethod(item: Item.SavedPaymentMethod) { binding.brandIcon.setImageResource(item.paymentMethod.getSavedPaymentMethodIcon() ?: 0) binding.label.text = item.paymentMethod.getLabel(itemView.resources) binding.root.contentDescription = item.getDescription(itemView.resources) binding.deleteIcon.contentDescription = itemView.resources.getString( R.string.stripe_paymentsheet_remove_pm, item.getDescription(itemView.resources) ) } fun setSelected(selected: Boolean) { binding.root.isSelected = selected binding.checkIcon.isVisible = selected binding.card.strokeWidth = cardStrokeWidth(selected) } override fun setEnabled(enabled: Boolean) { binding.card.isEnabled = enabled binding.root.isEnabled = enabled binding.label.isEnabled = enabled binding.brandIcon.alpha = if (enabled) 1F else 0.6F } fun setEditing(editing: Boolean) { binding.deleteIcon.isVisible = editing binding.root.importantForAccessibility = if (editing) { IMPORTANT_FOR_ACCESSIBILITY_NO } else { IMPORTANT_FOR_ACCESSIBILITY_YES } } } private class AddNewPaymentMethodViewHolder( private val binding: LayoutPaymentsheetAddNewPaymentMethodItemBinding ) : PaymentOptionViewHolder( binding.root ) { constructor(parent: ViewGroup) : this( LayoutPaymentsheetAddNewPaymentMethodItemBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) override val cardView: View get() = binding.card override fun setEnabled(enabled: Boolean) { binding.card.isEnabled = enabled binding.root.isEnabled = enabled binding.label.isEnabled = enabled binding.plusIcon.alpha = if (enabled) 1F else 0.6F } } private class GooglePayViewHolder( private val binding: LayoutPaymentsheetGooglePayItemBinding ) : PaymentOptionViewHolder( binding.root ) { constructor(parent: ViewGroup) : this( LayoutPaymentsheetGooglePayItemBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) override val cardView: View get() = binding.card init { // ensure that the check icon is above the card binding.checkIcon.elevation = binding.card.elevation + 1 } fun setSelected(selected: Boolean) { binding.root.isSelected = selected binding.checkIcon.isVisible = selected binding.card.strokeWidth = cardStrokeWidth(selected) } override fun setEnabled(enabled: Boolean) { binding.card.isEnabled = enabled binding.root.isEnabled = enabled binding.label.isEnabled = enabled binding.googlePayMark.alpha = if (enabled) 1F else 0.6F } } internal abstract class PaymentOptionViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(parent) { abstract val cardView: View abstract fun setEnabled(enabled: Boolean) fun cardStrokeWidth(selected: Boolean): Int { return if (selected) { itemView.resources .getDimension(R.dimen.stripe_paymentsheet_card_stroke_width_selected) .roundToInt() } else { itemView.resources .getDimension(R.dimen.stripe_paymentsheet_card_stroke_width) .roundToInt() } } } internal enum class ViewType { SavedPaymentMethod, AddCard, GooglePay } internal sealed class Item { abstract val viewType: ViewType object AddCard : Item() { override val viewType: ViewType = ViewType.AddCard } object GooglePay : Item() { override val viewType: ViewType = ViewType.GooglePay } /** * Represents a [PaymentMethod] that is already saved and attached to the current customer. */ data class SavedPaymentMethod( val paymentMethod: PaymentMethod ) : Item() { override val viewType: ViewType = ViewType.SavedPaymentMethod fun getDescription(resources: Resources) = when (paymentMethod.type) { PaymentMethod.Type.Card -> resources.getString( R.string.card_ending_in, paymentMethod.card?.brand, paymentMethod.card?.last4 ) PaymentMethod.Type.SepaDebit -> resources.getString( R.string.bank_account_ending_in, paymentMethod.sepaDebit?.last4 ) else -> "" } } } }
58
null
515
914
d0e3a1528d6c68db55c939d2a770241570a55372
15,866
stripe-android
MIT License
src/main/kotlin/glm_/vec2/operators/opVec2.kt
kotlin-graphics
71,653,021
false
null
package glm_.vec2.operators import glm_.f import glm_.vec2.Vec2 import glm_.vec2.Vec2.Companion.div import glm_.vec2.Vec2.Companion.minus import glm_.vec2.Vec2.Companion.plus import glm_.vec2.Vec2.Companion.rem import glm_.vec2.Vec2.Companion.times /** * Created by GBarbieri on 13.12.2016. */ open class opVec2 { inline fun plus(res: Vec2, a: Vec2, bX: Float, bY: Float): Vec2 { res.x = a.x + bX res.y = a.y + bY return res } inline fun minus(res: Vec2, a: Vec2, bX: Float, bY: Float): Vec2 { res.x = a.x - bX res.y = a.y - bY return res } inline fun minus(res: Vec2, aX: Float, aY: Float, b: Vec2): Vec2 { res.x = aX - b.x res.y = aY - b.y return res } inline fun times(res: Vec2, a: Vec2, bX: Float, bY: Float): Vec2 { res.x = a.x * bX res.y = a.y * bY return res } inline fun div(res: Vec2, a: Vec2, bX: Float, bY: Float): Vec2 { res.x = a.x / bX res.y = a.y / bY return res } inline fun div(res: Vec2, aX: Float, aY: Float, b: Vec2): Vec2 { res.x = aX / b.x res.y = aY / b.y return res } inline fun rem(res: Vec2, a: Vec2, bX: Float, bY: Float): Vec2 { res.x = a.x % bX res.y = a.y % bY return res } inline fun rem(res: Vec2, aX: Float, aY: Float, b: Vec2): Vec2 { res.x = aX % b.x res.y = aY % b.y return res } } // -- Specific binary arithmetic operators -- infix operator fun Float.plus(b: Vec2) = plus(Vec2(), b, this, this) fun Float.plus(b: Vec2, res: Vec2) = plus(res, b, this, this) infix fun Float.plusAssign(b: Vec2) = plus(b, b, this, this) infix operator fun Float.minus(b: Vec2) = minus(Vec2(), this, this, b) // TODO it was wrong operand order, check others fun Float.minus(b: Vec2, res: Vec2) = minus(res, this, this, b) infix fun Float.minusAssign(b: Vec2) = minus(b, this, this, b) infix operator fun Float.times(b: Vec2) = times(Vec2(), b, this, this) fun Float.times(b: Vec2, res: Vec2) = times(res, b, this, this) infix fun Float.timesAssign(b: Vec2) = times(b, b, this, this) infix operator fun Float.div(b: Vec2) = div(Vec2(), this, this, b) fun Float.div(b: Vec2, res: Vec2) = div(res, b, this, this) infix fun Float.divAssign(b: Vec2) = div(b, this, this, b) infix operator fun Float.rem(b: Vec2) = rem(Vec2(), this, this, b) fun Float.rem(b: Vec2, res: Vec2) = rem(res, b, this, this) infix fun Float.remAssign(b: Vec2) = rem(b, this, this, b) // -- Generic binary arithmetic operators -- infix operator fun Number.plus(b: Vec2) = plus(Vec2(), b, f, f) fun Number.plus(b: Vec2, res: Vec2) = plus(res, b, f, f) infix fun Number.plusAssign(b: Vec2) = plus(b, b, f, f) infix operator fun Number.minus(b: Vec2) = minus(Vec2(), f, f, b) fun Number.minus(b: Vec2, res: Vec2) = minus(res, b, f, f) infix fun Number.minusAssign(b: Vec2) = minus(b, f, f, b) infix operator fun Number.times(b: Vec2) = times(Vec2(), b, f, f) fun Number.times(b: Vec2, res: Vec2) = times(res, b, f, f) infix fun Number.timesAssign(b: Vec2) = times(b, b, f, f) infix operator fun Number.div(b: Vec2) = div(Vec2(), f, f, b) fun Number.div(b: Vec2, res: Vec2) = div(res, b, f, f) infix fun Number.divAssign(b: Vec2) = div(b, f, f, b) infix operator fun Number.rem(b: Vec2) = rem(Vec2(), f, f, b) fun Number.rem(b: Vec2, res: Vec2) = rem(res, b, f, f) infix fun Number.remAssign(b: Vec2) = rem(b, f, f, b)
5
null
19
99
dcbdd6237fbc5af02722b8ea1b404a93ce38a043
3,487
glm
MIT License
model/src/test/kotlin/RuleSequenceTest.kt
yole
277,303,975
false
null
package ru.yole.etymograph import org.junit.Assert.assertEquals import org.junit.Test class RuleSequenceTest : QBaseTest() { @Test fun simpleSequence() { val repo = repoWithQ().apply { addLanguage(ce) } val qAiE = repo.rule("sound is 'a' and next sound is 'i':\n- new sound is 'e'", name = "q-ai-e") val qSfF = repo.rule("sound is 's' and next sound is 'f':\n- sound disappears") // inapplicable for this test val qWV = repo.rule("beginning of word and sound is 'w':\n- new sound is 'v'", name = "q-w-v") val seq = repo.addRuleSequence("ce-q", ce, q, listOf(qAiE, qSfF, qWV)) val ceWord = repo.addWord("waiwai", language = ce) val qWord = repo.addWord("vaiwe", language = q) val link = repo.addLink(qWord, ceWord, Link.Derived, emptyList(), emptyList(), null) repo.applyRuleSequence(link, seq) assertEquals(2, link.rules.size) } @Test fun normalize() { val repo = repoWithQ().apply { addLanguage(ce) } ce.phonemes += Phoneme(listOf("c", "k"), null, setOf("voiceless", "velar", "stop", "consonant")) ce.phonemes += Phoneme(listOf("g"), null, setOf("voiced", "velar", "stop", "consonant")) q.phonemes = q.phonemes.filter { "c" !in it.graphemes && "k" !in it.graphemes } + Phoneme(listOf("c", "k"), null, setOf("voiceless", "velar", "stop", "consonant")) val qVoiceless = repo.rule("sound is voiceless stop:\n- voiceless becomes voiced", name = "q-voiceless") val seq = repo.addRuleSequence("ce-q", ce, q, listOf(qVoiceless)) val ceWord = repo.addWord("aklar", language = ce) val qWord = repo.addWord("aglar", language = q) val link = repo.addLink(qWord, ceWord, Link.Derived, emptyList(), emptyList(), null) repo.applyRuleSequence(link, seq) assertEquals(1, link.rules.size) } }
0
null
1
16
4ca5e5d546c1837db0caf707f6e7ca463b1c5874
1,928
etymograph
Apache License 2.0
detekt-test-utils/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/KotlinEnvironmentTestSetup.kt
detekt
71,729,669
false
null
package io.gitlab.arturbosch.detekt.rules import io.github.detekt.test.utils.KotlinCoreEnvironmentWrapper import io.github.detekt.test.utils.createEnvironment import io.github.detekt.test.utils.resourceAsPath import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.junit.jupiter.api.extension.ExtendWith import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.api.extension.ParameterContext import org.junit.jupiter.api.extension.ParameterResolver import org.spekframework.spek2.dsl.Root import org.spekframework.spek2.lifecycle.CachingMode import java.io.File import java.nio.file.Path @Deprecated( "This is specific to Spek and will be removed in a future release. Documentation has been updated to " + "show alternative approaches: https://detekt.dev/type-resolution.html#testing-a-rule-that-uses-type-resolution" ) fun Root.setupKotlinEnvironment(additionalJavaSourceRootPath: Path? = null) { val wrapper by memoized( CachingMode.SCOPE, { createEnvironment(additionalJavaSourceRootPaths = listOfNotNull(additionalJavaSourceRootPath?.toFile())) }, { it.dispose() } ) // name is used for delegation @Suppress("UNUSED_VARIABLE") val env: KotlinCoreEnvironment by memoized(CachingMode.EACH_GROUP) { wrapper.env } } @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.CLASS) @ExtendWith(KotlinEnvironmentResolver::class) annotation class KotlinCoreEnvironmentTest( val additionalJavaSourcePaths: Array<String> = [] ) internal class KotlinEnvironmentResolver : ParameterResolver { private var ExtensionContext.wrapper: CloseableWrapper? get() = getStore(NAMESPACE)[WRAPPER_KEY, CloseableWrapper::class.java] set(value) = getStore(NAMESPACE).put(WRAPPER_KEY, value) override fun supportsParameter(parameterContext: ParameterContext, extensionContext: ExtensionContext): Boolean { return parameterContext.parameter.type == KotlinCoreEnvironment::class.java } override fun resolveParameter(parameterContext: ParameterContext, extensionContext: ExtensionContext): Any { val closeableWrapper = extensionContext.wrapper ?: CloseableWrapper( createEnvironment(additionalJavaSourceRootPaths = extensionContext.additionalJavaSourcePaths()) ).also { extensionContext.wrapper = it } return closeableWrapper.wrapper.env } companion object { private val NAMESPACE = ExtensionContext.Namespace.create("KotlinCoreEnvironment") private const val WRAPPER_KEY = "wrapper" private fun ExtensionContext.additionalJavaSourcePaths(): List<File> { val annotation = requiredTestClass.annotations .find { it is KotlinCoreEnvironmentTest } as? KotlinCoreEnvironmentTest ?: return emptyList() return annotation.additionalJavaSourcePaths.map { resourceAsPath(it).toFile() } } } private class CloseableWrapper(val wrapper: KotlinCoreEnvironmentWrapper) : ExtensionContext.Store.CloseableResource { override fun close() { wrapper.dispose() } } }
171
null
707
5,129
369d67390b6512ae01763e1fd71437d8a0f7b24a
3,167
detekt
Apache License 2.0
compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/inline/DeepCopyIrTreeWithDescriptors.kt
tnorbye
162,147,688
false
null
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.ir.backend.js.lower.inline import org.jetbrains.kotlin.backend.common.* import org.jetbrains.kotlin.backend.common.IrElementVisitorVoidWithContext import org.jetbrains.kotlin.backend.common.descriptors.* import org.jetbrains.kotlin.backend.common.lower.SimpleMemberScope import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.descriptors.impl.* import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.backend.js.JsIrBackendContext import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.declarations.impl.* import org.jetbrains.kotlin.ir.descriptors.IrTemporaryVariableDescriptorImpl import org.jetbrains.kotlin.ir.expressions.* import org.jetbrains.kotlin.ir.expressions.impl.* import org.jetbrains.kotlin.ir.symbols.* import org.jetbrains.kotlin.ir.symbols.impl.* import org.jetbrains.kotlin.ir.types.* import org.jetbrains.kotlin.ir.types.impl.IrSimpleTypeImpl import org.jetbrains.kotlin.ir.types.impl.IrStarProjectionImpl import org.jetbrains.kotlin.ir.types.impl.makeTypeProjection import org.jetbrains.kotlin.ir.util.* import org.jetbrains.kotlin.ir.visitors.* import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.DescriptorFactory import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassOrAny import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperInterfaces import org.jetbrains.kotlin.storage.LockBasedStorageManager import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.typeUtil.immediateSupertypes internal fun KotlinType?.createExtensionReceiver(owner: CallableDescriptor): ReceiverParameterDescriptor? = DescriptorFactory.createExtensionReceiverParameterForCallable( owner, this, Annotations.EMPTY ) fun ReferenceSymbolTable.translateErased(type: KotlinType): IrSimpleType { val descriptor = TypeUtils.getClassDescriptor(type) ?: return translateErased(type.immediateSupertypes().first()) val classSymbol = this.referenceClass(descriptor) val nullable = type.isMarkedNullable val arguments = type.arguments.map { IrStarProjectionImpl } return classSymbol.createType(nullable, arguments) } internal class DeepCopyIrTreeWithSymbolsForInliner(val context: Context, val typeArguments: Map<IrTypeParameterSymbol, IrType?>?, val parent: IrDeclarationParent?) : IrCopierForInliner { override fun copy(irElement: IrElement): IrElement { // Create new symbols. irElement.acceptVoid(symbolRemapper) // Make symbol remapper aware of the callsite's type arguments. symbolRemapper.typeArguments = typeArguments // Copy IR. val result = irElement.transform(copier, data = null) // Bind newly created IR with wrapped descriptors. result.acceptVoid(object: IrElementVisitorVoid { override fun visitElement(element: IrElement) { element.acceptChildrenVoid(this) } override fun visitClass(declaration: IrClass) { (declaration.descriptor as WrappedClassDescriptor).bind(declaration) declaration.acceptChildrenVoid(this) } override fun visitConstructor(declaration: IrConstructor) { (declaration.descriptor as WrappedClassConstructorDescriptor).bind(declaration) declaration.acceptChildrenVoid(this) } override fun visitEnumEntry(declaration: IrEnumEntry) { (declaration.descriptor as WrappedClassDescriptor).bind( declaration.correspondingClass ?: declaration.parentAsClass) declaration.acceptChildrenVoid(this) } override fun visitField(declaration: IrField) { (declaration.descriptor as WrappedPropertyDescriptor).bind(declaration) declaration.acceptChildrenVoid(this) } override fun visitFunction(declaration: IrFunction) { (declaration.descriptor as WrappedSimpleFunctionDescriptor).bind(declaration as IrSimpleFunction) declaration.acceptChildrenVoid(this) } override fun visitValueParameter(declaration: IrValueParameter) { (declaration.descriptor as? WrappedValueParameterDescriptor)?.bind(declaration) (declaration.descriptor as? WrappedReceiverParameterDescriptor)?.bind(declaration) declaration.acceptChildrenVoid(this) } override fun visitTypeParameter(declaration: IrTypeParameter) { (declaration.descriptor as WrappedTypeParameterDescriptor).bind(declaration) declaration.acceptChildrenVoid(this) } override fun visitVariable(declaration: IrVariable) { (declaration.descriptor as WrappedVariableDescriptor).bind(declaration) declaration.acceptChildrenVoid(this) } }) result.patchDeclarationParents(parent) return result } private var nameIndex = 0 private fun generateCopyName(name: Name) = Name.identifier(name.toString() + "_" + (nameIndex++).toString()) private inner class InlinerSymbolRenamer : SymbolRenamer { private val map = mutableMapOf<IrSymbol, Name>() override fun getClassName(symbol: IrClassSymbol) = map.getOrPut(symbol) { generateCopyName(symbol.owner.name) } override fun getFunctionName(symbol: IrSimpleFunctionSymbol) = map.getOrPut(symbol) { generateCopyName(symbol.owner.name) } override fun getFieldName(symbol: IrFieldSymbol) = symbol.owner.name override fun getFileName(symbol: IrFileSymbol) = symbol.owner.fqName override fun getExternalPackageFragmentName(symbol: IrExternalPackageFragmentSymbol) = symbol.owner.fqName override fun getEnumEntryName(symbol: IrEnumEntrySymbol) = symbol.owner.name override fun getVariableName(symbol: IrVariableSymbol) = map.getOrPut(symbol) { generateCopyName(symbol.owner.name) } override fun getTypeParameterName(symbol: IrTypeParameterSymbol) = symbol.owner.name override fun getValueParameterName(symbol: IrValueParameterSymbol) = symbol.owner.name } private inner class DescriptorsToIrRemapper : DescriptorsRemapper { override fun remapDeclaredClass(descriptor: ClassDescriptor) = WrappedClassDescriptor(descriptor.annotations, descriptor.source) override fun remapDeclaredConstructor(descriptor: ClassConstructorDescriptor) = WrappedClassConstructorDescriptor(descriptor.annotations, descriptor.source) override fun remapDeclaredEnumEntry(descriptor: ClassDescriptor) = WrappedClassDescriptor(descriptor.annotations, descriptor.source) override fun remapDeclaredField(descriptor: PropertyDescriptor) = WrappedPropertyDescriptor(descriptor.annotations, descriptor.source) override fun remapDeclaredSimpleFunction(descriptor: FunctionDescriptor) = WrappedSimpleFunctionDescriptor(descriptor.annotations, descriptor.source) override fun remapDeclaredTypeParameter(descriptor: TypeParameterDescriptor) = WrappedTypeParameterDescriptor(descriptor.annotations, descriptor.source) override fun remapDeclaredVariable(descriptor: VariableDescriptor) = WrappedVariableDescriptor(descriptor.annotations, descriptor.source) override fun remapDeclaredValueParameter(descriptor: ParameterDescriptor): ParameterDescriptor = if (descriptor is ReceiverParameterDescriptor) WrappedReceiverParameterDescriptor(descriptor.annotations, descriptor.source) else WrappedValueParameterDescriptor(descriptor.annotations, descriptor.source) } private inner class InlinerTypeRemapper(val symbolRemapper: SymbolRemapper, val typeArguments: Map<IrTypeParameterSymbol, IrType?>?) : TypeRemapper { override fun enterScope(irTypeParametersContainer: IrTypeParametersContainer) { } override fun leaveScope() { } private fun remapTypeArguments(arguments: List<IrTypeArgument>) = arguments.map { argument -> (argument as? IrTypeProjection)?.let { makeTypeProjection(remapType(it.type), it.variance) } ?: argument } override fun remapType(type: IrType): IrType { if (type !is IrSimpleType) return type val substitutedType = typeArguments?.get(type.classifier) if (substitutedType != null) { substitutedType as IrSimpleType return IrSimpleTypeImpl( kotlinType = null, classifier = substitutedType.classifier, hasQuestionMark = type.hasQuestionMark or substitutedType.isMarkedNullable(), arguments = substitutedType.arguments, annotations = substitutedType.annotations ) } return IrSimpleTypeImpl( kotlinType = null, classifier = symbolRemapper.getReferencedClassifier(type.classifier), hasQuestionMark = type.hasQuestionMark, arguments = remapTypeArguments(type.arguments), annotations = type.annotations.map { it.transform(copier, null) as IrCall } ) } } override fun addCurrentSubstituteMap(globalSubstituteMap: MutableMap<DeclarationDescriptor, SubstitutedDescriptor>) { } private class SymbolRemapperImpl(descriptorsRemapper: DescriptorsRemapper) : DeepCopySymbolRemapper(descriptorsRemapper) { var typeArguments: Map<IrTypeParameterSymbol, IrType?>? = null set(value) { if (field != null) return field = value?.asSequence()?.associate { (getReferencedClassifier(it.key) as IrTypeParameterSymbol) to it.value } } override fun getReferencedClassifier(symbol: IrClassifierSymbol): IrClassifierSymbol { val result = super.getReferencedClassifier(symbol) if (result !is IrTypeParameterSymbol) return result return typeArguments?.get(result)?.classifierOrNull ?: result } } private val symbolRemapper = SymbolRemapperImpl(DescriptorsToIrRemapper()) private val copier = DeepCopyIrTreeWithSymbols( symbolRemapper, InlinerTypeRemapper(symbolRemapper, typeArguments), InlinerSymbolRenamer() ) } internal interface IrCopierForInliner { fun copy(irElement: IrElement): IrElement fun addCurrentSubstituteMap(globalSubstituteMap: MutableMap<DeclarationDescriptor, SubstitutedDescriptor>) } internal class DeepCopyIrTreeWithDescriptors(val targetDescriptor: FunctionDescriptor, val parentDescriptor: DeclarationDescriptor, val context: JsIrBackendContext, val typeSubstitutor: TypeSubstitutor?) : IrCopierForInliner { private val descriptorSubstituteMap: MutableMap<DeclarationDescriptor, DeclarationDescriptor> = mutableMapOf() private var nameIndex = 0 //-------------------------------------------------------------------------// override fun copy(irElement: IrElement): IrElement { // Create all class descriptors and all necessary descriptors in order to create KotlinTypes. irElement.acceptVoid(DescriptorCollectorCreatePhase()) // Initialize all created descriptors possibly using previously created types. irElement.acceptVoid(DescriptorCollectorInitPhase()) return irElement.accept(InlineCopyIr(), null) } inner class DescriptorCollectorCreatePhase : IrElementVisitorVoidWithContext() { override fun visitElement(element: IrElement) { element.acceptChildren(this, null) } //---------------------------------------------------------------------// override fun visitClassNew(declaration: IrClass) { val oldDescriptor = declaration.descriptor val newDescriptor = copyClassDescriptor(oldDescriptor) descriptorSubstituteMap[oldDescriptor] = newDescriptor descriptorSubstituteMap[oldDescriptor.thisAsReceiverParameter] = newDescriptor.thisAsReceiverParameter super.visitClassNew(declaration) val constructors = oldDescriptor.constructors.map { oldConstructorDescriptor -> descriptorSubstituteMap[oldConstructorDescriptor] as ClassConstructorDescriptor }.toSet() val oldPrimaryConstructor = oldDescriptor.unsubstitutedPrimaryConstructor val primaryConstructor = oldPrimaryConstructor?.let { descriptorSubstituteMap[it] as ClassConstructorDescriptor } val contributedDescriptors = oldDescriptor.unsubstitutedMemberScope .getContributedDescriptors() .map { descriptorSubstituteMap[it]!! } newDescriptor.initialize( SimpleMemberScope(contributedDescriptors), constructors, primaryConstructor ) } //---------------------------------------------------------------------// override fun visitPropertyNew(declaration: IrProperty) { copyPropertyOrField(declaration.descriptor) super.visitPropertyNew(declaration) } //---------------------------------------------------------------------// override fun visitFieldNew(declaration: IrField) { val oldDescriptor = declaration.descriptor if (descriptorSubstituteMap[oldDescriptor] == null) { copyPropertyOrField(oldDescriptor) // A field without a property or a field of a delegated property. } super.visitFieldNew(declaration) } //---------------------------------------------------------------------// override fun visitFunctionNew(declaration: IrFunction) { val oldDescriptor = declaration.descriptor if (oldDescriptor !is PropertyAccessorDescriptor) { // Property accessors are copied along with their property. val oldContainingDeclaration = if (oldDescriptor.visibility == Visibilities.LOCAL) parentDescriptor else oldDescriptor.containingDeclaration descriptorSubstituteMap[oldDescriptor] = copyFunctionDescriptor(oldDescriptor, oldContainingDeclaration) } super.visitFunctionNew(declaration) } //--- Copy descriptors ------------------------------------------------// private fun generateCopyName(name: Name): Name { val declarationName = name.toString() // Name of declaration val indexStr = (nameIndex++).toString() // Unique for inline target index return Name.identifier(declarationName + "_" + indexStr) } //---------------------------------------------------------------------// private fun copyFunctionDescriptor(oldDescriptor: CallableDescriptor, oldContainingDeclaration: DeclarationDescriptor) = when (oldDescriptor) { is ConstructorDescriptor -> copyConstructorDescriptor(oldDescriptor) is SimpleFunctionDescriptor -> copySimpleFunctionDescriptor(oldDescriptor, oldContainingDeclaration) else -> TODO("Unsupported FunctionDescriptor subtype: $oldDescriptor") } //---------------------------------------------------------------------// private fun copySimpleFunctionDescriptor(oldDescriptor: SimpleFunctionDescriptor, oldContainingDeclaration: DeclarationDescriptor) : FunctionDescriptor { val newContainingDeclaration = descriptorSubstituteMap.getOrDefault(oldContainingDeclaration, oldContainingDeclaration) return SimpleFunctionDescriptorImpl.create( /* containingDeclaration = */ newContainingDeclaration, /* annotations = */ oldDescriptor.annotations, /* name = */ generateCopyName(oldDescriptor.name), /* kind = */ oldDescriptor.kind, /* source = */ oldDescriptor.source ) } //---------------------------------------------------------------------// private fun copyConstructorDescriptor(oldDescriptor: ConstructorDescriptor) : FunctionDescriptor { val oldContainingDeclaration = oldDescriptor.containingDeclaration val newContainingDeclaration = descriptorSubstituteMap.getOrDefault(oldContainingDeclaration, oldContainingDeclaration) return ClassConstructorDescriptorImpl.create( /* containingDeclaration = */ newContainingDeclaration as ClassDescriptor, /* annotations = */ oldDescriptor.annotations, /* isPrimary = */ oldDescriptor.isPrimary, /* source = */ oldDescriptor.source ) } //---------------------------------------------------------------------// private fun copyPropertyOrField(oldDescriptor: PropertyDescriptor) { val oldContainingDeclaration = oldDescriptor.containingDeclaration val newContainingDeclaration = descriptorSubstituteMap.getOrDefault(oldContainingDeclaration, oldContainingDeclaration) as ClassDescriptor @Suppress("DEPRECATION") val newDescriptor = PropertyDescriptorImpl.create( /* containingDeclaration = */ newContainingDeclaration, /* annotations = */ oldDescriptor.annotations, /* modality = */ oldDescriptor.modality, /* visibility = */ oldDescriptor.visibility, /* isVar = */ oldDescriptor.isVar, /* name = */ oldDescriptor.name, /* kind = */ oldDescriptor.kind, /* source = */ oldDescriptor.source, /* lateInit = */ oldDescriptor.isLateInit, /* isConst = */ oldDescriptor.isConst, /* isExpect = */ oldDescriptor.isExpect, /* isActual = */ oldDescriptor.isActual, /* isExternal = */ oldDescriptor.isExternal, /* isDelegated = */ oldDescriptor.isDelegated ) descriptorSubstituteMap[oldDescriptor] = newDescriptor } //---------------------------------------------------------------------// private fun copyClassDescriptor(oldDescriptor: ClassDescriptor): ClassDescriptorImpl { val oldSuperClass = oldDescriptor.getSuperClassOrAny() val newSuperClass = descriptorSubstituteMap.getOrDefault(oldSuperClass, oldSuperClass) as ClassDescriptor val oldInterfaces = oldDescriptor.getSuperInterfaces() val newInterfaces = oldInterfaces.map { descriptorSubstituteMap.getOrDefault(it, it) as ClassDescriptor } val oldContainingDeclaration = oldDescriptor.containingDeclaration val newContainingDeclaration = descriptorSubstituteMap.getOrDefault(oldContainingDeclaration, oldContainingDeclaration) val newName = if (DescriptorUtils.isAnonymousObject(oldDescriptor)) // Anonymous objects are identified by their name. oldDescriptor.name // We need to preserve it for LocalDeclarationsLowering. else generateCopyName(oldDescriptor.name) val visibility = oldDescriptor.visibility return object : ClassDescriptorImpl( /* containingDeclaration = */ newContainingDeclaration, /* name = */ newName, /* modality = */ oldDescriptor.modality, /* kind = */ oldDescriptor.kind, /* supertypes = */ listOf(newSuperClass.defaultType) + newInterfaces.map { it.defaultType }, /* source = */ oldDescriptor.source, /* isExternal = */ oldDescriptor.isExternal, /* storageManager = */ LockBasedStorageManager.NO_LOCKS ) { override fun getVisibility() = visibility override fun getDeclaredTypeParameters(): List<TypeParameterDescriptor> { return oldDescriptor.declaredTypeParameters } } } } //-------------------------------------------------------------------------// inner class DescriptorCollectorInitPhase : IrElementVisitorVoidWithContext() { private val initializedProperties = mutableSetOf<PropertyDescriptor>() override fun visitElement(element: IrElement) { element.acceptChildren(this, null) } //---------------------------------------------------------------------// override fun visitPropertyNew(declaration: IrProperty) { initPropertyOrField(declaration.descriptor) super.visitPropertyNew(declaration) } //---------------------------------------------------------------------// override fun visitFieldNew(declaration: IrField) { val oldDescriptor = declaration.descriptor if (!initializedProperties.contains(oldDescriptor)) { initPropertyOrField(oldDescriptor) // A field without a property or a field of a delegated property. } super.visitFieldNew(declaration) } //---------------------------------------------------------------------// override fun visitFunctionNew(declaration: IrFunction) { val oldDescriptor = declaration.descriptor if (oldDescriptor !is PropertyAccessorDescriptor) { // Property accessors are copied along with their property. val newDescriptor = initFunctionDescriptor(oldDescriptor) oldDescriptor.extensionReceiverParameter?.let { descriptorSubstituteMap[it] = newDescriptor.extensionReceiverParameter!! } } super.visitFunctionNew(declaration) } //---------------------------------------------------------------------// override fun visitVariable(declaration: IrVariable) { declaration.descriptor.let { descriptorSubstituteMap[it] = copyVariableDescriptor(it) } super.visitVariable(declaration) } //---------------------------------------------------------------------// override fun visitCatch(aCatch: IrCatch) { aCatch.parameter.let { descriptorSubstituteMap[it] = copyVariableDescriptor(it) } super.visitCatch(aCatch) } //--- Copy descriptors ------------------------------------------------// private fun generateCopyName(name: Name): Name { val declarationName = name.toString() // Name of declaration val indexStr = (nameIndex++).toString() // Unique for inline target index return Name.identifier(declarationName + "_" + indexStr) } //---------------------------------------------------------------------// private fun copyVariableDescriptor(oldDescriptor: VariableDescriptor): VariableDescriptor { val oldContainingDeclaration = oldDescriptor.containingDeclaration val newContainingDeclaration = descriptorSubstituteMap.getOrDefault(oldContainingDeclaration, oldContainingDeclaration) return IrTemporaryVariableDescriptorImpl( containingDeclaration = newContainingDeclaration, name = generateCopyName(oldDescriptor.name), outType = substituteType(oldDescriptor.type)!!, isMutable = oldDescriptor.isVar ) } //---------------------------------------------------------------------// private fun initFunctionDescriptor(oldDescriptor: CallableDescriptor): CallableDescriptor = when (oldDescriptor) { is ConstructorDescriptor -> initConstructorDescriptor(oldDescriptor) is SimpleFunctionDescriptor -> initSimpleFunctionDescriptor(oldDescriptor) else -> TODO("Unsupported FunctionDescriptor subtype: $oldDescriptor") } //---------------------------------------------------------------------// private fun initSimpleFunctionDescriptor(oldDescriptor: SimpleFunctionDescriptor): FunctionDescriptor = (descriptorSubstituteMap[oldDescriptor] as SimpleFunctionDescriptorImpl).apply { val oldDispatchReceiverParameter = oldDescriptor.dispatchReceiverParameter val newDispatchReceiverParameter = oldDispatchReceiverParameter?.let { descriptorSubstituteMap.getOrDefault(it, it) as ReceiverParameterDescriptor } val newTypeParameters = oldDescriptor.typeParameters // TODO substitute types val newValueParameters = copyValueParameters(oldDescriptor.valueParameters, this) val newReceiverParameterType = substituteType(oldDescriptor.extensionReceiverParameter?.type) val newReturnType = substituteType(oldDescriptor.returnType) initialize( /* receiverParameterType = */ newReceiverParameterType.createExtensionReceiver(this), /* dispatchReceiverParameter = */ newDispatchReceiverParameter, /* typeParameters = */ newTypeParameters, /* unsubstitutedValueParameters = */ newValueParameters, /* unsubstitutedReturnType = */ newReturnType, /* modality = */ oldDescriptor.modality, /* visibility = */ oldDescriptor.visibility ) isTailrec = oldDescriptor.isTailrec isSuspend = oldDescriptor.isSuspend overriddenDescriptors += oldDescriptor.overriddenDescriptors } //---------------------------------------------------------------------// private fun initConstructorDescriptor(oldDescriptor: ConstructorDescriptor): FunctionDescriptor = (descriptorSubstituteMap[oldDescriptor] as ClassConstructorDescriptorImpl).apply { val newTypeParameters = oldDescriptor.typeParameters val newValueParameters = copyValueParameters(oldDescriptor.valueParameters, this) val receiverParameterType = substituteType(oldDescriptor.dispatchReceiverParameter?.type) val returnType = substituteType(oldDescriptor.returnType) initialize( /* receiverParameterType = */ receiverParameterType.createExtensionReceiver(this), /* dispatchReceiverParameter = */ null, // For constructor there is no explicit dispatch receiver. /* typeParameters = */ newTypeParameters, /* unsubstitutedValueParameters = */ newValueParameters, /* unsubstitutedReturnType = */ returnType, /* modality = */ oldDescriptor.modality, /* visibility = */ oldDescriptor.visibility ) } //---------------------------------------------------------------------// private fun initPropertyOrField(oldDescriptor: PropertyDescriptor) { val newDescriptor = (descriptorSubstituteMap[oldDescriptor] as PropertyDescriptorImpl).apply { setType( /* outType = */ substituteType(oldDescriptor.type)!!, /* typeParameters = */ oldDescriptor.typeParameters, /* dispatchReceiverParameter = */ (containingDeclaration as ClassDescriptor).thisAsReceiverParameter, /* extensionReceiverParamter = */ substituteType(oldDescriptor.extensionReceiverParameter?.type).createExtensionReceiver(this)) initialize( /* getter = */ oldDescriptor.getter?.let { copyPropertyGetterDescriptor(it, this) }, /* setter = */ oldDescriptor.setter?.let { copyPropertySetterDescriptor(it, this) }) overriddenDescriptors += oldDescriptor.overriddenDescriptors } oldDescriptor.getter?.let { descriptorSubstituteMap[it] = newDescriptor.getter!! } oldDescriptor.setter?.let { descriptorSubstituteMap[it] = newDescriptor.setter!! } oldDescriptor.extensionReceiverParameter?.let { descriptorSubstituteMap[it] = newDescriptor.extensionReceiverParameter!! } initializedProperties.add(oldDescriptor) } //---------------------------------------------------------------------// private fun copyPropertyGetterDescriptor(oldDescriptor: PropertyGetterDescriptor, newPropertyDescriptor: PropertyDescriptor) = PropertyGetterDescriptorImpl( /* correspondingProperty = */ newPropertyDescriptor, /* annotations = */ oldDescriptor.annotations, /* modality = */ oldDescriptor.modality, /* visibility = */ oldDescriptor.visibility, /* isDefault = */ oldDescriptor.isDefault, /* isExternal = */ oldDescriptor.isExternal, /* isInline = */ oldDescriptor.isInline, /* kind = */ oldDescriptor.kind, /* original = */ null, /* source = */ oldDescriptor.source).apply { initialize(substituteType(oldDescriptor.returnType)) } //---------------------------------------------------------------------// private fun copyPropertySetterDescriptor(oldDescriptor: PropertySetterDescriptor, newPropertyDescriptor: PropertyDescriptor) = PropertySetterDescriptorImpl( /* correspondingProperty = */ newPropertyDescriptor, /* annotations = */ oldDescriptor.annotations, /* modality = */ oldDescriptor.modality, /* visibility = */ oldDescriptor.visibility, /* isDefault = */ oldDescriptor.isDefault, /* isExternal = */ oldDescriptor.isExternal, /* isInline = */ oldDescriptor.isInline, /* kind = */ oldDescriptor.kind, /* original = */ null, /* source = */ oldDescriptor.source).apply { initialize(copyValueParameters(oldDescriptor.valueParameters, this).single()) } //-------------------------------------------------------------------------// private fun copyValueParameters(oldValueParameters: List <ValueParameterDescriptor>, containingDeclaration: CallableDescriptor) = oldValueParameters.map { oldDescriptor -> val newDescriptor = ValueParameterDescriptorImpl( containingDeclaration = containingDeclaration, original = oldDescriptor.original, index = oldDescriptor.index, annotations = oldDescriptor.annotations, name = oldDescriptor.name, outType = substituteType(oldDescriptor.type)!!, declaresDefaultValue = oldDescriptor.declaresDefaultValue(), isCrossinline = oldDescriptor.isCrossinline, isNoinline = oldDescriptor.isNoinline, varargElementType = substituteType(oldDescriptor.varargElementType), source = oldDescriptor.source ) descriptorSubstituteMap[oldDescriptor] = newDescriptor newDescriptor } } //-----------------------------------------------------------------------------// @Suppress("DEPRECATION") inner class InlineCopyIr : DeepCopyIrTree() { override fun mapClassDeclaration (descriptor: ClassDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as ClassDescriptor override fun mapTypeAliasDeclaration (descriptor: TypeAliasDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as TypeAliasDescriptor override fun mapFunctionDeclaration (descriptor: FunctionDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as FunctionDescriptor override fun mapConstructorDeclaration (descriptor: ClassConstructorDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as ClassConstructorDescriptor override fun mapPropertyDeclaration (descriptor: PropertyDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as PropertyDescriptor override fun mapLocalPropertyDeclaration (descriptor: VariableDescriptorWithAccessors) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as VariableDescriptorWithAccessors override fun mapEnumEntryDeclaration (descriptor: ClassDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as ClassDescriptor override fun mapVariableDeclaration (descriptor: VariableDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as VariableDescriptor override fun mapErrorDeclaration (descriptor: DeclarationDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) override fun mapClassReference (descriptor: ClassDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as ClassDescriptor override fun mapValueReference (descriptor: ValueDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as ValueDescriptor override fun mapVariableReference (descriptor: VariableDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as VariableDescriptor override fun mapPropertyReference (descriptor: PropertyDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as PropertyDescriptor override fun mapCallee (descriptor: FunctionDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as FunctionDescriptor override fun mapDelegatedConstructorCallee (descriptor: ClassConstructorDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as ClassConstructorDescriptor override fun mapEnumConstructorCallee (descriptor: ClassConstructorDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as ClassConstructorDescriptor override fun mapLocalPropertyReference (descriptor: VariableDescriptorWithAccessors) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as VariableDescriptorWithAccessors override fun mapClassifierReference (descriptor: ClassifierDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as ClassifierDescriptor override fun mapReturnTarget (descriptor: FunctionDescriptor) = descriptorSubstituteMap.getOrDefault(descriptor, descriptor) as FunctionDescriptor //---------------------------------------------------------------------// override fun mapSuperQualifier(qualifier: ClassDescriptor?): ClassDescriptor? { if (qualifier == null) return null return descriptorSubstituteMap.getOrDefault(qualifier, qualifier) as ClassDescriptor } //--- Visits ----------------------------------------------------------// override fun visitCall(expression: IrCall): IrCall { if (expression !is IrCallImpl) return super.visitCall(expression) val newDescriptor = mapCallee(expression.descriptor) return IrCallImpl( startOffset = expression.startOffset, endOffset = expression.endOffset, type = context.symbolTable.translateErased(newDescriptor.returnType!!), descriptor = newDescriptor, typeArgumentsCount = expression.typeArgumentsCount, origin = expression.origin, superQualifierDescriptor = mapSuperQualifier(expression.superQualifier) ).apply { transformValueArguments(expression) substituteTypeArguments(expression) } } override fun visitField(declaration: IrField): IrField { val descriptor = mapPropertyDeclaration(declaration.descriptor) return IrFieldImpl( declaration.startOffset, declaration.endOffset, mapDeclarationOrigin(declaration.origin), descriptor, context.symbolTable.translateErased(descriptor.type), declaration.initializer?.transform(this@InlineCopyIr, null) ).apply { transformAnnotations(declaration) } } //---------------------------------------------------------------------// override fun visitFunction(declaration: IrFunction) = context.symbolTable.withScope(mapFunctionDeclaration(declaration.descriptor)) { descriptor -> IrFunctionImpl( startOffset = declaration.startOffset, endOffset = declaration.endOffset, origin = mapDeclarationOrigin(declaration.origin), descriptor = descriptor, returnType = declaration.returnType, body = declaration.body?.transform(this@InlineCopyIr, null) ).also { it.returnType = context.symbolTable.translateErased(descriptor.returnType!!) it.setOverrides(context.symbolTable) it.transformParameters(declaration) } } // override fun visitSimpleFunction(declaration: IrSimpleFunction): IrFunction { // val descriptor = mapFunctionDeclaration(declaration.descriptor) // return IrFunctionImpl( // startOffset = declaration.startOffset, // endOffset = declaration.endOffset, // origin = mapDeclarationOrigin(declaration.origin), // descriptor = descriptor // ).also { // it.returnType = context.symbolTable.translateErased(descriptor.returnType!!) // it.body = declaration.body?.transform(this, null) // // it.setOverrides(context.symbolTable) // }.transformParameters1(declaration) // } // override fun visitConstructor(declaration: IrConstructor): IrConstructor { // val descriptor = mapConstructorDeclaration(declaration.descriptor) // return IrConstructorImpl( // startOffset = declaration.startOffset, // endOffset = declaration.endOffset, // origin = mapDeclarationOrigin(declaration.origin), // descriptor = descriptor // ).also { // it.returnType = context.symbolTable.translateErased(descriptor.returnType) // it.body = declaration.body?.transform(this, null) // }.transformParameters1(declaration) // } private fun FunctionDescriptor.getTypeParametersToTransform() = when { this is PropertyAccessorDescriptor -> correspondingProperty.typeParameters else -> typeParameters } protected fun <T : IrFunction> T.transformParameters1(original: T): T = apply { transformTypeParameters(original, descriptor.getTypeParametersToTransform()) transformValueParameters1(original) } protected fun <T : IrFunction> T.transformValueParameters1(original: T) = apply { dispatchReceiverParameter = original.dispatchReceiverParameter?.replaceDescriptor1( descriptor.dispatchReceiverParameter ?: throw AssertionError("No dispatch receiver in $descriptor") ) extensionReceiverParameter = original.extensionReceiverParameter?.replaceDescriptor1( descriptor.extensionReceiverParameter ?: throw AssertionError("No extension receiver in $descriptor") ) original.valueParameters.mapIndexedTo(valueParameters) { i, originalValueParameter -> originalValueParameter.replaceDescriptor1(descriptor.valueParameters[i]) } } protected fun IrValueParameter.replaceDescriptor1(newDescriptor: ParameterDescriptor) = IrValueParameterImpl( startOffset, endOffset, mapDeclarationOrigin(origin), newDescriptor, context.symbolTable.translateErased(newDescriptor.type), (newDescriptor as? ValueParameterDescriptor)?.varargElementType?.let { context.symbolTable.translateErased(it) }, defaultValue?.transform(this@InlineCopyIr, null) ).apply { transformAnnotations(this) } //---------------------------------------------------------------------// override fun visitGetValue(expression: IrGetValue): IrGetValue { val descriptor = mapValueReference(expression.descriptor) return IrGetValueImpl( expression.startOffset, expression.endOffset, context.symbolTable.translateErased(descriptor.type), descriptor, mapStatementOrigin(expression.origin) ) } override fun visitVariable(declaration: IrVariable): IrVariable { val descriptor = mapVariableDeclaration(declaration.descriptor) return IrVariableImpl( declaration.startOffset, declaration.endOffset, mapDeclarationOrigin(declaration.origin), descriptor, context.symbolTable.translateErased(descriptor.type), declaration.initializer?.transform(this, null) ).apply { transformAnnotations(declaration) } } private fun <T : IrFunction> T.transformDefaults(original: T): T { for (originalValueParameter in original.descriptor.valueParameters) { val valueParameter = descriptor.valueParameters[originalValueParameter.index] original.getDefault(originalValueParameter)?.let { irDefaultParameterValue -> putDefault(valueParameter, irDefaultParameterValue.transform(this@InlineCopyIr, null)) } } return this } //---------------------------------------------------------------------// fun getTypeOperatorReturnType(operator: IrTypeOperator, type: IrType) : IrType { return when (operator) { IrTypeOperator.CAST, IrTypeOperator.IMPLICIT_CAST, IrTypeOperator.IMPLICIT_NOTNULL, IrTypeOperator.IMPLICIT_COERCION_TO_UNIT, IrTypeOperator.IMPLICIT_INTEGER_COERCION, IrTypeOperator.SAM_CONVERSION -> type IrTypeOperator.SAFE_CAST -> type.makeNullable() IrTypeOperator.INSTANCEOF, IrTypeOperator.NOT_INSTANCEOF -> context.irBuiltIns.booleanType } } //---------------------------------------------------------------------// override fun visitTypeOperator(expression: IrTypeOperatorCall): IrTypeOperatorCall { val erasedTypeOperand = substituteAndEraseType(expression.typeOperand)!! val typeOperand = substituteAndBreakType(expression.typeOperand) val returnType = getTypeOperatorReturnType(expression.operator, erasedTypeOperand) return IrTypeOperatorCallImpl( startOffset = expression.startOffset, endOffset = expression.endOffset, type = returnType, operator = expression.operator, typeOperand = typeOperand, argument = expression.argument.transform(this, null), typeOperandClassifier = (typeOperand as IrSimpleType).classifier ) } //---------------------------------------------------------------------// override fun visitReturn(expression: IrReturn): IrReturn = IrReturnImpl( startOffset = expression.startOffset, endOffset = expression.endOffset, type = substituteAndEraseType(expression.type)!!, returnTargetDescriptor = mapReturnTarget(expression.returnTarget), value = expression.value.transform(this, null) ) //---------------------------------------------------------------------// override fun visitBlock(expression: IrBlock): IrBlock { return if (expression is IrReturnableBlock) { IrReturnableBlockImpl( startOffset = expression.startOffset, endOffset = expression.endOffset, type = expression.type, descriptor = expression.descriptor, origin = mapStatementOrigin(expression.origin), statements = expression.statements.map { it.transform(this, null) }, sourceFileName = expression.sourceFileName ) } else { IrBlockImpl( expression.startOffset, expression.endOffset, substituteAndEraseType(expression.type)!!, mapStatementOrigin(expression.origin), expression.statements.map { it.transform(this, null) } ) } } //-------------------------------------------------------------------------// override fun visitClassReference(expression: IrClassReference): IrClassReference { val newExpressionType = substituteAndEraseType(expression.type)!! // Substituted expression type. val newDescriptorType = substituteType(expression.descriptor.defaultType)!! // Substituted type of referenced class. val classDescriptor = newDescriptorType.constructor.declarationDescriptor!! // Get ClassifierDescriptor of the referenced class. return IrClassReferenceImpl( startOffset = expression.startOffset, endOffset = expression.endOffset, type = newExpressionType, descriptor = classDescriptor, classType = expression.classType ) } //-------------------------------------------------------------------------// override fun visitGetClass(expression: IrGetClass): IrGetClass { val type = substituteAndEraseType(expression.type)!! return IrGetClassImpl( startOffset = expression.startOffset, endOffset = expression.endOffset, type = type, argument = expression.argument.transform(this, null) ) } //-------------------------------------------------------------------------// override fun getNonTransformedLoop(irLoop: IrLoop): IrLoop { return irLoop } override fun visitClass(declaration: IrClass): IrClass { val descriptor = this.mapClassDeclaration(declaration.descriptor) return context.symbolTable.declareClass( declaration.startOffset, declaration.endOffset, mapDeclarationOrigin(declaration.origin), descriptor ).apply { declaration.declarations.mapTo(this.declarations) { it.transform(this@InlineCopyIr, null) as IrDeclaration } this.transformAnnotations(declaration) this.thisReceiver = declaration.thisReceiver?.replaceDescriptor1(this.descriptor.thisAsReceiverParameter) this.transformTypeParameters(declaration, this.descriptor.declaredTypeParameters) descriptor.defaultType.constructor.supertypes.mapTo(this.superTypes) { context.symbolTable.translateErased(it) } } } } //-------------------------------------------------------------------------// private fun substituteType(type: KotlinType?): KotlinType? { val substitutedType = (type?.let { typeSubstitutor?.substitute(it, Variance.INVARIANT) } ?: type) ?: return null val oldClassDescriptor = TypeUtils.getClassDescriptor(substitutedType) ?: return substitutedType return descriptorSubstituteMap[oldClassDescriptor]?.let { (it as ClassDescriptor).defaultType } ?: substitutedType } private fun substituteAndEraseType(oldType: IrType?): IrType? { oldType ?: return null val substitutedKotlinType = substituteType(oldType.toKotlinType()) ?: return oldType return context.symbolTable.translateErased(substitutedKotlinType) } fun translateBroken(type: KotlinType): IrType { val declarationDescriptor = type.constructor.declarationDescriptor return when (declarationDescriptor) { is ClassDescriptor -> { val classifier = context.symbolTable.referenceClassifier(declarationDescriptor) val typeArguments = type.arguments.map { if (it.isStarProjection) { IrStarProjectionImpl } else { makeTypeProjection(translateBroken(it.type), it.projectionKind) } } IrSimpleTypeImpl( classifier, type.isMarkedNullable, typeArguments, emptyList() ) } is TypeParameterDescriptor -> IrSimpleTypeImpl( context.symbolTable.referenceTypeParameter(declarationDescriptor), type.isMarkedNullable, emptyList(), emptyList() ) else -> error(declarationDescriptor ?: "null") } } private fun substituteAndBreakType(oldType: IrType): IrType { return translateBroken(substituteType(oldType.toKotlinType())!!) } //-------------------------------------------------------------------------// private fun IrMemberAccessExpression.substituteTypeArguments(original: IrMemberAccessExpression) { for (index in 0 until original.typeArgumentsCount) { val originalTypeArgument = original.getTypeArgument(index) val newTypeArgument = substituteAndBreakType(originalTypeArgument!!) this.putTypeArgument(index, newTypeArgument) } } //-------------------------------------------------------------------------// override fun addCurrentSubstituteMap(globalSubstituteMap: MutableMap<DeclarationDescriptor, SubstitutedDescriptor>) { descriptorSubstituteMap.forEach { t, u -> globalSubstituteMap[t] = SubstitutedDescriptor(targetDescriptor, u) } } } class SubstitutedDescriptor(val inlinedFunction: FunctionDescriptor, val descriptor: DeclarationDescriptor) internal class DescriptorSubstitutorForExternalScope( val globalSubstituteMap: Map<DeclarationDescriptor, SubstitutedDescriptor>, val context: Context ) : IrElementTransformerVoidWithContext() { fun run(element: IrElement) { element.transformChildrenVoid(this) } override fun visitCall(expression: IrCall): IrExpression { val oldExpression = super.visitCall(expression) as IrCall val substitutedDescriptor = globalSubstituteMap[expression.descriptor.original] ?: return oldExpression if (allScopes.any { it.scope.scopeOwner == substitutedDescriptor.inlinedFunction }) return oldExpression return when (oldExpression) { is IrCallImpl -> copyIrCallImpl(oldExpression, substitutedDescriptor) is IrCallWithShallowCopy -> copyIrCallWithShallowCopy(oldExpression, substitutedDescriptor) else -> oldExpression } } //-------------------------------------------------------------------------// private fun copyIrCallImpl(oldExpression: IrCallImpl, substitutedDescriptor: SubstitutedDescriptor): IrCallImpl { val oldDescriptor = oldExpression.descriptor val newDescriptor = substitutedDescriptor.descriptor as FunctionDescriptor if (newDescriptor == oldDescriptor) return oldExpression return IrCallImpl( startOffset = oldExpression.startOffset, endOffset = oldExpression.endOffset, type = context.symbolTable.translateErased(newDescriptor.returnType!!), symbol = createFunctionSymbol(newDescriptor), descriptor = newDescriptor, typeArgumentsCount = oldExpression.typeArgumentsCount, origin = oldExpression.origin, superQualifierSymbol = createClassSymbolOrNull(oldExpression.superQualifier) ).apply { copyTypeArgumentsFrom(oldExpression) oldExpression.descriptor.valueParameters.forEach { val valueArgument = oldExpression.getValueArgument(it) putValueArgument(it.index, valueArgument) } extensionReceiver = oldExpression.extensionReceiver dispatchReceiver = oldExpression.dispatchReceiver } } //-------------------------------------------------------------------------// private fun copyIrCallWithShallowCopy(oldExpression: IrCallWithShallowCopy, substitutedDescriptor: SubstitutedDescriptor): IrCall { val oldDescriptor = oldExpression.descriptor val newDescriptor = substitutedDescriptor.descriptor as FunctionDescriptor if (newDescriptor == oldDescriptor) return oldExpression return oldExpression.shallowCopy(oldExpression.origin, createFunctionSymbol(newDescriptor), oldExpression.superQualifierSymbol) } }
1
null
2
2
b6be6a4919cd7f37426d1e8780509a22fa49e1b1
57,906
kotlin
Apache License 2.0
model/src/commonMain/kotlin/LocaledString.kt
DroidKaigi
143,598,291
false
null
package io.github.droidkaigi.confsched2020.model @AndroidParcelize data class LocaledString( val ja: String, val en: String ) : AndroidParcel { val currentLangString get() = getByLang(defaultLang()) fun getByLang(lang: Lang): String { return if (lang == Lang.JA) { ja } else { en } } }
46
null
331
828
839b6dca4780aac1746c819f7ca8af6100afcda8
356
conference-app-2019
Apache License 2.0
libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/internal/navigation/maneuver/ManeuverIconHelper.kt
joshkw
267,965,204
true
{"Java Properties": 3, "Markdown": 10, "Shell": 5, "Batchfile": 2, "Makefile": 1, "INI": 29, "Proguard": 15, "HTML": 8, "Kotlin": 491, "Java": 530, "JavaScript": 2, "Python": 2}
package com.mapbox.services.android.navigation.v5.internal.navigation.maneuver import androidx.core.util.Pair import com.mapbox.services.android.navigation.v5.navigation.NavigationConstants.STEP_MANEUVER_MODIFIER_LEFT import com.mapbox.services.android.navigation.v5.navigation.NavigationConstants.STEP_MANEUVER_MODIFIER_RIGHT import com.mapbox.services.android.navigation.v5.navigation.NavigationConstants.STEP_MANEUVER_MODIFIER_SHARP_LEFT import com.mapbox.services.android.navigation.v5.navigation.NavigationConstants.STEP_MANEUVER_MODIFIER_SHARP_RIGHT import com.mapbox.services.android.navigation.v5.navigation.NavigationConstants.STEP_MANEUVER_MODIFIER_SLIGHT_LEFT import com.mapbox.services.android.navigation.v5.navigation.NavigationConstants.STEP_MANEUVER_MODIFIER_SLIGHT_RIGHT import com.mapbox.services.android.navigation.v5.navigation.NavigationConstants.STEP_MANEUVER_MODIFIER_STRAIGHT import com.mapbox.services.android.navigation.v5.navigation.NavigationConstants.STEP_MANEUVER_MODIFIER_UTURN import com.mapbox.services.android.navigation.v5.navigation.NavigationConstants.STEP_MANEUVER_TYPE_ARRIVE import com.mapbox.services.android.navigation.v5.navigation.NavigationConstants.STEP_MANEUVER_TYPE_EXIT_ROTARY import com.mapbox.services.android.navigation.v5.navigation.NavigationConstants.STEP_MANEUVER_TYPE_EXIT_ROUNDABOUT import com.mapbox.services.android.navigation.v5.navigation.NavigationConstants.STEP_MANEUVER_TYPE_FORK import com.mapbox.services.android.navigation.v5.navigation.NavigationConstants.STEP_MANEUVER_TYPE_MERGE import com.mapbox.services.android.navigation.v5.navigation.NavigationConstants.STEP_MANEUVER_TYPE_OFF_RAMP import com.mapbox.services.android.navigation.v5.navigation.NavigationConstants.STEP_MANEUVER_TYPE_ROTARY import com.mapbox.services.android.navigation.v5.navigation.NavigationConstants.STEP_MANEUVER_TYPE_ROUNDABOUT import com.mapbox.services.android.navigation.v5.navigation.NavigationConstants.STEP_MANEUVER_TYPE_ROUNDABOUT_TURN object ManeuverIconHelper { const val DEFAULT_ROUNDABOUT_ANGLE = 180f private const val TOP_ROUNDABOUT_ANGLE_LIMIT = 300f private const val BOTTOM_ROUNDABOUT_ANGLE_LIMIT = 60f @JvmField val MANEUVER_ICON_DRAWER_MAP: Map<Pair<String, String>, ManeuverIconDrawer> = object : HashMap<Pair<String, String>, ManeuverIconDrawer>() { init { put(Pair(STEP_MANEUVER_TYPE_MERGE, null), ManeuverIconDrawer { canvas, primaryColor, secondaryColor, size, roundaboutAngle -> ManeuversStyleKit.drawMerge(canvas, primaryColor, secondaryColor, size) }) put(Pair(STEP_MANEUVER_TYPE_OFF_RAMP, null), ManeuverIconDrawer { canvas, primaryColor, secondaryColor, size, roundaboutAngle -> ManeuversStyleKit.drawOffRamp(canvas, primaryColor, secondaryColor, size) }) put(Pair(STEP_MANEUVER_TYPE_FORK, null), ManeuverIconDrawer { canvas, primaryColor, secondaryColor, size, roundaboutAngle -> ManeuversStyleKit.drawFork(canvas, primaryColor, secondaryColor, size) }) put(Pair(STEP_MANEUVER_TYPE_ROUNDABOUT, null), ManeuverIconDrawer { canvas, primaryColor, secondaryColor, size, roundaboutAngle -> ManeuversStyleKit.drawRoundabout( canvas, primaryColor, secondaryColor, size, roundaboutAngle ) }) put(Pair(STEP_MANEUVER_TYPE_ROUNDABOUT_TURN, null), ManeuverIconDrawer { canvas, primaryColor, secondaryColor, size, roundaboutAngle -> ManeuversStyleKit.drawRoundabout( canvas, primaryColor, secondaryColor, size, roundaboutAngle ) }) put(Pair(STEP_MANEUVER_TYPE_EXIT_ROUNDABOUT, null), ManeuverIconDrawer { canvas, primaryColor, secondaryColor, size, roundaboutAngle -> ManeuversStyleKit.drawRoundabout( canvas, primaryColor, secondaryColor, size, roundaboutAngle ) }) put(Pair(STEP_MANEUVER_TYPE_ROTARY, null), ManeuverIconDrawer { canvas, primaryColor, secondaryColor, size, roundaboutAngle -> ManeuversStyleKit.drawRoundabout( canvas, primaryColor, secondaryColor, size, roundaboutAngle ) }) put(Pair(STEP_MANEUVER_TYPE_EXIT_ROTARY, null), ManeuverIconDrawer { canvas, primaryColor, secondaryColor, size, roundaboutAngle -> ManeuversStyleKit.drawRoundabout( canvas, primaryColor, secondaryColor, size, roundaboutAngle ) }) put(Pair(STEP_MANEUVER_TYPE_ARRIVE, null), ManeuverIconDrawer { canvas, primaryColor, secondaryColor, size, roundaboutAngle -> ManeuversStyleKit.drawArrive(canvas, primaryColor, size) }) put(Pair(STEP_MANEUVER_TYPE_ARRIVE, STEP_MANEUVER_MODIFIER_STRAIGHT), ManeuverIconDrawer { canvas, primaryColor, secondaryColor, size, roundaboutAngle -> ManeuversStyleKit.drawArrive(canvas, primaryColor, size) }) put(Pair(STEP_MANEUVER_TYPE_ARRIVE, STEP_MANEUVER_MODIFIER_RIGHT), ManeuverIconDrawer { canvas, primaryColor, secondaryColor, size, roundaboutAngle -> ManeuversStyleKit.drawArriveRight(canvas, primaryColor, size) }) put(Pair(STEP_MANEUVER_TYPE_ARRIVE, STEP_MANEUVER_MODIFIER_LEFT), ManeuverIconDrawer { canvas, primaryColor, secondaryColor, size, roundaboutAngle -> ManeuversStyleKit.drawArriveRight(canvas, primaryColor, size) }) put(Pair(null, STEP_MANEUVER_MODIFIER_SLIGHT_RIGHT), ManeuverIconDrawer { canvas, primaryColor, secondaryColor, size, roundaboutAngle -> ManeuversStyleKit.drawArrowSlightRight(canvas, primaryColor, size) }) put(Pair(null, STEP_MANEUVER_MODIFIER_RIGHT), ManeuverIconDrawer { canvas, primaryColor, secondaryColor, size, roundaboutAngle -> ManeuversStyleKit.drawArrowRight(canvas, primaryColor, size) }) put(Pair(null, STEP_MANEUVER_MODIFIER_SHARP_RIGHT), ManeuverIconDrawer { canvas, primaryColor, secondaryColor, size, roundaboutAngle -> ManeuversStyleKit.drawArrowSharpRight(canvas, primaryColor, size) }) put(Pair(null, STEP_MANEUVER_MODIFIER_SLIGHT_LEFT), ManeuverIconDrawer { canvas, primaryColor, secondaryColor, size, roundaboutAngle -> ManeuversStyleKit.drawArrowSlightRight(canvas, primaryColor, size) }) put(Pair(null, STEP_MANEUVER_MODIFIER_LEFT), ManeuverIconDrawer { canvas, primaryColor, secondaryColor, size, roundaboutAngle -> ManeuversStyleKit.drawArrowRight(canvas, primaryColor, size) }) put(Pair(null, STEP_MANEUVER_MODIFIER_SHARP_LEFT), ManeuverIconDrawer { canvas, primaryColor, secondaryColor, size, roundaboutAngle -> ManeuversStyleKit.drawArrowSharpRight(canvas, primaryColor, size) }) put(Pair(null, STEP_MANEUVER_MODIFIER_UTURN), ManeuverIconDrawer { canvas, primaryColor, secondaryColor, size, roundaboutAngle -> ManeuversStyleKit.drawArrow180Right(canvas, primaryColor, size) }) put(Pair(null, STEP_MANEUVER_MODIFIER_STRAIGHT), ManeuverIconDrawer { canvas, primaryColor, secondaryColor, size, roundaboutAngle -> ManeuversStyleKit.drawArrowStraight(canvas, primaryColor, size) }) put(Pair(null, null), ManeuverIconDrawer { canvas, primaryColor, secondaryColor, size, roundaboutAngle -> ManeuversStyleKit.drawArrowStraight(canvas, primaryColor, size) }) } } @JvmField val SHOULD_FLIP_MODIFIERS: Set<String> = object : HashSet<String>() { init { add(STEP_MANEUVER_MODIFIER_SLIGHT_LEFT) add(STEP_MANEUVER_MODIFIER_LEFT) add(STEP_MANEUVER_MODIFIER_SHARP_LEFT) add(STEP_MANEUVER_MODIFIER_UTURN) } } @JvmField val ROUNDABOUT_MANEUVER_TYPES: Set<String> = object : HashSet<String>() { init { add(STEP_MANEUVER_TYPE_ROTARY) add(STEP_MANEUVER_TYPE_ROUNDABOUT) add(STEP_MANEUVER_TYPE_ROUNDABOUT_TURN) add(STEP_MANEUVER_TYPE_EXIT_ROUNDABOUT) add(STEP_MANEUVER_TYPE_EXIT_ROTARY) } } @JvmField val MANEUVER_TYPES_WITH_NULL_MODIFIERS: Set<String> = object : HashSet<String>() { init { add(STEP_MANEUVER_TYPE_OFF_RAMP) add(STEP_MANEUVER_TYPE_FORK) add(STEP_MANEUVER_TYPE_ROUNDABOUT) add(STEP_MANEUVER_TYPE_ROUNDABOUT_TURN) add(STEP_MANEUVER_TYPE_EXIT_ROUNDABOUT) add(STEP_MANEUVER_TYPE_ROTARY) add(STEP_MANEUVER_TYPE_EXIT_ROTARY) } } @JvmStatic fun isManeuverIconNeedFlip( maneuverType: String?, maneuverModifier: String?, drivingSide: String? ): Boolean { val leftDriving = STEP_MANEUVER_MODIFIER_LEFT == drivingSide val roundaboutManeuverType = ROUNDABOUT_MANEUVER_TYPES.contains(maneuverType) val uturnManeuverModifier = !maneuverModifier.isNullOrBlank() && STEP_MANEUVER_MODIFIER_UTURN.contains( maneuverModifier ) var flip = SHOULD_FLIP_MODIFIERS.contains(maneuverModifier) if (roundaboutManeuverType) { flip = leftDriving } return if (leftDriving && uturnManeuverModifier) { !flip } else { flip } } @JvmStatic fun adjustRoundaboutAngle(roundaboutAngle: Float): Float = when { roundaboutAngle < BOTTOM_ROUNDABOUT_ANGLE_LIMIT -> BOTTOM_ROUNDABOUT_ANGLE_LIMIT roundaboutAngle > TOP_ROUNDABOUT_ANGLE_LIMIT -> TOP_ROUNDABOUT_ANGLE_LIMIT else -> roundaboutAngle } }
0
null
0
0
7ce03b8464d0312692a53a5686c5f58007d7020e
11,490
mapbox-navigation-android
Apache License 2.0
app/src/main/java/com/aayar94/foodrecipes/utils/Constants.kt
AAyar94
646,751,480
false
null
package com.aayar94.foodrecipes.utils import com.aayar94.foodrecipes.BuildConfig class Constants { companion object { const val BASE_URL = "https://api.spoonacular.com" const val BASE_IMAGE_URL = "https://spoonacular.com/cdn/ingredients_100x100/" const val API_KEY = BuildConfig.FOOD_RECIPES_API_KEY const val RECIPE_KEY_RESULT = "recipeBundle" /** API Query Keys */ const val QUERY_SEARCH = "query" const val QUERY_NUMBER = "number" const val QUERY_API_KEY = "apiKey" const val QUERY_TYPE = "type" const val QUERY_DIET = "diet" const val QUERY_ADD_RECIPE_INFORMATION = "addRecipeInformation" const val QUERY_FILL_INGREDIENTS = "fillIngredients" /** ROOM Database */ const val DATABASE_NAME = "recipes_database" const val RECIPES_TABLE = "recipes_table" const val FAVORITE_RECIPES_TABLE = "favorite_recipes_table" const val FOOD_JOKE_TABLE = "food_joke_table" /** BottomSheet and Preferences */ const val DEFAULT_RECIPES_NUMBER = "50" const val DEFAULT_MEAL_TYPE = "main course" const val DEFAULT_DIET_TYPE = "gluten free" const val PREFERENCES_NAME = "food_recipes_preferences" const val PREFERENCES_MEAL_TYPE = "mealType" const val PREFERENCES_MEAL_TYPE_ID = "mealTypeId" const val PREFERENCES_DIET_TYPE = "dietType" const val PREFERENCES_DIET_TYPE_ID = "dietTypeId" const val PREFERENCES_BACK_ONLINE = "backOnline" const val PREFERENCES_LANDING_FINISHED = "landingFinished" } }
0
Kotlin
0
1
7410f3c68d050d8a6d9d0364fc7d7495ac62b1ff
1,628
Food_Recipes
MIT License
liveview-android/src/test/java/com/dockyard/liveviewtest/liveview/components/IconButtonShotTest.kt
liveview-native
459,214,950
false
{"Kotlin": 1385799, "Elixir": 68578}
package com.dockyard.liveviewtest.liveview.components import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.layout.Row import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AccountCircle import androidx.compose.material3.FilledIconButton import androidx.compose.material3.FilledTonalIconButton import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.OutlinedIconButton import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import com.dockyard.liveviewtest.liveview.util.LiveViewComposableTest import org.junit.Test class IconButtonShotTest : LiveViewComposableTest() { @Test fun simpleIconButtonTest() { compareNativeComposableWithTemplate( nativeComposable = { Row { IconButton(onClick = {}) { Icon(imageVector = Icons.Filled.AccountCircle, contentDescription = "") } IconButton(onClick = {}, enabled = false) { Icon(imageVector = Icons.Filled.AccountCircle, contentDescription = "") } } }, template = """ <Row> <IconButton phx-click=""> <Icon image-vector="filled:AccountCircle" /> </IconButton> <IconButton phx-click="" enabled="false"> <Icon image-vector="filled:AccountCircle" /> </IconButton> </Row> """ ) } @Test fun iconButtonWithCustomColorsTest() { compareNativeComposableWithTemplate( nativeComposable = { Row { IconButton( onClick = {}, colors = IconButtonDefaults.iconButtonColors( containerColor = Color.Red, contentColor = Color.Yellow, ), ) { Icon(imageVector = Icons.Filled.AccountCircle, contentDescription = "") } IconButton( onClick = {}, enabled = false, colors = IconButtonDefaults.iconButtonColors( disabledContainerColor = Color.Gray, disabledContentColor = Color.LightGray, ), ) { Icon(imageVector = Icons.Filled.AccountCircle, contentDescription = "") } } }, template = """ <Row> <IconButton phx-click="" colors="{'containerColor': '#FFFF0000', 'contentColor': '#FFFFFF00'}"> <Icon image-vector="filled:AccountCircle" /> </IconButton> <IconButton phx-click="" enabled="false" colors="{'disabledContainerColor': '#FF888888', 'disabledContentColor': '#FFCCCCCC'}"> <Icon image-vector="filled:AccountCircle" /> </IconButton> </Row> """ ) } @Test fun simpleFilledIconButtonTest() { compareNativeComposableWithTemplate( nativeComposable = { Row { FilledIconButton(onClick = {}) { Icon(imageVector = Icons.Filled.AccountCircle, contentDescription = "") } FilledIconButton(onClick = {}, enabled = false) { Icon(imageVector = Icons.Filled.AccountCircle, contentDescription = "") } } }, template = """ <Row> <FilledIconButton phx-click=""> <Icon image-vector="filled:AccountCircle" /> </FilledIconButton> <FilledIconButton phx-click="" enabled="false"> <Icon image-vector="filled:AccountCircle" /> </FilledIconButton> </Row> """ ) } @Test fun filledIconButtonWithCustomColorsTest() { compareNativeComposableWithTemplate( nativeComposable = { Row { FilledIconButton( onClick = {}, shape = RoundedCornerShape(8.dp), colors = IconButtonDefaults.iconButtonColors( containerColor = Color.Red, contentColor = Color.Yellow, ), ) { Icon(imageVector = Icons.Filled.AccountCircle, contentDescription = "") } FilledIconButton( onClick = {}, shape = RoundedCornerShape(8.dp), enabled = false, colors = IconButtonDefaults.iconButtonColors( disabledContainerColor = Color.Gray, disabledContentColor = Color.LightGray, ), ) { Icon(imageVector = Icons.Filled.AccountCircle, contentDescription = "") } } }, template = """ <Row> <FilledIconButton phx-click="" shape="8" colors="{'containerColor': '#FFFF0000', 'contentColor': '#FFFFFF00'}"> <Icon image-vector="filled:AccountCircle" /> </FilledIconButton> <FilledIconButton phx-click="" enabled="false" shape="8" colors="{'disabledContainerColor': '#FF888888', 'disabledContentColor': '#FFCCCCCC'}"> <Icon image-vector="filled:AccountCircle" /> </FilledIconButton> </Row> """ ) } @Test fun simpleFilledTonalIconButtonTest() { compareNativeComposableWithTemplate( nativeComposable = { Row { FilledTonalIconButton(onClick = {}) { Icon(imageVector = Icons.Filled.AccountCircle, contentDescription = "") } FilledTonalIconButton(onClick = {}, enabled = false) { Icon(imageVector = Icons.Filled.AccountCircle, contentDescription = "") } } }, template = """ <Row> <FilledTonalIconButton phx-click=""> <Icon image-vector="filled:AccountCircle" /> </FilledTonalIconButton> <FilledTonalIconButton phx-click="" enabled="false"> <Icon image-vector="filled:AccountCircle" /> </FilledTonalIconButton> </Row> """ ) } @Test fun filledTonalIconButtonWithCustomColorsTest() { compareNativeComposableWithTemplate( nativeComposable = { Row { FilledTonalIconButton( onClick = {}, shape = RoundedCornerShape(8.dp), colors = IconButtonDefaults.iconButtonColors( containerColor = Color.Red, contentColor = Color.Yellow, ), ) { Icon(imageVector = Icons.Filled.AccountCircle, contentDescription = "") } FilledTonalIconButton( onClick = {}, shape = RoundedCornerShape(8.dp), enabled = false, colors = IconButtonDefaults.iconButtonColors( disabledContainerColor = Color.Gray, disabledContentColor = Color.LightGray, ), ) { Icon(imageVector = Icons.Filled.AccountCircle, contentDescription = "") } } }, template = """ <Row> <FilledTonalIconButton phx-click="" shape="8" colors="{'containerColor': '#FFFF0000', 'contentColor': '#FFFFFF00'}"> <Icon image-vector="filled:AccountCircle" /> </FilledTonalIconButton> <FilledTonalIconButton phx-click="" enabled="false" shape="8" colors="{'disabledContainerColor': '#FF888888', 'disabledContentColor': '#FFCCCCCC'}"> <Icon image-vector="filled:AccountCircle" /> </FilledTonalIconButton> </Row> """ ) } @Test fun simpleOutlinedIconButtonTest() { compareNativeComposableWithTemplate( nativeComposable = { Row { OutlinedIconButton(onClick = {}) { Icon(imageVector = Icons.Filled.AccountCircle, contentDescription = "") } OutlinedIconButton(onClick = {}, enabled = false) { Icon(imageVector = Icons.Filled.AccountCircle, contentDescription = "") } } }, template = """ <Row> <OutlinedIconButton phx-click=""> <Icon image-vector="filled:AccountCircle" /> </OutlinedIconButton> <OutlinedIconButton phx-click="" enabled="false"> <Icon image-vector="filled:AccountCircle" /> </OutlinedIconButton> </Row> """ ) } @Test fun outlinedIconButtonWithCustomBorderTest() { compareNativeComposableWithTemplate( nativeComposable = { Row { OutlinedIconButton(onClick = {}, border = BorderStroke(2.dp, Color.Magenta)) { Icon(imageVector = Icons.Filled.AccountCircle, contentDescription = "") } OutlinedIconButton( onClick = {}, enabled = false, border = BorderStroke(2.dp, Color.Magenta) ) { Icon(imageVector = Icons.Filled.AccountCircle, contentDescription = "") } } }, template = """ <Row> <OutlinedIconButton phx-click="" border="{'width': '2', 'color': 'system-magenta'}"> <Icon image-vector="filled:AccountCircle" /> </OutlinedIconButton> <OutlinedIconButton phx-click="" enabled="false" border="{'width': '2', 'color': 'system-magenta'}"> <Icon image-vector="filled:AccountCircle" /> </OutlinedIconButton> </Row> """ ) } @Test fun outlinedIconButtonWithCustomColorsTest() { compareNativeComposableWithTemplate( nativeComposable = { Row { OutlinedIconButton( onClick = {}, shape = RoundedCornerShape(8.dp), border = BorderStroke(2.dp, Color.Magenta), colors = IconButtonDefaults.iconButtonColors( containerColor = Color.Red, contentColor = Color.Yellow, ), ) { Icon(imageVector = Icons.Filled.AccountCircle, contentDescription = "") } OutlinedIconButton( onClick = {}, shape = RoundedCornerShape(8.dp), border = BorderStroke(2.dp, Color.Magenta), enabled = false, colors = IconButtonDefaults.iconButtonColors( disabledContainerColor = Color.Gray, disabledContentColor = Color.LightGray, ), ) { Icon(imageVector = Icons.Filled.AccountCircle, contentDescription = "") } } }, template = """ <Row> <OutlinedIconButton phx-click="" shape="8" border="{'width': '2', 'color': 'system-magenta'}" colors="{'containerColor': '#FFFF0000', 'contentColor': '#FFFFFF00'}"> <Icon image-vector="filled:AccountCircle" /> </OutlinedIconButton> <OutlinedIconButton phx-click="" enabled="false" shape="8" border="{'width': '2', 'color': 'system-magenta'}" colors="{'disabledContainerColor': '#FF888888', 'disabledContentColor': '#FFCCCCCC'}"> <Icon image-vector="filled:AccountCircle" /> </OutlinedIconButton> </Row> """ ) } }
229
Kotlin
3
68
438752add625f97d6dec46eadf6735252fc70498
13,948
liveview-client-jetpack
MIT License
jvm/sql/src/main/kotlin/SqlParser.kt
houqp
262,223,654
false
null
package org.ballistacompute.sql import java.sql.SQLException import java.util.logging.Logger class SqlParser(val tokens: TokenStream) : PrattParser { private val logger = Logger.getLogger(SqlParser::class.simpleName) override fun nextPrecedence(): Int { val token = tokens.peek() ?: return 0 val precedence = when (token) { is KeywordToken -> { when (token.text) { "AS" -> 10 "OR" -> 20 "AND" -> 30 else -> 0 } } is OperatorToken -> { when (token.text) { "<", "<=", "=", "!=", ">=", ">" -> 40 "+", "-" -> 50 "*", "/" -> 60 else -> 0 } } is LParenToken -> 70 else -> 0 } logger.fine("nextPrecedence($token) returning $precedence") return precedence } override fun parsePrefix(): SqlExpr? { logger.fine("parsePrefix() next token = ${tokens.peek()}") val token = tokens.next() ?: return null val expr = when (token) { is KeywordToken -> { when (token.text) { "SELECT" -> parseSelect() "CAST" -> parseCast() else -> throw IllegalStateException("Unexpected keyword ${token.text}") } } is IdentifierToken -> SqlIdentifier(token.text) is LiteralStringToken -> SqlString(token.text) is LiteralLongToken -> SqlLong(token.text.toLong()) is LiteralDoubleToken -> SqlDouble(token.text.toDouble()) else -> throw IllegalStateException("Unexpected token $token") } logger.fine("parsePrefix() returning $expr") return expr } override fun parseInfix(left: SqlExpr, precedence: Int): SqlExpr { logger.fine("parseInfix() next token = ${tokens.peek()}") val token = tokens.peek() val expr = when (token) { is OperatorToken -> { tokens.next() // consume the token SqlBinaryExpr(left, token.text, parse(precedence) ?: throw SQLException("Error parsing infix")) } is KeywordToken -> { when (token.text) { "AS" -> { tokens.next() // consume the token SqlAlias(left, parseIdentifier()) } "AND", "OR" -> { tokens.next() // consume the token SqlBinaryExpr(left, token.text, parse(precedence) ?: throw SQLException("Error parsing infix")) } else -> throw IllegalStateException("Unexpected infix token $token") } } is LParenToken -> { if (left is SqlIdentifier) { tokens.next() // consume the token val args = parseExprList() assert(tokens.next() == RParenToken()) SqlFunction(left.id, args) } else { throw IllegalStateException("Unexpected LPAREN") } } else -> throw IllegalStateException("Unexpected infix token $token") } logger.fine("parseInfix() returning $expr") return expr } private fun parseCast() : SqlCast { assert(tokens.consumeToken(LParenToken())) val expr = parseExpr() ?: throw SQLException() val alias = expr as SqlAlias assert(tokens.consumeToken(RParenToken())) return SqlCast(alias.expr, alias.alias) } private fun parseSelect() : SqlSelect { val projection = parseExprList() if (tokens.consumeKeyword("FROM")) { val table = parseExpr() as SqlIdentifier // parse optional WHERE clause var filterExpr : SqlExpr? = null if (tokens.consumeKeyword("WHERE")) { filterExpr = parseExpr() } // parse optional GROUP BY clause var groupBy : List<SqlExpr> = listOf() if (tokens.consumeKeywords(listOf("GROUP", "BY"))) { groupBy = parseExprList() } return SqlSelect(projection, filterExpr, groupBy, table.id) } else { throw IllegalStateException("Expected FROM keyword, found ${tokens.peek()}") } } private fun parseExprList() : List<SqlExpr> { logger.fine("parseExprList()") val list = mutableListOf<SqlExpr>() var expr = parseExpr() while (expr != null) { //logger.fine("parseExprList parsed $expr") list.add(expr) if (tokens.peek() == CommaToken()) { tokens.next() } else { break } expr = parseExpr() } logger.fine("parseExprList() returning $list") return list } private fun parseExpr() = parse(0) /** Parse the next token as an identifier, throwing an exception if the next token is not an identifier. */ private fun parseIdentifier() : SqlIdentifier { val expr = parseExpr() ?: throw SQLException("Expected identifier, found EOF") return when (expr) { is SqlIdentifier -> expr else -> throw SQLException("Expected identifier, found $expr") } } }
1
null
1
1
7011dec497090403ae861b6ce78ec48349755090
5,550
ballista
Apache License 2.0
src/main/kotlin/org/rust/ide/refactoring/RsDowngradeModuleToFile.kt
intellij-rust
42,619,487
false
null
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.refactoring import com.intellij.lang.Language import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiFileSystemItem import com.intellij.psi.impl.file.PsiFileImplUtil import com.intellij.refactoring.RefactoringActionHandler import com.intellij.refactoring.actions.BaseRefactoringAction import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil import org.rust.RsBundle import org.rust.lang.RsConstants import org.rust.lang.RsLanguage import org.rust.lang.core.psi.RsFile import org.rust.openapiext.checkWriteAccessAllowed import org.rust.openapiext.runWriteCommandAction class RsDowngradeModuleToFile : BaseRefactoringAction() { override fun isEnabledOnElements(elements: Array<out PsiElement>): Boolean = elements.all { it.isDirectoryMod } override fun isAvailableOnElementInEditorAndFile( element: PsiElement, editor: Editor, file: PsiFile, context: DataContext ): Boolean { return file.isDirectoryMod } override fun getHandler(dataContext: DataContext): RefactoringActionHandler = Handler override fun isAvailableInEditorOnly(): Boolean = false // `ANY` language is here because the refactoring may be called for directory which language is `ANY` override fun isAvailableForLanguage(language: Language): Boolean = language.`is`(RsLanguage) || language.`is`(Language.ANY) private object Handler : RefactoringActionHandler { override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext?) { invoke(project, arrayOf(file), dataContext) } override fun invoke(project: Project, elements: Array<out PsiElement>, dataContext: DataContext?) { project.runWriteCommandAction(RsBundle.message("action.Rust.RsDowngradeModuleToFile.text")) { for (element in elements) { contractModule(element as PsiFileSystemItem) } } } } } private fun contractModule(fileOrDirectory: PsiFileSystemItem) { checkWriteAccessAllowed() val (file, dir) = when (fileOrDirectory) { is RsFile -> fileOrDirectory to fileOrDirectory.parent!! is PsiDirectory -> fileOrDirectory.children.single() as RsFile to fileOrDirectory else -> error("Can contract only files and directories") } val dst = dir.parent!! val fileName = "${dir.name}.rs" PsiFileImplUtil.setName(file, fileName) MoveFilesOrDirectoriesUtil.doMoveFile(file, dst) dir.delete() } private val PsiElement.isDirectoryMod: Boolean get() { return when (this) { is RsFile -> name == RsConstants.MOD_RS_FILE && containingDirectory?.children?.size == 1 is PsiDirectory -> { val child = children.singleOrNull() child is RsFile && child.name == RsConstants.MOD_RS_FILE } else -> false } }
1,841
null
380
4,528
c6657c02bb62075bf7b7ceb84d000f93dda34dc1
3,289
intellij-rust
MIT License
ui/src/test/kotlin/io/rippledown/caseview/ValueCellTest.kt
TimLavers
513,037,911
false
{"Kotlin": 992626, "Gherkin": 35600, "Java": 138}
package io.rippledown.caseview import androidx.compose.foundation.layout.RowScope import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.hasText import androidx.compose.ui.test.junit4.createComposeRule import io.kotest.matchers.shouldBe import io.mockk.every import io.mockk.mockk import io.rippledown.mocks.DummyRowScope import io.rippledown.model.Attribute import io.rippledown.model.ReferenceRange import io.rippledown.model.TestResult import org.junit.Rule import org.junit.Test @OptIn(ExperimentalTestApi::class) class ValueCellTest { @get:Rule var composeTestRule = createComposeRule() private val tsh = Attribute(12, "TSH") private val columnWidths = ColumnWidths(7) @Test fun `show result that does not have units`() { val testResult = TestResult("12.8", null, null) val rowScope: RowScope = DummyRowScope() composeTestRule.setContent { rowScope.ValueCell("Bondi", tsh, 1, testResult, columnWidths) } with(composeTestRule) { waitUntilExactlyOneExists(hasText("12.8")) } } @Test fun `column widths`() { val columnWidths = mockk<ColumnWidths>() every { columnWidths.valueColumnWeight() }.returns(0.5F) val testResult = TestResult("12.8", null, null) val rowScope: RowScope = DummyRowScope() composeTestRule.setContent { rowScope.ValueCell("Bondi", tsh, 1, testResult, columnWidths) } } @Test fun `show result that has units`() { val testResult = TestResult("12.8", null, "waves / sec") val rowScope: RowScope = DummyRowScope() composeTestRule.setContent { rowScope.ValueCell("Bondi", tsh, 1, testResult, columnWidths) } with(composeTestRule) { waitUntilExactlyOneExists(hasText("12.8 waves / sec")) } } @Test fun resultTextTest() { resultText(TestResult("44.1", null, null)) shouldBe "44.1" resultText(TestResult("44.1", ReferenceRange("1", "2"), null)) shouldBe "44.1" resultText(TestResult("44.1", null, "furlongs / fortnight")) shouldBe "44.1 furlongs / fortnight" resultText(TestResult("10", null, "mmol/L")) shouldBe "10 mmol/L" resultText(TestResult("10", null, " mmol/L ")) shouldBe "10 mmol/L" } }
0
Kotlin
0
0
755058472297b68284b515abc3e3e2fd5e3b1698
2,358
OpenRDR
MIT License
kotlin-native/runtime/src/main/kotlin/kotlin/native/runtime/NativeRuntimeApi.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package kotlin.native.runtime import kotlin.annotation.AnnotationTarget.* /** * This annotation marks the Kotlin/Native standard library API that tweaks * or otherwise accesses the Kotlin runtime behavior. * * The API marked with this annotation is considered unstable and is **not** intended to become stable in the future. * Behavior of such an API may be changed or the API may be removed completely in any further release. * * Any usage of a declaration annotated with `@NativeRuntimeApi` must be accepted either by * annotating that usage with the [OptIn] annotation, e.g. `@OptIn(NativeRuntimeApi::class)`, * or by using the compiler argument `-opt-in=kotlin.native.runtime.NativeRuntimeApi`. */ @RequiresOptIn(level = RequiresOptIn.Level.ERROR) @Retention(AnnotationRetention.BINARY) @Target( CLASS, ANNOTATION_CLASS, PROPERTY, FIELD, LOCAL_VARIABLE, VALUE_PARAMETER, CONSTRUCTOR, FUNCTION, PROPERTY_GETTER, PROPERTY_SETTER, TYPEALIAS ) @MustBeDocumented @SinceKotlin("1.9") public annotation class NativeRuntimeApi
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,332
kotlin
Apache License 2.0
test/com/intellij/stats/completion/storage/StorageTest.kt
JetBrains
45,971,220
false
null
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.stats.completion.storage import com.intellij.openapi.util.text.StringUtil import com.intellij.stats.logger.LineStorage import com.intellij.stats.logger.LogFileManager import com.intellij.stats.storage.UniqueFilesProvider import com.intellij.testFramework.PlatformTestCase import org.assertj.core.api.Assertions.assertThat import org.junit.After import org.junit.Before import org.junit.Test import java.io.File class FilesProviderTest { private lateinit var provider: UniqueFilesProvider @Before fun setUp() { provider = UniqueFilesProvider("chunk", ".", "logs-data") provider.getStatsDataDirectory().deleteRecursively() } @After fun tearDown() { provider.getStatsDataDirectory().deleteRecursively() } @Test fun `test three new files created`() { provider.getUniqueFile().createNewFile() provider.getUniqueFile().createNewFile() provider.getUniqueFile().createNewFile() val createdFiles = provider.getDataFiles().count() assertThat(createdFiles).isEqualTo(3) } } class AsciiMessageStorageTest { private lateinit var storage: LineStorage private lateinit var tmpFile: File @Before fun setUp() { storage = LineStorage() tmpFile = File("tmp_test") tmpFile.delete() } @After fun tearDown() { tmpFile.delete() } @Test fun `test size with new lines`() { val line = "text" storage.appendLine(line) assertThat(storage.sizeWithNewLine("")).isEqualTo(line.length + 2 * System.lineSeparator().length) } @Test fun `test size is same as file size`() { val line = "text" storage.appendLine(line) storage.appendLine(line) val expectedSize = 2 * (line.length + System.lineSeparator().length) assertThat(storage.size).isEqualTo(expectedSize) storage.dump(tmpFile) assertThat(tmpFile.length()).isEqualTo(expectedSize.toLong()) } } class FileLoggerTest : PlatformTestCase() { private lateinit var fileLogger: LogFileManager private lateinit var filesProvider: UniqueFilesProvider private lateinit var tempDirectory: File override fun setUp() { super.setUp() tempDirectory = createTempDirectory() filesProvider = UniqueFilesProvider("chunk", tempDirectory.absolutePath, "logs-data") fileLogger = LogFileManager(filesProvider) } override fun tearDown() { tempDirectory.deleteRecursively() super.tearDown() } fun `test chunk is around 256Kb`() { val bytesToWrite = 1024 * 200 val text = StringUtil.repeat("c", bytesToWrite) fileLogger.println(text) fileLogger.flush() val chunks = filesProvider.getDataFiles() assertThat(chunks).hasSize(1) val fileLength = chunks.first().length() assertThat(fileLength).isLessThan(256 * 1024) assertThat(fileLength).isGreaterThan(200 * 1024) } fun `test multiple chunks`() { writeKb(1024) val files = filesProvider.getDataFiles() val fileIndexes = files.map { it.name.substringAfter('_').toInt() } assertThat(files.isNotEmpty()).isTrue() assertThat(fileIndexes).isEqualTo((0 until files.size).toList()) } fun `test delete old stuff`() { writeKb(4096) val files = filesProvider.getDataFiles() val totalSizeAfterCleanup = files.fold(0L) { total, file -> total + file.length() } assertThat(totalSizeAfterCleanup < 2 * 1024 * 1024).isTrue() val firstAfter = files .map { it.name.substringAfter('_').toInt() } .sorted() .first() assertThat(firstAfter).isGreaterThan(0) } private fun writeKb(kb: Int) { val lineLength = System.lineSeparator().length (0..kb * 1024 / lineLength).forEach { fileLogger.println("") } fileLogger.flush() } }
2
null
2
8
3db7f480f7996504ee4edf3265469c88f182cae3
4,652
intellij-stats-collector
Apache License 2.0
ktor-hosts/ktor-servlet/src/org/jetbrains/ktor/servlet/ServletApplicationRequest.kt
cbeust
64,515,203
true
{"Kotlin": 928027, "FreeMarker": 6356, "CSS": 5404, "HTML": 1964, "JavaScript": 1451, "Shell": 158}
package org.jetbrains.ktor.servlet import org.jetbrains.ktor.application.* import org.jetbrains.ktor.host.* import org.jetbrains.ktor.http.* import org.jetbrains.ktor.nio.* import org.jetbrains.ktor.request.* import org.jetbrains.ktor.util.* import java.io.* import javax.servlet.http.* class ServletApplicationRequest(override val call: ServletApplicationCall, val servletRequest: HttpServletRequest) : ApplicationRequest { override val local: RequestConnectionPoint = ServletConnectionPoint(servletRequest) override val parameters: ValuesMap by lazy { object : ValuesMap { override fun getAll(name: String): List<String> = servletRequest.getParameterValues(name)?.asList() ?: emptyList() override fun entries(): Set<Map.Entry<String, List<String>>> { return servletRequest.parameterNames.asSequence().map { object : Map.Entry<String, List<String>> { override val key: String get() = it override val value: List<String> get() = getAll(it) } }.toSet() } override fun isEmpty(): Boolean = servletRequest.parameterNames.asSequence().none() override val caseInsensitiveKey: Boolean get() = false override fun names(): Set<String> = servletRequest.parameterNames.asSequence().toSet() } } override val headers: ValuesMap by lazy { object : ValuesMap { override fun getAll(name: String): List<String> = servletRequest.getHeaders(name)?.toList() ?: emptyList() override fun entries(): Set<Map.Entry<String, List<String>>> { return servletRequest.headerNames.asSequence().map { object : Map.Entry<String, List<String>> { override val key: String get() = it override val value: List<String> get() = getAll(it) } }.toSet() } override fun isEmpty(): Boolean = servletRequest.headerNames.asSequence().none() override val caseInsensitiveKey: Boolean get() = true override fun names(): Set<String> = servletRequest.headerNames.asSequence().toSet() } } private val servletReadChannel by lazy { val providedChannel = call.attributes.getOrNull(BaseApplicationCall.RequestChannelOverride) if (providedChannel == null) { call.ensureAsync() ServletReadChannel(servletRequest.inputStream) } else providedChannel } override val content: RequestContent = object : RequestContent(this) { override fun getMultiPartData(): MultiPartData = ServletMultiPartData(this@ServletApplicationRequest, servletRequest) override fun getInputStream(): InputStream = servletRequest.inputStream override fun getReadChannel(): ReadChannel = servletReadChannel } override val cookies: RequestCookies = ServletRequestCookies(servletRequest, this) } private class ServletRequestCookies(val servletRequest: HttpServletRequest, request: ApplicationRequest) : RequestCookies(request) { override val parsedRawCookies: Map<String, String> by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { servletRequest.cookies?.associateBy({ it.name }, { it.value }) ?: emptyMap() } }
0
Kotlin
0
1
8dc7ac666a336cba0f23a72cc31b8c0b14ad4f09
3,358
ktor
Apache License 2.0
turtle/src/main/kotlin/com/lordcodes/turtle/Executable.kt
lordcodes
202,986,234
false
null
package com.lordcodes.turtle import java.net.URL /** * Command executable, e.g. 'cd', with its [name] and a [helpUrl] to provide the user help if the executable isn't * found on the system. * * @property [name] The command executable name, e.g. 'cd'. * @property [helpUrl] A url that gives help for the executable if it isn't found on the system. */ data class Executable( val name: String, val helpUrl: URL? = null, ) { /** * Creates a [Command] using this executable with the provided [arguments]. * * ``` * ls + Arguments("-l", "-a") * ``` * * @return [Command] The created command. * * @param [arguments] The arguments to pass to this executable. */ operator fun plus(arguments: Arguments): Command = Command(this, arguments) /** * Creates a [Command] using this executable with the provided [withArguments]. * * ``` * ls + withArgs * ``` * * @return [Command] The created command. * * @param [withArguments] The arguments to pass to this executable. */ operator fun plus(withArguments: Iterable<WithArgument>): Command = Command(this, Arguments(withArguments)) /** * Creates a [Command] using this executable with the provided [withArgument]. * * ``` * ls + withArg * ``` * * @return [Command] The created command. * * @param [withArgument] The argument to pass to this executable. */ operator fun plus(withArgument: WithArgument): Command = Command(this, Arguments(withArgument)) }
5
null
10
249
cd30c8e1e457de2c66b7897d879b80b736b7f101
1,580
turtle
Apache License 2.0
compiler/frontend.common/src/org/jetbrains/kotlin/diagnostics/rendering/DiagnosticRenderer.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.diagnostics.rendering import org.jetbrains.kotlin.diagnostics.UnboundDiagnostic interface DiagnosticRenderer<in D : UnboundDiagnostic> { fun render(diagnostic: D): String fun renderParameters(diagnostic: D): Array<out Any?> }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
476
kotlin
Apache License 2.0
android-kotlin/android-extensions-idea-common/src/org/jetbrains/kotlin/android/synthetic/idea/ExperimentalUtils.kt
JetBrains
60,701,247
false
null
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.android.synthetic.idea import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.module.Module import kotlinx.android.extensions.CacheImplementation import org.jetbrains.android.facet.AndroidFacet import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.android.synthetic.AndroidCommandLineProcessor.Companion.ANDROID_COMPILER_PLUGIN_ID import org.jetbrains.kotlin.android.synthetic.AndroidCommandLineProcessor.Companion.EXPERIMENTAL_OPTION import org.jetbrains.kotlin.android.synthetic.AndroidCommandLineProcessor.Companion.ENABLED_OPTION import org.jetbrains.kotlin.android.synthetic.AndroidCommandLineProcessor.Companion.DEFAULT_CACHE_IMPL_OPTION import org.jetbrains.kotlin.android.synthetic.AndroidComponentRegistrar.Companion.parseCacheImplementationType import org.jetbrains.kotlin.compiler.plugin.CliOption import org.jetbrains.kotlin.idea.caches.resolve.ModuleSourceInfo import org.jetbrains.kotlin.idea.facet.KotlinFacet private val ANNOTATION_OPTION_PREFIX = "plugin:$ANDROID_COMPILER_PLUGIN_ID:" private fun Module.getOptionValueInFacet(option: CliOption): String? { val kotlinFacet = KotlinFacet.get(this) ?: return null val commonArgs = kotlinFacet.configuration.settings.compilerArguments ?: return null val prefix = ANNOTATION_OPTION_PREFIX + option.name + "=" val optionValue = commonArgs.pluginOptions ?.firstOrNull { it.startsWith(prefix) } ?.substring(prefix.length) return optionValue } private fun isTestMode(module: Module): Boolean { return ApplicationManager.getApplication().isUnitTestMode && AndroidFacet.getInstance(module) != null } internal val Module.androidExtensionsIsEnabled: Boolean get() = isTestMode(this) || getOptionValueInFacet(ENABLED_OPTION) == "true" internal val ModuleInfo.androidExtensionsIsEnabled: Boolean get() { val module = (this as? ModuleSourceInfo)?.module ?: return false return module.androidExtensionsIsEnabled } internal val ModuleInfo.androidExtensionsIsExperimental: Boolean get() { val module = (this as? ModuleSourceInfo)?.module ?: return false return module.androidExtensionsIsExperimental } internal val Module.androidExtensionsIsExperimental: Boolean get() { if (isTestMode(this)) return true return getOptionValueInFacet(EXPERIMENTAL_OPTION) == "true" } val ModuleInfo.androidExtensionsGlobalCacheImpl: CacheImplementation get() { val module = (this as? ModuleSourceInfo)?.module ?: return CacheImplementation.NO_CACHE return parseCacheImplementationType(module.getOptionValueInFacet(DEFAULT_CACHE_IMPL_OPTION)) }
4
null
5074
941
569edfadfa3d6a8b1d2560022923817df46a8bc3
3,319
android
Apache License 2.0
app/src/test/java/com/kickstarter/viewmodels/ProjectNotificationSettingsViewModelTest.kt
kickstarter
76,278,501
false
{"Kotlin": 5269841, "Java": 317201, "Ruby": 22177, "Shell": 6325, "Makefile": 3750}
package com.kickstarter.viewmodels import com.kickstarter.KSRobolectricTestCase import com.kickstarter.libs.Environment import com.kickstarter.libs.utils.extensions.addToDisposable import com.kickstarter.mock.factories.ProjectNotificationFactory import com.kickstarter.mock.services.MockApiClientV2 import com.kickstarter.models.ProjectNotification import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import io.reactivex.subscribers.TestSubscriber import org.junit.After import org.junit.Test import java.util.Collections class ProjectNotificationSettingsViewModelTest : KSRobolectricTestCase() { private lateinit var vm: ProjectNotificationSettingsViewModel.ProjectNotificationSettingsViewModel private val projectNotifications = TestSubscriber<List<ProjectNotification>>() private val unableToFetchProjectNotificationsError = TestSubscriber<Unit>() private val disposables = CompositeDisposable() private fun setUpEnvironment(environment: Environment) { this.vm = ProjectNotificationSettingsViewModel.ProjectNotificationSettingsViewModel(environment) this.vm.outputs.projectNotifications().subscribe { this.projectNotifications.onNext(it) } .addToDisposable(disposables) this.vm.outputs.unableToFetchProjectNotificationsError() .subscribe { this.unableToFetchProjectNotificationsError.onNext(it) } .addToDisposable(disposables) } @Test fun testProjectNotifications() { val projectNotifications = Collections.singletonList(ProjectNotificationFactory.disabled()) setUpEnvironment( environment().toBuilder().apiClientV2(object : MockApiClientV2() { override fun fetchProjectNotifications(): Observable<List<ProjectNotification>> { return Observable.just(projectNotifications) } }).build() ) this.projectNotifications.assertValue(projectNotifications) } @Test fun testUnableToFetchProjectNotificationsError() { setUpEnvironment( environment().toBuilder().apiClientV2(object : MockApiClientV2() { override fun fetchProjectNotifications(): Observable<List<ProjectNotification>> { return Observable.error(Throwable("error")) } }).build() ) this.unableToFetchProjectNotificationsError.assertValueCount(1) } @After fun clear() { disposables.clear() } }
8
Kotlin
989
5,752
a9187fb484c4d12137c7919a2a53339d67cab0cb
2,536
android-oss
Apache License 2.0
app/src/main/java/com/zt/coolweather/db/Province.kt
ztisdashen
320,441,385
false
null
package com.zt.coolweather.db import org.litepal.crud.LitePalSupport data class Province(var id: Int?, var provinceName: String?, var provinceCode: Int?) : LitePalSupport() data class City(var id: Int?, var cityName: String?, var cityCode: Int?, var provinceId: Int?) : LitePalSupport() /** * */ data class County(var id: Int?, var countyName: String?, var weatherId: String?, var cityId: Int?) : LitePalSupport()
0
Kotlin
0
0
912a26e5f8dfbdd12439d2fdc5c74e8c787c51cf
428
coolWeather
Apache License 2.0
viewer/src/main/kotlin/li/doerf/feeder/viewer/controllers/UserController.kt
doerfli
188,579,479
false
{"Kotlin": 190694, "Vue": 48142, "JavaScript": 21033, "SCSS": 2537, "HTML": 616}
package li.doerf.feeder.viewer.controllers import li.doerf.feeder.common.util.getLogger import li.doerf.feeder.viewer.config.JwtTokenProvider import li.doerf.feeder.viewer.dto.UserPasswordResetRequestDto import li.doerf.feeder.viewer.dto.UserRequestDto import li.doerf.feeder.viewer.dto.UserResetPasswordRequestDto import li.doerf.feeder.viewer.dto.UserResponseDto import li.doerf.feeder.viewer.services.UserService import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* @RestController @PrefixController @RequestMapping("/users") class UserController @Autowired constructor( private val userService: UserService, private val jwtTokenProvider: JwtTokenProvider ){ companion object { @Suppress("JAVA_CLASS_ON_COMPANION") private val log = getLogger(javaClass) } @PostMapping("/signup") fun signup(@RequestBody userRequest: UserRequestDto): HttpStatus { log.debug("signup user ${userRequest.username}") userService.signup(userRequest.username, userRequest.password) return HttpStatus.OK } @GetMapping("/confirm/{token}") fun confirm(@PathVariable token: String): ResponseEntity<UserResponseDto> { log.debug("confirming user with token $token") val jwtToken = userService.confirm(token) return ResponseEntity.ok(UserResponseDto(jwtToken, jwtTokenProvider.getUsername(jwtToken))) } @PostMapping("/signin") fun login(@RequestBody userRequest: UserRequestDto): ResponseEntity<UserResponseDto> { log.debug("login user ${userRequest.username}") val jwtToken = userService.signin(userRequest.username, userRequest.password) return ResponseEntity.ok(UserResponseDto(jwtToken, jwtTokenProvider.getUsername(jwtToken))) } @PostMapping("/passwordReset") fun requestPasswordReset(@RequestBody userRequest: UserPasswordResetRequestDto): HttpStatus { log.debug("request password reset for user ${userRequest.username}") userService.requestPasswordReset(userRequest.username) return HttpStatus.OK } @PostMapping("/passwordReset/{token}") fun passwordReset(@PathVariable token: String, @RequestBody userRequest: UserResetPasswordRequestDto): HttpStatus { log.debug("password reset with token $token") userService.resetPassword(token, userRequest.password) return HttpStatus.OK } }
30
Kotlin
0
0
f0a7ab9a8367ba49a7171b594b64ae2dea5deb87
2,538
feedscraper
MIT License
app/src/main/java/io/deus/wallet/modules/settings/faq/FaqModule.kt
DeusWallet
810,708,619
false
{"Kotlin": 5009329, "Shell": 6095, "Ruby": 1350}
package io.deus.wallet.modules.settings.faq import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import io.deus.wallet.core.App import io.deus.wallet.core.managers.FaqManager object FaqModule { class Factory : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { val faqRepository = FaqRepository(FaqManager, App.connectivityManager, App.languageManager) return FaqViewModel(faqRepository) as T } } }
0
Kotlin
0
0
f4c5e0fadbf2955edf7ba35d4617f148c191c02b
554
deus-wallet-android
MIT License
compiler/src/org/jetbrains/dukat/compiler/translator/IdlInputTranslator.kt
Kotlin
159,510,660
false
null
package org.jetbrains.dukat.compiler.translator import org.jetbrains.dukat.astModel.SourceSetModel import org.jetbrains.dukat.astModel.modifiers.VisibilityModifierModel import org.jetbrains.dukat.commonLowerings.AddExplicitGettersAndSetters import org.jetbrains.dukat.idlLowerings.addConstructors import org.jetbrains.dukat.idlLowerings.addImportsForUsedPackages import org.jetbrains.dukat.idlLowerings.addItemArrayLike import org.jetbrains.dukat.idlLowerings.addKDocs import org.jetbrains.dukat.idlLowerings.addMissingMembers import org.jetbrains.dukat.idlLowerings.addOverloadsForCallbacks import org.jetbrains.dukat.idlLowerings.markAbstractOrOpen import org.jetbrains.dukat.idlLowerings.omitStdLib import org.jetbrains.dukat.idlLowerings.relocateDeclarations import org.jetbrains.dukat.idlLowerings.resolveImplementsStatements import org.jetbrains.dukat.idlLowerings.resolveMixins import org.jetbrains.dukat.idlLowerings.resolvePartials import org.jetbrains.dukat.idlLowerings.resolveTypedefs import org.jetbrains.dukat.idlLowerings.resolveTypes import org.jetbrains.dukat.idlLowerings.specifyDefaultValues import org.jetbrains.dukat.idlLowerings.specifyEventHandlerTypes import org.jetbrains.dukat.idlModels.convertToModel import org.jetbrains.dukat.idlParser.parseIDL import org.jetbrains.dukat.idlReferenceResolver.IdlReferencesResolver import org.jetbrains.dukat.model.commonLowerings.EscapeIdentificators import org.jetbrains.dukat.model.commonLowerings.LowerOverrides import org.jetbrains.dukat.model.commonLowerings.VisibilityModifierResolver import org.jetbrains.dukat.model.commonLowerings.lower import org.jetbrains.dukat.model.commonLowerings.resolveTopLevelVisibility import org.jetbrains.dukat.translator.InputTranslator private fun alwaysPublic(): VisibilityModifierResolver = object : VisibilityModifierResolver { override fun resolve(): VisibilityModifierModel = VisibilityModifierModel.PUBLIC } class IdlInputTranslator(private val nameResolver: IdlReferencesResolver) : InputTranslator<String> { fun translateSet(fileName: String): SourceSetModel { return parseIDL(fileName, nameResolver) .resolvePartials() .addConstructors() .resolveTypedefs() .specifyEventHandlerTypes() .specifyDefaultValues() .resolveImplementsStatements() .resolveMixins() .addItemArrayLike() .resolveTypes() .markAbstractOrOpen() .addMissingMembers() .addOverloadsForCallbacks() .convertToModel() .lower( LowerOverrides(), EscapeIdentificators(), AddExplicitGettersAndSetters() ) .addKDocs() .relocateDeclarations() .resolveTopLevelVisibility(alwaysPublic()) .addImportsForUsedPackages() .omitStdLib() } override fun translate(data: String): SourceSetModel { return translateSet(data) } }
227
null
37
430
c92dd392d853a6869abd5bea80403158ec8fecb6
3,118
dukat
Apache License 2.0
app/src/main/java/com/example/doomnews/MainActivity.kt
JavRuiz16
716,851,066
false
{"Kotlin": 31635}
package com.example.doomnews import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.example.doomnews.ui.DoomNewsApp import com.example.doomnews.ui.theme.DoomNewsTheme class MainActivity : ComponentActivity() { @OptIn(ExperimentalMaterial3WindowSizeClassApi::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { DoomNewsTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { val windowSize = calculateWindowSizeClass(this) DoomNewsApp( windowSize = windowSize.widthSizeClass ) } } } } } // TODO: Add previews for different screen sizes
0
Kotlin
0
0
8f5146b2e37d0ee10d64aad40e3f5937e57e1ee9
1,499
Hw7DoomNews
Apache License 2.0
app/src/main/java/com/rrg/dinnerrecommendation/di/AppModule.kt
ROHANGYA
501,564,909
false
null
package com.rrg.dinnerrecommendation.di import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory import com.rrg.dinnerrecommendation.BuildConfig.BASE_URL_COCKTAIL import com.rrg.dinnerrecommendation.BuildConfig.BASE_URL_MEAL import com.rrg.dinnerrecommendation.BuildConfig.DEBUG import com.rrg.dinnerrecommendation.api.DrinkApi import com.rrg.dinnerrecommendation.api.MealApi import com.rrg.dinnerrecommendation.core.NetworkRequestManager import com.rrg.dinnerrecommendation.service.interceptor.CocktailSessionInterceptor import com.rrg.dinnerrecommendation.service.interceptor.MealSessionInterceptor import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Qualifier import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AppModule { @Provides @Singleton fun provideMealInterceptor(): MealSessionInterceptor { return MealSessionInterceptor() } @Provides @Singleton @MealInterceptor fun provideMealApiKeyInterceptor( mealSessionInterceptor: MealSessionInterceptor? ): OkHttpClient { val connectionTimeout: Long = 60 val readTimeout: Long = 60 val okHttpClientBuilder = OkHttpClient.Builder() .connectTimeout(connectionTimeout, TimeUnit.SECONDS) .readTimeout(readTimeout, TimeUnit.SECONDS) mealSessionInterceptor?.let { okHttpClientBuilder.addInterceptor(mealSessionInterceptor) } if (DEBUG) { val httpLoggingInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } okHttpClientBuilder.addInterceptor(httpLoggingInterceptor) } return okHttpClientBuilder.build() } @Provides @Singleton fun provideCocktailInterceptor(): CocktailSessionInterceptor { return CocktailSessionInterceptor() } @Provides @Singleton @CocktailInterceptor fun provideCocktailApiKeyInterceptor( cocktailSessionInterceptor: CocktailSessionInterceptor? ): OkHttpClient { val connectionTimeout: Long = 60 val readTimeout: Long = 60 val okHttpClientBuilder = OkHttpClient.Builder() .connectTimeout(connectionTimeout, TimeUnit.SECONDS) .readTimeout(readTimeout, TimeUnit.SECONDS) cocktailSessionInterceptor?.let { okHttpClientBuilder.addInterceptor(cocktailSessionInterceptor) } if (DEBUG) { val httpLoggingInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } okHttpClientBuilder.addInterceptor(httpLoggingInterceptor) } return okHttpClientBuilder.build() } @Provides @Singleton @MealRetrofit fun provideMealRetrofit( @MealInterceptor httpClient: OkHttpClient ): Retrofit { return Retrofit.Builder() .client(httpClient) .baseUrl(BASE_URL_MEAL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(CoroutineCallAdapterFactory()) .build() } @Provides @Singleton @CocktailRetrofit fun provideCocktailRetrofit( @CocktailInterceptor httpClient: OkHttpClient ): Retrofit { return Retrofit.Builder() .client(httpClient) .baseUrl(BASE_URL_COCKTAIL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(CoroutineCallAdapterFactory()) .build() } @Provides @Singleton fun provideMealApi(@MealRetrofit retrofit: Retrofit): MealApi { return retrofit.create(MealApi::class.java) } @Provides @Singleton fun provideCocktailApi(@CocktailRetrofit retrofit: Retrofit): DrinkApi { return retrofit.create(DrinkApi::class.java) } @Provides @Singleton fun provideNetworkManager(): NetworkRequestManager { return NetworkRequestManager() } } @Qualifier @Retention(AnnotationRetention.BINARY) annotation class MealInterceptor @Qualifier @Retention(AnnotationRetention.BINARY) annotation class CocktailInterceptor @Qualifier @Retention(AnnotationRetention.BINARY) annotation class MealRetrofit @Qualifier @Retention(AnnotationRetention.BINARY) annotation class CocktailRetrofit
0
Kotlin
0
0
a8ef6493f4bc2dd86bc29db43988010f83a05011
4,674
DinnerRecommendationJetpack
MIT License
app/src/main/java/com/rrg/dinnerrecommendation/di/AppModule.kt
ROHANGYA
501,564,909
false
null
package com.rrg.dinnerrecommendation.di import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory import com.rrg.dinnerrecommendation.BuildConfig.BASE_URL_COCKTAIL import com.rrg.dinnerrecommendation.BuildConfig.BASE_URL_MEAL import com.rrg.dinnerrecommendation.BuildConfig.DEBUG import com.rrg.dinnerrecommendation.api.DrinkApi import com.rrg.dinnerrecommendation.api.MealApi import com.rrg.dinnerrecommendation.core.NetworkRequestManager import com.rrg.dinnerrecommendation.service.interceptor.CocktailSessionInterceptor import com.rrg.dinnerrecommendation.service.interceptor.MealSessionInterceptor import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Qualifier import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AppModule { @Provides @Singleton fun provideMealInterceptor(): MealSessionInterceptor { return MealSessionInterceptor() } @Provides @Singleton @MealInterceptor fun provideMealApiKeyInterceptor( mealSessionInterceptor: MealSessionInterceptor? ): OkHttpClient { val connectionTimeout: Long = 60 val readTimeout: Long = 60 val okHttpClientBuilder = OkHttpClient.Builder() .connectTimeout(connectionTimeout, TimeUnit.SECONDS) .readTimeout(readTimeout, TimeUnit.SECONDS) mealSessionInterceptor?.let { okHttpClientBuilder.addInterceptor(mealSessionInterceptor) } if (DEBUG) { val httpLoggingInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } okHttpClientBuilder.addInterceptor(httpLoggingInterceptor) } return okHttpClientBuilder.build() } @Provides @Singleton fun provideCocktailInterceptor(): CocktailSessionInterceptor { return CocktailSessionInterceptor() } @Provides @Singleton @CocktailInterceptor fun provideCocktailApiKeyInterceptor( cocktailSessionInterceptor: CocktailSessionInterceptor? ): OkHttpClient { val connectionTimeout: Long = 60 val readTimeout: Long = 60 val okHttpClientBuilder = OkHttpClient.Builder() .connectTimeout(connectionTimeout, TimeUnit.SECONDS) .readTimeout(readTimeout, TimeUnit.SECONDS) cocktailSessionInterceptor?.let { okHttpClientBuilder.addInterceptor(cocktailSessionInterceptor) } if (DEBUG) { val httpLoggingInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } okHttpClientBuilder.addInterceptor(httpLoggingInterceptor) } return okHttpClientBuilder.build() } @Provides @Singleton @MealRetrofit fun provideMealRetrofit( @MealInterceptor httpClient: OkHttpClient ): Retrofit { return Retrofit.Builder() .client(httpClient) .baseUrl(BASE_URL_MEAL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(CoroutineCallAdapterFactory()) .build() } @Provides @Singleton @CocktailRetrofit fun provideCocktailRetrofit( @CocktailInterceptor httpClient: OkHttpClient ): Retrofit { return Retrofit.Builder() .client(httpClient) .baseUrl(BASE_URL_COCKTAIL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(CoroutineCallAdapterFactory()) .build() } @Provides @Singleton fun provideMealApi(@MealRetrofit retrofit: Retrofit): MealApi { return retrofit.create(MealApi::class.java) } @Provides @Singleton fun provideCocktailApi(@CocktailRetrofit retrofit: Retrofit): DrinkApi { return retrofit.create(DrinkApi::class.java) } @Provides @Singleton fun provideNetworkManager(): NetworkRequestManager { return NetworkRequestManager() } } @Qualifier @Retention(AnnotationRetention.BINARY) annotation class MealInterceptor @Qualifier @Retention(AnnotationRetention.BINARY) annotation class CocktailInterceptor @Qualifier @Retention(AnnotationRetention.BINARY) annotation class MealRetrofit @Qualifier @Retention(AnnotationRetention.BINARY) annotation class CocktailRetrofit
0
Kotlin
0
0
a8ef6493f4bc2dd86bc29db43988010f83a05011
4,674
DinnerRecommendationJetpack
MIT License
src/main/kotlin/com/example/v1oauthauthorizationservice/domain/oauth/api/OAuthApi.kt
team-xquare
494,272,840
false
{"Kotlin": 89041, "Shell": 417, "Dockerfile": 391}
package com.example.v1oauthauthorizationservice.domain.oauth.api import com.example.v1oauthauthorizationservice.infrastructure.oauth2.presentation.dto.request.RegisterClientRequest import com.example.v1oauthauthorizationservice.infrastructure.oauth2.presentation.dto.request.UpdateClientRequest import com.example.v1oauthauthorizationservice.infrastructure.oauth2.presentation.dto.response.ClientsResponse import com.example.v1oauthauthorizationservice.infrastructure.oauth2.presentation.dto.response.RegenerateSecretResponse import com.example.v1oauthauthorizationservice.infrastructure.oauth2.presentation.dto.response.RegisterClientResponse import com.example.v1oauthauthorizationservice.infrastructure.oauth2.presentation.dto.response.UpdateClientResponse interface OAuthApi { fun getClient(): ClientsResponse fun registerClient(request: RegisterClientRequest): RegisterClientResponse fun updateClient(clientId: String, request: UpdateClientRequest): UpdateClientResponse fun regenerateSecret(clientId: String): RegenerateSecretResponse }
1
Kotlin
0
2
c739e8d85e5885fdb22790393a9dba9fa749637f
1,061
v1-service-oauth
MIT License
app/src/main/java/com/febers/uestc_bbs/home/HomeSecondContainer.kt
Febers
135,606,653
false
null
package com.febers.uestc_bbs.home import android.os.Bundle import com.febers.uestc_bbs.R import com.febers.uestc_bbs.base.BaseFragment import com.febers.uestc_bbs.module.more.BlockFragment class HomeSecondContainer : BaseFragment() { override fun setContentView(): Int { return R.layout.container_home_second } override fun onLazyInitView(savedInstanceState: Bundle?) { super.onLazyInitView(savedInstanceState) if (findChildFragment(BlockFragment::class.java) == null) { loadRootFragment(R.id.home_second_container, BlockFragment()) } } }
1
Kotlin
11
41
b9da253984e2febc235121ac6745bfbc215a7609
601
UESTC_BBS
Apache License 2.0
src/main/kotlin/com/example/jpajoin/JpaJoinApplication.kt
eiselems
313,986,270
false
null
package com.example.jpajoin import com.example.jpajoin.persistence.entities.CompanyProfile import com.example.jpajoin.persistence.entities.CompanyRepository import com.example.jpajoin.persistence.entities.Role import com.example.jpajoin.persistence.entities.User import com.example.jpajoin.persistence.entities.UserCompanyRoles import org.springframework.boot.ApplicationArguments import org.springframework.boot.ApplicationRunner import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.transaction.annotation.Transactional import kotlin.random.Random @SpringBootApplication class JpaJoinApplication(val companyRepository: CompanyRepository) : ApplicationRunner { @Transactional override fun run(args: ApplicationArguments) { val user = User(firstName = "Hans") val companyProfile = CompanyProfile(profileId = "1234567CDEF", companyId = "1234567CDEF", companyName = "My company ${Random.nextInt()}") companyProfile.users val userCompanyRoles = UserCompanyRoles(user = user, company = companyProfile, roles = setOf(Role.ADMIN, Role.MANAGER, Role.USER)) companyProfile.users = listOf(userCompanyRoles) user.companies = listOf(userCompanyRoles) companyRepository.save(companyProfile) println("${companyRepository.count()}") val findAll = companyRepository.findAll() //causes a lot of subselects to get all the users and roles per company - a single resultset would be much better findAll.flatMap { it.users }.forEach { println("${it.user.firstName}, ${it.company.companyName}, ${it.roles}") } //maybe it would be even better to make the path not "traversible in the entity" } } fun main(args: Array<String>) { runApplication<JpaJoinApplication>(*args) }
0
Kotlin
0
0
1b8fdbee88779711eec8210158399bd6fc12b960
1,856
jpa-playground
MIT License
src/main/kotlin/me/aberrantfox/judgebot/listeners/JoinLeaveListener.kt
the-programmers-hangout
251,074,065
false
null
package me.aberrantfox.judgebot.listeners import com.google.common.eventbus.Subscribe import me.aberrantfox.judgebot.services.DatabaseService import net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent import org.joda.time.DateTime class JoinLeaveListener(private val databaseService: DatabaseService) { @Subscribe fun onGuildMemberLeave(event: GuildMemberRemoveEvent) { val userRecord = databaseService.users.getOrCreateUser(event.member!!, event.guild.id) val leaveTime = DateTime.now().millis // databaseService.users.insertGuildLeave(userRecord, event.guild, event.member!!.timeJoined, leaveTime) } }
0
Kotlin
0
1
3d70f5d4cb3dbf17bfcfad7bb9db21785a6ab343
652
JudgeBot-old
MIT License
carp.common/src/commonTest/kotlin/dk/cachet/carp/common/application/TestInstances.kt
cph-cachet
116,270,288
false
null
package dk.cachet.carp.common.application import dk.cachet.carp.common.application.data.* import dk.cachet.carp.common.application.data.input.* import dk.cachet.carp.common.application.data.input.elements.* import dk.cachet.carp.common.application.devices.* import dk.cachet.carp.common.application.sampling.* import dk.cachet.carp.common.application.tasks.* import dk.cachet.carp.common.application.triggers.* import dk.cachet.carp.common.application.users.* import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds /** * An instance for each of the extending types from base classes in [dk.cachet.carp.common]. */ val commonInstances = listOf( // `data` namespace. Acceleration( 42.0, 42.0, 42.0 ), AngularVelocity( 42.0, 42.0, 42.0 ), CompletedTask( "Task", null ), ECG( 42.0 ), EDA( 42.0 ), Geolocation( 42.0, 42.0 ), HeartRate( 60 ), InterbeatInterval(), NoData, NonGravitationalAcceleration( 42.0, 42.0, 42.0 ), PPG( mapOf( "green" to 42.0 ) ), SensorSkinContact( true ), SignalStrength( 0 ), StepCount( 42 ), TriggeredTask( 1, "Some task", "Destination device", TaskControl.Control.Start ), // `data.input` namespace. CustomInput( "42" ), Sex.Male, // `data.input.elements` namespace. SelectOne( "Sex", setOf( "Male", "Female" ) ), Text( "Name" ), // Devices in `devices` namespace. AltBeacon( "Kitchen" ), AltBeaconDeviceRegistration( 0, UUID.randomUUID(), 0, 0, 0 ), BLEHeartRateDevice( "Polar" ), BLESerialNumberDeviceRegistration( "123456789" ), CustomProtocolDevice( "User's phone" ), Smartphone( "User's phone" ), // Shared device registrations in `devices` namespace. DefaultDeviceRegistration(), MACAddressDeviceRegistration( MACAddress( "00-00-00-00-00-00" ) ), // `sampling` namespace. BatteryAwareSamplingConfiguration( GranularitySamplingConfiguration( Granularity.Balanced ), GranularitySamplingConfiguration( Granularity.Coarse ), ), GranularitySamplingConfiguration( Granularity.Balanced ), IntervalSamplingConfiguration( 1000.milliseconds ), NoOptionsSamplingConfiguration, // `tasks` namespace. BackgroundTask( "Start measures", listOf() ), CustomProtocolTask( "Custom study runtime", "{ \"\$type\": \"Study\", \"custom\": \"protocol\" }" ), WebTask( "Survey", emptyList(), "Some survey", "http://survey.com" ), // `triggers` namespace. ElapsedTimeTrigger( Smartphone( "User's phone" ), Duration.ZERO ), ManualTrigger( "User's phone", "Mood", "Describe how you are feeling at the moment." ), ScheduledTrigger( Smartphone( "User's phone"), TimeOfDay( 12 ), RecurrenceRule( RecurrenceRule.Frequency.DAILY ) ), // `users` namespace. EmailAccountIdentity( "<EMAIL>" ), UsernameAccountIdentity( "Some user" ), )
93
null
3
21
7b6fa58bc97ab0c244b81897bc837def3b0d7daf
2,946
carp.core-kotlin
MIT License
carp.common/src/commonTest/kotlin/dk/cachet/carp/common/application/TestInstances.kt
cph-cachet
116,270,288
false
null
package dk.cachet.carp.common.application import dk.cachet.carp.common.application.data.* import dk.cachet.carp.common.application.data.input.* import dk.cachet.carp.common.application.data.input.elements.* import dk.cachet.carp.common.application.devices.* import dk.cachet.carp.common.application.sampling.* import dk.cachet.carp.common.application.tasks.* import dk.cachet.carp.common.application.triggers.* import dk.cachet.carp.common.application.users.* import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds /** * An instance for each of the extending types from base classes in [dk.cachet.carp.common]. */ val commonInstances = listOf( // `data` namespace. Acceleration( 42.0, 42.0, 42.0 ), AngularVelocity( 42.0, 42.0, 42.0 ), CompletedTask( "Task", null ), ECG( 42.0 ), EDA( 42.0 ), Geolocation( 42.0, 42.0 ), HeartRate( 60 ), InterbeatInterval(), NoData, NonGravitationalAcceleration( 42.0, 42.0, 42.0 ), PPG( mapOf( "green" to 42.0 ) ), SensorSkinContact( true ), SignalStrength( 0 ), StepCount( 42 ), TriggeredTask( 1, "Some task", "Destination device", TaskControl.Control.Start ), // `data.input` namespace. CustomInput( "42" ), Sex.Male, // `data.input.elements` namespace. SelectOne( "Sex", setOf( "Male", "Female" ) ), Text( "Name" ), // Devices in `devices` namespace. AltBeacon( "Kitchen" ), AltBeaconDeviceRegistration( 0, UUID.randomUUID(), 0, 0, 0 ), BLEHeartRateDevice( "Polar" ), BLESerialNumberDeviceRegistration( "123456789" ), CustomProtocolDevice( "User's phone" ), Smartphone( "User's phone" ), // Shared device registrations in `devices` namespace. DefaultDeviceRegistration(), MACAddressDeviceRegistration( MACAddress( "00-00-00-00-00-00" ) ), // `sampling` namespace. BatteryAwareSamplingConfiguration( GranularitySamplingConfiguration( Granularity.Balanced ), GranularitySamplingConfiguration( Granularity.Coarse ), ), GranularitySamplingConfiguration( Granularity.Balanced ), IntervalSamplingConfiguration( 1000.milliseconds ), NoOptionsSamplingConfiguration, // `tasks` namespace. BackgroundTask( "Start measures", listOf() ), CustomProtocolTask( "Custom study runtime", "{ \"\$type\": \"Study\", \"custom\": \"protocol\" }" ), WebTask( "Survey", emptyList(), "Some survey", "http://survey.com" ), // `triggers` namespace. ElapsedTimeTrigger( Smartphone( "User's phone" ), Duration.ZERO ), ManualTrigger( "User's phone", "Mood", "Describe how you are feeling at the moment." ), ScheduledTrigger( Smartphone( "User's phone"), TimeOfDay( 12 ), RecurrenceRule( RecurrenceRule.Frequency.DAILY ) ), // `users` namespace. EmailAccountIdentity( "<EMAIL>" ), UsernameAccountIdentity( "Some user" ), )
93
null
3
21
7b6fa58bc97ab0c244b81897bc837def3b0d7daf
2,946
carp.core-kotlin
MIT License
android/app/src/main/java/com/algorand/android/discover/common/ui/BaseDiscoverFragment.kt
perawallet
364,359,642
false
{"Swift": 8753304, "Kotlin": 7709389, "Objective-C": 88978, "Shell": 7715, "Ruby": 4727, "C": 596}
/* * Copyright 2022 Pera Wallet, LDA * 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.algorand.android.discover.common.ui import android.content.res.Configuration import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.WebSettings import androidx.annotation.LayoutRes import androidx.core.content.ContextCompat import com.algorand.android.R import com.algorand.android.customviews.PeraWebView import com.algorand.android.discover.common.ui.model.WebViewTheme import com.algorand.android.discover.utils.getJavascriptThemeChangeFunctionForTheme import com.algorand.android.models.AnnotatedString import com.algorand.android.modules.perawebview.ui.BasePeraWebViewFragment import com.algorand.android.utils.PERA_VERIFICATION_MAIL_ADDRESS import com.algorand.android.utils.copyToClipboard import com.algorand.android.utils.getCustomLongClickableSpan import com.algorand.android.utils.preference.ThemePreference abstract class BaseDiscoverFragment( @LayoutRes private val layoutResId: Int, ) : BasePeraWebViewFragment(layoutResId) { override val basePeraWebViewViewModel get() = discoverViewModel abstract val discoverViewModel: BaseDiscoverViewModel abstract fun onReportActionFailed() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = super.onCreateView(inflater, container, savedInstanceState) val themePreference = discoverViewModel.getDiscoverThemePreference() getWebView(binding.root)?.let { currentWebView -> handleWebViewTheme(themePreference, currentWebView) currentWebView.evaluateJavascript( getJavascriptThemeChangeFunctionForTheme(getWebViewThemeFromThemePreference(themePreference)), null ) } // Otherwise we just bind the view as we have no previously saved state to show return view } override fun onSendMailRequestFailed() { onReportActionFailed() } protected fun getTitleForFailedReport(): AnnotatedString { return AnnotatedString(R.string.report_an_asa) } protected fun getDescriptionForFailedReport(): AnnotatedString { val longClickSpannable = getCustomLongClickableSpan( clickableColor = ContextCompat.getColor(binding.root.context, R.color.positive), onLongClick = { context?.copyToClipboard(PERA_VERIFICATION_MAIL_ADDRESS) } ) return AnnotatedString( stringResId = R.string.you_can_send_us_an, customAnnotationList = listOf("verification_mail_click" to longClickSpannable), replacementList = listOf("verification_mail" to PERA_VERIFICATION_MAIL_ADDRESS) ) } protected fun getWebViewThemeFromThemePreference(themePreference: ThemePreference): WebViewTheme { val themeFromSystem = when ( resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK ) { Configuration.UI_MODE_NIGHT_YES -> WebViewTheme.DARK Configuration.UI_MODE_NIGHT_NO -> WebViewTheme.LIGHT else -> null } return WebViewTheme.getByThemePreference(themePreference, themeFromSystem) } private fun handleWebViewTheme( themePreference: ThemePreference, webView: PeraWebView ) { with(webView.settings) { val isDarkMode = getWebViewThemeFromThemePreference(themePreference) == WebViewTheme.DARK if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { isAlgorithmicDarkeningAllowed = isDarkMode return } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { forceDark = if (isDarkMode) WebSettings.FORCE_DARK_ON else WebSettings.FORCE_DARK_OFF return } } } }
22
Swift
62
181
92fc77f73fa4105de82d5e87b03c1e67600a57c0
4,492
pera-wallet
Apache License 2.0
android/app/src/main/java/com/algorand/android/discover/common/ui/BaseDiscoverFragment.kt
perawallet
364,359,642
false
{"Swift": 8753304, "Kotlin": 7709389, "Objective-C": 88978, "Shell": 7715, "Ruby": 4727, "C": 596}
/* * Copyright 2022 Pera Wallet, LDA * 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.algorand.android.discover.common.ui import android.content.res.Configuration import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.WebSettings import androidx.annotation.LayoutRes import androidx.core.content.ContextCompat import com.algorand.android.R import com.algorand.android.customviews.PeraWebView import com.algorand.android.discover.common.ui.model.WebViewTheme import com.algorand.android.discover.utils.getJavascriptThemeChangeFunctionForTheme import com.algorand.android.models.AnnotatedString import com.algorand.android.modules.perawebview.ui.BasePeraWebViewFragment import com.algorand.android.utils.PERA_VERIFICATION_MAIL_ADDRESS import com.algorand.android.utils.copyToClipboard import com.algorand.android.utils.getCustomLongClickableSpan import com.algorand.android.utils.preference.ThemePreference abstract class BaseDiscoverFragment( @LayoutRes private val layoutResId: Int, ) : BasePeraWebViewFragment(layoutResId) { override val basePeraWebViewViewModel get() = discoverViewModel abstract val discoverViewModel: BaseDiscoverViewModel abstract fun onReportActionFailed() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = super.onCreateView(inflater, container, savedInstanceState) val themePreference = discoverViewModel.getDiscoverThemePreference() getWebView(binding.root)?.let { currentWebView -> handleWebViewTheme(themePreference, currentWebView) currentWebView.evaluateJavascript( getJavascriptThemeChangeFunctionForTheme(getWebViewThemeFromThemePreference(themePreference)), null ) } // Otherwise we just bind the view as we have no previously saved state to show return view } override fun onSendMailRequestFailed() { onReportActionFailed() } protected fun getTitleForFailedReport(): AnnotatedString { return AnnotatedString(R.string.report_an_asa) } protected fun getDescriptionForFailedReport(): AnnotatedString { val longClickSpannable = getCustomLongClickableSpan( clickableColor = ContextCompat.getColor(binding.root.context, R.color.positive), onLongClick = { context?.copyToClipboard(PERA_VERIFICATION_MAIL_ADDRESS) } ) return AnnotatedString( stringResId = R.string.you_can_send_us_an, customAnnotationList = listOf("verification_mail_click" to longClickSpannable), replacementList = listOf("verification_mail" to PERA_VERIFICATION_MAIL_ADDRESS) ) } protected fun getWebViewThemeFromThemePreference(themePreference: ThemePreference): WebViewTheme { val themeFromSystem = when ( resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK ) { Configuration.UI_MODE_NIGHT_YES -> WebViewTheme.DARK Configuration.UI_MODE_NIGHT_NO -> WebViewTheme.LIGHT else -> null } return WebViewTheme.getByThemePreference(themePreference, themeFromSystem) } private fun handleWebViewTheme( themePreference: ThemePreference, webView: PeraWebView ) { with(webView.settings) { val isDarkMode = getWebViewThemeFromThemePreference(themePreference) == WebViewTheme.DARK if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { isAlgorithmicDarkeningAllowed = isDarkMode return } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { forceDark = if (isDarkMode) WebSettings.FORCE_DARK_ON else WebSettings.FORCE_DARK_OFF return } } } }
22
Swift
62
181
92fc77f73fa4105de82d5e87b03c1e67600a57c0
4,492
pera-wallet
Apache License 2.0
vm/src/main/kotlin/gay/pizza/pork/vm/ops/UnaryPlusOpHandler.kt
GayPizzaSpecifications
680,636,847
false
{"Kotlin": 364750}
package gay.pizza.pork.vm.ops import gay.pizza.pork.bytecode.Op import gay.pizza.pork.bytecode.Opcode import gay.pizza.pork.vm.InternalMachine import gay.pizza.pork.vm.OpHandler object UnaryPlusOpHandler : OpHandler(Opcode.UnaryPlus) { override fun handle(machine: InternalMachine, op: Op) { val value = machine.pop<Int>() machine.push(+value) } }
0
Kotlin
1
0
962d079acce1c07ca151ea470532d549d39a0da6
362
pork
MIT License
ospf-kotlin-core/src/main/fuookami/ospf/kotlin/core/backend/intermediate_model/QuadraticTetradModel.kt
fuookami
359,831,793
false
{"Kotlin": 2440181, "Python": 6629}
package fuookami.ospf.kotlin.core.backend.intermediate_model import java.io.* import kotlinx.coroutines.* import fuookami.ospf.kotlin.utils.math.* import fuookami.ospf.kotlin.utils.concept.* import fuookami.ospf.kotlin.utils.operator.* import fuookami.ospf.kotlin.utils.functional.* import fuookami.ospf.kotlin.core.frontend.model.mechanism.* import fuookami.ospf.kotlin.core.frontend.variable.* data class QuadraticConstraintCell( override val rowIndex: Int, val colIndex1: Int, val colIndex2: Int?, override val coefficient: Flt64 ) : ConstraintCell, Cloneable, Copyable<QuadraticConstraintCell> { override fun copy() = QuadraticConstraintCell(rowIndex, colIndex1, colIndex2, coefficient.copy()) override fun clone() = copy() } typealias QuadraticConstraint = Constraint<QuadraticConstraintCell> data class QuadraticObjectiveCell( val colIndex1: Int, val colIndex2: Int?, override val coefficient: Flt64 ) : Cell, Cloneable, Copyable<QuadraticObjectiveCell> { override fun copy() = QuadraticObjectiveCell(colIndex1, colIndex2, coefficient.copy()) override fun clone() = copy() } typealias QuadraticObjective = Objective<QuadraticObjectiveCell> class BasicQuadraticTetradModel( override val variables: List<Variable>, override val constraints: QuadraticConstraint, override val name: String ) : BasicModelView<QuadraticConstraintCell>, Cloneable, Copyable<BasicQuadraticTetradModel> { override fun copy() = BasicQuadraticTetradModel( variables.map { it.copy() }, constraints.copy(), name ) override fun clone() = copy() fun normalized(): Boolean { return variables.any { !(it.lowerBound.isNegativeInfinity() || (it.lowerBound eq Flt64.zero)) || !(it.upperBound.isInfinity() || (it.upperBound eq Flt64.zero)) } } fun linearRelax() { variables.forEach { when (it.type) { is Binary -> { it._type = Percentage } is Ternary, is UInteger -> { it._type = UContinuous } is BalancedTernary, is fuookami.ospf.kotlin.core.frontend.variable.Integer -> { it._type = Continuous } else -> {} } } } fun normalize() { for (variable in variables) { if (!(variable.lowerBound.isNegativeInfinity() || (variable.lowerBound eq Flt64.zero))) { constraints._lhs.add( listOf( QuadraticConstraintCell( constraints.size, variable.index, null, Flt64.one ) ) ) constraints._signs.add(Sign.GreaterEqual) constraints._rhs.add(variable.lowerBound) constraints._names.add("${variable.name}_lb") variable._lowerBound = Flt64.negativeInfinity } if (!(variable.upperBound.isInfinity() || (variable.upperBound eq Flt64.zero))) { constraints._lhs.add( listOf( QuadraticConstraintCell( constraints.size, variable.index, null, Flt64.one ) ) ) constraints._signs.add(Sign.LessEqual) constraints._rhs.add(variable.upperBound) constraints._names.add("${variable.name}_ub") variable._upperBound = Flt64.infinity } } } override fun exportLP(writer: FileWriter): Try { writer.append("Subject To\n") for (i in constraints.indices) { writer.append(" ${constraints.names[i]}: ") var flag = false for (j in constraints.lhs[i].indices) { val coefficient = if (j != 0) { if (constraints.lhs[i][j].coefficient leq Flt64.zero) { writer.append(" - ") } else { writer.append(" + ") } abs(constraints.lhs[i][j].coefficient) } else { constraints.lhs[i][j].coefficient } if (coefficient neq Flt64.zero) { if (coefficient neq Flt64.one) { writer.append("$coefficient ") } if (constraints.lhs[i][j].colIndex2 == null) { writer.append("${variables[constraints.lhs[i][j].colIndex1]}") } else { writer.append("${variables[constraints.lhs[i][j].colIndex1]} * ${variables[constraints.lhs[i][j].colIndex2!!]}") } } flag = true } if (!flag) { writer.append("0") } writer.append(" ${constraints.signs[i]} ${constraints.rhs[i]}\n") } writer.append("\n") writer.append("Bounds\n") for (variable in variables) { val lowerInf = variable.lowerBound.isNegativeInfinity() val upperInf = variable.upperBound.isInfinity() if (lowerInf && upperInf) { writer.append(" $variable free\n") } else if (lowerInf) { writer.append(" $variable <= ${variable.upperBound}\n") } else if (upperInf) { writer.append(" $variable >= ${variable.lowerBound}\n") } else { if (variable.lowerBound eq variable.upperBound) { writer.append(" $variable = ${variable.lowerBound}\n") } else { writer.append(" ${variable.lowerBound} <= $variable <= ${variable.upperBound}\n") } } } writer.append("\n") if (containsBinary) { writer.append("Binaries\n") for (variable in variables) { if (variable.type.isBinaryType) { writer.append(" $variable") } } writer.append("\n") } if (containsNotBinaryInteger) { writer.append("Generals\n") for (variable in variables) { if (variable.type.isNotBinaryIntegerType) { writer.append(" $variable") } } writer.append("\n") } writer.append("End\n") return ok } } typealias QuadraticTetradModelView = ModelView<QuadraticConstraintCell, QuadraticObjectiveCell> data class QuadraticTetradModel( private val impl: BasicQuadraticTetradModel, override val objective: QuadraticObjective, ) : QuadraticTetradModelView, Cloneable, Copyable<QuadraticTetradModel> { override val variables: List<Variable> by impl::variables override val constraints: QuadraticConstraint by impl::constraints override val name: String by impl::name companion object { suspend operator fun invoke(model: QuadraticMechanismModel): QuadraticTetradModel { val tokens = model.tokens.tokens val tokenIndexes = model.tokens.tokenIndexMap return coroutineScope { val variablePromise = async(Dispatchers.Default) { val variables = ArrayList<Variable?>() for (i in tokens.indices) { variables.add(null) } for (token in tokens) { val index = tokenIndexes[token]!! variables[index] = Variable( index, token.lowerBound, token.upperBound, token.variable.type, token.variable.name, token.result ) } variables.map { it!! } } val constraintPromises = model.constraints.withIndex().map { (index, constraint) -> async(Dispatchers.Default) { val lhs = ArrayList<QuadraticConstraintCell>() for (cell in constraint.lhs) { val temp = cell as QuadraticCell lhs.add( QuadraticConstraintCell( index, tokenIndexes[temp.token1]!!, temp.token2?.let { tokenIndexes[it]!! }, temp.coefficient ) ) } lhs } } val constraintPromise = async(Dispatchers.Default) { val lhs = ArrayList<List<QuadraticConstraintCell>>() val signs = ArrayList<Sign>() val rhs = ArrayList<Flt64>() val names = ArrayList<String>() for ((index, constraint) in model.constraints.withIndex()) { lhs.add(constraintPromises[index].await()) signs.add(constraint.sign) rhs.add(constraint.rhs) names.add(constraint.name) } QuadraticConstraint(lhs, signs, rhs, names) } val objectiveCategory = if (model.objectFunction.subObjects.size == 1) { model.objectFunction.subObjects.first().category } else { model.objectFunction.category } val objectivePromise = async(Dispatchers.Default) { val coefficient = tokens.indices.map { HashMap<Int?, Flt64>() }.toMutableList() for (subObject in model.objectFunction.subObjects) { if (subObject.category == objectiveCategory) { for (cell in subObject.cells) { val temp = cell as QuadraticCell val value = coefficient[tokenIndexes[temp.token1]!!][temp.token2?.let { tokenIndexes[it]!! }] ?: Flt64.zero coefficient[tokenIndexes[temp.token1]!!][temp.token2?.let { tokenIndexes[it]!! }] = value + temp.coefficient } } else { for (cell in subObject.cells) { val temp = cell as QuadraticCell val value = coefficient[tokenIndexes[temp.token1]!!][temp.token2?.let { tokenIndexes[it]!! }] ?: Flt64.zero coefficient[tokenIndexes[temp.token1]!!][temp.token2?.let { tokenIndexes[it]!! }] = value - temp.coefficient } } } val objective = ArrayList<QuadraticObjectiveCell>() for (i in tokens.indices) { for ((j, value) in coefficient[i]) { objective.add( QuadraticObjectiveCell( i, j, value ) ) } } objective } QuadraticTetradModel( BasicQuadraticTetradModel( variablePromise.await(), constraintPromise.await(), model.name ), QuadraticObjective(objectiveCategory, objectivePromise.await()) ) } } } override fun copy() = QuadraticTetradModel(impl.copy(), objective.copy()) override fun clone() = copy() fun normalized() { impl.normalized() } fun linearRelax() { impl.linearRelax() } fun normalize() { impl.normalize() } override fun exportLP(writer: FileWriter): Try { writer.write("${objective.category}\n") var i = 0 for (cell in objective.obj) { if (cell.coefficient eq Flt64.zero) { continue } val coefficient = if (i != 0) { if (cell.coefficient leq Flt64.zero) { writer.append(" - ") } else { writer.append(" + ") } abs(cell.coefficient) } else { cell.coefficient } if (coefficient neq Flt64.zero) { if (coefficient neq Flt64.one) { writer.append("$coefficient ") } writer.append("${variables[cell.colIndex1]}") if (cell.colIndex2 != null) { writer.append(" * ${variables[cell.colIndex2]}") } } ++i } writer.append("\n\n") return when (val result = impl.exportLP(writer)) { is Failed -> { Failed(result.error) } is Ok -> { ok } } } }
0
Kotlin
0
4
b34cda509b31884e6a15d77f00a6134d001868de
13,781
ospf-kotlin
Apache License 2.0
src/main/kotlin/no/nav/henvendelsesarkiv/Application.kt
navikt
144,120,896
false
null
package no.nav.henvendelsesarkiv import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import no.nav.common.nais.utils.NaisUtils import no.nav.henvendelsesarkiv.PropertyNames.* import no.nav.henvendelsesarkiv.db.UpdateService import no.nav.henvendelsesarkiv.db.coroutineAwareJdbcTemplate import org.flywaydb.core.Flyway import org.slf4j.LoggerFactory import java.util.* import java.util.concurrent.TimeUnit import kotlin.concurrent.schedule private const val FEM_MINUTTER: Long = 1000 * 60 * 5 private val log = LoggerFactory.getLogger("henvendelsesarkiv.Application") data class ApplicationState( val properties: ApplicationProperties, var running: Boolean = true, var initialized: Boolean = false ) fun main() { loadEnvironmentFromVault() runDatabaseMigrationOnStartup() val applicationState = ApplicationState(ApplicationProperties()) val applicationServer = createHttpServer(applicationState = applicationState) val kasseringstimer = Timer() Runtime.getRuntime().addShutdownHook( Thread { log.info("Shutdown hook called, shutting down gracefully") kasseringstimer.cancel() applicationState.initialized = false applicationServer.stop(10, 15, TimeUnit.SECONDS) } ) startKasseringsjobb(kasseringstimer) applicationServer.start(wait = true) } private fun runDatabaseMigrationOnStartup() { val flyway = Flyway() flyway.dataSource = coroutineAwareJdbcTemplate.dataSource flyway.migrate() } private fun loadEnvironmentFromVault() { val serviceUser = NaisUtils.getCredentials("service_user") setProperty(SRVHENVENDELSESARKIV2_USERNAME, serviceUser.username) setProperty(SRVHENVENDELSESARKIV2_PASSWORD, <PASSWORD>) val dbUser = NaisUtils.getCredentials("db_user") setProperty(HENVENDELSESARKIVDATASOURCE_USERNAME, dbUser.username) setProperty(HENVENDELSESARKIVDATASOURCE_PASSWORD, <PASSWORD>) val dbUrl = NaisUtils.getFileContent("/var/run/secrets/nais.io/db_config/jdbc_url") setProperty(HENVENDELSESARKIVDATASOURCE_URL, dbUrl) } private fun startKasseringsjobb(timer: Timer) { log.info("Starter kasseringsjobb.") timer.schedule(FEM_MINUTTER, FEM_MINUTTER) { GlobalScope.launch { try { UpdateService().kasserUtgaatteHenvendelser() } catch (e: Exception) { log.error("Kassering feilet, men schedulering mรฅ overleve, sรฅ dette bare logges", e) } } } }
0
Kotlin
0
0
1f749334203a0b86285f6cc543bde94e4adb508f
2,527
henvendelsesarkiv-2
MIT License
adapter/src/main/kotlin/org/javacs/ktda/classpath/PathUtils.kt
fwcd
144,839,079
false
null
package org.javacs.ktda.classpath import org.javacs.kt.LOG import org.javacs.ktda.util.firstNonNull import java.nio.file.Files import java.nio.file.Paths import java.nio.file.Path private val fileSeparator by lazy { "[/\\\\]".toRegex() } private val sourceFileExtensions = setOf(".kt", ".kts", ".java") /** * Converts a file path to multiple possible JVM class names. * * For example: * * ".../src/main/kotlin/com/abc/MyClass.kt" will be converted to * [com.abc.MyClass, com.abc.MyClassKt] */ fun toJVMClassNames(filePath: String): List<String>? { // TODO: Implement this using the Kotlin compiler API instead // See https://github.com/JetBrains/kotlin-netbeans/blob/c3360e8c89c1d4dac1e6f18267052ff740705079/src/main/java/org/jetbrains/kotlin/debugger/KotlinDebugUtils.java#L166-L194 val rawClassName = filePath.split(fileSeparator) // TODO: Use Project.sourcesRoot instead .takeLastWhile { it != "kotlin" && it != "java" } // Assuming .../src/main/kotlin/... directory structure .joinToString(separator = ".") val className = sourceFileExtensions .asSequence() .find { filePath.endsWith(it) } ?.let { rawClassName.dropLast(it.length) } ?: return null val ktClassName = className .capitalizeCharAt(className.lastIndexOf(".") + 1) + "Kt" // Class name to PascalCase return listOf(className, ktClassName) } // TODO: Better path resolution, especially when dealing with // *.class files inside JARs fun findValidKtFilePath(filePathToClass: Path, sourceName: String?) = filePathToClass.resolveSibling(sourceName).ifExists() ?: filePathToClass.withExtension(".kt").ifExists() private fun Path.ifExists() = if (Files.exists(this)) this else null private fun Path.withExtension(extension: String) = resolveSibling(fileName.toString() + extension) private fun String.capitalizeCharAt(index: Int) = take(index) + this[index].toUpperCase() + substring(index + 1)
32
null
19
96
7f05669b642d21afa46ac7b75307fa5d523a7263
1,895
kotlin-debug-adapter
MIT License
app/src/main/java/com/jiangyy/wanandroid/ui/article/TreeActivity.kt
jyygithub
563,629,875
false
null
package com.jiangyy.wanandroid.ui.article import android.content.Context import android.content.Intent import android.view.View import androidx.activity.viewModels import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup import com.jiangyy.common.view.BaseLoadActivity import com.jiangyy.wanandroid.databinding.ContentPageListBinding import com.jiangyy.wanandroid.entity.Tree import com.jiangyy.wanandroid.ui.adapter.TreeAdapter class TreeActivity : BaseLoadActivity<ContentPageListBinding>(ContentPageListBinding::inflate) { override val viewBindStatus: View get() = binding.refreshLayout private val mAdapter = TreeAdapter() private val mViewModel by viewModels<TreeViewModel>() override fun initWidget() { super.initWidget() binding.toolbar.setTitle("ไฝ“็ณป") binding.recyclerView.layoutManager = GridLayoutManager(this, 2).apply { spanSizeLookup = object : SpanSizeLookup() { override fun getSpanSize(position: Int): Int { return if (mAdapter.getItemViewType(position) == 0) 2 else 1 } } } binding.recyclerView.adapter = mAdapter mAdapter.itemClick { position -> mAdapter.getItem(position).let { if (it.itemType == 1) { ArticlesActivity.actionStart(this, "tree", it) } } } binding.refreshLayout.setOnRefreshListener { preLoad() } } override fun initObserver() { super.initObserver() mViewModel.treeResult.observe(this) { binding.refreshLayout.isRefreshing = false val result = mutableListOf<Tree>() if (it.isSuccess) { preLoadSuccess() mAdapter.submitList = null if (it.getOrNull().isNullOrEmpty()) return@observe it.getOrNull()?.forEach { parent -> result.add(parent) parent.children?.forEach { children -> result.add(children) } } mAdapter.submitList = result } else { preLoadError(it.exceptionOrNull()?.message.orEmpty()) } } } override fun preLoad() { super.preLoad() mViewModel.tree() } companion object { fun actionStart(context: Context) { Intent(context, TreeActivity::class.java).apply { context.startActivity(this) } } } }
0
Kotlin
0
0
d4eff0b8b2faf6875781ef7445d2e4220f25a174
2,641
wanandroid
Apache License 2.0
goblin-core/src/main/java/org/goblinframework/core/event/timer/MinuteTimerEventGenerator.kt
xiaohaiz
206,246,434
false
{"Java": 807217, "Kotlin": 650572, "FreeMarker": 27779, "JavaScript": 968}
package org.goblinframework.core.event.timer import org.goblinframework.core.event.EventBus import org.goblinframework.core.schedule.CronConstants import org.goblinframework.core.schedule.CronTask import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicLong class MinuteTimerEventGenerator internal constructor() : CronTask { private val sequence = AtomicLong() override fun name(): String { return "MinuteTimerEventGenerator" } override fun cronExpression(): String { return CronConstants.MINUTE_TIMER } override fun concurrent(): Boolean { return true } override fun flight(): Boolean { return false } override fun execute() { val next = sequence.getAndIncrement() val event = GoblinTimerEvent(TimeUnit.MINUTES, next) EventBus.publish("/goblin/timer", event) } }
0
Java
6
9
b1db234912ceb23bdd81ac66a3bf61933b717d0b
844
goblinframework
Apache License 2.0
frontend/app/src/main/java/com/harissabil/anidex/ui/screen/library/LibraryViewModel.kt
harissabil
718,008,784
false
{"Kotlin": 279663, "PHP": 35922}
package com.harissabil.anidex.ui.screen.library import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.harissabil.anidex.data.local.UserPreference import com.harissabil.anidex.data.repository.ProjekBasdatRepository import com.harissabil.anidex.util.Resource import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class LibraryViewModel @Inject constructor( private val userPreference: UserPreference, private val repository: ProjekBasdatRepository, ) : ViewModel() { private val _eventFlow = MutableSharedFlow<UIEvent>() val eventFlow: SharedFlow<UIEvent> = _eventFlow.asSharedFlow() private val _state = mutableStateOf(LibraryScreenUIState()) val state: State<LibraryScreenUIState> = _state private var usernamePref = mutableStateOf("") private fun getUser() { viewModelScope.launch { userPreference.getUser().collectLatest { user -> usernamePref.value = user.username } } } fun readLibrary( username: String = usernamePref.value ) { viewModelScope.launch { repository.readLibrary(username).collect { result -> when (result) { is Resource.Error -> { _eventFlow.emit( UIEvent.ShowSnackbar( result.data?.message ?: "Oops, something went wrong!" ) ) } is Resource.Loading -> _state.value = state.value.copy( isLoading = true, ) is Resource.Success -> _state.value = state.value.copy( isLoading = false, libraryAnime = result.data?.data ?: emptyList(), ) } } } } fun readReview( username: String = usernamePref.value ) { viewModelScope.launch { repository.readReview(username).collect { result -> when (result) { is Resource.Error -> { _eventFlow.emit( UIEvent.ShowSnackbar( result.data?.message ?: "Oops, something went wrong!" ) ) } is Resource.Loading -> _state.value = state.value.copy( isLoading = true, ) is Resource.Success -> _state.value = state.value.copy( isLoading = false, reviewAnime = result.data?.data ?: emptyList(), ) } } } } fun deleteReview( reviewId: Int ) { viewModelScope.launch { val library = repository.deleteReview(reviewId) library.collectLatest { result -> when (result) { is Resource.Success -> { _eventFlow.emit(UIEvent.ShowSnackbar(result.data?.message.toString())) } is Resource.Error -> { _eventFlow.emit(UIEvent.ShowSnackbar(result.data?.message.toString())) } is Resource.Loading -> { } } } } readReview() } init { getUser() viewModelScope.launch { readLibrary() readReview() } } sealed class UIEvent { data class ShowSnackbar(val message: String) : UIEvent() } }
0
Kotlin
0
0
4d90767118de195fcda1c209208bdbc3292e7a86
4,067
TemanWibu
MIT License
src/main/kotlin/br/com/zup/edu/keymanager/busca/ConsultaChavePixController.kt
luizpcarvalho
354,830,926
true
{"Kotlin": 21020}
package br.com.zup.edu.keymanager.busca import br.com.zup.edu.ConsultaChavePixRequest import br.com.zup.edu.KeyManagerConsultaServiceGrpc import br.com.zup.edu.KeyManagerListaServiceGrpc import br.com.zup.edu.ListaChavePixRequest import io.micronaut.http.HttpResponse import io.micronaut.http.annotation.Controller import io.micronaut.http.annotation.Get import org.slf4j.LoggerFactory import java.util.* @Controller("/api/v1/clientes/{clienteId}") class ConsultaChavePixController( private val consultaChavePixClient: KeyManagerConsultaServiceGrpc.KeyManagerConsultaServiceBlockingStub, private val listaChavesPixClient: KeyManagerListaServiceGrpc.KeyManagerListaServiceBlockingStub ) { private val LOGGER = LoggerFactory.getLogger(this::class.java) @Get("/pix/{pixId}") fun consulta(clienteId: UUID, pixId: UUID): HttpResponse<Any> { LOGGER.info("[$clienteId] consultando a chave pix $pixId") val response = consultaChavePixClient.consulta( ConsultaChavePixRequest.newBuilder() .setPixId( ConsultaChavePixRequest.FiltroPorPixId.newBuilder() .setClienteId(clienteId.toString()) .setPixId(pixId.toString()) ) .build() ) return HttpResponse.ok(DetalheChavePixResponse(response)) } @Get("/pix") fun lista(clienteId: UUID): HttpResponse<Any> { LOGGER.info("[$clienteId] consultando a lista de chaves Pix") val response = listaChavesPixClient.lista(ListaChavePixRequest.newBuilder() .setClienteId(clienteId.toString()) .build()) val chaves = response.chavesList.map { ListaChavesPixResponse(it) } return HttpResponse.ok(chaves) } }
0
Kotlin
0
0
96b22f2960bd1e93e98b10b56531f58a0584ee89
1,936
orange-talents-01-template-pix-keymanager-rest
Apache License 2.0
app/src/main/kotlin/des/c5inco/pokedexer/ui/moves/MovesListScreen.kt
c5inco
461,368,002
false
{"Kotlin": 295756}
package des.c5inco.pokedexer.ui.moves import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background 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.WindowInsets import androidx.compose.foundation.layout.asPaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.navigationBars import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredWidth import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.LocalContentColor import androidx.compose.material3.LocalTextStyle import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import des.c5inco.pokedexer.data.moves.SampleMoves import des.c5inco.pokedexer.model.Move import des.c5inco.pokedexer.ui.common.CategoryIcon import des.c5inco.pokedexer.ui.common.NavigationTopAppBar import des.c5inco.pokedexer.ui.common.TypeLabel import des.c5inco.pokedexer.ui.common.TypeLabelMetrics.Companion.MEDIUM import des.c5inco.pokedexer.ui.theme.AppTheme import des.c5inco.pokedexer.ui.theme.PokemonTypesTheme @Composable fun MovesListScreenRoute( viewModel: MovesListViewModel, onBackClick: () -> Unit = {} ) { MovesListScreen( loading = viewModel.uiState.loading, moves = viewModel.uiState.moves, onBackClick = onBackClick ) } @Composable fun MovesListScreen( loading: Boolean, moves: List<Move>, onBackClick: () -> Unit = {}, ) { Surface { Column( Modifier.fillMaxSize() ) { NavigationTopAppBar( modifier = Modifier .statusBarsPadding() .padding(top = 16.dp), onBackClick = onBackClick ) Column( Modifier .weight(1f) .padding(horizontal = 24.dp) ) { Text( text = "Moves", style = MaterialTheme.typography.headlineMedium, modifier = Modifier.padding( top = 16.dp, bottom = 24.dp ) ) if (loading) { CircularProgressIndicator() } else { MovesList(moves = moves) } } } } } @OptIn(ExperimentalFoundationApi::class) @Composable private fun MovesList( modifier: Modifier = Modifier, moves: List<Move> = SampleMoves ) { LazyColumn( modifier = modifier, contentPadding = WindowInsets.navigationBars.asPaddingValues() ) { stickyHeader { val textStyle = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Bold) CompositionLocalProvider( LocalTextStyle provides textStyle, LocalContentColor provides MaterialTheme.colorScheme.onSurfaceVariant ) { Row( Modifier .fillMaxWidth() .background(MaterialTheme.colorScheme.surface) .padding(vertical = 12.dp), horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = "Move", modifier = Modifier.weight(1f), ) Box( Modifier.requiredWidth(75.dp), contentAlignment = Alignment.Center ) { Text("Type") } Box( Modifier.requiredWidth(48.dp), contentAlignment = Alignment.Center ) { Text("Cat") } Text( text = "Pwr", textAlign = TextAlign.End, modifier = Modifier.requiredWidth(40.dp) ) Text( text = "Acc", textAlign = TextAlign.End, modifier = Modifier.requiredWidth(40.dp) ) } } } items(moves) { move -> Row( Modifier .fillMaxWidth() .padding(bottom = 8.dp) , horizontalArrangement = Arrangement.SpaceBetween ) { Text( move.name.split("-").joinToString(" ") { it[0].uppercase() + it.substring(1) }, Modifier.weight(1f) ) PokemonTypesTheme(types = listOf(move.type)) { TypeLabel( modifier = Modifier.requiredWidth(75.dp), text = move.type, colored = true, metrics = MEDIUM ) } Box( Modifier.requiredWidth(48.dp), contentAlignment = Alignment.Center ) { CategoryIcon( modifier = Modifier.size(24.dp), move = move ) } Text( "${move.power ?: "โ€”"}", textAlign = TextAlign.End, modifier = Modifier.requiredWidth(40.dp) ) Text( text = "${move.accuracy ?: "โ€”"}", textAlign = TextAlign.End, modifier = Modifier.requiredWidth(40.dp) ) } } } } @Preview @Composable fun MovesListScreenPreview() { AppTheme { Surface { MovesListScreen( loading = false, moves = SampleMoves ) } } } @Preview @Composable fun MovesListPreview() { AppTheme { Surface { MovesList() } } }
0
Kotlin
12
115
78babffb491ec9032f90565aeef61ef62bf2a616
7,069
compose-pokedexer
MIT License
desktopApp/src/jvmMain/kotlin/com/prof18/feedflow/desktop/home/components/FeedWithContentView.desktop.kt
prof18
600,257,020
false
{"Kotlin": 746513, "HTML": 182777, "Swift": 163455, "SCSS": 161629, "CSS": 16810, "Shell": 2392, "JavaScript": 1214}
package com.prof18.feedflow.desktop.home.components import androidx.compose.animation.AnimatedVisibility import androidx.compose.desktop.ui.tooling.preview.Preview import androidx.compose.foundation.VerticalScrollbar import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.rememberScrollbarAdapter import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.prof18.feedflow.core.model.FeedItem import com.prof18.feedflow.core.model.FeedItemId import com.prof18.feedflow.core.model.FeedItemUrlInfo import com.prof18.feedflow.shared.domain.model.FeedUpdateStatus import com.prof18.feedflow.shared.presentation.preview.feedItemsForPreview import com.prof18.feedflow.shared.presentation.preview.inProgressFeedUpdateStatus import com.prof18.feedflow.shared.ui.home.components.FeedItemView import com.prof18.feedflow.shared.ui.home.components.FeedList import com.prof18.feedflow.shared.ui.style.Spacing import com.prof18.feedflow.shared.ui.theme.FeedFlowTheme import com.prof18.feedflow.shared.ui.utils.LocalFeedFlowStrings import kotlinx.collections.immutable.ImmutableList @Composable internal fun FeedWithContentView( paddingValues: PaddingValues, feedState: ImmutableList<FeedItem>, loadingState: FeedUpdateStatus, listState: LazyListState, updateReadStatus: (Int) -> Unit, onFeedItemClick: (FeedItemUrlInfo) -> Unit, onBookmarkClick: (FeedItemId, Boolean) -> Unit, onReadStatusClick: (FeedItemId, Boolean) -> Unit, onCommentClick: (FeedItemUrlInfo) -> Unit, requestMoreItems: () -> Unit, modifier: Modifier = Modifier, ) { Column( modifier = modifier, ) { FeedLoader(loadingState = loadingState) Box( modifier = Modifier.fillMaxSize() .padding(paddingValues) .padding(end = 4.dp), ) { FeedList( modifier = Modifier, feedItems = feedState, listState = listState, requestMoreItems = requestMoreItems, updateReadStatus = { index -> updateReadStatus(index) }, ) { feedItem, index -> FeedItemView( feedItem = feedItem, index = index, onFeedItemClick = onFeedItemClick, onBookmarkClick = onBookmarkClick, onReadStatusClick = onReadStatusClick, onCommentClick = onCommentClick, feedItemImage = { url -> FeedItemImage( modifier = Modifier .padding(start = Spacing.regular), url = url, width = 96.dp, ) }, ) } VerticalScrollbar( modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight(), adapter = rememberScrollbarAdapter( scrollState = listState, ), ) } } } @Composable private fun ColumnScope.FeedLoader(loadingState: FeedUpdateStatus) { AnimatedVisibility(loadingState.isLoading()) { val feedRefreshCounter = """ ${loadingState.refreshedFeedCount}/${loadingState.totalFeedCount} """.trimIndent() Text( modifier = Modifier .fillMaxWidth() .padding(horizontal = Spacing.regular), text = LocalFeedFlowStrings.current.loadingFeedMessage(feedRefreshCounter), textAlign = TextAlign.Center, style = MaterialTheme.typography.titleMedium, ) } } @Preview @Composable private fun FeedWithContentViewPreview() { FeedFlowTheme { FeedWithContentView( feedState = feedItemsForPreview, loadingState = inProgressFeedUpdateStatus, listState = LazyListState(), updateReadStatus = { }, onFeedItemClick = { }, onBookmarkClick = { _, _ -> }, onReadStatusClick = { _, _ -> }, onCommentClick = { }, requestMoreItems = { }, paddingValues = PaddingValues(), ) } }
27
Kotlin
18
332
60c15c24c157e46625e05158c5d048d4ca4b7217
4,957
feed-flow
Apache License 2.0
src/main/kotlin/com/sparetimedevs/ami/midi/player/MidiPlayer.kt
sparetimedevs
731,672,148
false
{"Kotlin": 242073}
/* * Copyright (c) 2023 sparetimedevs and respective authors and developers. * * 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.sparetimedevs.ami.midi.player import com.sparetimedevs.ami.midi.Metronome import com.sparetimedevs.ami.midi.MidiPlayerSettings import com.sparetimedevs.ami.music.data.kotlin.note.Note import com.sparetimedevs.ami.music.data.kotlin.note.NoteName import com.sparetimedevs.ami.music.data.kotlin.note.Pitch import java.time.Duration import javax.sound.midi.Receiver import javax.sound.midi.ShortMessage import kotlinx.coroutines.CoroutineScope class MidiPlayer(settings: MidiPlayerSettings, scope: CoroutineScope) : Player( settings.metronomeMidiChannelNumber, settings.scoreMidiChannelNumber, settings.metronome, settings.isMetronomeEnabled, scope ) { private val receiver: Receiver = settings.midiDevice.receiver override fun playNote(note: Note, onMidiChannelNumber: Int) { println("Playing $note on thread ${Thread.currentThread().name}") val midinote = helperFunForPitchOfNoteToMidiNoteValue(note) // val midiVel = (127f * note.amp).toInt() // TODO we don't have a volume attribute // yet (or any indication of how loud a note should be played). val midiVel = (127f * 0.5f).toInt() val noteOnMsg = ShortMessage(ShortMessage.NOTE_ON, onMidiChannelNumber, midinote, midiVel) receiver.send(noteOnMsg, -1) } override fun stopNote(note: Note, onMidiChannelNumber: Int) { val midinote = helperFunForPitchOfNoteToMidiNoteValue(note) // val midiVel = (127f * note.amp).toInt() // TODO we don't have a volume attribute // yet (or any indication of how loud a note should be played). val midiVel = (127f * 0.5f).toInt() // val noteOffAt = playAt.plus((note.duration * metronome.millisPerBeat).toLong(), // ChronoUnit.MILLIS) val noteOffMsg = ShortMessage(ShortMessage.NOTE_OFF, onMidiChannelNumber, midinote, midiVel) receiver.send(noteOffMsg, -1) } } fun helperFunForPitchOfNoteToMidiNoteValue(note: Note): Int = when (note) { is Note.Pitched -> helperFunForPitchToMidiNoteValue(note.pitch) else -> 0 } fun helperFunForPitchToMidiNoteValue(pitch: Pitch): Int { // TODO should also take into consideration the pitch.alter val octaveInByte: Byte = pitch.octave.value val y = when (octaveInByte) { 0.toByte() -> 8 1.toByte() -> 20 2.toByte() -> 32 3.toByte() -> 44 4.toByte() -> 56 5.toByte() -> 68 6.toByte() -> 80 7.toByte() -> 92 8.toByte() -> 104 9.toByte() -> 116 10.toByte() -> 128 11.toByte() -> 130 12.toByte() -> 142 else -> 56 // Default to octave 4 } // The limit is the 128 notes Midi supports. return y + helperFunForPitchToMidiNoteValue(pitch.noteName) - 56 // TODO this - 56 should be refactored away (deduct it from `NoteName.A_FLAT -> 56` etc.) } fun helperFunForPitchToMidiNoteValue(noteName: NoteName): Int = when (noteName) { NoteName.A_FLAT -> 56 NoteName.A -> 57 NoteName.A_SHARP -> 58 NoteName.B_FLAT -> 58 NoteName.B -> 59 NoteName.C -> 60 NoteName.C_SHARP -> 61 NoteName.D_FLAT -> 61 NoteName.D -> 62 NoteName.D_SHARP -> 63 NoteName.E_FLAT -> 63 NoteName.E -> 64 NoteName.F -> 65 NoteName.F_SHARP -> 66 NoteName.G_FLAT -> 66 NoteName.G -> 67 NoteName.G_SHARP -> 68 } fun helperFunForDurationOfNoteToJavaTimeDuration(note: Note, metronome: Metronome): Duration { // For 4/4 time signature val millis = (note.duration.value * 4 * metronome.millisPerBeat).toLong() return Duration.ofMillis(millis) }
1
Kotlin
0
0
ede30b57915691105418c9dd27d176e70422b833
4,469
ami-desktop
Apache License 2.0
kafka-delayed-producer-core/src/main/kotlin/com/github/martintomac/kafkadelayedproducer/Reference.kt
martintomac
328,480,243
false
null
package com.github.martintomac.kafkadelayedproducer interface Reference<T : Any> { val value: T fun release() { } } interface ReferenceFactory<T : Any> { fun create(value: T): Reference<T> companion object { @Suppress("UNCHECKED_CAST") fun <T : Any> instance() = DirectReferenceFactory as ReferenceFactory<T> } private object DirectReferenceFactory : ReferenceFactory<Any> { override fun create(value: Any): Reference<Any> = DirectReference(value) private class DirectReference(override val value: Any) : Reference<Any> } }
0
Kotlin
0
3
04bfc2f200b7f4f5cb9f7c25543d49a5f9b92614
594
kafka-delayed-producer
MIT License
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/cognito/UserPoolDomainPropsDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.cognito import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import kotlin.Unit import software.amazon.awscdk.services.cognito.CognitoDomainOptions import software.amazon.awscdk.services.cognito.CustomDomainOptions import software.amazon.awscdk.services.cognito.IUserPool import software.amazon.awscdk.services.cognito.UserPoolDomainProps /** * Props for UserPoolDomain construct. * * Example: * ``` * import software.amazon.awscdk.services.certificatemanager.*; * Vpc vpc; * Certificate certificate; * ApplicationLoadBalancer lb = ApplicationLoadBalancer.Builder.create(this, "LB") * .vpc(vpc) * .internetFacing(true) * .build(); * UserPool userPool = new UserPool(this, "UserPool"); * UserPoolClient userPoolClient = UserPoolClient.Builder.create(this, "Client") * .userPool(userPool) * // Required minimal configuration for use with an ELB * .generateSecret(true) * .authFlows(AuthFlow.builder() * .userPassword(true) * .build()) * .oAuth(OAuthSettings.builder() * .flows(OAuthFlows.builder() * .authorizationCodeGrant(true) * .build()) * .scopes(List.of(OAuthScope.EMAIL)) * .callbackUrls(List.of(String.format("https://%s/oauth2/idpresponse", * lb.getLoadBalancerDnsName()))) * .build()) * .build(); * CfnUserPoolClient cfnClient = (CfnUserPoolClient)userPoolClient.getNode().getDefaultChild(); * cfnClient.addPropertyOverride("RefreshTokenValidity", 1); * cfnClient.addPropertyOverride("SupportedIdentityProviders", List.of("COGNITO")); * UserPoolDomain userPoolDomain = UserPoolDomain.Builder.create(this, "Domain") * .userPool(userPool) * .cognitoDomain(CognitoDomainOptions.builder() * .domainPrefix("test-cdk-prefix") * .build()) * .build(); * lb.addListener("Listener", BaseApplicationListenerProps.builder() * .port(443) * .certificates(List.of(certificate)) * .defaultAction(AuthenticateCognitoAction.Builder.create() * .userPool(userPool) * .userPoolClient(userPoolClient) * .userPoolDomain(userPoolDomain) * .next(ListenerAction.fixedResponse(200, FixedResponseOptions.builder() * .contentType("text/plain") * .messageBody("Authenticated") * .build())) * .build()) * .build()); * CfnOutput.Builder.create(this, "DNS") * .value(lb.getLoadBalancerDnsName()) * .build(); * ``` */ @CdkDslMarker public class UserPoolDomainPropsDsl { private val cdkBuilder: UserPoolDomainProps.Builder = UserPoolDomainProps.builder() /** * @param cognitoDomain Associate a cognito prefix domain with your user pool Either * `customDomain` or `cognitoDomain` must be specified. */ public fun cognitoDomain(cognitoDomain: CognitoDomainOptionsDsl.() -> Unit = {}) { val builder = CognitoDomainOptionsDsl() builder.apply(cognitoDomain) cdkBuilder.cognitoDomain(builder.build()) } /** * @param cognitoDomain Associate a cognito prefix domain with your user pool Either * `customDomain` or `cognitoDomain` must be specified. */ public fun cognitoDomain(cognitoDomain: CognitoDomainOptions) { cdkBuilder.cognitoDomain(cognitoDomain) } /** * @param customDomain Associate a custom domain with your user pool Either `customDomain` or * `cognitoDomain` must be specified. */ public fun customDomain(customDomain: CustomDomainOptionsDsl.() -> Unit = {}) { val builder = CustomDomainOptionsDsl() builder.apply(customDomain) cdkBuilder.customDomain(builder.build()) } /** * @param customDomain Associate a custom domain with your user pool Either `customDomain` or * `cognitoDomain` must be specified. */ public fun customDomain(customDomain: CustomDomainOptions) { cdkBuilder.customDomain(customDomain) } /** @param userPool The user pool to which this domain should be associated. */ public fun userPool(userPool: IUserPool) { cdkBuilder.userPool(userPool) } public fun build(): UserPoolDomainProps = cdkBuilder.build() }
3
null
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
4,239
awscdk-dsl-kotlin
Apache License 2.0
app/src/main/java/com/sjl/bookmark/ui/activity/BookSearchActivity.kt
kellysong
258,122,128
false
{"HTML": 2024914, "Java": 804499, "Kotlin": 753949, "CSS": 18483, "JavaScript": 365}
package com.sjl.bookmark.ui.activity import android.os.Build import android.text.Editable import android.text.TextWatcher import android.view.* import android.widget.* import androidx.core.content.ContextCompat import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.sjl.bookmark.R import com.sjl.bookmark.entity.zhuishu.SearchBookDto.BooksBean import com.sjl.bookmark.ui.adapter.* import com.sjl.bookmark.ui.contract.BookSearchContract import com.sjl.bookmark.ui.presenter.BookSearchPresenter import com.sjl.core.mvp.BaseActivity import com.sjl.core.util.* import com.zhy.adapter.recyclerview.MultiItemTypeAdapter import kotlinx.android.synthetic.main.book_search_activity.* import kotlinx.android.synthetic.main.fragment_refresh_list.* import me.gujun.android.taggroup.TagGroup.OnTagClickListener /** * ไนฆ็ฑๆœ็ดข * * @author Kelly * @version 1.0.0 * @filename BookSearchActivity.java * @time 2018/11/30 16:58 * @copyright(C) 2018 song */ class BookSearchActivity : BaseActivity<BookSearchPresenter>(), BookSearchContract.View { /* @BindView(R.id.search_rv_history) RecyclerView mRvHistory;*/ private lateinit var mKeyWordAdapter: BookKeyWordAdapter private lateinit var mSearchAdapter: SearchBookAdapter /** * trueๆ˜พ็คบๅ…ณ้”ฎๅญ—ๆœ็ดข่‡ชๅŠจ่กฅๅ…จๅˆ—่กจ๏ผŒfalseๆ˜พ็คบๆœ็ดขไนฆ็ฑๅˆ—่กจ */ private var contentFlag: Boolean = true private var isTag: Boolean = false private var mHotTagList: List<String>? = null private var mTagStart: Int = 0 override fun getLayoutId(): Int { return R.layout.book_search_activity } override fun initView() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { refresh_layout.background = ContextCompat.getDrawable(this, R.color.white) } } override fun initListener() { //้€€ๅ‡บ search_iv_back.setOnClickListener(object : View.OnClickListener { override fun onClick(v: View) { finish() } }) //่พ“ๅ…ฅๆก† search_et_input.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged( s: CharSequence, start: Int, count: Int, after: Int ) { } override fun onTextChanged( s: CharSequence, start: Int, before: Int, count: Int ) { if ((s.toString().trim { it <= ' ' } == "")) { //้š่—deleteๆŒ‰้’ฎๅ’Œๅ…ณ้”ฎๅญ—ๆ˜พ็คบๅ†…ๅฎน if (search_iv_delete.visibility == View.VISIBLE) { search_iv_delete.visibility = View.INVISIBLE refresh_layout.visibility = View.INVISIBLE //ๅˆ ้™คๅ…จ้ƒจ่ง†ๅ›พ mKeyWordAdapter.datas.clear() mSearchAdapter.datas.clear() refresh_rv_content.removeAllViews() } return } //็”ฑๅŽŸๆฅ้š่—ๅ˜ๅฏ่ง๏ผŒๆ˜พ็คบdeleteๆŒ‰้’ฎ if (search_iv_delete.visibility == View.INVISIBLE) { search_iv_delete.visibility = View.VISIBLE refresh_layout.visibility = View.VISIBLE //้ป˜่ฎคๆ˜ฏๆ˜พ็คบๅฎŒๆˆ็Šถๆ€ refresh_layout.showFinish() } //ๆœ็ดข val query: String = s.toString().trim { it <= ' ' } if (isTag) { contentFlag = false refresh_layout.showLoading() mPresenter.searchBook(query) isTag = false } else { //ไผ ้€’ contentFlag = true mPresenter.searchKeyWord(query) } } override fun afterTextChanged(s: Editable) {} }) //้”ฎ็›˜็š„ๆœ็ดข search_et_input.setOnKeyListener(object : View.OnKeyListener { override fun onKey(v: View, keyCode: Int, event: KeyEvent): Boolean { //ไฟฎๆ”นๅ›ž่ฝฆ้”ฎๅŠŸ่ƒฝ if (keyCode == KeyEvent.KEYCODE_ENTER) { contentFlag = false searchBook() return true } return false } }) //่ฟ›่กŒๆœ็ดข search_iv_search.setOnClickListener(object : View.OnClickListener { override fun onClick(v: View) { contentFlag = false searchBook() } }) //ๅˆ ้™คๅญ— search_iv_delete.setOnClickListener(object : View.OnClickListener { override fun onClick(v: View) { search_et_input.setText("") ViewUtils.toggleKeyboard(this@BookSearchActivity) } }) //Tag็š„็‚นๅ‡ปไบ‹ไปถ search_tg_hot.setOnTagClickListener(object : OnTagClickListener { override fun onTagClick(tag: String) { isTag = true search_et_input.setText(tag) } }) //Tag็š„ๅˆทๆ–ฐไบ‹ไปถ search_book_tv_refresh_hot.setOnClickListener(object : View.OnClickListener { override fun onClick(v: View) { refreshTag() } }) } override fun initData() { mKeyWordAdapter = BookKeyWordAdapter(this, R.layout.search_book_keyword_recycle_item, null) mSearchAdapter = SearchBookAdapter(this, R.layout.search_book_recycle_item, null) refresh_rv_content.layoutManager = LinearLayoutManager(this) refresh_rv_content.addItemDecoration( RecyclerViewDivider( this, LinearLayoutManager.VERTICAL ) ) //็‚นๅ‡ปๅ…ณ้”ฎๅญ—ๆŸฅไนฆ mKeyWordAdapter.setOnItemClickListener(object : MultiItemTypeAdapter.OnItemClickListener { override fun onItemClick( view: View, holder: RecyclerView.ViewHolder, position: Int ) { //ๆ˜พ็คบๆญฃๅœจๅŠ ่ฝฝ contentFlag = false refresh_layout.showLoading() val book: String? = mKeyWordAdapter.getItem(position) mPresenter.searchBook(book) ViewUtils.toggleKeyboard(this@BookSearchActivity) } override fun onItemLongClick( view: View, holder: RecyclerView.ViewHolder, position: Int ): Boolean { return false } }) //ไนฆๆœฌ็š„็‚นๅ‡ปไบ‹ไปถ mSearchAdapter.setOnItemClickListener(object : MultiItemTypeAdapter.OnItemClickListener { override fun onItemClick( view: View, holder: RecyclerView.ViewHolder, position: Int ) { val item: BooksBean = mSearchAdapter.getItem(position) val bookId: String = item._id BookDetailActivity.startActivity(this@BookSearchActivity, bookId) } override fun onItemLongClick( view: View, holder: RecyclerView.ViewHolder, position: Int ): Boolean { return false } }) //้ป˜่ฎค้š่— refresh_layout.visibility = View.GONE //่Žทๅ–็ƒญ่ฏ mPresenter.searchHotWord() } override fun finishHotWords(hotWords: List<String>) { mHotTagList = hotWords refreshTag() } override fun finishKeyWords(keyWords: List<String>) { if (keyWords == null || keyWords.size == 0) refresh_layout!!.visibility = View.INVISIBLE //BookKeyWordAdapterใ€SearchBookAdapterๅ…ฑ็”จไธ€ไธชRecyclerView,ๅ…ˆ่ฎพ็ฝฎ้€‚้…ๅ™จๅœจๅˆทๆ–ฐ if (contentFlag) { //่ฎพ็ฝฎmRefreshLayoutใ€mRecyclerViewๆ˜พ็คบ๏ผŒๅฆๅˆ™ๆœ็ดขไนฆ็ฑๆœ็ดขๅˆ—่กจๆ—ถๅฏผ่‡ดmRecyclerView้š่— refresh_layout.visibility = View.VISIBLE refresh_rv_content.visibility = View.VISIBLE refresh_rv_content.adapter = mKeyWordAdapter mKeyWordAdapter.refreshItems(keyWords) } } override fun finishBooks(books: List<BooksBean>) { if (books == null || books.size == 0) { refresh_layout!!.showEmpty() } else { //ๆ˜พ็คบๅฎŒๆˆ refresh_layout!!.showFinish() } //ๅŠ ่ฝฝ if (!contentFlag) { refresh_rv_content.adapter = mSearchAdapter mSearchAdapter.refreshItems(books) } } override fun errorBooks() { refresh_layout!!.showEmpty() } /** * ๆขไธ€ๆ‰น */ private fun refreshTag() { if (mHotTagList == null) { return } var last: Int = mTagStart + TAG_LIMIT if (mHotTagList!!.size <= last) { mTagStart = 0 if (mHotTagList!!.size < TAG_LIMIT) { last = mTagStart + mHotTagList!!.size } else { last = mTagStart + TAG_LIMIT } showShortToast(getString(R.string.no_load_more)) } val tags: List<String> = mHotTagList!!.subList(mTagStart, last) search_tg_hot.setTags(tags) //่ฎพ็ฝฎๅˆฐๆŽงไปถTagGroup mTagStart += TAG_LIMIT } /** * ไนฆ็ฑๆŸฅ่ฏข */ private fun searchBook() { val query: String = search_et_input!!.text.toString().trim { it <= ' ' } if (!(query == "")) { refresh_layout.visibility = View.VISIBLE //ๆ˜พ็คบๆญฃๅœจๅŠ ่ฝฝ refresh_layout.showLoading() mPresenter.searchBook(query) ViewUtils.toggleKeyboard(this) } } companion object { private val TAG_LIMIT: Int = 8 } }
0
HTML
0
0
edd0990579fe1368a58af87007be3cd68081f5c8
9,671
my-bookmark-master
Apache License 2.0
js/js.frontend/src/org/jetbrains/kotlin/js/resolve/diagnostics/JsModuleCheckUtil.kt
JakeWharton
99,388,807
false
null
/* * Copyright 2010-2016 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.js.resolve.diagnostics import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor import org.jetbrains.kotlin.diagnostics.DiagnosticSink import org.jetbrains.kotlin.js.resolve.MODULE_KIND import org.jetbrains.kotlin.js.translate.utils.AnnotationsUtils import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.util.FakeCallableDescriptorForObject import org.jetbrains.kotlin.serialization.js.ModuleKind fun checkJsModuleUsage( bindingContext: BindingContext, diagnosticSink: DiagnosticSink, container: DeclarationDescriptor, callee: DeclarationDescriptor, reportOn: PsiElement ) { val module = DescriptorUtils.getContainingModule(container) val moduleKind = bindingContext[MODULE_KIND, module] ?: return val calleeRootContainer = findRoot(callee) val callToModule = AnnotationsUtils.getModuleName(calleeRootContainer) != null || AnnotationsUtils.getFileModuleName(bindingContext, calleeRootContainer) != null val callToNonModule = AnnotationsUtils.isNonModule(calleeRootContainer) || AnnotationsUtils.isFromNonModuleFile(bindingContext, calleeRootContainer) if (moduleKind == ModuleKind.UMD) { if (!callToNonModule && callToModule || callToNonModule && !callToModule) { diagnosticSink.report(ErrorsJs.CALL_FROM_UMD_MUST_BE_JS_MODULE_AND_JS_NON_MODULE.on(reportOn)) } } else { if (moduleKind == ModuleKind.PLAIN) { if (!callToNonModule && callToModule) { diagnosticSink.report(ErrorsJs.CALL_TO_JS_MODULE_WITHOUT_MODULE_SYSTEM.on(reportOn, normalizeDescriptor(callee))) } } else { if (!callToModule && callToNonModule) { diagnosticSink.report(ErrorsJs.CALL_TO_JS_NON_MODULE_WITH_MODULE_SYSTEM.on(reportOn, normalizeDescriptor(callee))) } } } } private fun normalizeDescriptor(descriptor: DeclarationDescriptor): DeclarationDescriptor { if (descriptor is FakeCallableDescriptorForObject) return descriptor.classDescriptor return descriptor } private fun findRoot(callee: DeclarationDescriptor) = generateSequence(callee) { it.containingDeclaration } .takeWhile { it !is PackageFragmentDescriptor } .last()
179
null
5640
83
4383335168338df9bbbe2a63cb213a68d0858104
3,111
kotlin
Apache License 2.0
app/src/main/java/com/example/hotplenavigation/data/get_result_path/Goal.kt
HanBI24
469,585,277
false
null
package com.example.hotplenavigation.data.get_result_path // 20197138 ์žฅ์€์ง€ data class Goal( val dir: Int, val location: List<Double> )
19
Kotlin
0
0
35f6795e1bfc03455619ecf8941f7838b1afd8de
143
2022_1_Capston_Edge-Map
MIT License
shoring/desk/src/main/kotlin/com/panopset/marin/oldswpkg/games/blackjack/LayoutChips.kt
panopset
752,122,553
false
{"Kotlin": 596701, "Java": 26106, "Shell": 9728, "CSS": 4623, "JavaScript": 4084, "Batchfile": 2807, "HTML": 1317}
package com.panopset.marin.oldswpkg.games.blackjack class LayoutChips(val chipXnextBet: Int, bottom: Int, chipWidth: Int, chipHeight: Int) { val chipXstack: Int val chipY: Int init { chipXstack = chipXnextBet + chipWidth chipY = bottom - (chipHeight * 1.5).toInt() } }
0
Kotlin
0
0
3d7e49a48689a580a7cf7b5d738c2aa4abf23b15
303
pan
MIT License
src/test/kotlin/io/spine/publishing/given/PipelineTestEnv.kt
SpineEventEngine
267,584,112
false
null
package io.spine.publishing.given import com.google.common.io.Files import io.spine.publishing.* import io.spine.publishing.git.GitHubRepoUrl import io.spine.publishing.git.GitRepository import java.nio.file.Path /** * Utilities for testing the [io.spine.publishing.PublishingPipeline] */ object PipelineTestEnv { val sampleRemote = GitHubRepoUrl("sample_org", "sample_library") private lateinit var versionFile: Path private fun copyResourceFile() { val tempDir = Files.createTempDir() versionFile = tempDir.toPath().resolve("version.gradle.kts") versionFile.toFile().createNewFile() @Suppress("RECEIVER_NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS") val text = PipelineTestEnv::javaClass.get().classLoader.getResource("version.gradle.kts").readText() versionFile.toFile().writeText(text) } fun sampleLibrary(): Library { if (!this::versionFile.isInitialized) { copyResourceFile() } return Library("base", listOf(), GitRepository(versionFile.parent, sampleRemote), Artifact(GroupId("hk", "sample"), "library")) } /** * An operation that always throws an exception. */ object ThrowingOperation : PipelineOperation() { override fun perform(libraries: LibrariesToPublish): OperationResult = throw IllegalStateException() } /** * An operation that always returns an [io.spine.publishing.Error] */ object ErroneousOperation : PipelineOperation() { override fun perform(libraries: LibrariesToPublish): OperationResult = Error("An erroneous operation always errors.") } class CollectingOperation : PipelineOperation() { private val seenLibraries: MutableList<Library> = mutableListOf() override fun perform(libraries: LibrariesToPublish): OperationResult { seenLibraries.addAll(libraries.toSet()) return Ok } fun seenLibraries(): List<Library> = seenLibraries.toList() } }
5
Kotlin
1
0
d5d01acadf110fb3f28126d4a3499653e587d190
2,096
publishing
Apache License 2.0
app/src/main/java/com/fadenai/androidsample1/data/di/RepositoryModule.kt
MohammadFeyzian
857,478,261
false
{"Kotlin": 61298}
package com.fadenai.androidsample1.data.di import com.fadenai.androidsample1.data.repository.DataRepository import com.fadenai.androidsample1.data.repository.DataRepositoryImpl import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) interface RepositoryModule { @Binds fun repo(repoImpl: DataRepositoryImpl): DataRepository }
0
Kotlin
0
0
e8ca359a62e87eee80d7522149c6109fb30e6250
445
android-sample-1
MIT License
plot-base-portable/src/commonMain/kotlin/jetbrains/datalore/plot/base/render/point/symbol/SquareGlyph.kt
JetBrains
176,771,727
false
null
/* * Copyright (c) 2020. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package jetbrains.datalore.plot.base.render.point.symbol import jetbrains.datalore.base.geometry.DoubleVector import org.jetbrains.letsPlot.datamodel.svg.dom.slim.SvgSlimElements import org.jetbrains.letsPlot.datamodel.svg.dom.slim.SvgSlimShape internal class SquareGlyph(location: DoubleVector, size: Double) : SingletonGlyph(location, size) { override fun createShape(location: DoubleVector, width: Double): SvgSlimShape { return SvgSlimElements.rect( location.x - width / 2, location.y - width / 2, width, width) } }
98
Kotlin
47
889
c5c66ceddc839bec79b041c06677a6ad5f54e416
748
lets-plot
MIT License
app/src/main/java/at/guger/moneybook/ui/home/overview/dues/OverviewDuesViewHolder.kt
guger
198,668,519
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 at.guger.moneybook.ui.home.overview.dues import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import at.guger.moneybook.R import at.guger.moneybook.core.ui.recyclerview.viewholder.BindingViewHolder import at.guger.moneybook.data.model.Transaction import at.guger.moneybook.databinding.ItemOverviewDuesBinding import at.guger.moneybook.ui.home.HomeViewModel import kotlin.math.min /** * [RecyclerView.ViewHolder] for the dues overview item. */ class OverviewDuesViewHolder(binding: ItemOverviewDuesBinding) : BindingViewHolder<ItemOverviewDuesBinding, HomeViewModel>(binding) { override fun bind(viewModel: HomeViewModel) { binding.viewModel = viewModel binding.executePendingBindings() viewModel.claimsAndDebts.observe(binding.lifecycleOwner!!) { transactions -> binding.mOverviewDuesDivider.setDistributions( listOf( transactions.filter { !it.isPaid && it.type == Transaction.TransactionType.CLAIM }.sumOf { it.value }.toFloat(), transactions.filter { !it.isPaid && it.type == Transaction.TransactionType.DEBT }.sumOf { it.value }.toFloat() ), colorsRes = listOf( R.color.color_claim, R.color.color_debt ) ) } binding.mOverviewDuesRecyclerView.apply { layoutManager = LinearLayoutManager(context) adapter = OverviewDuesListAdapter().apply { viewModel.claimsAndDebts.observe(binding.lifecycleOwner!!) { transactions -> val unpaidDues = transactions.filterNot { it.isPaid } submitList(unpaidDues.subList(0, min(unpaidDues.size, 3))) } } } } }
18
null
1
13
cc374cf434aad9db5a3fc8f336aaf3e4eb91100d
2,456
MoneyBook
Apache License 2.0
src/test/kotlin/eu/europa/ec/eudi/sdjwt/examples/ExampleHandlingStructuredClaims01.kt
eu-digital-identity-wallet
656,042,600
false
{"Kotlin": 247799}
/* * Copyright (c) 2023 European Commission * * 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 eu.europa.ec.eudi.sdjwt.examples import eu.europa.ec.eudi.sdjwt.* import kotlinx.serialization.json.* val handlingStructuredClaims = sdJwt { iss("https://issuer.example.com") iat(1683000000) exp(1883000000) sd { put("sub", "6c5c0a49-b589-431d-bae7-219122a9ec2c") put("given_name", "ๅคช้ƒŽ") put("family_name", "ๅฑฑ็”ฐ") put("email", "\"unusual email address\"@example.jp") put("phone_number", "+81-80-1234-5678") put("birthdate", "1940-01-01") } structured("address") { sd { put("street_address", "ๆฑไบฌ้ƒฝๆธฏๅŒบ่Šๅ…ฌๅœ’๏ผ”ไธ็›ฎ๏ผ’โˆ’๏ผ˜") put("locality", "ๆฑไบฌ้ƒฝ") put("region", "ๆธฏๅŒบ") put("country", "JP") } } }
2
Kotlin
2
9
d918b31c862043d96d05ca93ac997fad89342913
1,420
eudi-lib-jvm-sdjwt-kt
Apache License 2.0
javatests/com/google/android/libraries/pcc/chronicle/api/remote/RemoteRequestTest.kt
google
564,990,777
false
{"Kotlin": 1440403, "Starlark": 163473, "Java": 10061, "AIDL": 5852, "Python": 4367, "Dockerfile": 2035, "Shell": 1301}
/* * Copyright 2022 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 com.google.android.libraries.pcc.chronicle.api.remote import android.os.Bundle import android.os.Parcel import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.android.libraries.pcc.chronicle.api.remote.testutil.Person import com.google.android.libraries.pcc.chronicle.api.storage.EntityMetadata import com.google.common.truth.Truth.assertThat import com.google.protobuf.Empty import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class RemoteRequestTest { @Test fun writeToParcel_createFromParcel_roundtrip() { val metadata = RemoteRequestMetadata.newBuilder() .setStore( StoreRequest.newBuilder() .setDataTypeName("Person") .setCreate(Empty.getDefaultInstance()) ) .setUsageType("Testing Usage") .build() val entities = listOf( RemoteEntity.fromProto( metadata = EntityMetadata.getDefaultInstance(), message = Person.newBuilder().setName("Larry").setAge(35).build() ), RemoteEntity.fromProto( metadata = EntityMetadata.getDefaultInstance(), message = Person.newBuilder().setName("Sergey").setAge(38).build() ), ) val extras = Bundle() .apply { putString("MyString", "MyStringValue") } val request = RemoteRequest(metadata, entities, extras) val parcel = Parcel.obtain() val output = try { request.writeToParcel(parcel, 0) parcel.setDataPosition(0) RemoteRequest.CREATOR.createFromParcel(parcel).also { it.extras.keySet() } } finally { parcel.recycle() } assertThat(output.metadata).isEqualTo(request.metadata) assertThat(output.entities).hasSize(request.entities.size) assertThat(output.extras.getString("MyString")) .isEqualTo(request.extras.getString("MyString")) } }
0
Kotlin
7
29
5bd69054d06ea31fb01a1feaa0f52b32bee94dfe
2,475
private-compute-libraries
Apache License 2.0
app/src/main/java/com/vivek/eton/feature_note/domain/use_case/GetNotes.kt
V9vek
450,054,297
false
{"Kotlin": 49875}
package com.vivek.eton.feature_note.domain.use_case import com.vivek.eton.feature_note.domain.model.Note import com.vivek.eton.feature_note.domain.repository.NoteRepository import com.vivek.eton.feature_note.domain.util.NoteOrder import com.vivek.eton.feature_note.domain.util.OrderType.Ascending import com.vivek.eton.feature_note.domain.util.OrderType.Descending import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map class GetNotes( private val repository: NoteRepository ) { operator fun invoke( noteOrder: NoteOrder = NoteOrder.Date(orderType = Descending) ): Flow<List<Note>> { return repository.getNotes().map { notes -> when (noteOrder.orderType) { is Ascending -> { when (noteOrder) { is NoteOrder.Title -> notes.sortedBy { it.title.lowercase() } is NoteOrder.Date -> notes.sortedBy { it.timestamp } is NoteOrder.Color -> notes.sortedBy { it.color } } } is Descending -> { when (noteOrder) { is NoteOrder.Title -> notes.sortedByDescending { it.title.lowercase() } is NoteOrder.Date -> notes.sortedByDescending { it.timestamp } is NoteOrder.Color -> notes.sortedByDescending { it.color } } } } } } }
0
Kotlin
0
3
3f598e2e4c74bf77e303afaf423cd93e1414dfc8
1,502
Eton
Apache License 2.0
subprojects/gradle/tech-budget/src/main/kotlin/com/avito/android/tech_budget/internal/module_dependencies/ModuleDependenciesConfigurator.kt
avito-tech
230,265,582
false
null
package com.avito.android.tech_budget.internal.module_dependencies import com.avito.android.tech_budget.TechBudgetExtension import com.avito.android.tech_budget.internal.TechBudgetConfigurator import com.avito.android.tech_budget.internal.owners.requireCodeOwnershipExtension import com.avito.kotlin.dsl.isRoot import org.gradle.api.Project import org.gradle.kotlin.dsl.getByType import org.gradle.kotlin.dsl.register internal class ModuleDependenciesConfigurator : TechBudgetConfigurator { override fun configure(project: Project) { if (!project.isRoot()) return project.tasks.register<UploadModuleDependenciesTask>(UploadModuleDependenciesTask.NAME) { val techBudgetExtension = project.extensions.getByType<TechBudgetExtension>() this.ownerSerializer.set(project.requireCodeOwnershipExtension().ownerSerializersProvider) this.dumpInfoConfiguration.set(techBudgetExtension.dumpInfo) } } }
8
null
49
412
244c6a588abe14367f927746a8e4832abbc067fa
963
avito-android
MIT License
subprojects/gradle/tech-budget/src/main/kotlin/com/avito/android/tech_budget/internal/module_dependencies/ModuleDependenciesConfigurator.kt
avito-tech
230,265,582
false
null
package com.avito.android.tech_budget.internal.module_dependencies import com.avito.android.tech_budget.TechBudgetExtension import com.avito.android.tech_budget.internal.TechBudgetConfigurator import com.avito.android.tech_budget.internal.owners.requireCodeOwnershipExtension import com.avito.kotlin.dsl.isRoot import org.gradle.api.Project import org.gradle.kotlin.dsl.getByType import org.gradle.kotlin.dsl.register internal class ModuleDependenciesConfigurator : TechBudgetConfigurator { override fun configure(project: Project) { if (!project.isRoot()) return project.tasks.register<UploadModuleDependenciesTask>(UploadModuleDependenciesTask.NAME) { val techBudgetExtension = project.extensions.getByType<TechBudgetExtension>() this.ownerSerializer.set(project.requireCodeOwnershipExtension().ownerSerializersProvider) this.dumpInfoConfiguration.set(techBudgetExtension.dumpInfo) } } }
8
null
49
412
244c6a588abe14367f927746a8e4832abbc067fa
963
avito-android
MIT License
core/database/src/main/java/com/ahmetocak/database/db/UserDatabase.kt
AhmetOcak
793,949,918
false
{"Kotlin": 406065}
package com.ahmetocak.database.db import androidx.room.Database import androidx.room.RoomDatabase import com.ahmetocak.database.dao.ChatGroupDao import com.ahmetocak.database.dao.MessageDao import com.ahmetocak.database.dao.RemoteKeyDao import com.ahmetocak.database.dao.UserDao import com.ahmetocak.database.entity.ChatGroupEntity import com.ahmetocak.database.entity.ChatGroupParticipantsEntity import com.ahmetocak.database.entity.MessageEntity import com.ahmetocak.database.entity.RemoteKeyEntity import com.ahmetocak.database.entity.UserEntity @Database( entities = [ UserEntity::class, ChatGroupEntity::class, ChatGroupParticipantsEntity::class, MessageEntity::class, RemoteKeyEntity::class ], version = 1 ) abstract class UserDatabase : RoomDatabase() { abstract fun userDao(): UserDao abstract fun chatGroupDao(): ChatGroupDao abstract fun messageDao(): MessageDao abstract fun remoteKeyDao(): RemoteKeyDao }
0
Kotlin
0
0
61d1fad8809e1420fd767c33806f994443062b6b
987
ChatApp
MIT License
ground/src/test/java/com/google/android/ground/ui/MarkerIconFactoryTest.kt
google
127,777,820
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.google.android.ground.ui import android.content.Context import android.graphics.Bitmap import android.graphics.Color import androidx.appcompat.content.res.AppCompatResources import androidx.core.content.res.ResourcesCompat import com.google.android.ground.BaseHiltTest import com.google.android.ground.Config import com.google.android.ground.R import com.google.common.truth.Truth.assertThat import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.testing.HiltAndroidTest import javax.inject.Inject import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @HiltAndroidTest @RunWith(RobolectricTestRunner::class) class MarkerIconFactoryTest : BaseHiltTest() { @Inject @ApplicationContext lateinit var context: Context @Inject lateinit var markerIconFactory: MarkerIconFactory private var markerUnscaledWidth = 0 private var markerUnscaledHeight = 0 @Before override fun setUp() { super.setUp() val outline = AppCompatResources.getDrawable(context, R.drawable.ic_marker_outline) markerUnscaledWidth = outline!!.intrinsicWidth markerUnscaledHeight = outline.intrinsicHeight } @Test fun markerBitmap_zoomedOut_scaleIsSetCorrectly() { val bitmap = markerIconFactory.getMarkerBitmap(Color.BLUE, Config.ZOOM_LEVEL_THRESHOLD - 0.1f) val scale = ResourcesCompat.getFloat(context.resources, R.dimen.marker_bitmap_default_scale) verifyBitmapScale(bitmap, scale) } @Test fun markerBitmap_zoomedIn_scaleIsSetCorrectly() { val bitmap = markerIconFactory.getMarkerBitmap(Color.BLUE, Config.ZOOM_LEVEL_THRESHOLD) val scale = ResourcesCompat.getFloat(context.resources, R.dimen.marker_bitmap_zoomed_scale) verifyBitmapScale(bitmap, scale) } @Test fun markerBitmap_zoomedOut_isSelected_scaleIsSetCorrectly() { val bitmap = markerIconFactory.getMarkerBitmap(Color.BLUE, Config.ZOOM_LEVEL_THRESHOLD - 0.1f, true) val scale = ResourcesCompat.getFloat(context.resources, R.dimen.marker_bitmap_default_scale) + 1 verifyBitmapScale(bitmap, scale) } @Test fun markerBitmap_zoomedIn_isSelected_scaleIsSetCorrectly() { val bitmap = markerIconFactory.getMarkerBitmap(Color.BLUE, Config.ZOOM_LEVEL_THRESHOLD, true) val scale = ResourcesCompat.getFloat(context.resources, R.dimen.marker_bitmap_zoomed_scale) + 1 verifyBitmapScale(bitmap, scale) } private fun verifyBitmapScale(bitmap: Bitmap, scale: Float) { val expectedWidth = (markerUnscaledWidth * scale).toInt() val expectedHeight = (markerUnscaledHeight * scale).toInt() assertThat(bitmap.width).isEqualTo(expectedWidth) assertThat(bitmap.height).isEqualTo(expectedHeight) } }
184
null
118
214
5699f58f4a906f031d97e4603f80ae2177bd6b35
3,345
ground-android
Apache License 2.0
enode/src/main/java/org/enodeframework/common/io/Task.kt
anruence
165,245,292
false
null
package org.enodeframework.common.io import org.enodeframework.common.exception.EnodeInterruptException import java.util.concurrent.CompletableFuture import java.util.concurrent.CountDownLatch /** * @author <EMAIL> */ object Task { @JvmField var completedTask: CompletableFuture<Boolean> = CompletableFuture.completedFuture(true) @JvmStatic fun await(latch: CountDownLatch) { try { latch.await() } catch (e: InterruptedException) { throw EnodeInterruptException(e) } } @JvmStatic fun <T> await(future: CompletableFuture<T>): T { return future.join() } @JvmStatic fun sleep(sleepMilliseconds: Long) { try { Thread.sleep(sleepMilliseconds) } catch (e: InterruptedException) { throw EnodeInterruptException(e) } } }
1
null
55
205
22c81b98b36a6a221d026272594eaf7817145e0f
867
enode
MIT License
src/me/anno/tsunamis/draw/Drawing.kt
AntonioNoack
438,142,549
false
{"Kotlin": 254088}
package me.anno.tsunamis.draw import me.anno.gpu.GFX import me.anno.gpu.framebuffer.Framebuffer import me.anno.gpu.shader.ComputeShader import me.anno.gpu.shader.ComputeTextureMode import me.anno.gpu.texture.Texture2D import me.anno.input.Input import me.anno.tsunamis.FluidSim import me.anno.tsunamis.engine.CPUEngine import me.anno.tsunamis.engine.TsunamiEngine.Companion.getMaxValue import me.anno.tsunamis.engine.gpu.Compute16Engine import me.anno.tsunamis.engine.gpu.GPUEngine import me.anno.utils.LOGGER import me.anno.utils.hpc.HeavyProcessing import org.joml.Vector3f import org.lwjgl.opengl.GL30C.* import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.math.sqrt object Drawing { val rgbaShaders = DrawShaders(comp16engine = false, halfPrecisionBath = false) private val r16b16 = DrawShaders(comp16engine = true, halfPrecisionBath = true) private val r16b32 = DrawShaders(comp16engine = true, halfPrecisionBath = false) fun drawLineSegment( cmp: Vector3f, lmp: Vector3f, sim: FluidSim ) { // convert global hit coordinates into local space // convert brush size into local coordinates // compute the area of effect val brushSize = sim.brushSize / sim.cellSizeMeters val vx = cmp.x val vy = cmp.y val wx = lmp.x val wy = lmp.y val dwx1 = wx - vx val dwy1 = wy - vy val lineLengthSquared = dwx1 * dwx1 + dwy1 * dwy1 val sqrt = sqrt(lineLengthSquared) // only extend brush area 90ยฐ rotated to its movement direction val deltaX = abs(+dwy1 * brushSize / sqrt) val deltaY = abs(-dwx1 * brushSize / sqrt) val cellMinX = max((min(vx, wx) - deltaX).toInt(), 0) val cellMaxX = min((max(vx, wx) + deltaX).toInt() + 1, sim.width) val cellMinY = max((min(vy, wy) - deltaY).toInt(), 0) val cellMaxY = min((max(vy, wy) + deltaY).toInt() + 1, sim.height) // apply brush with circular falloff val invBrushSize = 1f / brushSize val dwx2 = dwx1 / lineLengthSquared val dwy2 = dwy1 / lineLengthSquared // compute brush strength val brushStrength = (if (Input.isShiftDown) -1f else +1f) * sim.brushStrength * sqrt(lineLengthSquared) when (val engine = sim.engine) { is GPUEngine<*> -> { // this casting is currently correct, but may become incorrect with more engines val src = engine.src as? Texture2D ?: (engine.src as Framebuffer).getTexture0() as Texture2D val tmp = engine.tmp as? Texture2D ?: (engine.tmp as Framebuffer).getTexture0() as Texture2D drawLineSegment( src, tmp, null, 0, rgbaShaders, GL_RGBA32F, cellMinX, cellMaxX, cellMinY, cellMaxY, brushStrength, invBrushSize, dwx1, dwy1, dwx2, dwy2, vx, vy ) } is Compute16Engine -> { drawLineSegment( engine.surface0, engine.surface1, engine.bathymetryTex, if (engine.bathymetryFp16) GL_R16F else GL_R32F, if (engine.bathymetryFp16) r16b16 else r16b32, GL_R16F, cellMinX, cellMaxX, cellMinY, cellMaxY, brushStrength, invBrushSize, dwx1, dwy1, dwx2, dwy2, vx, vy ) engine.invalidate() } is CPUEngine -> { val minPerThread = 4000 / (cellMaxX - cellMinX) HeavyProcessing.processBalanced(cellMinY, cellMaxY, minPerThread) { y0, y1 -> // shorten line by 1px, so we don't draw that pixel twice? // todo or draw using a spline instead? val fluidHeight = engine.fluidHeight for (yi in y0 until y1) { var index = sim.getIndex(cellMinX, yi) for (xi in cellMinX until cellMaxX) { val px = xi.toFloat() val py = yi.toFloat() // minimum distance between line segment vw and point p, reformed a lot // from https://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment var dpx = px - vx var dpy = py - vy // "percentage" from cmp to lmp // val t = clamp(dpx * dwx + dpy * dwy, 0f, lineLengthSquared) * lineLengthSqInv val t = dpx * dwx2 + dpy * dwy2 if (t in 0f..1f) {// on the left/right of the line segment // if we wouldn't have this if(), we'd draw caps at the end of the segment dpx -= t * dwx1 dpy -= t * dwy1 val d2 = (dpx * dpx + dpy * dpy) val strength = brushStrength * getNormalizedBrushShape(d2 * invBrushSize) fluidHeight[index] += strength * (dpy * dwx2 - dpx * dwy2) } index++ } } } // if paused & maxVisualizedValue == 0f, then update min/max if (sim.isPaused && sim.maxVisualizedValue == 0f) { sim.maxSurfaceHeight = getMaxValue(sim.width, sim.height, sim.coarsening, engine.fluidHeight, engine.bathymetry) } } null -> {} else -> LOGGER.warn("Drawing not supported on ${engine.javaClass.simpleName}") } // something has changed, to update the mesh sim.invalidateFluid() } private fun slerp(x: Float): Float { return x * x * (3f - 2f * x) } private fun getNormalizedBrushShape(d2: Float): Float { return if (d2 < 1f) slerp(1f - d2) else 0f } fun drawLineSegment( src: Texture2D, tmp: Texture2D, bath: Texture2D?, bathFormat: Int, shaders: DrawShaders, format: Int, cellMinX: Int, cellMaxX: Int, cellMinY: Int, cellMaxY: Int, brushStrength: Float, invBrushSize: Float, dwx1: Float, dwy1: Float, dwx2: Float, dwy2: Float, vx: Float, vy: Float ) { var shader = shaders.drawShader val width = cellMaxX - cellMinX val height = cellMaxY - cellMinY GFX.check() shader.use() GFX.check() shader.v2i("inSize", width, height) shader.v2i("offset", cellMinX, cellMinY) shader.v2f("v", vx, vy) shader.v2f("brush", brushStrength, invBrushSize) shader.v4f("dw", dwx1, dwy1, dwx2, dwy2) GFX.check() ComputeShader.bindTexture(0, src, ComputeTextureMode.READ, format) ComputeShader.bindTexture(1, tmp, ComputeTextureMode.WRITE, format) if (bath != null) { ComputeShader.bindTexture(2, bath, ComputeTextureMode.WRITE, bathFormat) } GFX.check() shader.runBySize(width, height) GFX.check() shader = shaders.copyShader shader.use() shader.v2i("inSize", width, height) shader.v2i("offset", cellMinX, cellMinY) GFX.check() ComputeShader.bindTexture(0, tmp, ComputeTextureMode.READ, format) ComputeShader.bindTexture(1, src, ComputeTextureMode.WRITE, format) GFX.check() shader.runBySize(width, height) GFX.check() } }
0
Kotlin
0
1
acac2c3c23136e59b43f4e2c6114c6e7743686eb
7,908
RemsTsunamis
Apache License 2.0
lib/src/main/java/com/kotlin/inaction/chapter_8/8_1_5_1_ReturningFuntionsFromFunctions.kt
jhwsx
167,022,805
false
null
package com.kotlin.inaction.chapter_8 /** * * @author wzc * @date 2019/6/2 */ enum class Delivery { STANDARD, EXPEDITED } class Order(val itemCount: Int) // ่ฟ™ๆ˜ฏๅฃฐๆ˜Žไธ€ไธช่ฟ”ๅ›žๅ‡ฝๆ•ฐ็ฑปๅž‹็š„ๅ‡ฝๆ•ฐ๏ผŒ่ฟ”ๅ›ž็š„ๆ˜ฏ่ฎก็ฎ—่ฟ่พ“่ดน็”จ็š„ๆ–นๅผใ€‚ fun getShippingCostCalculator(delivery: Delivery): (Order) -> Double { if (delivery == Delivery.EXPEDITED) { return { order -> 6 + 2.1 * order.itemCount } } return { order -> 1.2 * order.itemCount } // ่ฟ”ๅ›žไธ€ไธช lambda } fun main(args: Array<String>) { val calculator = getShippingCostCalculator(Delivery.EXPEDITED) println("EXPEDITED Shipping costs ${calculator(Order(3))}") val calculator1 = getShippingCostCalculator(Delivery.STANDARD) println("STANDARD Shipping costs ${calculator1(Order(3))}") }
1
Kotlin
1
1
5d8c5f88e35edf2e4693becd47a31fb127afe618
727
KotlinInAction
MIT License
test_runner/src/main/kotlin/ftl/cli/firebase/test/ios/IosRunCommand.kt
hiyangyue
267,499,333
false
{"Git Config": 1, "Markdown": 14, "Text": 5, "Ignore List": 11, "YAML": 29, "Gradle Kotlin DSL": 4, "Shell": 11, "Java Properties": 2, "Batchfile": 2, "INI": 1, "Kotlin": 211, "JSON": 11, "XML": 21, "HTML": 2, "Maven POM": 1, "Java": 70, "Gradle": 3, "Proguard": 1, "Go": 1, "Go Module": 1, "JSON with Comments": 1, "JavaScript": 2, "SVG": 1, "TSX": 4, "CSS": 2}
package ftl.cli.firebase.test.ios import ftl.args.IosArgs import ftl.cli.firebase.test.CommonRunCommand import ftl.config.Device import ftl.config.FtlConstants import ftl.config.FtlConstants.defaultIosModel import ftl.config.FtlConstants.defaultIosVersion import ftl.mock.MockServer import ftl.run.common.prettyPrint import ftl.run.newTestRun import kotlinx.coroutines.runBlocking import picocli.CommandLine.Command import picocli.CommandLine.Option import java.nio.file.Files import java.nio.file.Paths @Command( name = "run", sortOptions = false, headerHeading = "", synopsisHeading = "%n", descriptionHeading = "%n@|bold,underline Description:|@%n%n", parameterListHeading = "%n@|bold,underline Parameters:|@%n", optionListHeading = "%n@|bold,underline Options:|@%n", header = ["Run tests on Firebase Test Lab"], description = ["""Uploads the app and tests to GCS. Runs the XCTests and XCUITests. Configuration is read from flank.yml """], usageHelpAutoWidth = true ) class IosRunCommand : CommonRunCommand(), Runnable { override fun run() { if (dryRun) { MockServer.start() } val config = IosArgs.load(Paths.get(configPath), cli = this) if (dumpShards) { val testShardChunksJson: String = prettyPrint.toJson(config.testShardChunks) Files.write(Paths.get(shardFile), testShardChunksJson.toByteArray()) println("Saved shards to $shardFile") } else { runBlocking { newTestRun(config) } } } companion object { private const val shardFile = "ios_shards.json" } // Flank debug @Option(names = ["--dump-shards"], description = ["Dumps the shards to $shardFile for debugging"]) var dumpShards: Boolean = false // Flank specific @Option( names = ["-c", "--config"], description = ["YAML config file path"] ) var configPath: String = FtlConstants.defaultIosConfig // IosGcloudYml.kt @Option( names = ["--test"], description = ["The path to the test package (a zip file containing the iOS app " + "and XCTest files). The given path may be in the local filesystem or in Google Cloud Storage using a URL " + "beginning with gs://. Note: any .xctestrun file in this zip file will be ignored if --xctestrun-file " + "is specified."] ) var test: String? = null @Option( names = ["--xctestrun-file"], description = ["The path to an .xctestrun file that will override any " + ".xctestrun file contained in the --test package. Because the .xctestrun file contains environment variables " + "along with test methods to run and/or ignore, this can be useful for customizing or sharding test suites. The " + "given path may be in the local filesystem or in Google Cloud Storage using a URL beginning with gs://."] ) var xctestrunFile: String? = null @Option( names = ["--xcode-version"], description = ["The version of Xcode that should be used to run an XCTest. " + "Defaults to the latest Xcode version supported in Firebase Test Lab. This Xcode version must be supported by " + "all iOS versions selected in the test matrix."] ) var xcodeVersion: String? = null @Option( names = ["--device"], split = ",", description = ["A list of DIMENSION=VALUE pairs which specify a target " + "device to test against. This flag may be repeated to specify multiple devices. The four device dimensions are: " + "model, version, locale, and orientation. If any dimensions are omitted, they will use a default value. Omitting " + "all of the preceding dimension-related flags will run tests against a single device using defaults for all four " + "device dimensions."] ) fun deviceMap(map: Map<String, String>?) { if (map.isNullOrEmpty()) return val androidDevice = Device( model = map.getOrDefault("model", defaultIosModel), version = map.getOrDefault("version", defaultIosVersion), locale = map.getOrDefault("locale", FtlConstants.defaultLocale), orientation = map.getOrDefault("orientation", FtlConstants.defaultOrientation) ) if (device == null) device = mutableListOf() device?.add(androidDevice) } var device: MutableList<Device>? = null // IosFlankYml.kt @Option( names = ["--test-targets"], split = ",", description = ["A list of one or more test method " + "names to run (default: run all test targets)."] ) var testTargets: List<String>? = null }
1
null
1
1
b9596bc83027a5bc94bb5d1dca9a8adb81dcea5a
4,856
flank
Apache License 2.0
libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/model/KotlinModel.kt
chirino
3,596,099
false
null
package org.jetbrains.kotlin.doc.model import java.io.File import java.util.* import org.jetbrains.jet.internal.com.intellij.openapi.vfs.local.CoreLocalVirtualFile import org.jetbrains.jet.internal.com.intellij.psi.PsiDirectory import org.jetbrains.jet.internal.com.intellij.psi.PsiElement import org.jetbrains.jet.internal.com.intellij.psi.PsiFile import org.jetbrains.jet.internal.com.intellij.psi.PsiFileSystemItem import org.jetbrains.jet.lang.descriptors.CallableDescriptor import org.jetbrains.jet.lang.descriptors.ClassDescriptor import org.jetbrains.jet.lang.descriptors.ClassKind import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor import org.jetbrains.jet.lang.descriptors.ModuleDescriptor import org.jetbrains.jet.lang.descriptors.NamespaceDescriptor import org.jetbrains.jet.lang.descriptors.PropertyDescriptor import org.jetbrains.jet.lang.descriptors.TypeParameterDescriptor import org.jetbrains.jet.lang.descriptors.ValueParameterDescriptor import org.jetbrains.jet.lang.descriptors.Visibilities import org.jetbrains.jet.lang.diagnostics.DiagnosticUtils import org.jetbrains.jet.lang.diagnostics.DiagnosticUtils.LineAndColumn import org.jetbrains.jet.lang.psi.JetFile import org.jetbrains.jet.lang.resolve.BindingContext import org.jetbrains.jet.lang.resolve.BindingContextUtils import org.jetbrains.jet.lang.resolve.scopes.JetScope import org.jetbrains.jet.lang.resolve.scopes.receivers.ExtensionReceiver import org.jetbrains.jet.lang.types.JetType import org.jetbrains.jet.lexer.JetTokens import org.jetbrains.kotlin.doc.* import org.jetbrains.kotlin.doc.highlighter.SyntaxHighligher import org.jetbrains.kotlin.doc.templates.KDocTemplate import org.pegdown.Extensions import org.pegdown.LinkRenderer import org.pegdown.LinkRenderer.Rendering import org.pegdown.PegDownProcessor import org.pegdown.ast.AutoLinkNode import org.pegdown.ast.ExpLinkNode import org.pegdown.ast.RefLinkNode import org.pegdown.ast.WikiLinkNode /** * Returns the collection of functions with duplicate function names filtered out * so only the first one is included */ fun filterDuplicateNames(functions: Collection<KFunction>): Collection<KFunction> { var lastName = "" return functions.filter{ val name = it.name val answer = name != lastName lastName = name answer } } fun containerName(descriptor: DeclarationDescriptor): String = qualifiedName(descriptor.getContainingDeclaration()) fun qualifiedName(descriptor: DeclarationDescriptor?): String { if (descriptor == null || descriptor is ModuleDescriptor) { return "" } else { val parent = containerName(descriptor) var name = descriptor.getName()?.getName() ?: "" if (name.startsWith("<")) { name = "" } val answer = if (parent.length() > 0) parent + "." + name else name return if (answer.startsWith(".")) answer.substring(1) else answer } } fun warning(message: String) { println("Warning: $message") } fun info(message: String) { // println("info: $message") } // TODO for some reason the SortedMap causes kotlin to freak out a little :) fun inheritedExtensionFunctions(functions: Collection<KFunction>): Map<KClass, SortedSet<KFunction>> { //fun inheritedExtensionFunctions(functions: Collection<KFunction>): SortedMap<KClass, SortedSet<KFunction>> { val map = extensionFunctions(functions) // for each class, lets walk its base classes and add any other extension functions from base classes val answer = TreeMap<KClass, SortedSet<KFunction>>() for (c in map.keySet()) { val allFunctions = map.get(c).orEmpty().toSortedSet() answer.put(c, allFunctions) val des = c.descendants() for (b in des) { val list = map.get(b) if (list != null) { if (allFunctions != null) { for (f in list) { if (f != null) { // add the methods from the base class if we don't have a matching method if (!allFunctions.any{ it.name == f.name && it.parameterTypeText == f.parameterTypeText}) { allFunctions.add(f) } } } } } } } return answer } // TODO for some reason the SortedMap causes kotlin to freak out a little :) fun inheritedExtensionProperties(properties: Collection<KProperty>): Map<KClass, SortedSet<KProperty>> { val map = extensionProperties(properties) // for each class, lets walk its base classes and add any other extension properties from base classes val answer = TreeMap<KClass, SortedSet<KProperty>>() for (c in map.keySet()) { val allProperties = map.get(c).orEmpty().toSortedSet() answer.put(c, allProperties) val des = c.descendants() for (b in des) { val list = map.get(b) if (list != null) { if (allProperties != null) { for (f in list) { if (f != null) { // add the proeprties from the base class if we don't have a matching method if (!allProperties.any{ it.name == f.name}) { allProperties.add(f) } } } } } } } return answer } // TODO for some reason the SortedMap causes kotlin to freak out a little :) fun extensionFunctions(functions: Collection<KFunction>): Map<KClass, List<KFunction>> { val map = TreeMap<KClass, List<KFunction>>() functions.filter{ it.extensionClass != null }.groupByTo(map){ it.extensionClass.sure() } return map } // TODO for some reason the SortedMap causes kotlin to freak out a little :) fun extensionProperties(properties: Collection<KProperty>): Map<KClass, List<KProperty>> { val map = TreeMap<KClass, List<KProperty>>() properties.filter{ it.extensionClass != null }.groupByTo(map){ it.extensionClass.sure() } return map } abstract class KClassOrPackage(model: KModel, declarationDescriptor: DeclarationDescriptor): KAnnotated(model, declarationDescriptor) { public open val functions: SortedSet<KFunction> = TreeSet<KFunction>() public open val properties: SortedSet<KProperty> = TreeSet<KProperty>() fun findProperty(name: String): KProperty? { // TODO we should use a Map<String>? return properties.find{ it.name == name } } fun findFunction(expression: String): KFunction? { val idx = expression.indexOf('(') val name = if (idx > 0) expression.substring(0, idx) else expression val postfix = if (idx > 0) expression.substring(idx).trimTrailing("()") else "" return functions.find{ it.name == name && it.parameterTypeText == postfix } } } // htmlPath does not include "html-src" prefix class SourceInfo(val psi: JetFile, val relativePath: String, val htmlPath: String) class KModel(val context: BindingContext, val config: KDocConfig, val sourceDirs: List<File>, val sources: List<JetFile>) { // TODO generates java.lang.NoSuchMethodError: kotlin.util.namespace.hashMap(Ljet/TypeInfo;Ljet/TypeInfo;)Ljava/util/HashMap; //val packages = sortedMap<String,KPackage>() public val packageMap: SortedMap<String, KPackage> = TreeMap<String, KPackage>() public val allPackages: Collection<KPackage> get() = packageMap.values().sure() /** Returns the local packages */ public val packages: Collection<KPackage> get() = allPackages.filter{ it.local && config.includePackage(it) } public val classes: Collection<KClass> get() = packages.flatMap{ it.classes } public var markdownProcessor: PegDownProcessor = PegDownProcessor(Extensions.ALL) public var highlighter: SyntaxHighligher = SyntaxHighligher() public val title: String get() = config.title public val version: String get() = config.version private var _projectRootDir: String? = null /** * File names we look for in a package directory for the overall description of a package for KDoc */ val packageDescriptionFiles = arrayList("readme.md", "ReadMe.md, readme.html, ReadMe.html") private val readMeDirsScanned = HashSet<String>() val sourcesInfo: List<SourceInfo> ;{ val normalizedSourceDirs: List<String> = sourceDirs.map { file -> file.getCanonicalPath()!! } fun relativePath(psiFile: PsiFile): String { val file = File((psiFile.getVirtualFile() as CoreLocalVirtualFile).getPath()).getCanonicalFile()!! val filePath = file.getPath()!! for (sourceDirPath in normalizedSourceDirs) { if (filePath.startsWith(sourceDirPath) && filePath.length() > sourceDirPath.length()) { return filePath.substring(sourceDirPath.length + 1) } } throw Exception("$file is not a child of any source roots $normalizedSourceDirs") } sourcesInfo = sources.map { source -> val relativePath = relativePath(source) val htmlPath = relativePath.replaceFirst("\\.kt$", "") + ".html" SourceInfo(source, relativePath, htmlPath) } } private val sourceInfoByFile = sourcesInfo.toHashMapMappingToKey<JetFile, SourceInfo> { sourceInfo -> sourceInfo.psi } fun sourceInfoByFile(file: JetFile) = sourceInfoByFile.get(file)!! ;{ /** Loads the model from the given set of source files */ val allNamespaces = HashSet<NamespaceDescriptor>() for (source in sources) { // We retrieve a descriptor by a PSI element from the context val namespaceDescriptor = BindingContextUtils.namespaceDescriptor(context, source) if (namespaceDescriptor != null) { allNamespaces.add(namespaceDescriptor); } else { warning("No NamespaceDescriptor for source $source") } } val allClasses = HashSet<KClass>() for (namespace in allNamespaces) { getPackage(namespace) for (descriptor in namespace.getMemberScope().getAllDescriptors()) { if (descriptor is ClassDescriptor) { val klass = getClass(descriptor) if (klass != null) { allClasses.add(klass) } } else if (descriptor is NamespaceDescriptor) { getPackage(descriptor) } } } } /** * Returns the root project directory for calculating relative source links */ fun projectRootDir(): String { if (_projectRootDir == null) { val rootDir = config.projectRootDir _projectRootDir = if (rootDir == null) { warning("KDocConfig does not have a projectRootDir defined so we cannot generate relative source Hrefs") "" } else { File(rootDir).getCanonicalPath() ?: "" } } return _projectRootDir ?: "" } /* Returns the package for the given name or null if it does not exist */ fun getPackage(name: String): KPackage? = packageMap.get(name) /** Returns the package for the given descriptor, creating one if its not available */ fun getPackage(descriptor: NamespaceDescriptor): KPackage { val name = qualifiedName(descriptor) var created = false val pkg = packageMap.getOrPut(name) { created = true KPackage(this, descriptor, name) } if (created) { configureComments(pkg, descriptor) val scope = descriptor.getMemberScope() addFunctions(pkg, scope) pkg.local = isLocal(descriptor) pkg.useExternalLink = pkg.model.config.resolveLink(pkg.name, false).notEmpty() if (pkg.wikiDescription.isEmpty()) { // lets try find a custom doc var file = config.packageDescriptionFiles[name] loadWikiDescription(pkg, file) } } return pkg; } protected fun loadWikiDescription(pkg: KPackage, file: String?): Unit { if (file != null) { try { pkg.wikiDescription = File(file).readText() } catch (e: Throwable) { warning("Failed to load package ${pkg.name} documentation file $file. Reason $e") } } } /** * If a package has no detailed description lets try load it from the descriptors * source directory if we've not checked that directory before */ fun tryLoadReadMe(pkg: KPackage, descriptor: DeclarationDescriptor): Unit { if (pkg.wikiDescription.isEmpty()) { // lets try find the package.html or package.md file val srcPath = pkg.model.filePath(descriptor) if (srcPath != null) { val srcFile = File(srcPath) val dir = if (srcFile.isDirectory()) srcFile else srcFile.getParentFile() if (dir != null && readMeDirsScanned.add(dir.getPath()!!)) { val f = packageDescriptionFiles.map{ File(dir, it) }.find{ it.exists() } if (f != null) { val file = f.getCanonicalPath() loadWikiDescription(pkg, file) } else { info("package ${pkg.name} has no ReadMe.(html|md) in $dir") } } } } } fun wikiConvert(text: String, linkRenderer: LinkRenderer, fileName: String?): String { return markdownProcessor.markdownToHtml(text, linkRenderer).sure() } fun sourceLinkFor(filePath: String, sourceLine: Int, lineLinkText: String = "#L"): String? { val root = config.sourceRootHref if (root != null) { // lets remove the root project directory val rootDir = projectRootDir() val canonicalFile = File(filePath).getCanonicalPath() ?: "" //println("=========== root dir for filePath: $canonicalFile is $rootDir") val relativeFile = if (canonicalFile.startsWith(rootDir)) canonicalFile.substring(rootDir.length()) else canonicalFile val cleanRoot = root.trimTrailing("/") val cleanPath = relativeFile.trimLeading("/") return "$cleanRoot/$cleanPath$lineLinkText$sourceLine" } return null } protected fun isLocal(descriptor: DeclarationDescriptor): Boolean { return if (descriptor is ModuleDescriptor) { true } else { val parent = descriptor.getContainingDeclaration() if (parent != null) { isLocal(parent) } else { false } } } fun addFunctions(owner: KClassOrPackage, scope: JetScope): Unit { try { val descriptors = scope.getAllDescriptors() for (descriptor in descriptors) { if (descriptor is PropertyDescriptor) { val name = descriptor.getName().getName() val returnType = getType(descriptor.getReturnType()) if (returnType != null) { val receiver = descriptor.getReceiverParameter() val extensionClass = if (receiver is ExtensionReceiver) { getType(receiver.getType()) } else null val property = KProperty(owner, descriptor, name, returnType, extensionClass?.klass) owner.properties.add(property) } } else if (descriptor is CallableDescriptor) { val function = createFunction(owner, descriptor) if (function != null) { owner.functions.add(function) } } } } catch (e: Throwable) { warning("Caught exception finding function declarations on $owner $e") e.printStackTrace() } } protected fun createFunction(owner: KClassOrPackage, descriptor: CallableDescriptor): KFunction? { val returnType = getType(descriptor.getReturnType()) if (returnType != null) { val name = descriptor.getName().getName() val parameters = ArrayList<KParameter>() val params = descriptor.getValueParameters() for (param in params) { if (param != null) { val p = createParameter(param) if (p != null) { parameters.add(p) } } } val function = KFunction(descriptor, owner, name, returnType, parameters) addTypeParameters(function.typeParameters, descriptor.getTypeParameters()) configureComments(function, descriptor) val receiver = descriptor.getReceiverParameter() if (receiver is ExtensionReceiver) { val receiverType = getType(receiver.getType()) function.receiverType = receiverType function.extensionClass = receiverType?.klass } return function } return null } fun addTypeParameters(answer: MutableList<KTypeParameter>, descriptors: List<TypeParameterDescriptor?>): Unit { for (typeParam in descriptors) { if (typeParam != null) { val p = createTypeParameter(typeParam) if (p != null){ answer.add(p) } } } } protected fun createTypeParameter(descriptor: TypeParameterDescriptor): KTypeParameter? { val name = descriptor.getName().getName() val answer = KTypeParameter(name, descriptor, this) configureComments(answer, descriptor) return answer } protected fun createParameter(descriptor: ValueParameterDescriptor): KParameter? { val returnType = getType(descriptor.getReturnType()) if (returnType != null) { val name = descriptor.getName().getName() val answer = KParameter(descriptor, name, returnType) configureComments(answer, descriptor) return answer } return null } fun locationFor(descriptor: DeclarationDescriptor): LineAndColumn? { val psiElement = getPsiElement(descriptor) if (psiElement != null) { val document = psiElement.getContainingFile()?.getViewProvider()?.getDocument() if (document != null) { val offset = psiElement.getTextOffset() return DiagnosticUtils.offsetToLineAndColumn(document, offset) } } return null } fun fileFor(descriptor: DeclarationDescriptor): String? { val psiElement = getPsiElement(descriptor) return psiElement?.getContainingFile()?.getName() } fun filePath(descriptor: DeclarationDescriptor): String? { val psiElement = getPsiElement(descriptor) val file = psiElement?.getContainingFile() return filePath(file) } fun getPsiElement(descriptor: DeclarationDescriptor): PsiElement? { return try { BindingContextUtils.descriptorToDeclaration(context, descriptor) } catch (e: Throwable) { // ignore exceptions on fake descriptors null } } protected fun commentsFor(descriptor: DeclarationDescriptor): String { val psiElement = getPsiElement(descriptor) // This method is a hack. Doc comments should be easily accessible, but they aren't for now. if (psiElement != null) { var node = psiElement.getNode()?.getTreePrev() while (node != null && (node?.getElementType() == JetTokens.WHITE_SPACE || node?.getElementType() == JetTokens.BLOCK_COMMENT)) { node = node?.getTreePrev() } if (node == null) return "" if (node?.getElementType() != JetTokens.DOC_COMMENT) return "" var text = node?.getText() ?: "" // lets remove the comment tokens val lines = text.trim().split("\\n") // lets remove the /** ... * ... */ tokens val buffer = StringBuilder() val last = lines.size - 1 for (i in 0.rangeTo(last)) { var text = lines[i] ?: "" text = text.trim() if (i == 0) { text = text.trimLeading("/**").trimLeading("/*") } else { buffer.append("\n") } if (i >= last) { text = text.trimTrailing("*/") } else if (i > 0) { text = text.trimLeading("* ") if (text == "*") text = "" } text = processMacros(text, psiElement) buffer.append(text) } return buffer.toString() ?: "" } return "" } protected fun processMacros(textWithWhitespace: String, psiElement: PsiElement): String { val text = textWithWhitespace.trim() // lets check for javadoc style @ tags and macros if (text.startsWith("@")) { val remaining = text.substring(1) val macro = "includeFunctionBody" if (remaining.startsWith(macro)) { val next = remaining.substring(macro.length()).trim() val words = next.split("\\s") // TODO we could default the test function name to match that of the // source code function if folks adopted a convention of naming the test method after the // method its acting as a demo/test for if (words.size > 1) { val includeFile = words[0].sure() val fnName = words[1].sure() val content = findFunctionInclude(psiElement, includeFile, fnName) if (content != null) { return content } else { warning("could not find function $fnName in file $includeFile from source file ${psiElement.getContainingFile()}") } } } else { warning("Unknown kdoc macro @$remaining") } } return textWithWhitespace } protected fun findFunctionInclude(psiElement: PsiElement, includeFile: String, functionName: String): String? { var dir = psiElement.getContainingFile()?.getParent() if (dir != null) { val file = relativeFile(dir.sure(), includeFile) if (file != null) { val text = file.getText() if (text != null) { // lets find the function definition val regex = """fun\s+$functionName\(.*\)""".toRegex() val matcher = regex.matcher(text)!! if (matcher.find()) { val idx = matcher.end() val remaining = text.substring(idx) val content = extractBlock(remaining) if (content != null) { val highlight = highlighter.highlight(content) val filePath = filePath(file) val sourceLine = text.substring(0, idx).count{ it == '\n'} + 1 val link = if (filePath != null) sourceLinkFor(filePath, sourceLine) else null return if (link != null) """<div class="source-detail"><a href="$link" target="_top" class="repoSourceCode">source</a></div> $highlight""" else highlight } } } } } return null } protected fun filePath(file: PsiFileSystemItem?): String? { if (file != null) { var dir = file.getParent() if (dir != null) { val parentName = filePath(dir) ?: "" return parentName + "/" + file.getName() } } return null } /** * Extracts the block of code within { .. } tokens or returning null if it can't be found */ protected fun extractBlock(text: String): String? { val idx = text.indexOf('{') if (idx >= 0) { var remaining = text.substring(idx + 1) // lets remove any leading blank lines while (true) { val nidx = remaining.indexOf('\n') if (nidx >= 0) { val line = remaining.substring(0, nidx).trim() if (line.isEmpty()) { remaining = remaining.substring(nidx + 1) continue } } break } var count = 1 for (i in 0.rangeTo(remaining.size - 1)) { val ch = remaining[i] if (ch == '{') count ++ else if (ch == '}') { if (--count <= 0) { return remaining.substring(0, i) } } } warning("missing } in code block for $remaining") return remaining } return null } protected fun relativeFile(directory: PsiDirectory, relativeName: String): PsiFile? { // TODO would have thought there's some helper function already to resolve relative names! var dir: PsiDirectory? = directory // lets try resolve the include name relative to this file val paths = relativeName.split("/") val size = paths.size for (i in 0.rangeTo(size - 2)) { val path = paths[i] if (path == ".") continue else if (path == "..") dir = dir?.getParent() else dir = dir?.findSubdirectory(path) } val name = paths[size - 1] if (dir != null) { val file = dir?.findFile(name) if (file != null) { return file } else { warning("could not find file $relativeName in $dir with name $name") } } return null } fun configureComments(annotated: KAnnotated, descriptor: DeclarationDescriptor): Unit { val detailedText = commentsFor(descriptor).trim() annotated.wikiDescription = detailedText } fun getType(aType: JetType?): KType? { if (aType != null) { val classifierDescriptor = aType.getConstructor().getDeclarationDescriptor() val klass = if (classifierDescriptor is ClassDescriptor) { getClass(classifierDescriptor) } else null return KType(aType, this, klass) } return null } /** * Returns the [[KClass]] for the fully qualified name or null if it could not be found */ fun getClass(qualifiedName: String): KClass? { // TODO warning this only works for top level classes // a better algorithm is to walk down each dot path dealing with nested packages/classes val idx = qualifiedName.lastIndexOf('.') val pkgName = if (idx >= 0) qualifiedName.substring(0, idx) else "" val pkg = getPackage(pkgName) if (pkg != null) { val simpleName = if (idx >= 0) qualifiedName.substring(idx + 1) else qualifiedName return pkg.classMap.get(simpleName) } return null } fun getClass(classElement: ClassDescriptor): KClass? { val name = classElement.getName().getName() var dec: DeclarationDescriptor? = classElement.getContainingDeclaration() while (dec != null) { val container = dec if (container is NamespaceDescriptor) { val pkg = getPackage(container) return pkg.getClass(classElement) } else { dec = dec?.getContainingDeclaration() } } warning("no package found for class $name") return null } fun previous(pkg: KPackage): KPackage? { // TODO return null } fun next(pkg: KPackage): KPackage? { // TODO return null } } class TemplateLinkRenderer(val annotated: KAnnotated, val template: KDocTemplate): LinkRenderer() { // TODO dirty hack - remove when this issue is fixed // http://youtrack.jetbrains.com/issue/KT-1524 val hackedLinks = hashMap( Pair("IllegalArgumentException", Pair("java.lang", "java/lang/IllegalArgumentException.html")), Pair("IllegalStateException", Pair("java.lang", "java/lang/IllegalStateException.html")), Pair("Map.Entry", Pair("java.util", "java/util/Map.Entry.html")), Pair("System.in", Pair("java.lang", "java/lang/System.html#in")), Pair("System.out", Pair("java.lang", "java/lang/System.html#in")), Pair("#equals()", Pair("java.lang", "java/lang/Object.html#equals(java.lang.Object)")), Pair("#hashCode()", Pair("java.lang", "java/lang/Object.html#hashCode()")) ) public override fun render(node: WikiLinkNode?): Rendering? { val answer = super.render(node) if (answer != null) { val text = answer.text if (text != null) { val qualified = resolveToQualifiedName(text) var href = resolveClassNameLink(qualified) if (href != null) { answer.href = href } else { // TODO really dirty hack alert!!! // until the resolver is working, lets try adding a few prefixes :) for (prefix in arrayList("java.lang", "java.util", "java.util.concurrent", "java.util.regex", "java.io", "jet", "java.awt", "java.awt.event", "java.sql", "java.beans", "javax.swing", "javax.swing.event", "org.w3c.dom", "kotlin.template")) { if (href == null) { href = resolveClassNameLink(prefix + "." + qualified) if (href != null) { break } } } } if (href == null) { // TODO even hacker than the above hack! val link = hackedLinks.get(text) if (link != null) { href = annotated.model.config.resolveLink(link.first) + link.second } } if (href != null) { answer.href = href } else { answer.href = "#NotImplementedYet" warning("could not resolve expression: $qualified into a wiki link") } } } return answer } /** * Try to resolve a fully qualified class name as a link */ protected fun resolveClassNameLink(qualifiedName: String): String? { val model = annotated.model val pkg = model.getPackage(qualifiedName) if (pkg != null) { return template.href(pkg) } val klass = model.getClass(qualifiedName) if (klass != null) { return template.href(klass) } else { // is it a method? val idx = qualifiedName.lastIndexOf('.') if (idx > 0) { val className = qualifiedName.substring(0, idx) val c = model.getClass(className) if (c != null) { // lets try find method... val remaining = qualifiedName.substring(idx + 1) // lets try find the function val fn = c.findFunction(remaining) if (fn != null) { return template.href(fn) } val p = c.findProperty(remaining) if (p != null) { return template.href(p) } } } return null } } /** * Attempts to resolve the class, method or property expression using the * current imports and declaraiton */ protected fun resolveToQualifiedName(text: String): String { // TODO use the CompletionContributors maybe to figure out what local names are imported??? return text /* val scope = findWritableScope(annotated.declarationDescriptor) if (scope != null) { val classifierDescriptor = scope.getClassifier(text) if (classifierDescriptor == null) { val o = scope.getObjectDescriptor(text) println("Attempt to resolve HREF: $text Found objectDescriptor $o") } else { println("Attempt to resolve HREF: $text Found classifierDescriptor $classifierDescriptor") } } } protected fun findWritableScope(declarationDescriptor: DeclarationDescriptor) : WritableScopeImpl? { val container = declarationDescriptor.getContainingDeclaration() if (container is NamespaceDescriptor) { val scope = container.getMemberScope() if (scope is WritableScopeImpl) { return scope } } else if (container != null) { return findWritableScope(container) } return null */ } public override fun render(node: RefLinkNode?, url: String?, title: String?, text: String?): Rendering? { return super.render(node, url, title, text) } public override fun render(node: AutoLinkNode?): Rendering? { return super.render(node) } public override fun render(node: ExpLinkNode?, text: String?): Rendering? { return super.render(node, text) } } abstract class KAnnotated(val model: KModel, val declarationDescriptor: DeclarationDescriptor) { public open var wikiDescription: String = "" public open var deprecated: Boolean = false open fun description(template: KDocTemplate): String { val detailedText = detailedDescription(template) val idx = detailedText.indexOf("</p>") return if (idx > 0) { detailedText.substring(0, idx).trimLeading("<p>") } else { detailedText } } fun detailedDescription(template: KDocTemplate): String { val wiki = wikiDescription return wikiConvert(wiki, template) } protected fun wikiConvert(wiki: String, template: KDocTemplate): String { val file = model.fileFor(declarationDescriptor) return model.wikiConvert(wiki, TemplateLinkRenderer(this, template), file) } fun isLinkToSourceRepo(): Boolean { return model.config.sourceRootHref != null } fun sourceTargetAttribute(): String { return if (isLinkToSourceRepo()) " target=\"_top\" class=\"repoSourceCode\"" else "" } fun sourceLink(): String { val file = filePath() if (file != null) { val link = model.sourceLinkFor(file, sourceLine) if (link != null) return link } return "" } fun filePath(): String? = model.filePath(declarationDescriptor) fun location(): LineAndColumn? = model.locationFor(declarationDescriptor) val sourceLine: Int get() { val loc = location() return if (loc != null) loc.getLine() else 1 } } abstract class KNamed(val name: String, model: KModel, declarationDescriptor: DeclarationDescriptor): KAnnotated(model, declarationDescriptor), Comparable<KNamed> { public override fun compareTo(other: KNamed): Int = name.compareTo(other.name) open fun equals(other: KPackage) = name == other.name open fun toString() = name } class KPackage(model: KModel, val descriptor: NamespaceDescriptor, val name: String, var local: Boolean = false, var useExternalLink: Boolean = false): KClassOrPackage(model, descriptor), Comparable<KPackage> { // TODO generates java.lang.NoSuchMethodError: kotlin.util.namespace.hashMap(Ljet/TypeInfo;Ljet/TypeInfo;)Ljava/util/HashMap; //val classes = sortedMap<String,KClass>() public val classMap: SortedMap<String, KClass> = TreeMap<String, KClass>() public val classes: Collection<KClass> get() = classMap.values().sure().filter{ it.isApi() } public val annotations: Collection<KClass> = ArrayList<KClass>() public override fun compareTo(other: KPackage): Int = name.compareTo(other.name) fun equals(other: KPackage) = name == other.name fun toString() = "KPackage($name)" fun getClass(descriptor: ClassDescriptor): KClass { val name = descriptor.getName().getName() var created = false val klass = classMap.getOrPut(name) { created = true val psiFile = model.getPsiElement(descriptor)?.getContainingFile() val jetFile = psiFile as? JetFile val sourceInfo = if (jetFile != null) model.sourceInfoByFile(jetFile) else null KClass(this, descriptor, sourceInfo) } if (created) { // sometimes we may have source files for a package in different source directories // such as the kotlin package in generated directory; so lets always check if we can find // the readme model.tryLoadReadMe(this, descriptor) model.configureComments(klass, descriptor) val typeConstructor = descriptor.getTypeConstructor() val superTypes = typeConstructor.getSupertypes() for (st in superTypes) { val sc = model.getType(st) if (sc != null) { klass.baseClasses.add(sc) } } val scope = descriptor.getDefaultType().getMemberScope() model.addFunctions(klass, scope) model.addTypeParameters(klass.typeParameters, typeConstructor.getParameters()) } return klass } /** Returns the name as a directory using '/' instead of '.' */ public val nameAsPath: String get() = if (name.length() == 0) "." else name.replace('.', '/') /** Returns a list of all the paths in the package name */ public val namePaths: List<String> get() { val answer = ArrayList<String>() for (n in name.split("\\.")) { answer.add(n) } return answer; } /** Returns a relative path like ../.. for each path in the name */ public val nameAsRelativePath: String get() { val answer = namePaths.map{ ".." }.makeString("/") return if (answer.length == 0) "" else answer + "/" } override fun description(template: KDocTemplate): String { // lets see if we can find a custom summary val text = model.config.packageSummaryText[name] return if (text != null) wikiConvert(text, template).trimLeading("<p>").trimTrailing("</p>") else super<KClassOrPackage>.description(template) } fun qualifiedName(simpleName: String): String { return if (name.length() > 0) { "${name}.${simpleName}" } else { simpleName } } fun previous(pkg: KClass): KClass? { // TODO return null } fun next(pkg: KClass): KClass? { // TODO return null } fun groupClassMap(): Map<String, List<KClass>> { return classes.groupByTo(TreeMap<String, List<KClass>>()){it.group} } fun packageFunctions() = functions.filter{ it.extensionClass == null } fun packageProperties() = properties.filter{ it.extensionClass == null && it.isPublic() } } class KType(val jetType: JetType, model: KModel, val klass: KClass?, val arguments: MutableList<KType> = ArrayList<KType>()) : KNamed(klass?.name ?: jetType.toString().sure(), model, jetType.getConstructor().getDeclarationDescriptor().sure()) { { if (klass != null) { this.wikiDescription = klass.wikiDescription } for (arg in jetType.getArguments()) { if (arg != null) { val argJetType = arg.getType() val t = model.getType(argJetType) if (t != null) { arguments.add(t) } } } } override fun toString() = if (nullable) "$name?" else name val nullable: Boolean get() = jetType.isNullable() } class KClass( val pkg: KPackage, val descriptor: ClassDescriptor, val sourceInfo: SourceInfo?) : KClassOrPackage(pkg.model, descriptor), Comparable<KClass> { val simpleName = descriptor.getName().getName() var group: String = "Other" var annotations: List<KAnnotation> = arrayList<KAnnotation>() var typeParameters: MutableList<KTypeParameter> = arrayList<KTypeParameter>() var since: String = "" var authors: List<String> = arrayList<String>() var baseClasses: MutableList<KType> = arrayList<KType>() var nestedClasses: List<KClass> = arrayList<KClass>() public override fun compareTo(other: KClass): Int = name.compareTo(other.name) fun equals(other: KClass) = name == other.name fun toString() = "$kind($name)" fun isApi(): Boolean { val visibility = descriptor.getVisibility() return visibility.isPublicAPI() } val kind: String get() { val k = descriptor.getKind() return if (k == ClassKind.TRAIT) "trait" else if (k == ClassKind.OBJECT) "object" else if (k == ClassKind.ENUM_CLASS || k == ClassKind.ENUM_ENTRY) "enum" else if (k == ClassKind.ANNOTATION_CLASS) "annotation" else "class" } val kindCode: String get() { val k = descriptor.getKind() return if (k == ClassKind.TRAIT) "trait" else if (k == ClassKind.OBJECT) "object" else if (k == ClassKind.ENUM_CLASS || k == ClassKind.ENUM_ENTRY) "enum class" else if (k == ClassKind.ANNOTATION_CLASS) "class" else "class" } val visibility: String get() { val v = descriptor.getVisibility() return if (v == Visibilities.PUBLIC) "public" else if (v == Visibilities.PROTECTED) "protected" else if (v == Visibilities.PRIVATE) "private" else "" } /** Link to the type which is relative if its a local type but could be a type in a different library or null if no link */ public var url: String? = null get() { if ($url == null) $url = "${nameAsPath}.html" return $url } public val name: String = pkg.qualifiedName(descriptor.getName().getName()) public val packageName: String = pkg.name /** Returns the name as a directory using '/' instead of '.' */ public val nameAsPath: String get() = name.replace('.', '/') fun isAnnotation() = kind == "annotation" fun isInterface() = kind == "interface" /** Returns all of the base classes and all of their descendants */ fun descendants(answer: MutableSet<KClass> = LinkedHashSet<KClass>()): Set<KClass> { for (b in baseClasses) { val c = b.klass if (c != null) { answer.add(c) c.descendants(answer) } } return answer } } class KFunction(val descriptor: CallableDescriptor, val owner: KClassOrPackage, val name: String, var returnType: KType, var parameters: List<KParameter>, var receiverType: KType? = null, var extensionClass: KClass? = null, var modifiers: List<String> = arrayList<String>(), var typeParameters: MutableList<KTypeParameter> = arrayList<KTypeParameter>(), var exceptions: List<KClass> = arrayList<KClass>(), var annotations: List<KAnnotation> = arrayList<KAnnotation>()): KAnnotated(owner.model, descriptor), Comparable<KFunction> { public val parameterTypeText: String = parameters.map{ it.aType.name }.makeString(", ") public override fun compareTo(other: KFunction): Int { var answer = name.compareTo(other.name) if (answer == 0) { answer = parameterTypeText.compareTo(other.parameterTypeText) if (answer == 0) { val ec1 = extensionClass?.name ?: "" val ec2 = other.extensionClass?.name ?: "" answer = ec1.compareTo(ec2) } } return answer } fun equals(other: KFunction) = name == other.name && this.parameterTypeText == other.parameterTypeText && this.extensionClass == other.extensionClass && this.owner == other.owner fun toString() = "fun $name($parameterTypeText): $returnType" public val link: String = "$name($parameterTypeText)" /** Returns a list of generic type parameter names kinds like "A, I" */ public val typeParametersText: String get() = typeParameters.map{ it.name }.makeString(", ") } class KProperty(val owner: KClassOrPackage, val descriptor: PropertyDescriptor, val name: String, val returnType: KType, val extensionClass: KClass?): KAnnotated(owner.model, descriptor), Comparable<KProperty> { public override fun compareTo(other: KProperty): Int = name.compareTo(other.name) public val link: String = "$name" fun equals(other: KFunction) = name == other.name fun isVar(): Boolean = descriptor.isVar() fun kind(): String = if (isVar()) "var" else "val" fun isPublic(): Boolean { val visibility = descriptor.getVisibility() return visibility.isPublicAPI() } fun toString() = "property $name" } class KParameter(val descriptor: ValueParameterDescriptor, val name: String, var aType: KType): KAnnotated(aType.model, aType.declarationDescriptor) { fun toString() = "$name: ${aType.name}" fun isVarArg(): Boolean = descriptor.getVarargElementType() != null fun hasDefaultValue(): Boolean = descriptor.hasDefaultValue() fun varArgType(): KType? { val varType = descriptor.getVarargElementType() return if (varType != null) { aType.model.getType(varType) } else null } } class KTypeParameter(val name: String, val descriptor: TypeParameterDescriptor, model: KModel, var extends: List<KClass> = arrayList<KClass>()): KAnnotated(model, descriptor) { fun toString() = "$name" } class KAnnotation(var klass: KClass): KAnnotated(klass.model, klass.descriptor) { // TODO add some parameter values? fun toString() = "@$klass.simpleName" }
2
null
28
71
ac434d48525a0e5b57c66b9f61b388ccf3d898b5
47,640
kotlin
Apache License 2.0
src/test/java/org/jetbrains/plugins/ideavim/action/motion/mark/MotionMarkActionTest.kt
JetBrains
1,459,486
false
null
/* * Copyright 2003-2023 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package org.jetbrains.plugins.ideavim.action.motion.mark import com.intellij.ide.bookmark.BookmarksManager import com.intellij.ide.bookmark.LineBookmark import com.intellij.testFramework.PlatformTestUtil import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.group.createLineBookmark import com.maddyhome.idea.vim.group.mnemonic import com.maddyhome.idea.vim.vimscript.services.IjOptionConstants import junit.framework.TestCase import org.jetbrains.plugins.ideavim.OptionValueType import org.jetbrains.plugins.ideavim.VimOptionTestCase import org.jetbrains.plugins.ideavim.VimOptionTestConfiguration import org.jetbrains.plugins.ideavim.VimTestOption class MotionMarkActionTest : VimOptionTestCase(IjOptionConstants.ideamarks) { @VimOptionTestConfiguration(VimTestOption(IjOptionConstants.ideamarks, OptionValueType.NUMBER, "1")) fun `test simple add mark`() { val keys = injector.parser.parseKeys("mA") val text = """ A Discovery I ${c}found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() configureByText(text) typeText(keys) checkMarks('A' to 2) } @VimOptionTestConfiguration(VimTestOption(IjOptionConstants.ideamarks, OptionValueType.NUMBER, "1")) fun `test simple add multiple marks`() { val keys = injector.parser.parseKeys("mAj" + "mBj" + "mC") val text = """ A Discovery I ${c}found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() configureByText(text) typeText(keys) checkMarks('A' to 2, 'B' to 3, 'C' to 4) } @VimOptionTestConfiguration(VimTestOption(IjOptionConstants.ideamarks, OptionValueType.NUMBER, "1")) fun `test simple add multiple marks on same line`() { val keys = injector.parser.parseKeys("mA" + "mB" + "mC") val text = """ A Discovery I ${c}found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() configureByText(text) typeText(keys) checkMarks('A' to 2) // Previously it was like this, but now it's impossible to set multiple bookmarks on the same line. // checkMarks('A' to 2, 'B' to 2, 'C' to 2) } @VimOptionTestConfiguration(VimTestOption(IjOptionConstants.ideamarks, OptionValueType.NUMBER, "1")) fun `test move to another line`() { val keys = injector.parser.parseKeys("mAjj" + "mA") val text = """ A Discovery I ${c}found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() configureByText(text) typeText(keys) checkMarks('A' to 4) } @VimOptionTestConfiguration(VimTestOption(IjOptionConstants.ideamarks, OptionValueType.NUMBER, "1")) fun `test simple system mark`() { val text = """ A Discovery I ${c}found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() configureByText(text) myFixture.project.createLineBookmark(myFixture.editor, 2, 'A') PlatformTestUtil.dispatchAllInvocationEventsInIdeEventQueue() val vimMarks = injector.markService.getAllGlobalMarks() TestCase.assertEquals(1, vimMarks.size) TestCase.assertEquals('A', vimMarks.first().key) } @VimOptionTestConfiguration(VimTestOption(IjOptionConstants.ideamarks, OptionValueType.NUMBER, "1")) fun `test system mark move to another line`() { val text = """ A Discovery I ${c}found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() configureByText(text) val bookmark = myFixture.project.createLineBookmark(myFixture.editor, 2, 'A') BookmarksManager.getInstance(myFixture.project)?.remove(bookmark!!) myFixture.project.createLineBookmark(myFixture.editor, 4, 'A') PlatformTestUtil.dispatchAllInvocationEventsInIdeEventQueue() val vimMarks = injector.markService.getAllGlobalMarks() TestCase.assertEquals(1, vimMarks.size) val mark = vimMarks.first() TestCase.assertEquals('A', mark.key) TestCase.assertEquals(4, mark.line) } private fun checkMarks(vararg marks: Pair<Char, Int>) { val project = myFixture.project val validBookmarks = BookmarksManager.getInstance(project)!!.bookmarks.sortedBy { it.mnemonic(project) } assertEquals(marks.size, validBookmarks.size) marks.sortedBy { it.first }.forEachIndexed { index, (mn, line) -> assertEquals(mn, validBookmarks[index].mnemonic(project)) assertEquals(line, (validBookmarks[index] as LineBookmark).line) } } }
6
Kotlin
679
7,221
9b56fbc3ed5d7558f37cd5c4661de4a2c6c9e001
5,478
ideavim
MIT License
idea/src/org/jetbrains/kotlin/idea/parameterInfo/custom/DisableReturnLambdaHintOptionAction.kt
android
263,405,600
false
null
/* * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.parameterInfo.custom import com.intellij.codeInsight.hints.InlayParameterHintsExtension import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ex.EditorSettingsExternalizable import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.parameterInfo.HintType import org.jetbrains.kotlin.idea.util.refreshAllOpenEditors class DisableReturnLambdaHintOptionAction : IntentionAction, LowPriorityAction { override fun getText(): String { return HintType.LAMBDA_RETURN_EXPRESSION.doNotShowDesc } override fun getFamilyName(): String = text override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean { if (file.language != KotlinLanguage.INSTANCE) return false InlayParameterHintsExtension.forLanguage(file.language) ?: return false if (!EditorSettingsExternalizable.getInstance().isShowParameterNameHints || !HintType.LAMBDA_RETURN_EXPRESSION.enabled) { return false } return KotlinCodeHintsModel.getInstance(project).getExtensionInfoAtOffset(editor) != null } override fun invoke(project: Project, editor: Editor, file: PsiFile) { HintType.LAMBDA_RETURN_EXPRESSION.option.set(false) refreshAllOpenEditors() } override fun startInWriteAction(): Boolean = false }
0
null
37
316
74126637a097f5e6b099a7b7a4263468ecfda144
1,778
kotlin
Apache License 2.0
gamespot-api/src/main/java/com/paulrybitskyi/gamedge/gamespot/api/common/Response.kt
mars885
289,036,871
false
null
/* * Copyright 2021 Paul Rybitskyi, [email protected] * * 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.paulrybitskyi.gamedge.gamespot.api.common import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable internal data class Response<T : Any>( @SerialName(Schema.RESULTS) val results: List<T> = emptyList(), ) { object Schema { const val RESULTS = "results" } }
4
null
63
659
69b3ada08cb877af9b775c6a4f3d9eb1c3470d9c
964
gamedge
Apache License 2.0
src/main/kotlin/org/ivcode/shm/params/service/ParameterService.kt
self-host-manager
668,078,860
false
null
package org.ivcode.shm.params.service import org.ivcode.shm.params.repository.ParamGroupDao import org.ivcode.shm.params.repository.ParamValueDao import org.ivcode.shm.params.repository.entities.ParamGroupEntity import org.ivcode.shm.params.repository.entities.ParamValueEntity import org.ivcode.shm.params.repository.entities.ParamValueEntityKey import org.ivcode.shm.params.service.domain.ParamValue import org.ivcode.shm.params.service.domain.SaveParam import org.ivcode.shm.params.service.domain.toDomain import org.ivcode.shm.utils.createRandomPassword import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service class ParameterService ( private val paramGroupDao: ParamGroupDao, private val paramValueDao: ParamValueDao, ) { fun listGroups(): List<String> = paramGroupDao.findAll().map { grp -> grp.name!! } fun deleteGroup(group: String) = paramGroupDao.deleteById(group) @Transactional fun createGroup(group: String): ParamGroupEntity = paramGroupDao.saveAndFlush(ParamGroupEntity(name=group)) fun listParams(group: String): List<ParamValue> = paramValueDao.findByGroup(group).map { value -> value.toDomain() } @Transactional fun saveParams( group: String, name: String, saveParam: SaveParam ) { // make sure the group exists val value = createValue(saveParam) paramValueDao.saveAndFlush(ParamValueEntity( key = ParamValueEntityKey( paramGroupName = group, name = name ), value = value )) } fun createValue ( saveParam: SaveParam ): String { if(saveParam.value==null && saveParam.random==null) { throw IllegalArgumentException("value must be set or set to random") } if(saveParam.value!=null && saveParam.random!=null) { throw IllegalArgumentException("value must be set or set to random, but not both") } return if(saveParam.random!=null) { val random = saveParam.random createRandomPassword( length = random.length, enableUpper = random.enableUpper, minimumUpper = random.minimumUpper, enableLower = random.enableLower, minimumLower = random.minimumLower, enableNumber = random.enableNumber, minimumNumber = random.minimumNumber, enableSpecial = random.enableSpecial, minimumSpecial = random.minimumSpecial ) } else { saveParam.value!! } } }
0
Kotlin
0
0
8537398dfb332436a6d2ba604014a9a7ac97ae0b
2,711
self-host-manager
Apache License 2.0
app/src/main/java/com/example/noterapp/ui/fragments/CreateNoteFragment.kt
sabinmhx
671,497,047
false
null
package com.example.noterapp.ui.fragments import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBinderMapper import androidx.databinding.DataBindingUtil import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import androidx.navigation.findNavController import com.example.noterapp.R import com.example.noterapp.databinding.FragmentCreateNoteBinding import com.example.noterapp.db.NotesDatabase import com.example.noterapp.mvvm.NotesFactoryViewModel import com.example.noterapp.mvvm.NotesRepository import com.example.noterapp.mvvm.NotesViewModel class CreateNoteFragment : Fragment() { lateinit var binding : FragmentCreateNoteBinding lateinit var viewModel: NotesViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment (activity as AppCompatActivity).supportActionBar?.setTitle("CREATE NOTE") binding = DataBindingUtil.inflate(inflater, R.layout.fragment_create_note, container, false) val dao = NotesDatabase.getInstance(requireContext()).notesDao val repostiry = NotesRepository(dao) val factory = NotesFactoryViewModel(repostiry) viewModel = ViewModelProvider(this, factory)[NotesViewModel::class.java] binding.viewModel = viewModel binding.lifecycleOwner = this binding.saveBtn.setOnClickListener { viewModel.addNotes() view?.findNavController()?.navigate(R.id.action_createNoteFragment2_to_homeFragment2) } return binding.root } }
0
Kotlin
0
1
cdd5e0686e5d365b311edfaa02a7e7bdc31682eb
1,886
noter
MIT License
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/CalendarDollar.kt
walter-juan
868,046,028
false
{"Kotlin": 20416825}
package com.woowla.compose.icon.collections.tabler.tabler.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound public val OutlineGroup.CalendarDollar: ImageVector get() { if (_calendarDollar != null) { return _calendarDollar!! } _calendarDollar = Builder(name = "CalendarDollar", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(13.0f, 21.0f) horizontalLineToRelative(-7.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.0f, -2.0f) verticalLineToRelative(-12.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, -2.0f) horizontalLineToRelative(12.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, 2.0f) verticalLineToRelative(3.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(16.0f, 3.0f) verticalLineToRelative(4.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(8.0f, 3.0f) verticalLineToRelative(4.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(4.0f, 11.0f) horizontalLineToRelative(12.5f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(21.0f, 15.0f) horizontalLineToRelative(-2.5f) arcToRelative(1.5f, 1.5f, 0.0f, false, false, 0.0f, 3.0f) horizontalLineToRelative(1.0f) arcToRelative(1.5f, 1.5f, 0.0f, false, true, 0.0f, 3.0f) horizontalLineToRelative(-2.5f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(19.0f, 21.0f) verticalLineToRelative(1.0f) moveToRelative(0.0f, -8.0f) verticalLineToRelative(1.0f) } } .build() return _calendarDollar!! } private var _calendarDollar: ImageVector? = null
0
Kotlin
0
1
b037895588c2f62d069c724abe624b67c0889bf9
4,026
compose-icon-collections
MIT License
gematria/src/commonTest/kotlin/com/kdroid/gematria/GematriaCaculatorTest.kt
kdroidFilter
854,676,682
false
{"Kotlin": 10151}
package com.kdroid.gematria import com.kdroid.gematria.converter.toDafGemara import com.kdroid.gematria.converter.toGematria import com.kdroid.gematria.converter.toHebrewNumeral import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFails class GematriaCaculatorTest { @Test fun numberToHebrewNumeralConverter() { assertFails { (-1).toHebrewNumeral() } assertEquals( expected = "ื”ืณ", actual = 5.toHebrewNumeral() ) assertEquals( expected = "ื ืณ", actual = 50.toHebrewNumeral() ) assertEquals( expected = "ืชืชืงืดื”", actual = 905.toHebrewNumeral() ) assertEquals( expected = "ื”ืณืชืฉืคืดื”", actual = 5785.toHebrewNumeral() ) } @Test fun textToHebrewGematriaConverter(){ assertEquals( expected = 0, actual = "".toGematria() ) assertEquals( expected = 784, actual = "ืชืฉืคื“".toGematria() ) assertEquals( expected = 515, actual = "ื•ืืชื—ื ืŸ ".toGematria() ) assertEquals( expected = 113, actual = "ืื ื™ ื‘ืŸ 18 ".toGematria() ) } @Test fun idToDafGemaraConverter() { assertFails { (-1).toDafGemara() } assertEquals( expected = "ื‘.", actual = 1.toDafGemara() ) assertEquals( expected = "ื‘:", actual = 2.toDafGemara() ) assertEquals( expected = "ื’.", actual = 3.toDafGemara() ) assertEquals( expected = "ื’:", actual = 4.toDafGemara() ) assertEquals( expected = "ื“.", actual = 5.toDafGemara() ) assertEquals( expected = "ื“:", actual = 6.toDafGemara() ) assertEquals( expected = "ื”.", actual = 7.toDafGemara() ) assertEquals( expected = "ื”:", actual = 8.toDafGemara() ) assertEquals( expected = "ื•.", actual = 9.toDafGemara() ) assertEquals( expected = "ื•:", actual = 10.toDafGemara() ) assertEquals( expected = "ื–.", actual = 11.toDafGemara() ) assertEquals( expected = "ื–:", actual = 12.toDafGemara() ) assertEquals( expected = "ื—.", actual = 13.toDafGemara() ) assertEquals( expected = "ื˜.", actual = 15.toDafGemara() ) assertEquals( expected = "ื˜ื•.", actual = 27.toDafGemara() ) } }
0
Kotlin
0
2
1a67f02a4ff92b6a00dc3be4ca180e44130b7baa
2,910
HebrewNumeralsLibrary
Apache License 2.0
domain/src/main/kotlin/io/github/fobo66/domain/usecase/ResolveRatingStateImpl.kt
fobo66
117,318,095
false
{"Kotlin": 113184}
/* * Copyright 2022 <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 io.github.fobo66.domain.usecase import io.github.fobo66.data.entities.MatchmakingRating import io.github.fobo66.data.repositories.RatingRepository import io.github.fobo66.data.repositories.SettingsRepository import io.github.fobo66.domain.entities.RatingState import timber.log.Timber class ResolveRatingStateImpl( private val settingsRepository: SettingsRepository, private val ratingRepository: RatingRepository ) : ResolveRatingState { override suspend fun execute(): RatingState { val isFirstLaunch = settingsRepository.loadFirstLaunch() return if (isFirstLaunch) { Timber.d("First time launching the app") settingsRepository.saveFirstLaunch(false) RatingState.NoPlayerId } else { val playerId = settingsRepository.loadPlayerId() if (playerId > 0) { val rating = ratingRepository.loadRating(playerId) Timber.d("Loaded rating for %s", playerId) resolveRatingState(rating) } else { Timber.d("No player id found") RatingState.NoPlayerId } } } private fun resolveRatingState(rating: MatchmakingRating?) = rating?.let { if (it.name.isNullOrEmpty() && it.personaName.isNullOrEmpty() && it.rating == null ) { Timber.d("Empty rating, likely player id is not actual") RatingState.InvalidPlayerId } else { RatingState.LoadedRating( playerName = it.name.orEmpty(), personaName = it.personaName.orEmpty(), rating = (it.rating ?: 0).toString(), avatarUrl = it.avatarUrl.orEmpty() ) } } ?: RatingState.NoRating }
3
Kotlin
0
5
4ab2e4f1bda297ffad17882b3bac0c712b4e7450
2,425
WearMMR
Apache License 2.0
game-api/src/main/java/org/runestar/client/game/api/live/LiveCanvas.kt
forsco
246,016,204
true
{"Kotlin": 1389228, "Java": 1029180}
package org.runestar.client.game.api.live import hu.akarnokd.rxjava2.swing.SwingObservable import io.reactivex.Observable import org.runestar.client.game.api.Canvas import org.runestar.client.game.raw.CLIENT import org.runestar.client.game.raw.access.XGameShell import org.runestar.client.game.raw.access.XRasterProvider import java.awt.Graphics2D import java.awt.Rectangle import java.awt.event.ComponentEvent import java.awt.event.FocusEvent object LiveCanvas : Canvas { override val shape get() = Rectangle(CLIENT.canvas.size) val repaints: Observable<Graphics2D> = XRasterProvider.drawFull0.enter.map { it.instance.image.graphics as Graphics2D } val canvasReplacements: Observable<java.awt.Canvas> = XGameShell.addCanvas.exit.map { CLIENT.canvas } .startWith(CLIENT.canvas) /** * @see[java.awt.event.FocusListener] */ val focusEvents: Observable<FocusEvent> = canvasReplacements.flatMap { SwingObservable.focus(it) } /** * @see[java.awt.event.ComponentListener] */ val componentEvents: Observable<ComponentEvent> = canvasReplacements.flatMap { SwingObservable.component(it) } override fun toString(): String { return "LiveCanvas(shape=$shape)" } }
0
null
0
0
b15c07570af82377bcd2be48b00a5e9708be08ab
1,247
client
MIT License
common/api/src/commonMain/kotlin/com/denchic45/studiversity/api/course/work/model/UpdateCourseWorkRequest.kt
denchic45
435,895,363
false
{"Kotlin": 2110094, "Vue": 15083, "JavaScript": 2830, "CSS": 1496, "HTML": 867}
package com.denchic45.studiversity.api.course.work.model import com.denchic45.studiversity.util.* import kotlinx.serialization.Serializable import java.time.LocalDate import java.time.LocalTime @Serializable data class UpdateCourseWorkRequest( @Serializable(OptionalPropertySerializer::class) val name: OptionalProperty<String> = OptionalProperty.NotPresent, @Serializable(OptionalPropertySerializer::class) val description: OptionalProperty<String?> = OptionalProperty.NotPresent, @Serializable(OptionalPropertySerializer::class) val dueDate: OptionalProperty<@Serializable(LocalDateSerializer::class)LocalDate?> = OptionalProperty.NotPresent, @Serializable(OptionalPropertySerializer::class) val dueTime:OptionalProperty<@Serializable(LocalTimeSerializer::class)LocalTime?> = OptionalProperty.NotPresent, @Serializable(OptionalPropertySerializer::class) val maxGrade: OptionalProperty<Short> = OptionalProperty.NotPresent, )
0
Kotlin
0
7
293132d2f93ba3e42a3efe9b54deb07d7ff5ecf9
971
Studiversity
Apache License 2.0
app/src/main/java/com/soojeongshin/imagegallery/overview/OverviewFragment.kt
sooshin
209,974,333
false
null
package com.soojeongshin.imagegallery.overview import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import com.soojeongshin.imagegallery.databinding.FragmentOverviewBinding /** * A simple [Fragment] subclass. */ class OverviewFragment : Fragment() { /** * Lazily initialize our [OverviewViewModel] */ private val viewModel: OverviewViewModel by lazy { ViewModelProvider(this).get(OverviewViewModel::class.java) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val binding = FragmentOverviewBinding.inflate(inflater) // Allows Data Binding to observe LiveData with the lifecycle of this Fragment binding.setLifecycleOwner(this) // Giving the binding access to the OverviewModel binding.viewModel = viewModel // Sets the adapter of the photoStaggeredGrid RecyclerView with clickHandler lambda that tells // the viewModel when our hit is clicked binding.photosStaggeredGrid.adapter = PhotoStaggeredGridAdapter( PhotoStaggeredGridAdapter.OnClickListener { viewModel.displayHitDetails(it) }) // Observe the navigateToSelectedHit LiveData and Navigate when it isn't null. // After navigation, call displayHitDetailsComplete() so that the ViewModel is ready // for another navigation event. viewModel.navigateToSelectedHit.observe(viewLifecycleOwner, Observer { if (null != it) { // Must find the NavController from the Fragment this.findNavController().navigate(OverviewFragmentDirections.actionShowDetail(it)) // Tell the ViewModel we've made the navigation call to prevent multiple navigation viewModel.displayHitDetailsComplete() } }) // Inflate the layout for this fragment return binding.root } }
0
null
0
3
6dd5ce6304f7546caa2b157b76ecf3e8f5aad223
2,221
ImageGallery
Apache License 2.0
clouditor-engine/src/main/java/io/clouditor/EngineApplication.kt
subham-deepsource
369,631,943
true
{"Java": 634388, "Go": 42286, "Kotlin": 9387, "ANTLR": 1620, "Dockerfile": 875}
/* * Copyright 2016-2019 Fraunhofer AISEC * * 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. * * $$\ $$\ $$\ $$\ * $$ | $$ |\__| $$ | * $$$$$$$\ $$ | $$$$$$\ $$\ $$\ $$$$$$$ |$$\ $$$$$$\ $$$$$$\ $$$$$$\ * $$ _____|$$ |$$ __$$\ $$ | $$ |$$ __$$ |$$ |\_$$ _| $$ __$$\ $$ __$$\ * $$ / $$ |$$ / $$ |$$ | $$ |$$ / $$ |$$ | $$ | $$ / $$ |$$ | \__| * $$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ |$$\ $$ | $$ |$$ | * \$$$$$$\ $$ |\$$$$$ |\$$$$$ |\$$$$$$ |$$ | \$$$ |\$$$$$ |$$ | * \_______|\__| \______/ \______/ \_______|\__| \____/ \______/ \__| * * This file is part of Clouditor Community Edition. */ package io.clouditor object EngineApplication { /** * The main entry point for the Clouditor Engine Application. * * @param args command line arguments */ @Throws(InterruptedException::class) @JvmStatic fun main(args: Array<String>) { val engine = Engine() engine.start(args) Thread.currentThread().join() // shutdown if finished Runtime.getRuntime().addShutdownHook(Thread { engine.shutdown() }) } }
0
null
0
0
c9aa94a2e4fd3b25b30559af1ea497f94b610903
1,705
clouditor
Apache License 2.0
clouditor-engine/src/main/java/io/clouditor/EngineApplication.kt
subham-deepsource
369,631,943
true
{"Java": 634388, "Go": 42286, "Kotlin": 9387, "ANTLR": 1620, "Dockerfile": 875}
/* * Copyright 2016-2019 Fraunhofer AISEC * * 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. * * $$\ $$\ $$\ $$\ * $$ | $$ |\__| $$ | * $$$$$$$\ $$ | $$$$$$\ $$\ $$\ $$$$$$$ |$$\ $$$$$$\ $$$$$$\ $$$$$$\ * $$ _____|$$ |$$ __$$\ $$ | $$ |$$ __$$ |$$ |\_$$ _| $$ __$$\ $$ __$$\ * $$ / $$ |$$ / $$ |$$ | $$ |$$ / $$ |$$ | $$ | $$ / $$ |$$ | \__| * $$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ |$$\ $$ | $$ |$$ | * \$$$$$$\ $$ |\$$$$$ |\$$$$$ |\$$$$$$ |$$ | \$$$ |\$$$$$ |$$ | * \_______|\__| \______/ \______/ \_______|\__| \____/ \______/ \__| * * This file is part of Clouditor Community Edition. */ package io.clouditor object EngineApplication { /** * The main entry point for the Clouditor Engine Application. * * @param args command line arguments */ @Throws(InterruptedException::class) @JvmStatic fun main(args: Array<String>) { val engine = Engine() engine.start(args) Thread.currentThread().join() // shutdown if finished Runtime.getRuntime().addShutdownHook(Thread { engine.shutdown() }) } }
0
null
0
0
c9aa94a2e4fd3b25b30559af1ea497f94b610903
1,705
clouditor
Apache License 2.0
example/src/main/java/com/example/Person.kt
doananhtuan22111996
769,875,617
false
{"Kotlin": 166269}
package com.example class Person(lastName: String, firstName: String) { val fullName = "$firstName $lastName" } fun main() { val person = Person(lastName = "Tuan", firstName = "Doan") // Set to View println("Full Name: ${person.fullName}") }
0
Kotlin
0
0
a75c1a7630a574cf6b0965bbf6d7447008501972
259
android_architecture
MIT License