path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
756M
| is_fork
bool 2
classes | languages_distribution
stringlengths 12
2.44k
⌀ | content
stringlengths 6
6.29M
| issues
float64 0
10k
⌀ | main_language
stringclasses 128
values | forks
int64 0
54.2k
| stars
int64 0
157k
| commit_sha
stringlengths 40
40
| size
int64 6
6.29M
| name
stringlengths 1
100
| license
stringclasses 104
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
domain/src/commonMain/kotlin/app/tivi/domain/observers/ObserveRecommendedShows.kt | ra0926 | 646,050,051 | false | null | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.tivi.domain.observers
import app.tivi.data.compoundmodels.RecommendedEntryWithShow
import app.tivi.data.daos.RecommendedDao
import app.tivi.domain.SubjectInteractor
import kotlinx.coroutines.flow.Flow
import me.tatarka.inject.annotations.Inject
@Inject
class ObserveRecommendedShows(
private val recommendedDao: RecommendedDao,
) : SubjectInteractor<ObserveRecommendedShows.Params, List<RecommendedEntryWithShow>>() {
override fun createObservable(
params: Params,
): Flow<List<RecommendedEntryWithShow>> {
return recommendedDao.entriesObservable(params.count, 0)
}
data class Params(val count: Int = 20)
}
| 0 | Kotlin | 0 | 4 | e780a4c48545d5198290e4f79e5b0fda28f30d40 | 1,254 | CelebrationMessage | Apache License 2.0 |
compiler/tests-spec/testData/diagnostics/linked/expressions/constant-literals/real-literals/p-4/pos/1.3.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* KOTLIN DIAGNOSTICS SPEC TEST (POSITIVE)
*
* SPEC VERSION: 0.1-100
* MAIN LINK: expressions, constant-literals, real-literals -> paragraph 4 -> sentence 1
* NUMBER: 3
* DESCRIPTION: Real literals suffixed by f/F (float suffix) with an exponent mark and underscores in a whole-number part, a fraction part and an exponent part.
*/
// TESTCASE NUMBER: 1
val value_1 = 0.0_0e1_0f
// TESTCASE NUMBER: 2
val value_2 = 0.0__0e-0___0
// TESTCASE NUMBER: 3
val value_3 = 0.0_0E-0__0_0F
// TESTCASE NUMBER: 4
val value_4 = 0__0.0e0f
// TESTCASE NUMBER: 5
val value_5 = 0_0_0.0_0E0_0
// TESTCASE NUMBER: 6
val value_6 = 00_______________00.0_0e+0_0
// TESTCASE NUMBER: 7
val value_7 = 2_2.0e1_0F
// TESTCASE NUMBER: 8
val value_8 = 33__3.0e10__0
// TESTCASE NUMBER: 9
val value_9 = 4_44____4.0E0______00F
// TESTCASE NUMBER: 10
val value_10 = 5_________555_________5.0e-9
// TESTCASE NUMBER: 11
val value_11 = 666_666.0__________________________________________________1E+2___________________________________________________________________0F
// TESTCASE NUMBER: 12
val value_12 = 7777777.0_0e3_0
// TESTCASE NUMBER: 13
val value_13 = 8888888_8.000e0f
// TESTCASE NUMBER: 14
val value_14 = 9_______9______9_____9____9___9__9_9.0E-1
// TESTCASE NUMBER: 15
val value_15 = <!FLOAT_LITERAL_CONFORMS_INFINITY!>0_0_0_0_0_0_0_0_0_0.12345678e+90F<!>
// TESTCASE NUMBER: 16
val value_16 = 1_2_3_4_5_6_7_8_9.2_3_4_5_6_7_8_9e-0
// TESTCASE NUMBER: 17
val value_17 = <!FLOAT_LITERAL_CONFORMS_INFINITY!>234_5_678.345______________6e7_______8f<!>
// TESTCASE NUMBER: 18
val value_18 = 3_456_7.45_6E7f
// TESTCASE NUMBER: 19
val value_19 = 456.5e0_6
// TESTCASE NUMBER: 20
val value_20 = 5.6_0E+05F
// TESTCASE NUMBER: 21
val value_21 = 6_54.76_5e-4
// TESTCASE NUMBER: 22
val value_22 = <!FLOAT_LITERAL_CONFORMS_INFINITY!>7_6543.8E7654_3<!>
// TESTCASE NUMBER: 23
val value_23 = <!FLOAT_LITERAL_CONFORMS_INFINITY!>876543_____________2.9E+0_____________8765432f<!>
// TESTCASE NUMBER: 24
val value_24 = <!FLOAT_LITERAL_CONFORMS_ZERO!>9_____________87654321.0e-9_8765432_____________1F<!>
// TESTCASE NUMBER: 25
val value_25 = 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000___0.000000000000000000000000e000000000000000000000000000000000000000000000000000000000000000_0F
// TESTCASE NUMBER: 26
val value_26 = 0_000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.0E-0___000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
// TESTCASE NUMBER: 27
val value_27 = <!FLOAT_LITERAL_CONFORMS_INFINITY!>9999999999999999999999999999999999999999999_______________999999999999999999999999999999999999999999999.33333333333333333333333333333333333333333333333_333333333333333333333333333333333333333e3_3f<!>
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 2,819 | kotlin | Apache License 2.0 |
kt/godot-library/src/main/kotlin/godot/gen/godot/InputEventWithModifiers.kt | utopia-rise | 289,462,532 | false | {"Kotlin": 1464908, "GDScript": 492843, "C++": 484675, "C#": 10278, "C": 8523, "Shell": 8429, "Java": 2136, "CMake": 939, "Python": 75} | // THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY!
@file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier",
"UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST",
"RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT",
"RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate")
package godot
import godot.KeyModifierMaskValue
import godot.`annotation`.GodotBaseType
import godot.core.TypeManager
import godot.core.VariantType.BOOL
import godot.core.VariantType.LONG
import godot.core.VariantType.NIL
import godot.core.memory.TransferContext
import godot.util.VoidPtr
import kotlin.Boolean
import kotlin.Int
import kotlin.Long
import kotlin.Suppress
/**
* Abstract base class for input events affected by modifier keys like [kbd]Shift[/kbd] and [kbd]Alt[/kbd].
*
* Tutorials:
* [$DOCS_URL/tutorials/inputs/inputevent.html]($DOCS_URL/tutorials/inputs/inputevent.html)
*
* Stores information about mouse, keyboard, and touch gesture input events. This includes information about which modifier keys are pressed, such as [kbd]Shift[/kbd] or [kbd]Alt[/kbd]. See [godot.Node.Input].
*/
@GodotBaseType
public open class InputEventWithModifiers internal constructor() : InputEventFromWindow() {
/**
* Automatically use [kbd]Meta[/kbd] ([kbd]Cmd[/kbd]) on macOS and [kbd]Ctrl[/kbd] on other platforms. If `true`, [ctrlPressed] and [metaPressed] cannot be set.
*/
public var commandOrControlAutoremap: Boolean
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.isCommandOrControlAutoremapPtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
set(`value`) {
TransferContext.writeArguments(BOOL to value)
TransferContext.callMethod(rawPtr, MethodBindings.setCommandOrControlAutoremapPtr, NIL)
}
/**
* State of the [kbd]Alt[/kbd] modifier.
*/
public var altPressed: Boolean
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.isAltPressedPtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
set(`value`) {
TransferContext.writeArguments(BOOL to value)
TransferContext.callMethod(rawPtr, MethodBindings.setAltPressedPtr, NIL)
}
/**
* State of the [kbd]Shift[/kbd] modifier.
*/
public var shiftPressed: Boolean
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.isShiftPressedPtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
set(`value`) {
TransferContext.writeArguments(BOOL to value)
TransferContext.callMethod(rawPtr, MethodBindings.setShiftPressedPtr, NIL)
}
/**
* State of the [kbd]Ctrl[/kbd] modifier.
*/
public var ctrlPressed: Boolean
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.isCtrlPressedPtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
set(`value`) {
TransferContext.writeArguments(BOOL to value)
TransferContext.callMethod(rawPtr, MethodBindings.setCtrlPressedPtr, NIL)
}
/**
* State of the [kbd]Meta[/kbd] modifier. On Windows and Linux, this represents the Windows key (sometimes called "meta" or "super" on Linux). On macOS, this represents the Command key.
*/
public var metaPressed: Boolean
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.isMetaPressedPtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
set(`value`) {
TransferContext.writeArguments(BOOL to value)
TransferContext.callMethod(rawPtr, MethodBindings.setMetaPressedPtr, NIL)
}
public override fun new(scriptIndex: Int): Boolean {
callConstructor(ENGINECLASS_INPUTEVENTWITHMODIFIERS, scriptIndex)
return true
}
/**
* On macOS, returns `true` if [kbd]Meta[/kbd] ([kbd]Cmd[/kbd]) is pressed.
*
* On other platforms, returns `true` if [kbd]Ctrl[/kbd] is pressed.
*/
public fun isCommandOrControlPressed(): Boolean {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.isCommandOrControlPressedPtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
/**
* Returns the keycode combination of modifier keys.
*/
public fun getModifiersMask(): KeyModifierMask {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getModifiersMaskPtr, LONG)
return KeyModifierMaskValue(TransferContext.readReturnValue(LONG) as Long)
}
public companion object
internal object MethodBindings {
public val setCommandOrControlAutoremapPtr: VoidPtr =
TypeManager.getMethodBindPtr("InputEventWithModifiers", "set_command_or_control_autoremap")
public val isCommandOrControlAutoremapPtr: VoidPtr =
TypeManager.getMethodBindPtr("InputEventWithModifiers", "is_command_or_control_autoremap")
public val isCommandOrControlPressedPtr: VoidPtr =
TypeManager.getMethodBindPtr("InputEventWithModifiers", "is_command_or_control_pressed")
public val setAltPressedPtr: VoidPtr =
TypeManager.getMethodBindPtr("InputEventWithModifiers", "set_alt_pressed")
public val isAltPressedPtr: VoidPtr =
TypeManager.getMethodBindPtr("InputEventWithModifiers", "is_alt_pressed")
public val setShiftPressedPtr: VoidPtr =
TypeManager.getMethodBindPtr("InputEventWithModifiers", "set_shift_pressed")
public val isShiftPressedPtr: VoidPtr =
TypeManager.getMethodBindPtr("InputEventWithModifiers", "is_shift_pressed")
public val setCtrlPressedPtr: VoidPtr =
TypeManager.getMethodBindPtr("InputEventWithModifiers", "set_ctrl_pressed")
public val isCtrlPressedPtr: VoidPtr =
TypeManager.getMethodBindPtr("InputEventWithModifiers", "is_ctrl_pressed")
public val setMetaPressedPtr: VoidPtr =
TypeManager.getMethodBindPtr("InputEventWithModifiers", "set_meta_pressed")
public val isMetaPressedPtr: VoidPtr =
TypeManager.getMethodBindPtr("InputEventWithModifiers", "is_meta_pressed")
public val getModifiersMaskPtr: VoidPtr =
TypeManager.getMethodBindPtr("InputEventWithModifiers", "get_modifiers_mask")
}
}
| 61 | Kotlin | 33 | 445 | 1dfa11d5c43fc9f85de2260b8e88f4911afddcb9 | 6,483 | godot-kotlin-jvm | MIT License |
compiler/fir/checkers/build.gradle.kts | android | 263,405,600 | true | null | plugins {
kotlin("jvm")
id("jps-compatible")
}
dependencies {
compile(project(":compiler:fir:resolve"))
compileOnly(project(":kotlin-reflect-api"))
compileOnly(intellijCoreDep()) { includeJars("intellij-core", "guava", rootProject = rootProject) }
}
sourceSets {
"main" { projectDefault() }
"test" { none() }
}
| 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 342 | kotlin | Apache License 2.0 |
compiler/testData/diagnostics/tests/multiplatform/java/inheritedJavaMembers.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // FIR_IDENTICAL
// WITH_STDLIB
// MODULE: m1-common
// FILE: common.kt
interface MutableListEx<E> : MutableList<E> {
fun removeRange(fromIndex: Int, toIndex: Int)
fun addAll(elements: FastArrayList<E>): Boolean = addAll(elements as Collection<E>)
fun setAddAll(index: Int, elements: FastArrayList<E>, offset: Int = 0, size: Int = elements.size - offset) {}
fun setAll(index: Int, elements: FastArrayList<E>, offset: Int = 0, size: Int = elements.size - offset) {}
fun addAll(elements: FastArrayList<E>, offset: Int = 0, size: Int = elements.size - offset) {}
fun removeToSize(size: Int) {}
}
expect class FastArrayList<E> : MutableListEx<E>, RandomAccess {
constructor()
constructor(initialCapacity: Int)
constructor(elements: Collection<E>)
fun trimToSize()
override fun removeRange(fromIndex: Int, toIndex: Int)
fun ensureCapacity(minCapacity: Int)
override val size: Int
override fun isEmpty(): Boolean
override fun contains(element: E): Boolean
override fun containsAll(elements: Collection<E>): Boolean
override operator fun get(index: Int): E
override fun indexOf(element: E): Int
override fun lastIndexOf(element: E): Int
override fun iterator(): MutableIterator<E>
override fun add(element: E): Boolean
override fun remove(element: E): Boolean
override fun addAll(elements: Collection<E>): Boolean
override fun addAll(index: Int, elements: Collection<E>): Boolean
override fun removeAll(elements: Collection<E>): Boolean
override fun retainAll(elements: Collection<E>): Boolean
override fun clear()
override operator fun set(index: Int, element: E): E
override fun add(index: Int, element: E)
override fun removeAt(index: Int): E
override fun listIterator(): MutableListIterator<E>
override fun listIterator(index: Int): MutableListIterator<E>
override fun subList(fromIndex: Int, toIndex: Int): MutableList<E>
}
// MODULE: m2-jvm()()(m1-common)
// FILE: jvm.kt
public actual open class FastArrayList<E> internal constructor(
var array: Array<Any?>,
var _size: Int = array.size,
var arrayCapacity: Int = array.size,
) : AbstractMutableList<E>(), MutableListEx<E>, RandomAccess {
public actual constructor() : this(arrayOfNulls(16), 0) {}
public actual constructor(initialCapacity: Int) : this(arrayOfNulls(initialCapacity), 0) {}
public actual constructor(elements: Collection<E>) : this(elements.toTypedArray<Any?>()) {}
public actual fun trimToSize() {}
public actual fun ensureCapacity(minCapacity: Int) {}
actual override val size: Int get() = _size
@Suppress("UNCHECKED_CAST") actual override fun get(index: Int): E = array[0] as E
actual override fun set(index: Int, element: E): E = element
actual override fun add(element: E): Boolean = true
actual override fun add(index: Int, element: E) {}
actual override fun addAll(elements: Collection<E>): Boolean = true
actual override fun addAll(index: Int, elements: Collection<E>): Boolean = true
actual override fun remove(element: E): Boolean = true
@Suppress("UNCHECKED_CAST") actual override fun removeAt(index: Int): E = array[0] as E
actual override fun removeRange(fromIndex: Int, toIndex: Int) {}
override fun setAll(index: Int, elements: FastArrayList<E>, offset: Int, size: Int) {}
override fun addAll(elements: FastArrayList<E>, offset: Int, size: Int) {}
actual override fun clear() {}
actual override fun contains(element: E): Boolean = false
actual override fun indexOf(element: E): Int = -1
actual override fun lastIndexOf(element: E): Int = -1
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 3,658 | kotlin | Apache License 2.0 |
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/resources/testProject/composite-build-with-cinterop-commonization/lib/src/linuxArm64Main/kotlin/LinuxArm64.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | package lib
@OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
fun linuxArm64(
a: cinterop.lib.a.StructA
) {
cinterop.lib.a.a()
cinterop.lib.c.c()
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 165 | kotlin | Apache License 2.0 |
kotlinx-reflect-integration-test/build.gradle.kts | dhakehurst | 189,049,817 | false | {"Kotlin": 146833} | /**
* Copyright (C) 2019 Dr. <NAME> (http://dr.david.h.akehurst.net)
*
* 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.
*/
import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension
import java.io.File
plugins {
//kotlin("multiplatform") version ("1.5.255-SNAPSHOT") apply false
kotlin("multiplatform") version ("1.6.0-RC") apply false
}
allprojects {
val version_project: String by project
val group_project = rootProject.name
group = group_project
version = version_project
buildDir = File(rootProject.projectDir, ".gradle-build/${project.name}")
}
subprojects {
repositories {
mavenLocal()
mavenCentral()
}
apply(plugin = "org.jetbrains.kotlin.multiplatform")
configure<KotlinMultiplatformExtension> {
jvm("jvm8") {
val main by compilations.getting {
kotlinOptions {
jvmTarget = JavaVersion.VERSION_1_8.toString()
}
}
val test by compilations.getting {
kotlinOptions {
jvmTarget = JavaVersion.VERSION_1_8.toString()
}
}
}
js("js",IR) {
nodejs()
browser()
}
}
dependencies {
"commonTestImplementation"(kotlin("test"))
"commonTestImplementation"(kotlin("test-annotations-common"))
}
}
| 0 | Kotlin | 0 | 0 | 0c00e5bf1fd98e5bcbfc700867df92780cdb3e51 | 1,928 | net.akehurst.kotlinx | Apache License 2.0 |
src/main/java/com/sayzen/campfiresdk/models/splashs/SplashTagCreate.kt | timas130 | 443,351,244 | true | {"Kotlin": 1939317} | package com.sayzen.campfiresdk.screens.fandoms.tags
import android.view.View
import android.widget.Button
import android.widget.ImageView
import com.dzen.campfire.api.API
import com.dzen.campfire.api.API_RESOURCES
import com.dzen.campfire.api.API_TRANSLATE
import com.dzen.campfire.api.requests.tags.RTagsChange
import com.dzen.campfire.api.requests.tags.RTagsCreate
import com.sayzen.campfiresdk.support.ApiRequestsSupporter
import com.dzen.campfire.api.models.publications.tags.PublicationTag
import com.sayzen.campfiresdk.R
import com.sayzen.campfiresdk.controllers.t
import com.sayzen.campfiresdk.screens.fandoms.STags
import com.sup.dev.android.libs.screens.navigator.Navigator
import com.sup.dev.android.tools.ToolsBitmap
import com.sup.dev.android.libs.image_loader.ImageLoader
import com.sup.dev.android.tools.ToolsToast
import com.sup.dev.android.tools.ToolsView
import com.sup.dev.android.views.screens.SCrop
import com.sup.dev.android.views.settings.SettingsField
import com.sup.dev.android.views.support.watchers.TextWatcherChanged
import com.sup.dev.android.views.splash.Splash
import com.sup.dev.android.views.splash.SplashChooseImage
import com.sup.dev.java.tools.ToolsText
import com.sup.dev.java.tools.ToolsThreads
class SplashTagCreate private constructor(
private val tag: PublicationTag?,
private val parentId: Long,
private val fandomId: Long,
private val languageId: Long
) : Splash(R.layout.splash_tag_create) {
private val vName: SettingsField = findViewById(R.id.vName)
private val vComment: SettingsField = findViewById(R.id.vComment)
private val vEnter: Button = findViewById(R.id.vEnter)
private val vCancel: Button = findViewById(R.id.vCancel)
private val vImage: ImageView = findViewById(R.id.vImage)
private val vImageIcon: View = findViewById(R.id.vImageIcon)
private var removeImage: Boolean = false
private var image: ByteArray? = null
constructor(tag: PublicationTag) : this(tag, tag.parentPublicationId, tag.fandom.id, tag.fandom.languageId) {}
constructor(parentId: Long, fandomId: Long, languageId: Long) : this(null, parentId, fandomId, languageId) {}
init {
vCancel.text = t(API_TRANSLATE.app_cancel)
vEnter.text = t(API_TRANSLATE.app_create)
vComment.setHint(t(API_TRANSLATE.moderation_widget_comment))
vCancel.setOnClickListener { hide() }
vEnter.setOnClickListener { onActionClicked() }
vImage.setOnClickListener { chooseImage() }
vName.setHint(t(API_TRANSLATE.fandom_tags_name))
vName.vField.addTextChangedListener(TextWatcherChanged { updateFinishEnabled() })
vComment.vField.addTextChangedListener(TextWatcherChanged { updateFinishEnabled() })
if (tag != null) {
vName.setText(tag.name)
vEnter.setText(t(API_TRANSLATE.app_change))
if (tag.imageId != 0L) {
ImageLoader.load(tag.imageId).into(vImage)
vImageIcon.visibility = View.GONE
}
}
asSheetShow()
updateFinishEnabled()
}
override fun onShow() {
super.onShow()
// Хак. Не отображается клавиатура при открытии диалога
vComment.showKeyboard()
ToolsThreads.main(200) {
vName.showKeyboard()
}
}
private fun updateFinishEnabled() {
val t = vName.getText()
vEnter.isEnabled = ToolsText.inBounds(t, API.TAG_NAME_MIN_L, API.TAG_NAME_MAX_L) && vComment.getText().isNotEmpty()
}
override fun setEnabled(enabled: Boolean): SplashTagCreate {
super.setEnabled(enabled)
vName.isEnabled = enabled
vEnter.isEnabled = enabled
vCancel.isEnabled = enabled
vComment.isEnabled = enabled
vImage.isEnabled = enabled
return this
}
private fun chooseImage() {
if (image != null || tag != null && tag.imageId != 0L && !removeImage) {
image = null
removeImage = true
vImageIcon.visibility = View.VISIBLE
vImage.setImageBitmap(null)
} else {
removeImage = false
hide()
SplashChooseImage()
.setOnSelectedBitmap { _, b ->
Navigator.to(SCrop(b, API.TAG_IMAGE_SIDE, API.TAG_IMAGE_SIDE) { screen, b2, _, _, _, _ ->
this.image = ToolsBitmap.toBytes(ToolsBitmap.resize(b2, API.TAG_IMAGE_SIDE), API.TAG_IMAGE_WEIGHT)
vImage.setImageBitmap(b2)
vImageIcon.visibility = View.GONE
screen.back()
}
.setAutoBackOnCrop(false)
.setOnHide { ToolsThreads.main(100) { asSheetShow() }}
)
}
.asSheetShow()
}
}
private fun onActionClicked() {
if (tag == null)
sendCreate()
else
sendChange()
}
private fun sendCreate() {
ApiRequestsSupporter.executeEnabled(this, RTagsCreate(vName.getText(), vComment.getText(), fandomId, languageId, parentId, image)
) {
ToolsToast.show(t(API_TRANSLATE.app_done))
STags.instance(fandomId, languageId, Navigator.REPLACE)
}
}
private fun sendChange() {
ApiRequestsSupporter.executeEnabled(this, RTagsChange(tag!!.id, vName.getText(), vComment.getText(), image, removeImage)
) {
ToolsToast.show(t(API_TRANSLATE.app_done))
STags.instance(fandomId, languageId, Navigator.REPLACE)
}
}
}
| 0 | Kotlin | 2 | 0 | 9930e65c1f213bac9266046be22eb937a03f151e | 5,722 | CampfireSDK | Apache License 2.0 |
app/src/espresso/kotlin/xyz/lbres/trickcalculator/ui/calculator/testDataPersisted.kt | lbressler13 | 464,331,572 | false | {"Kotlin": 360254} | package xyz.lbres.trickcalculator.ui.calculator
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import org.hamcrest.Matchers.not
import xyz.lbres.trickcalculator.R
import xyz.lbres.trickcalculator.testutils.clearText
import xyz.lbres.trickcalculator.testutils.closeFragment
import xyz.lbres.trickcalculator.testutils.equals
import xyz.lbres.trickcalculator.testutils.isDisplayedWithText
import xyz.lbres.trickcalculator.testutils.openSettingsFragment
import xyz.lbres.trickcalculator.testutils.textsaver.TextSaver.Companion.saveText
import xyz.lbres.trickcalculator.testutils.textsaver.TextSaver.Companion.withSavedText
import xyz.lbres.trickcalculator.testutils.typeText
import xyz.lbres.trickcalculator.testutils.withAnyText
import xyz.lbres.trickcalculator.testutils.withEmptyString
private val mainText = onView(withId(R.id.mainText))
private val errorText = onView(withId(R.id.errorText))
fun testDataPersistedOnLeave() {
// typed text
leaveAndReturn()
mainText.check(matches(withEmptyString()))
errorText.check(matches(not(isDisplayed())))
clearText()
typeText("1")
leaveAndReturn()
mainText.check(matches(withText("1")))
clearText()
val longText = "1.003(8-9+2)/(1.5)^4"
typeText(longText)
leaveAndReturn()
mainText.check(matches(withText(longText)))
clearText()
typeText("1+2")
leaveAndReturn()
typeText("x4")
leaveAndReturn()
mainText.check(matches(withText(("1+2x4"))))
clearText()
typeText("3+") // would give error
leaveAndReturn()
mainText.check(matches(withText(("3+"))))
// computed value
clearText()
typeText("1.003")
equals()
leaveAndReturn()
mainText.check(matches(withText(("[1.003]"))))
clearText()
typeText("(0000000123)")
equals()
leaveAndReturn()
mainText.check(matches(withText(("[123]"))))
var options = setOf(5, -3, 4, 0.25)
checkComputedValuePersisted("1+4", options)
options = setOf(
3, 22, 3.25, // + = +
1, -18, 0.75, // + = -
14, 6, 2.5, // + = x
4.4, -3.6, 1.6 // + = /
)
checkComputedValuePersisted("2+5-4", options)
options = setOf(
10, -21.5, 11.875, -5, -21.875, -5.75, // + = +
10, 41.5, 8.125, 25, 41.875, 25.75, // + = -
8.875, -9, 1.125, 19, -12.75, 15.25, // + = *
-8, 12, 48, 28, 66, 94 // + = /
)
checkComputedValuePersisted("10-.5x4/2+16", options)
// error
checkErrorPersisted("+", "+", "Error: Syntax error")
clearText()
openSettingsFragment()
onView(withId(R.id.clearOnErrorSwitch)).perform(click())
closeFragment()
checkErrorPersisted("1+1..0", "", "Error: Syntax error")
}
/**
* Test that text in main textview is persisted with a previously computed value
*
* @param text [String]: computation to type
* @param options [Set]<Number>: possible results of computation
*/
private fun checkComputedValuePersisted(text: String, options: Set<Number>) {
clearText()
typeText(text)
equals()
mainText.check(matches(withAnyText(resultsOf(options))))
mainText.perform(saveText())
leaveAndReturn()
mainText.check(matches(withSavedText()))
}
/**
* Test that error message and text in main textview are persisted
*
* @param text [String]: computation to type
* @param textAfterError [String]: value expected in main textview after error
* @param errorMessage [String]: expected error message
*/
private fun checkErrorPersisted(text: String, textAfterError: String, errorMessage: String) {
clearText()
typeText(text)
equals()
mainText.check(matches(withText(textAfterError)))
errorText.check(matches(isDisplayedWithText(errorMessage)))
leaveAndReturn()
mainText.check(matches(withText(textAfterError)))
errorText.check(matches(isDisplayedWithText(errorMessage)))
}
| 0 | Kotlin | 0 | 2 | 5569809d1754159f4b5c6b409f7f93b09f8fcdb6 | 4,274 | trick-calculator | MIT License |
compiler/testData/diagnostics/tests/inference/builderInference/fixingTVForLambadaWithShallowDependencyToOuter3.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | class Controller<T> {
fun yield(t: T): Boolean = true
fun get(): T = TODO()
}
fun <S> generate(g: suspend Controller<S>.() -> Unit): S = TODO()
fun <R> foo(w: R, x: (R) -> R): R = TODO()
fun <Q> materialize(): Q = TODO()
fun bar(x: String) {}
fun main() {
generate {
// S <: String
bar(get())
// R <: S
// R <: String
// R = String
yield(foo(materialize()) { it.length.toString() })
}
generate {
// String <: S
yield("")
// S <: R
// => String <: R
// R = CST(S, String) = String
foo(get()) { it.length.toString() }
}
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 645 | kotlin | Apache License 2.0 |
mvicore-plugin/idea/src/main/java/com/badoo/mvicore/plugin/utils/Display.kt | emreakcan | 287,947,555 | true | {"Kotlin": 172910, "Java": 1704, "Shell": 279} | package com.badoo.mvicore.plugin.utils
import com.badoo.mvicore.plugin.model.ConnectionData
import javax.swing.tree.DefaultMutableTreeNode
import javax.swing.tree.MutableTreeNode
fun ConnectionData.toTreeNode(): MutableTreeNode {
val connectionNode = DefaultMutableTreeNode(this)
from?.shortName?.let {
connectionNode.add(
DefaultMutableTreeNode("from: $it")
)
}
to?.shortName?.let {
connectionNode.add(
DefaultMutableTreeNode("to: $it")
)
}
connectionNode.userObject = this
return connectionNode
}
| 10 | Kotlin | 0 | 2 | b381a0c3684afca743a39808fbc8a2e37a722375 | 587 | MVICore | Apache License 2.0 |
compiler/testData/codegen/box/multifileClasses/samePartNameDifferentFacades.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // TARGET_BACKEND: JVM
// WITH_STDLIB
// FILE: 1/part.kt
@file:JvmName("Foo")
@file:JvmMultifileClass
package test
fun foo(): String = "O"
// FILE: 2/part.kt
@file:JvmName("Bar")
@file:JvmMultifileClass
package test
fun bar(): String = "K"
// FILE: box.kt
package test
fun box(): String = foo() + bar()
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 311 | kotlin | Apache License 2.0 |
app/src/main/java/com/bhm/rtspdemo/rtsp/rtp/packets/AudioPacketCallback.kt | buhuiming | 563,235,995 | false | {"Kotlin": 136967} |
package com.bhm.rtspdemo.rtsp.rtp.packets
import com.bhm.rtspdemo.rtsp.rtsp.RtpFrame
interface AudioPacketCallback {
fun onAudioFrameCreated(rtpFrame: RtpFrame)
} | 0 | Kotlin | 0 | 1 | ebec44981d93b18d201680165f1b576658127fa0 | 166 | RtspDemo | The Unlicense |
idea/testData/quickfix/createFromUsage/createFunction/set/createSetFromUsage2.kt | android | 263,405,600 | true | null | // "Create extension function 'Any.set'" "true"
// WITH_RUNTIME
class Foo<T> {
fun <T> x (y: Any, w: java.util.ArrayList<T>) {
y<caret>["", w] = w
}
}
| 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 168 | kotlin | Apache License 2.0 |
compiler/tests-common-new/tests/org/jetbrains/kotlin/test/builders/DefaultsProviderBuilder.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* 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.test.builders
import org.jetbrains.kotlin.config.ApiVersion
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.config.LanguageVersionSettingsImpl
import org.jetbrains.kotlin.util.PrivateForInline
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.test.TargetBackend
import org.jetbrains.kotlin.test.model.BinaryKind
import org.jetbrains.kotlin.test.services.DefaultsDsl
import org.jetbrains.kotlin.test.services.DefaultsProvider
import org.jetbrains.kotlin.test.model.DependencyKind
import org.jetbrains.kotlin.test.model.FrontendKind
@DefaultsDsl
class DefaultsProviderBuilder {
lateinit var frontend: FrontendKind<*>
var targetBackend: TargetBackend? = null
lateinit var targetPlatform: TargetPlatform
var artifactKind: BinaryKind<*>? = null
lateinit var dependencyKind: DependencyKind
@PrivateForInline
var languageVersionSettings: LanguageVersionSettings? = null
@PrivateForInline
var languageVersionSettingsBuilder: LanguageVersionSettingsBuilder? = null
@OptIn(PrivateForInline::class)
inline fun languageSettings(init: LanguageVersionSettingsBuilder.() -> Unit) {
languageVersionSettings = LanguageVersionSettingsBuilder().apply(init).also {
languageVersionSettingsBuilder = it
}.build()
}
@OptIn(PrivateForInline::class)
fun build(): DefaultsProvider {
return DefaultsProvider(
frontend,
languageVersionSettings ?: LanguageVersionSettingsImpl(LanguageVersion.LATEST_STABLE, ApiVersion.LATEST_STABLE),
languageVersionSettingsBuilder ?: LanguageVersionSettingsBuilder(),
targetPlatform,
artifactKind,
targetBackend,
dependencyKind
)
}
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 2,092 | kotlin | Apache License 2.0 |
Android/app/src/main/java/com/fungarium/gdziejestkuku/FolloweeMarker.kt | mgrzyb | 730,359,404 | false | {"Kotlin": 45416, "TypeScript": 8454} | package com.fungarium.gdziejestkuku
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import com.google.android.gms.maps.model.LatLng
import java.time.Instant
class FolloweeMarker(val followee: Followee, position: LatLng, timestamp: Instant) {
private val _position : MutableState<LatLng>
val position : LatLng
get() = _position.value
private val _timestamp : MutableState<Instant>
val timestamp : Instant
get() = _timestamp.value
init {
_position = mutableStateOf(position)
_timestamp = mutableStateOf(timestamp)
}
fun updatePosition(position: LatLng, timestamp: Instant) {
_position.value = position
_timestamp.value = timestamp
}
} | 0 | Kotlin | 0 | 0 | 9513882205a952f4a786f36f787e9cce9ca61079 | 763 | GdzieJestKuKu | MIT License |
compiler/fir/tree/gen/org/jetbrains/kotlin/fir/expressions/impl/FirWhenSubjectExpressionImpl.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2024 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.
*/
// This file was generated automatically. See compiler/fir/tree/tree-generator/Readme.md.
// DO NOT MODIFY IT MANUALLY.
@file:Suppress("DuplicatedCode", "unused")
package org.jetbrains.kotlin.fir.expressions.impl
import org.jetbrains.kotlin.KtSourceElement
import org.jetbrains.kotlin.fir.FirExpressionRef
import org.jetbrains.kotlin.fir.MutableOrEmptyList
import org.jetbrains.kotlin.fir.builder.toMutableOrEmpty
import org.jetbrains.kotlin.fir.expressions.FirAnnotation
import org.jetbrains.kotlin.fir.expressions.FirWhenExpression
import org.jetbrains.kotlin.fir.expressions.FirWhenSubjectExpression
import org.jetbrains.kotlin.fir.expressions.UnresolvedExpressionTypeAccess
import org.jetbrains.kotlin.fir.types.ConeKotlinType
import org.jetbrains.kotlin.fir.types.constructClassLikeType
import org.jetbrains.kotlin.fir.visitors.FirTransformer
import org.jetbrains.kotlin.fir.visitors.FirVisitor
import org.jetbrains.kotlin.fir.visitors.transformInplace
import org.jetbrains.kotlin.name.StandardClassIds
internal class FirWhenSubjectExpressionImpl(
override val source: KtSourceElement?,
override var annotations: MutableOrEmptyList<FirAnnotation>,
override val whenRef: FirExpressionRef<FirWhenExpression>,
) : FirWhenSubjectExpression() {
@OptIn(UnresolvedExpressionTypeAccess::class)
override val coneTypeOrNull: ConeKotlinType?
get() = whenRef.value.subject?.coneTypeOrNull ?: StandardClassIds.Unit.constructClassLikeType()
override fun <R, D> acceptChildren(visitor: FirVisitor<R, D>, data: D) {
annotations.forEach { it.accept(visitor, data) }
}
override fun <D> transformChildren(transformer: FirTransformer<D>, data: D): FirWhenSubjectExpressionImpl {
transformAnnotations(transformer, data)
return this
}
override fun <D> transformAnnotations(transformer: FirTransformer<D>, data: D): FirWhenSubjectExpressionImpl {
annotations.transformInplace(transformer, data)
return this
}
override fun replaceConeTypeOrNull(newConeTypeOrNull: ConeKotlinType?) {}
override fun replaceAnnotations(newAnnotations: List<FirAnnotation>) {
annotations = newAnnotations.toMutableOrEmpty()
}
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 2,419 | kotlin | Apache License 2.0 |
api/src/main/kotlin/dev/gleroy/ivanachess/api/security/RoleGrantedAuthority.kt | leroyguillaume | 378,921,142 | false | null | package dev.gleroy.ivanachess.api.security
import dev.gleroy.ivanachess.core.User
import org.springframework.security.core.GrantedAuthority
/**
* Role implementation of granted authority.
*
* @param role Role.
*/
data class RoleGrantedAuthority(
val role: User.Role
) : GrantedAuthority {
override fun getAuthority() = when (role) {
User.Role.Simple -> "simple"
User.Role.Admin -> "admin"
User.Role.SuperAdmin -> "super_admin"
}
}
| 0 | Kotlin | 1 | 0 | 6e6b8da2b5b84fc2ad946ddd7899c35904974a87 | 473 | ivana-chess | Apache License 2.0 |
app/src/main/java/com/waseem/libroom/feature/auth/data/AuthRepositoryImpl.kt | waseemabbas8 | 629,653,320 | false | {"Kotlin": 167882} | package com.waseem.libroom.feature.auth.data
import com.google.firebase.auth.FirebaseAuth
import com.waseem.libroom.feature.auth.domain.AuthRepository
import com.waseem.libroom.feature.auth.domain.User
import kotlinx.coroutines.tasks.await
import javax.inject.Inject
class AuthRepositoryImpl @Inject constructor(
private val firebaseAuth: FirebaseAuth
) : AuthRepository {
override suspend fun signIn(email: String, password: String): Result<User> {
val authResult = firebaseAuth.signInWithEmailAndPassword(email, password).await()
authResult.user?.let {firebaseUser ->
return Result.success(
User(
id = firebaseUser.uid,
email = firebaseUser.email ?: "invalid email",
name = firebaseUser.displayName
)
)
} ?: run {
return Result.failure(Exception("User not found"))
}
}
override suspend fun signOut(): Result<Boolean> {
firebaseAuth.signOut()
return Result.success(true)
}
} | 0 | Kotlin | 6 | 23 | 92387428329ea06d093a12f4749f92b28851058e | 1,074 | libroom-android | MIT License |
compiler/testData/codegen/box/functions/typeParametersInLocalFunction.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} |
class Holder<T: Any>(val v: T)
fun <C: Any> outer(arg: C): C {
fun <HC: Holder<C>> inner1(hh: HC): C {
fun inner2() = hh.v // two type parameters: C and HC
return inner2()
}
return inner1(Holder(arg))
}
fun box(): String = outer("OK")
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 266 | kotlin | Apache License 2.0 |
simplecloud-base/src/main/kotlin/eu/thesimplecloud/base/manager/network/packets/player/PacketOutGetPlayerOnlineStatus.kt | theSimpleCloud | 270,085,977 | false | {"Kotlin": 2004142, "Java": 4872, "Shell": 1302, "Batchfile": 156} | /*
* MIT License
*
* Copyright (C) 2020-2022 The SimpleCloud authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package eu.thesimplecloud.base.manager.network.packets.player
import eu.thesimplecloud.clientserverapi.lib.connection.IConnection
import eu.thesimplecloud.clientserverapi.lib.packet.packettype.ObjectPacket
import eu.thesimplecloud.clientserverapi.lib.promise.ICommunicationPromise
import java.util.*
/**
* Created by IntelliJ IDEA.
* User: Philipp.Eistrach
* Date: 10.04.2020
* Time: 21:28
*/
class PacketOutGetPlayerOnlineStatus() : ObjectPacket<UUID>() {
constructor(uuid: UUID) : this() {
this.value = uuid
}
override suspend fun handle(connection: IConnection): ICommunicationPromise<Any> {
return unit()
}
} | 11 | Kotlin | 47 | 101 | d8ad6e6f627b1ad80034dfb9c97393dd47905825 | 1,800 | SimpleCloud | MIT License |
compiler/testData/diagnostics/tests/declarationChecks/mulitpleVarargParameters.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // FIR_IDENTICAL
// !DIAGNOSTICS: -UNUSED_PARAMETER -PRIMARY_CONSTRUCTOR_DELEGATION_CALL_EXPECTED
fun test(<!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x1: Int, <!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x2: Int) {
fun test2(<!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x1: Int, <!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x2: Int) {
class LocalClass(<!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x1: Int, <!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x2: Int) {
constructor(<!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x1: Int, <!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x2: Int, xx: Int) {}
}
fun test3(<!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x1: Int, <!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x2: Int) {}
}
}
fun Any.test(<!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x1: Int, <!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x2: Int, <!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x3: Int) {}
interface I {
fun test(<!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x1: Int, <!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x2: Int)
}
abstract class C(<!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x1: Int, <!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x2: Int, b: Boolean) {
fun test(<!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x1: Int, <!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x2: Int) {}
abstract fun test2(<!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x1: Int, <!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x2: Int)
class CC(<!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x1: Int, <!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x2: Int, b: Boolean) {
constructor(<!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x1: Int, <!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x2: Int) {}
fun test(<!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x1: Int, <!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x2: Int) {}
}
}
object O {
fun test(<!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x1: Int, <!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x2: Int) {}
class CC(<!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x1: Int, <!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x2: Int, b: Boolean) {
constructor(<!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x1: Int, <!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x2: Int) {}
fun test(<!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x1: Int, <!MULTIPLE_VARARG_PARAMETERS!>vararg<!> x2: Int) {}
}
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 2,239 | kotlin | Apache License 2.0 |
src/main/kotlin/cat/kiwi/minecraft/etcdchat/Application.kt | Agenda-Minecraft | 432,429,341 | false | {"Kotlin": 8236} | package cat.kiwi.minecraft.etcdchat
import cat.kiwi.minecraft.etcdchat.model.*
import cat.kiwi.minecraft.etcdchat.util.applyFormatCode
import cat.kiwi.minecraft.etcdchat.util.toMessage
class Application {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val msgJson1 = "&fpri".applyFormatCode().tagPrivate("s","t").toJson()
val msgJson2 = "&fpub".applyFormatCode().tagPublic().toJson()
println(msgJson1)
println(msgJson2)
val umJson1 = msgJson1.toMessage()
val umJson2 = msgJson2.toMessage()
when(umJson1.type) {
"public" -> println("PrivateMessage: $umJson1")
"private" -> println("PublicMessage $umJson1")
}
when(umJson2.type) {
"public" -> println("PrivateMessage: $umJson2 ")
"private" -> println("PublicMessage $umJson2")
}
// val client: Client = Client.builder().target("ip:///127.0.0.1:12379").build()
// val kvClient = client.kvClient
// println(msg)
// kvClient.put("foo".toByteSequence(),"bar".toByteSequence())
// println(kvClient.get("foo".toByteSequence()).get())
}
}
} | 0 | Kotlin | 0 | 0 | 140077bedbcf33fc5c2560d22c56ef7dc0c97224 | 1,279 | EtcdChat | MIT License |
app/src/main/java/avinash/Kumar/bigRun/MainActivity.kt | aviavinashkr | 278,115,911 | false | null | package avinash.Kumar.bigRun
import android.content.Intent
import android.content.res.Configuration
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
import kotlin.collections.ArrayList
class MainActivity : AppCompatActivity() {
var score: Int = 0
var imageViewArray = ArrayList<ImageView>()
var gamehandler: Handler = Handler()
var runnable: Runnable = Runnable { }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
score = 0
imageViewArray = arrayListOf(
imageView1,
imageView2,
imageView3,
imageView4,
imageView5,
imageView6,
imageView7,
imageView8,
imageView9
)
ImageHide()
object : CountDownTimer(30000, 1000) {
override fun onFinish() {
TimeTxt.text = "Time Over"
gamehandler.removeCallbacks(runnable)
for (image in imageViewArray) {
image.visibility = View.INVISIBLE
retryBtn.visibility = View.VISIBLE
}
}
override fun onTick(millisUntilFinished: Long) {
TimeTxt.text = "Time: " + millisUntilFinished / 1000
}
}.start()
backBtn.setOnClickListener {
val intent = Intent(this,MainScreen::class.java)
startActivity(intent)
}
retryBtn.setOnClickListener {
val intent = Intent(this,MainActivity::class.java)
startActivity(intent)
}
}
fun ImageHide() {
runnable = object : Runnable {
override fun run() {
for (image in imageViewArray) {
image.visibility = View.INVISIBLE
}
val random = Random()
val index = random.nextInt(8 - 0)
imageViewArray[index].visibility = View.VISIBLE
gamehandler.postDelayed(runnable, 450)
}
}
gamehandler.post(runnable)
}
fun ScoreIncrease(view:View) {
score++
ScoreTxt.text = "Score:" + score
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
if (newConfig.orientation === Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show()
} else if (newConfig.orientation === Configuration.ORIENTATION_PORTRAIT) {
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show()
}
}
} | 0 | Kotlin | 0 | 0 | 0d674932f4924385234a00a9778c58505eb9018c | 2,982 | BigRun | The Unlicense |
sphinx/activity/main/activitymain/src/main/java/chat/sphinx/activitymain/navigation/navigators/primary/DashboardBottomNavBarNavigatorImpl.kt | stakwork | 340,103,148 | false | {"Kotlin": 4002503, "Java": 403469, "JavaScript": 4745, "HTML": 4706, "Shell": 2453} | package chat.sphinx.activitymain.navigation.navigators.primary
import chat.sphinx.activitymain.navigation.drivers.DetailNavigationDriver
import chat.sphinx.dashboard.navigation.DashboardBottomNavBarNavigator
import chat.sphinx.payment_receive.navigation.ToPaymentReceiveDetail
import chat.sphinx.payment_send.navigation.ToPaymentSendDetail
import chat.sphinx.transactions.navigation.ToTransactionsDetail
import chat.sphinx.wrapper_common.dashboard.ContactId
import chat.sphinx.wrapper_common.lightning.LightningNodePubKey
import chat.sphinx.wrapper_common.lightning.LightningRouteHint
import javax.inject.Inject
internal class DashboardBottomNavBarNavigatorImpl @Inject constructor(
navigationDriver: DetailNavigationDriver
): DashboardBottomNavBarNavigator(navigationDriver)
{
override suspend fun toTransactionsDetail() {
navigationDriver.submitNavigationRequest(ToTransactionsDetail())
}
override suspend fun toPaymentReceiveDetail() {
navigationDriver.submitNavigationRequest(ToPaymentReceiveDetail())
}
override suspend fun toPaymentSendDetail(lightningNodePubKey: LightningNodePubKey?, routeHint: LightningRouteHint?, contactId: ContactId?) {
navigationDriver.submitNavigationRequest(ToPaymentSendDetail(lightningNodePubKey = lightningNodePubKey, routeHint = routeHint, contactId = contactId))
}
}
| 96 | Kotlin | 8 | 18 | 4fd9556a4a34f14126681535558fe1e39747b323 | 1,360 | sphinx-kotlin | MIT License |
libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/plugin/ide/IdeMultiplatformImportImpl.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.gradle.plugin.ide
import org.jetbrains.kotlin.gradle.dsl.KotlinProjectExtension
import org.jetbrains.kotlin.gradle.idea.proto.tcs.toByteArray
import org.jetbrains.kotlin.gradle.idea.proto.toByteArray
import org.jetbrains.kotlin.gradle.idea.serialize.IdeaKotlinExtrasSerializationExtension
import org.jetbrains.kotlin.gradle.idea.serialize.IdeaKotlinSerializationContext
import org.jetbrains.kotlin.gradle.idea.tcs.IdeaKotlinDependency
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet
import org.jetbrains.kotlin.gradle.plugin.ide.IdeDependencyResolver.Companion.resolvedBy
import org.jetbrains.kotlin.gradle.plugin.ide.IdeMultiplatformImport.*
import org.jetbrains.kotlin.gradle.plugin.ide.IdeMultiplatformImport.AdditionalArtifactResolutionPhase.SourcesAndDocumentationResolution
import org.jetbrains.kotlin.gradle.plugin.ide.IdeMultiplatformImport.Companion.logger
import org.jetbrains.kotlin.tooling.core.Extras
import org.jetbrains.kotlin.tooling.core.HasMutableExtras
import org.jetbrains.kotlin.utils.addToStdlib.measureTimeMillisWithResult
import kotlin.system.measureTimeMillis
internal class IdeMultiplatformImportImpl(
private val extension: KotlinProjectExtension,
) : IdeMultiplatformImport {
override fun resolveDependencies(sourceSetName: String): Set<IdeaKotlinDependency> {
return resolveDependencies(extension.sourceSets.getByName(sourceSetName))
}
override fun resolveDependencies(sourceSet: KotlinSourceSet): Set<IdeaKotlinDependency> {
return createDependencyResolver().resolve(sourceSet)
}
override fun resolveDependenciesSerialized(sourceSetName: String): List<ByteArray> {
return serialize(resolveDependencies(sourceSetName))
}
override fun resolveExtrasSerialized(owner: Any): ByteArray? {
if (owner !is HasMutableExtras) return null
return owner.extras.toByteArray(createSerializationContext())
}
override fun serialize(dependencies: Iterable<IdeaKotlinDependency>): List<ByteArray> {
val context = createSerializationContext()
return dependencies.map { dependency -> dependency.toByteArray(context) }
}
override fun <T : Any> serialize(key: Extras.Key<T>, value: T): ByteArray? {
val context = createSerializationContext()
return context.extrasSerializationExtension.serializer(key)?.serialize(context, value)
}
private val registeredDependencyResolvers = mutableListOf<RegisteredDependencyResolver>()
private val registeredAdditionalArtifactResolvers = mutableListOf<RegisteredAdditionalArtifactResolver>()
private val registeredDependencyTransformers = mutableListOf<RegisteredDependencyTransformer>()
private val registeredDependencyEffects = mutableListOf<RegisteredDependencyEffect>()
private val registeredExtrasSerializationExtensions = mutableListOf<IdeaKotlinExtrasSerializationExtension>()
/**
* System property passed down by the IDE, reflecting the users setting of 'Download sources during sync'
* This property is expected to be present in IDEs > 23.3
* If 'true' the import is instructed to download all sources.jar eagerly.
* If 'false' the import is instructed to not download any sources.jar
*/
private val ideaGradleDownloadSourcesProperty =
extension.project.providers.systemProperty("idea.gradle.download.sources")
/**
* As of right now (08.2023), IntelliJ does not fully support lazy downloading of sources of knm files.
* To prevent user confusion, we do not support the 'idea.gradle.download.sources' by default.
* This property is internal and for testing of this component only.
*/
private val ideaGradleDownloadSourcesEnabledProperty =
extension.project.providers.gradleProperty("kotlin.mpp.idea.gradle.download.sources.enabled")
@OptIn(Idea222Api::class)
override fun registerDependencyResolver(
resolver: IdeDependencyResolver,
constraint: SourceSetConstraint,
phase: DependencyResolutionPhase,
priority: Priority,
) {
registeredDependencyResolvers.add(
RegisteredDependencyResolver(extension.project.kotlinIdeMultiplatformImportStatistics, resolver, constraint, phase, priority)
)
if (resolver is IdeDependencyResolver.WithBuildDependencies) {
val project = extension.project
val dependencies = project.provider { resolver.dependencies(project) }
extension.project.locateOrRegisterIdeResolveDependenciesTask().configure { it.dependsOn(dependencies) }
extension.project.prepareKotlinIdeaImportTask.configure { it.dependsOn(dependencies) }
}
}
override fun registerDependencyTransformer(
transformer: IdeDependencyTransformer,
constraint: SourceSetConstraint,
phase: DependencyTransformationPhase,
) {
registeredDependencyTransformers.add(
RegisteredDependencyTransformer(transformer, constraint, phase)
)
}
override fun registerAdditionalArtifactResolver(
resolver: IdeAdditionalArtifactResolver,
constraint: SourceSetConstraint,
phase: AdditionalArtifactResolutionPhase,
priority: Priority,
) {
registeredAdditionalArtifactResolvers.add(
RegisteredAdditionalArtifactResolver(
extension.project.kotlinIdeMultiplatformImportStatistics, resolver, constraint, phase, priority
)
)
}
override fun registerDependencyEffect(effect: IdeDependencyEffect, constraint: SourceSetConstraint) {
registeredDependencyEffects.add(
RegisteredDependencyEffect(effect, constraint)
)
}
override fun registerExtrasSerializationExtension(extension: IdeaKotlinExtrasSerializationExtension) {
registeredExtrasSerializationExtensions.add(extension)
}
override fun registerImportAction(action: IdeMultiplatformImportAction) {
IdeMultiplatformImportAction.extensionPoint.register(extension.project, action)
}
private fun createDependencyResolver(): IdeDependencyResolver {
return IdeDependencyResolver(
DependencyResolutionPhase.values().map { phase -> createDependencyResolver(phase) }
)
.withAdditionalArtifactResolver(createAdditionalArtifactsResolver())
.withTransformer(createDependencyTransformer())
.withEffect(createDependencyEffect())
}
private fun createDependencyResolver(phase: DependencyResolutionPhase) = IdeDependencyResolver resolve@{ sourceSet ->
val applicableResolvers = registeredDependencyResolvers
.filter { it.phase == phase }
.filter { it.constraint(sourceSet) }
.groupBy { it.priority }
/* Find resolvers in the highest resolution level and only consider those */
applicableResolvers.keys.sortedDescending().forEach { priority ->
val resolvers = applicableResolvers[priority].orEmpty()
if (resolvers.isNotEmpty()) {
return@resolve IdeDependencyResolver(resolvers).resolve(sourceSet)
}
}
/* No resolvers found */
emptySet()
}
private fun createAdditionalArtifactsResolver() = IdeAdditionalArtifactResolver(
AdditionalArtifactResolutionPhase.values().map { phase -> createAdditionalArtifactsResolver(phase) })
private fun createAdditionalArtifactsResolver(phase: AdditionalArtifactResolutionPhase): IdeAdditionalArtifactResolver {
/*
Skip resolving sources if IDE instructs us to (ideaGradleDownloadSourcesProperty is passed by the IDE, reflecting user settings)
*/
if (phase == SourcesAndDocumentationResolution &&
ideaGradleDownloadSourcesEnabledProperty.orNull?.toBoolean() == true &&
ideaGradleDownloadSourcesProperty.orNull?.toBoolean() == false
) {
return IdeAdditionalArtifactResolver.empty
}
return IdeAdditionalArtifactResolver resolve@{ sourceSet, dependencies ->
val applicableResolvers = registeredAdditionalArtifactResolvers
.filter { it.phase == phase }
.filter { it.constraint(sourceSet) }
.groupBy { it.priority }
applicableResolvers.keys.sortedDescending().forEach { priority ->
val resolvers = applicableResolvers[priority].orEmpty()
if (resolvers.isNotEmpty()) {
resolvers.forEach { resolver -> resolver.resolve(sourceSet, dependencies) }
return@resolve
}
}
}
}
private fun createDependencyTransformer(): IdeDependencyTransformer {
return IdeDependencyTransformer(DependencyTransformationPhase.values().map { phase ->
createDependencyTransformer(phase)
})
}
private fun createDependencyTransformer(phase: DependencyTransformationPhase): IdeDependencyTransformer {
return IdeDependencyTransformer { sourceSet, dependencies ->
IdeDependencyTransformer(
registeredDependencyTransformers
.filter { it.phase == phase }
.filter { it.constraint(sourceSet) }
.map { it.transformer }
).transform(sourceSet, dependencies)
}
}
private fun createDependencyEffect(): IdeDependencyEffect = IdeDependencyEffect { sourceSet, dependencies ->
registeredDependencyEffects
.filter { it.constraint(sourceSet) }
.forEach { it.effect(sourceSet, dependencies) }
}
private fun createSerializationContext(): IdeaKotlinSerializationContext {
return IdeaKotlinSerializationContext(
logger = extension.project.logger,
extrasSerializationExtensions = registeredExtrasSerializationExtensions.toList()
)
}
private data class RegisteredDependencyTransformer(
val transformer: IdeDependencyTransformer,
val constraint: SourceSetConstraint,
val phase: DependencyTransformationPhase,
)
private data class RegisteredDependencyEffect(
val effect: IdeDependencyEffect,
val constraint: SourceSetConstraint,
)
private data class RegisteredDependencyResolver(
private val statistics: IdeMultiplatformImportStatistics,
private val resolver: IdeDependencyResolver,
val constraint: SourceSetConstraint,
val phase: DependencyResolutionPhase,
val priority: Priority,
) : IdeDependencyResolver {
private class TimeMeasuredResult(val timeInMillis: Long, val dependencies: Set<IdeaKotlinDependency>)
override fun resolve(sourceSet: KotlinSourceSet): Set<IdeaKotlinDependency> {
return runCatching { resolveTimed(sourceSet) }
.onFailure { error -> reportError(sourceSet, error) }
.onSuccess { result -> reportSuccess(sourceSet, result) }
.onSuccess { result -> attachResolvedByExtra(result.dependencies) }
.getOrNull()?.dependencies.orEmpty()
}
private fun resolveTimed(sourceSet: KotlinSourceSet): TimeMeasuredResult {
val (time, result) = measureTimeMillisWithResult { resolver.resolve(sourceSet) }
statistics.addExecutionTime(resolver::class.java, time)
return TimeMeasuredResult(time, result)
}
private fun reportError(sourceSet: KotlinSourceSet, error: Throwable) {
logger.error("e: ${resolver::class.java.name} failed on ${IdeaKotlinSourceCoordinates(sourceSet)}", error)
}
private fun reportSuccess(sourceSet: KotlinSourceSet, result: TimeMeasuredResult) {
if (!logger.isDebugEnabled) return
logger.debug(
"${resolver::class.java.name} resolved on ${IdeaKotlinSourceCoordinates(sourceSet)}: " +
"${result.dependencies} (${result.timeInMillis} ms)"
)
}
private fun attachResolvedByExtra(dependencies: Iterable<IdeaKotlinDependency>) {
dependencies.forEach { dependency ->
if (dependency.resolvedBy == null) dependency.resolvedBy = resolver
}
}
}
private class RegisteredAdditionalArtifactResolver(
private val statistics: IdeMultiplatformImportStatistics,
private val resolver: IdeAdditionalArtifactResolver,
val constraint: SourceSetConstraint,
val phase: AdditionalArtifactResolutionPhase,
val priority: Priority,
) : IdeAdditionalArtifactResolver {
override fun resolve(sourceSet: KotlinSourceSet, dependencies: Set<IdeaKotlinDependency>) {
runCatching { measureTimeMillis { resolver.resolve(sourceSet, dependencies) } }
.onFailure { logger.error("e: ${resolver::class.java.name} failed on ${IdeaKotlinSourceCoordinates(sourceSet)}", it) }
.onSuccess { statistics.addExecutionTime(resolver::class.java, it) }
}
}
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 13,328 | kotlin | Apache License 2.0 |
core-models/src/main/java/com/anytypeio/anytype/core_models/NetworkModeConstants.kt | anyproto | 647,371,233 | false | {"Kotlin": 9971954, "Java": 69306, "Shell": 11126, "Makefile": 1276} | package com.anytypeio.anytype.core_models
object NetworkModeConstants {
const val NETWORK_MODE_LOCAL = "local"
const val NETWORK_MODE_DEFAULT = "default"
const val NETWORK_MODE_CUSTOM = "custom"
} | 33 | Kotlin | 26 | 301 | 8b3b7dacae68c015fb8b1b7c9cc76e53f0706430 | 209 | anytype-kotlin | RSA Message-Digest License |
paymentsheet/src/main/java/com/stripe/android/paymentsheet/injection/PaymentSheetLauncherComponent.kt | vlad-roid | 283,964,949 | true | {"Kotlin": 7742919, "Java": 67407, "Shell": 18256, "Python": 13146, "Ruby": 5171} | package com.stripe.android.paymentsheet.injection
import android.content.Context
import com.stripe.android.core.injection.CoreCommonModule
import com.stripe.android.core.injection.CoroutineContextModule
import com.stripe.android.core.injection.Injectable
import com.stripe.android.core.injection.NonFallbackInjector
import com.stripe.android.payments.core.injection.PRODUCT_USAGE
import com.stripe.android.payments.core.injection.StripeRepositoryModule
import com.stripe.android.paymentsheet.PaymentOptionsViewModel
import com.stripe.android.paymentsheet.forms.FormViewModel
import com.stripe.android.ui.core.forms.resources.injection.ResourceRepositoryModule
import dagger.BindsInstance
import dagger.Component
import javax.inject.Named
import javax.inject.Singleton
@Singleton
@Component(
modules = [
StripeRepositoryModule::class,
PaymentSheetCommonModule::class,
PaymentOptionsViewModelModule::class,
CoroutineContextModule::class,
CoreCommonModule::class,
ResourceRepositoryModule::class
]
)
internal abstract class PaymentOptionsViewModelFactoryComponent : NonFallbackInjector {
abstract fun inject(factory: PaymentOptionsViewModel.Factory)
abstract fun inject(factory: FormViewModel.Factory)
override fun inject(injectable: Injectable<*>) {
when (injectable) {
is PaymentOptionsViewModel.Factory -> inject(injectable)
is FormViewModel.Factory -> inject(injectable)
else -> {
throw IllegalArgumentException("invalid Injectable $injectable requested in $this")
}
}
}
@Component.Builder
interface Builder {
@BindsInstance
fun context(context: Context): Builder
@BindsInstance
fun productUsage(@Named(PRODUCT_USAGE) productUsage: Set<String>): Builder
fun build(): PaymentOptionsViewModelFactoryComponent
}
}
| 5 | Kotlin | 0 | 1 | b3086c08a51dcc95408359537892711121601749 | 1,922 | stripe-android | MIT License |
libraries/stdlib/coroutines-experimental/jvm/test/CoroutineContextTest.kt | android | 263,405,600 | true | null | /*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package test.coroutines
import kotlin.test.*
import kotlin.coroutines.experimental.*
class CoroutineContextTest {
data class CtxA(val i: Int) : AbstractCoroutineContextElement(CtxA) {
companion object Key : CoroutineContext.Key<CtxA>
}
data class CtxB(val i: Int) : AbstractCoroutineContextElement(CtxB) {
companion object Key : CoroutineContext.Key<CtxB>
}
data class CtxC(val i: Int) : AbstractCoroutineContextElement(CtxC) {
companion object Key : CoroutineContext.Key<CtxC>
}
object Disp1 : AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor {
override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> = continuation
override fun toString(): String = "Disp1"
}
object Disp2 : AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor {
override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> = continuation
override fun toString(): String = "Disp2"
}
@Test
fun testGetPlusFold() {
var ctx: CoroutineContext = EmptyCoroutineContext
assertContents(ctx)
assertEquals("EmptyCoroutineContext", ctx.toString())
ctx += CtxA(1)
assertContents(ctx, CtxA(1))
assertEquals("CtxA(i=1)", ctx.toString())
assertEquals(CtxA(1), ctx[CtxA])
assertEquals(null, ctx[CtxB])
assertEquals(null, ctx[CtxC])
ctx += CtxB(2)
assertContents(ctx, CtxA(1), CtxB(2))
assertEquals("[CtxA(i=1), CtxB(i=2)]", ctx.toString())
assertEquals(CtxA(1), ctx[CtxA])
assertEquals(CtxB(2), ctx[CtxB])
assertEquals(null, ctx[CtxC])
ctx += CtxC(3)
assertContents(ctx, CtxA(1), CtxB(2), CtxC(3))
assertEquals("[CtxA(i=1), CtxB(i=2), CtxC(i=3)]", ctx.toString())
assertEquals(CtxA(1), ctx[CtxA])
assertEquals(CtxB(2), ctx[CtxB])
assertEquals(CtxC(3), ctx[CtxC])
ctx += CtxB(4)
assertContents(ctx, CtxA(1), CtxC(3), CtxB(4))
assertEquals("[CtxA(i=1), CtxC(i=3), CtxB(i=4)]", ctx.toString())
assertEquals(CtxA(1), ctx[CtxA])
assertEquals(CtxB(4), ctx[CtxB])
assertEquals(CtxC(3), ctx[CtxC])
ctx += CtxA(5)
assertContents(ctx, CtxC(3), CtxB(4), CtxA(5))
assertEquals("[CtxC(i=3), CtxB(i=4), CtxA(i=5)]", ctx.toString())
assertEquals(CtxA(5), ctx[CtxA])
assertEquals(CtxB(4), ctx[CtxB])
assertEquals(CtxC(3), ctx[CtxC])
}
@Test
fun testMinusKey() {
var ctx: CoroutineContext = CtxA(1) + CtxB(2) + CtxC(3)
assertContents(ctx, CtxA(1), CtxB(2), CtxC(3))
assertEquals("[CtxA(i=1), CtxB(i=2), CtxC(i=3)]", ctx.toString())
ctx = ctx.minusKey(CtxA)
assertContents(ctx, CtxB(2), CtxC(3))
assertEquals("[CtxB(i=2), CtxC(i=3)]", ctx.toString())
assertEquals(null, ctx[CtxA])
assertEquals(CtxB(2), ctx[CtxB])
assertEquals(CtxC(3), ctx[CtxC])
ctx = ctx.minusKey(CtxC)
assertContents(ctx, CtxB(2))
assertEquals("CtxB(i=2)", ctx.toString())
assertEquals(null, ctx[CtxA])
assertEquals(CtxB(2), ctx[CtxB])
assertEquals(null, ctx[CtxC])
ctx = ctx.minusKey(CtxC)
assertContents(ctx, CtxB(2))
assertEquals("CtxB(i=2)", ctx.toString())
assertEquals(null, ctx[CtxA])
assertEquals(CtxB(2), ctx[CtxB])
assertEquals(null, ctx[CtxC])
ctx = ctx.minusKey(CtxB)
assertContents(ctx)
assertEquals("EmptyCoroutineContext", ctx.toString())
assertEquals(null, ctx[CtxA])
assertEquals(null, ctx[CtxB])
assertEquals(null, ctx[CtxC])
assertEquals(EmptyCoroutineContext, ctx)
}
@Test
fun testPlusCombined() {
val ctx1 = CtxA(1) + CtxB(2)
val ctx2 = CtxB(3) + CtxC(4)
val ctx = ctx1 + ctx2
assertContents(ctx, CtxA(1), CtxB(3), CtxC(4))
assertEquals("[CtxA(i=1), CtxB(i=3), CtxC(i=4)]", ctx.toString())
assertEquals(CtxA(1), ctx[CtxA])
assertEquals(CtxB(3), ctx[CtxB])
assertEquals(CtxC(4), ctx[CtxC])
}
@Test
fun testLastDispatcher() {
var ctx: CoroutineContext = EmptyCoroutineContext
assertContents(ctx)
ctx += CtxA(1)
assertContents(ctx, CtxA(1))
ctx += Disp1
assertContents(ctx, CtxA(1), Disp1)
ctx += CtxA(2)
assertContents(ctx, CtxA(2), Disp1)
ctx += CtxB(3)
assertContents(ctx, CtxA(2), CtxB(3), Disp1)
ctx += Disp2
assertContents(ctx, CtxA(2), CtxB(3), Disp2)
ctx += (CtxB(4) + CtxC(5))
assertContents(ctx, CtxA(2), CtxB(4), CtxC(5), Disp2)
}
@Test
fun testEquals() {
val ctx1 = CtxA(1) + CtxB(2) + CtxC(3)
val ctx2 = CtxB(2) + CtxC(3) + CtxA(1) // same
val ctx3 = CtxC(3) + CtxA(1) + CtxB(2) // same
val ctx4 = CtxA(1) + CtxB(2) + CtxC(4) // different
assertEquals(ctx1, ctx2)
assertEquals(ctx1, ctx3)
assertEquals(ctx2, ctx3)
assertNotEquals(ctx1, ctx4)
assertNotEquals(ctx2, ctx4)
assertNotEquals(ctx3, ctx4)
}
private fun assertContents(ctx: CoroutineContext, vararg elements: CoroutineContext.Element) {
val set = ctx.fold(setOf<CoroutineContext>()) { a, b -> a + b }
assertEquals(listOf(*elements), set.toList())
for (elem in elements)
assertTrue(ctx[elem.key] == elem)
}
}
| 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 5,796 | kotlin | Apache License 2.0 |
src/main/kotlin/com/grpc/client/ClientLauncher.kt | TitoGrine | 348,773,661 | false | null | @file:JvmName("ClientLauncher")
package com.grpc.client
import io.grpc.ManagedChannelBuilder
import kotlinx.coroutines.asCoroutineDispatcher
import java.util.concurrent.Executors
fun main(args: Array<String>) {
Executors.newCachedThreadPool().asCoroutineDispatcher().use { dispatcher ->
GRPCClient(
ManagedChannelBuilder.forAddress(args[0], args[1].toInt()).usePlaintext(), dispatcher
).use { client ->
println("Starting client on port ${args[1]}")
client.start()
}
}
} | 6 | Kotlin | 0 | 1 | 2bbb0c8b24ab71849263e5be58bd525720d18e4c | 539 | LAPD_Project | MIT License |
compiler/ir/serialization.js/src/org/jetbrains/kotlin/ir/backend/js/checkers/declarations/JsKlibOtherModuleExportsChecker.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.ir.backend.js.checkers.declarations
import org.jetbrains.kotlin.ir.IrDiagnosticReporter
import org.jetbrains.kotlin.ir.backend.js.checkers.*
object JsKlibOtherModuleExportsChecker : JsKlibExportedDeclarationsChecker {
private fun <T> MutableMap<T, MutableList<JsKlibExport>>.addExport(key: T, export: JsKlibExport) {
getOrPut(key) { mutableListOf() }.add(export)
}
private fun collectClashesByFqNames(declarations: List<JsKlibExportingDeclaration>): Map<String, List<JsKlibExport>> {
return buildMap<String, MutableList<JsKlibExport>> {
for (declaration in declarations) {
addExport(declaration.fqName, declaration)
var packageFqName = declaration.containingPackageFqName
while (packageFqName.isNotEmpty()) {
addExport(packageFqName, JsKlibExportingPackage(declaration.containingFile, packageFqName))
packageFqName = packageFqName.substringBeforeLast(".", "")
}
}
}
}
private fun collectClashes(declarations: List<JsKlibExportingDeclaration>): Map<JsKlibExportingDeclaration, List<JsKlibExport>> {
val clashesByFqNames = collectClashesByFqNames(declarations)
return buildMap {
for (clashingExports in clashesByFqNames.values) {
for ((index, export) in clashingExports.withIndex()) {
if (export is JsKlibExportingDeclaration) {
val clashedWith = clashingExports.filterIndexed { i, _ -> i != index }
if (clashedWith.isNotEmpty()) {
put(export, clashedWith)
}
}
}
}
}
}
override fun check(
declarations: List<JsKlibExportingDeclaration>,
context: JsKlibDiagnosticContext,
reporter: IrDiagnosticReporter,
) {
val clashes = collectClashes(declarations)
for ((declaration, clashedWith) in clashes) {
if (declaration.declaration != null) {
reporter.at(declaration.declaration, context).report(
JsKlibErrors.EXPORTING_JS_NAME_CLASH,
declaration.exportingName,
clashedWith
)
}
}
}
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 2,592 | kotlin | Apache License 2.0 |
analysis/low-level-api-fir/tests/org/jetbrains/kotlin/analysis/low/level/api/fir/resolve/AbstractLazyDeclarationResolveScopeBasedTest.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.low.level.api.fir.resolve
import org.jetbrains.kotlin.analysis.low.level.api.fir.api.LLFirResolveSession
import org.jetbrains.kotlin.analysis.low.level.api.fir.api.resolveToFirSymbolOfType
import org.jetbrains.kotlin.analysis.low.level.api.fir.lazyResolveRenderer
import org.jetbrains.kotlin.analysis.low.level.api.fir.resolveWithClearCaches
import org.jetbrains.kotlin.analysis.low.level.api.fir.test.configurators.AnalysisApiFirOutOfContentRootTestConfigurator
import org.jetbrains.kotlin.analysis.low.level.api.fir.test.configurators.AnalysisApiFirScriptTestConfigurator
import org.jetbrains.kotlin.analysis.low.level.api.fir.test.configurators.AnalysisApiFirSourceTestConfigurator
import org.jetbrains.kotlin.analysis.test.framework.base.AbstractAnalysisApiBasedTest
import org.jetbrains.kotlin.analysis.test.framework.services.expressionMarkerProvider
import org.jetbrains.kotlin.fir.declarations.FirResolvePhase
import org.jetbrains.kotlin.fir.scopes.ProcessorAction
import org.jetbrains.kotlin.fir.scopes.processAllCallables
import org.jetbrains.kotlin.fir.scopes.processAllOverriddenCallables
import org.jetbrains.kotlin.fir.scopes.unsubstitutedScope
import org.jetbrains.kotlin.fir.symbols.impl.FirCallableSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirClassSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirNamedFunctionSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirPropertySymbol
import org.jetbrains.kotlin.fir.symbols.lazyResolveToPhase
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.test.model.TestModule
import org.jetbrains.kotlin.test.services.TestServices
import org.jetbrains.kotlin.test.services.assertions
/**
* This test exists to check lazy resolution for fake overrides
*/
abstract class AbstractLazyDeclarationResolveScopeBasedTest : AbstractAnalysisApiBasedTest() {
override fun doTestByMainFile(mainFile: KtFile, mainModule: TestModule, testServices: TestServices) {
val classOrObject = testServices.expressionMarkerProvider.getElementOfTypeAtCaret<KtClassOrObject>(mainFile)
resolveWithClearCaches(classOrObject) { session ->
val classSymbol = classOrObject.resolveToFirSymbolOfType<FirClassSymbol<*>>(session)
val symbols = collectAllCallableDeclarations(classSymbol, session)
val dumpBefore = dumpSymbols(symbols)
testServices.assertions.assertEqualsToTestDataFileSibling(dumpBefore, extension = "before.txt")
for (callableSymbol in symbols) {
callableSymbol.lazyResolveToPhase(FirResolvePhase.BODY_RESOLVE)
}
val dumpAfter = dumpSymbols(symbols)
testServices.assertions.assertEqualsToTestDataFileSibling(dumpAfter, extension = "after.txt")
}
}
}
private fun collectAllCallableDeclarations(classSymbol: FirClassSymbol<*>, session: LLFirResolveSession): Collection<FirCallableSymbol<*>> {
val baseScope = classSymbol.unsubstitutedScope(
session.useSiteFirSession,
session.getScopeSessionFor(session.useSiteFirSession),
false,
FirResolvePhase.STATUS,
)
return buildSet {
baseScope.processAllCallables { callable ->
add(callable)
baseScope.processAllOverriddenCallables(
callable,
processor = {
add(it)
ProcessorAction.NEXT
},
processDirectOverriddenCallablesWithBaseScope = { declaration, processor ->
if (declaration is FirPropertySymbol) {
processDirectOverriddenPropertiesWithBaseScope(declaration, processor)
} else {
declaration as FirNamedFunctionSymbol
processDirectOverriddenFunctionsWithBaseScope(declaration, processor)
}
}
)
}
}
}
private fun dumpSymbols(symbols: Collection<FirCallableSymbol<*>>): String {
val builder = StringBuilder()
val renderer = lazyResolveRenderer(builder)
for (callableSymbol in symbols) {
if (builder.isNotEmpty()) builder.appendLine()
renderer.renderElementAsString(callableSymbol.fir)
}
return builder.toString()
}
abstract class AbstractSourceLazyDeclarationResolveScopeBasedTest : AbstractLazyDeclarationResolveScopeBasedTest() {
override val configurator = AnalysisApiFirSourceTestConfigurator(analyseInDependentSession = false)
}
abstract class AbstractOutOfContentRootLazyDeclarationResolveScopeBasedTest : AbstractLazyDeclarationResolveScopeBasedTest() {
override val configurator get() = AnalysisApiFirOutOfContentRootTestConfigurator
}
abstract class AbstractScriptLazyDeclarationResolveScopeBasedTest : AbstractLazyDeclarationResolveScopeBasedTest() {
override val configurator = AnalysisApiFirScriptTestConfigurator(analyseInDependentSession = false)
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 5,225 | kotlin | Apache License 2.0 |
app/src/test/java/org/simple/clinic/user/NewlyVerifiedUserTest.kt | simpledotorg | 132,515,649 | false | {"Kotlin": 5970450, "Shell": 1660, "HTML": 545} | package org.simple.clinic.user
import com.google.common.truth.Truth
import io.reactivex.subjects.PublishSubject
import junitparams.JUnitParamsRunner
import junitparams.Parameters
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.simple.sharedTestCode.TestData
import org.simple.sharedTestCode.util.RxErrorsRule
import java.util.Optional
@RunWith(JUnitParamsRunner::class)
class NewlyVerifiedUserTest {
@get:Rule
val rxErrorsRule = RxErrorsRule()
private lateinit var newlyVerifiedUser: NewlyVerifiedUser
private lateinit var receivedUsers: MutableList<User>
private val userEmitter = PublishSubject.create<Optional<User>>()!!
@Before
fun setUp() {
newlyVerifiedUser = NewlyVerifiedUser()
receivedUsers = mutableListOf()
userEmitter.compose(newlyVerifiedUser)
.subscribe { receivedUsers.add(it) }
}
@Test
@Parameters(value = [
"OTP_REQUESTED|OTP_REQUESTED|LOGGED_IN|true",
"LOGGED_IN|LOGGED_IN|LOGGED_IN|false"
])
fun `when the user status changes to verified, it should emit the user`(
previousLoggedInStatus2: User.LoggedInStatus,
previousLoggedInStatus1: User.LoggedInStatus,
currentLoggedInStatus: User.LoggedInStatus,
shouldEmitUser: Boolean
) {
val user = TestData.loggedInUser(loggedInStatus = previousLoggedInStatus2)
userEmitter.onNext(Optional.of(user))
userEmitter.onNext(Optional.of(user.copy(loggedInStatus = previousLoggedInStatus1)))
val expectedUser = user.copy(loggedInStatus = currentLoggedInStatus)
userEmitter.onNext(Optional.of(expectedUser))
if (shouldEmitUser) {
Truth.assertThat(receivedUsers).isEqualTo(listOf(expectedUser))
}
}
}
| 4 | Kotlin | 73 | 223 | 58d14c702db2b27b9dc6c1298c337225f854be6d | 1,742 | simple-android | MIT License |
core_library_common/src/commonMain/kotlin/net/apptronic/core/viewmodel/navigation/ViewModelListMapperEntity.kt | apptronicnet | 264,405,837 | false | null | package net.apptronic.core.viewmodel.navigation
import net.apptronic.core.context.Context
import net.apptronic.core.context.Contextual
import net.apptronic.core.entity.Entity
import net.apptronic.core.entity.onchange.Next
import net.apptronic.core.entity.onchange.OnChangeProperty
import net.apptronic.core.entity.onchange.OnChangeValue
import net.apptronic.core.entity.onchange.onChangeValue
import net.apptronic.core.viewmodel.IViewModel
import net.apptronic.core.viewmodel.ViewModel
fun <T, Id, VM : IViewModel> Contextual.viewModelListMapper(adapter: ViewModelAdapter<T, Id, VM>): ViewModelListMapperEntity<T, Id, VM> {
return ViewModelListMapperEntity(context, adapter)
}
/**
* Class created to perform updates of list of [ViewModel].
* By using this class you can prevent from recreating [ViewModel] for item in list
* which only changed it's state but remains same instance (by id). In case if [ViewModel]
* for item in updated list already exists - it will not create new [ViewModel] but update
* existing [ViewModel] and place it in updates list at required place.
*/
class ViewModelListMapperEntity<T, Id, VM : IViewModel> internal constructor(
private val builderContext: Context,
private val adapter: ViewModelAdapter<T, Id, VM>,
private val onChangeValue: OnChangeValue<List<IViewModel>, Any> = builderContext.onChangeValue()
) : OnChangeProperty<List<IViewModel>, Any> by onChangeValue {
private inner class ViewModelHolder(
val id: Id,
val viewModel: VM
)
private val viewModelHolders = arrayListOf<ViewModelHolder>()
private val viewModels = builderContext.onChangeValue<List<IViewModel>, Any>()
/**
* Update list of [ViewModel]s automatically from given [Entity]
*/
fun updateFrom(entity: Entity<out List<T>>) {
entity.subscribe { update(it) }
}
/**
* Update list of [ViewModel]s automatically from given [Entity]
*/
fun updateFromChanges(entity: Entity<out Next<out List<T>, out Any>>) {
entity.subscribe { update(it.value, it.change) }
}
/**
* Update list of [ViewModel]s with new items.
*/
fun update(newList: List<T>, updateSpec: Any? = null) {
val oldIds = viewModelHolders.map { it.id }
val newIds = newList.map { adapter.getItemId(it) }
val newMap = hashMapOf<Id, T>()
newList.forEach {
newMap[adapter.getItemId(it)] = it
}
val same = oldIds.filter {
newIds.contains(it)
}.toSet()
val added = newIds.filter {
same.contains(it).not()
}.toSet()
val removed = oldIds.filter {
same.contains(it).not()
}.toSet()
val addedItems = newList.filter {
added.contains(adapter.getItemId(it))
}
viewModelHolders.removeAll { removed.contains(it.id) }
viewModelHolders.forEach { viewModelHolder ->
val id = viewModelHolder.id
if (same.contains(id)) {
val item = newMap[id]
if (item != null) {
adapter.updateViewModel(viewModelHolder.viewModel, item)
}
}
}
addedItems.forEach { item ->
val id = adapter.getItemId(item)
val viewModel = adapter.createViewModel(context, item)
viewModelHolders.add(ViewModelHolder(id, viewModel))
}
viewModelHolders.sortWith(PostArrangeComparator(newList))
val result = viewModelHolders.map { it.viewModel }
onChangeValue.set(result, updateSpec)
}
private inner class PostArrangeComparator(items: List<T>) :
Comparator<ViewModelHolder> {
private val indexes = hashMapOf<Id, Int>()
init {
items.forEachIndexed { index, item ->
indexes[adapter.getItemId(item)] = index
}
}
override fun compare(a: ViewModelHolder, b: ViewModelHolder): Int {
val aIndex = indexes[a.id]
val bIndex = indexes[b.id]
return if (aIndex != null && bIndex != null) {
aIndex.compareTo(bIndex)
} else 0
}
}
} | 2 | Kotlin | 0 | 6 | 5320427ddc9dd2393f01e75564dab126fdeaac72 | 4,223 | core | MIT License |
compiler/testData/diagnostics/tests/operatorRem/noDeprecatedModConventionWithoutFeature.fir.kt | android | 263,405,600 | true | null | // !LANGUAGE: -ProhibitOperatorMod
// !DIAGNOSTICS: -UNUSED_PARAMETER
object ModAndRem {
operator fun mod(x: Int) {}
operator fun rem(x: Int) {}
}
object OldMod {
operator fun mod(x: Int) {}
}
object ModAndRemExtension
operator fun ModAndRemExtension.mod(x: Int) {}
operator fun ModAndRemExtension.rem(x: Int) {}
object ModExtension
operator fun ModExtension.mod(x: Int) {}
object ModMemberAndRemExtension {
operator fun mod(x: Int) {}
}
operator fun ModMemberAndRemExtension.rem(x: Int) {}
fun foo() {
ModAndRem % 1
OldMod <!INAPPLICABLE_CANDIDATE!>%<!> 1
ModAndRemExtension % 1
ModExtension <!INAPPLICABLE_CANDIDATE!>%<!> 1
ModMemberAndRemExtension % 1
OldMod.mod(1)
ModExtension.mod(1)
} | 34 | Kotlin | 49 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 745 | kotlin | Apache License 2.0 |
widgets/src/androidTest/java/com/clearfashion/sdk/widgets/ui/component/generic/WidgetSubSectionTest.kt | Clothparency | 592,975,661 | false | null | package com.clearfashion.sdk.widgets.ui.component.generic
import androidx.activity.ComponentActivity
import androidx.compose.material.Text
import androidx.compose.ui.test.*
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import com.clearfashion.sdk.widgets.ui.component.widget.generic.WidgetSubSection
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class WidgetSubSectionTest {
@get:Rule
val composeTestRule = createAndroidComposeRule<ComponentActivity>()
private val content = "Content"
@Before
fun setup() {
composeTestRule.setContent {
WidgetSubSection {
Text(content)
}
}
}
@Test
fun testWidgetSubSection_display() {
composeTestRule.onRoot()
.assertExists()
.assertIsDisplayed()
}
@Test
fun testWidgetSubSection_displayContent() {
composeTestRule.onNodeWithText(content)
.assertExists()
.assertIsDisplayed()
}
} | 0 | Kotlin | 0 | 1 | 3d83e5162d7d287a4d7a7f13041ece904ed84cdf | 1,025 | android-widgets | RSA Message-Digest License |
src/main/kotlin/pcimcioch/gitlabci/dsl/DslBase.kt | pcimcioch | 247,550,225 | false | null | package pcimcioch.gitlabci.dsl
import com.charleskorn.kaml.Yaml
import com.charleskorn.kaml.YamlConfiguration
import kotlinx.serialization.Serializable
import kotlinx.serialization.KSerializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlin.reflect.KClass
@GitlabCiDslMarker
@Serializable(with = DslBase.DslBaseSerializer::class)
abstract class DslBase {
open fun validate(errors: MutableList<String>) {}
override fun toString(): String {
val config = YamlConfiguration(encodeDefaults = false)
val yaml = Yaml(configuration = config)
return yaml.encodeToString(serializer(), this)
}
companion object {
private val serializers: MutableMap<KClass<out DslBase>, KSerializer<out DslBase>> = mutableMapOf()
internal fun addError(errors: MutableList<String>, condition: Boolean?, message: String) {
if (condition == true) {
errors.add(message)
}
}
internal fun addErrors(errors: MutableList<String>, messagePrefix: String, objs: Collection<DslBase>) {
objs.forEach { addErrors(errors, messagePrefix, it) }
}
internal fun addErrors(errors: MutableList<String>, messagePrefix: String, vararg obj: DslBase?) {
val objErrors = mutableListOf<String>()
obj.forEach { it?.validate(objErrors) }
objErrors.forEach { errors.add("$messagePrefix$it") }
}
internal fun <T> addAndReturn(list: MutableList<T>, element: T): T {
list.add(element)
return element
}
internal fun isEmpty(tested: String?) = (tested == null || "" == tested)
internal fun <T : DslBase> addSerializer(clazz: KClass<T>, serializer: KSerializer<T>) {
serializers[clazz] = serializer
}
}
object DslBaseSerializer : KSerializer<DslBase> {
override val descriptor = PrimitiveSerialDescriptor("DslBase", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder): DslBase {
throw IllegalStateException("Deserialization is not supported for this DSL object")
}
override fun serialize(encoder: Encoder, value: DslBase) {
getSerializer(value).serialize(encoder, value)
}
@Suppress("UNCHECKED_CAST")
private fun <T : DslBase> getSerializer(value: T): KSerializer<T> {
for (serializer in serializers) {
if (serializer.key.isInstance(value)) {
return serializer.value as KSerializer<T>
}
}
throw IllegalStateException("No serializer found for value of type '${value.javaClass.kotlin.qualifiedName}'")
}
}
} | 0 | Kotlin | 5 | 20 | bf30d3edb0566613a27a787b7f6490f9507412d8 | 2,899 | gitlab-ci-kotlin-dsl | Apache License 2.0 |
androidx-app/src/test/java/com/ayvytr/coroutines/c2.kt | Ayvytr | 193,484,016 | false | {"Kotlin": 66555, "Java": 13995} | package com.ayvytr.coroutines
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicLong
/**
* @author admin
*/
fun main() {
//thread
// val c = AtomicLong()
// for (i in 1..1_000_000L) {
// thread(start = true) {
// c.addAndGet(i)
// println(i)
// }
// }
//
// println(c.get())
//协程coroutines, 但是不1秒就完成了,打印了任意数字,一些协程没有在main打印结果之前执行完毕了
val c = AtomicLong()
for (i in 1..1_000_000L) {
GlobalScope.launch {
c.addAndGet(i)
println(i)
}
}
println(c.get())
} | 0 | Kotlin | 3 | 7 | 6bc985684f828ca5cf76d49d3820bc627f7d28bb | 702 | Mvvm | Apache License 2.0 |
libraries/tools/kotlin-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/model/builder/KaptModelBuilder.kt | android | 263,405,600 | true | null | /*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.gradle.model.builder
import org.gradle.api.Project
import org.gradle.tooling.provider.model.ToolingModelBuilder
import org.jetbrains.kotlin.gradle.internal.KaptTask
import org.jetbrains.kotlin.gradle.model.Kapt
import org.jetbrains.kotlin.gradle.model.KaptSourceSet
import org.jetbrains.kotlin.gradle.model.impl.KaptImpl
import org.jetbrains.kotlin.gradle.model.impl.KaptSourceSetImpl
/**
* [ToolingModelBuilder] for [Kapt] models.
* This model builder is registered for Kapt Gradle sub-plugin.
*/
class KaptModelBuilder : ToolingModelBuilder {
override fun canBuild(modelName: String): Boolean {
return modelName == Kapt::class.java.name
}
override fun buildAll(modelName: String, project: Project): Any? {
if (modelName == Kapt::class.java.name) {
val kaptTasks = project.tasks.withType(KaptTask::class.java)
return KaptImpl(project.name, kaptTasks.map { it.createKaptSourceSet() })
}
return null
}
companion object {
private fun KaptTask.createKaptSourceSet(): KaptSourceSet {
val sourceSetName = kotlinCompileTask.sourceSetName
return KaptSourceSetImpl(
sourceSetName,
if (sourceSetName.contains(
"test",
true
)
) KaptSourceSet.KaptSourceSetType.TEST else KaptSourceSet.KaptSourceSetType.PRODUCTION,
destinationDir,
kotlinSourcesDestinationDir,
classesDir
)
}
}
} | 34 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 1,811 | kotlin | Apache License 2.0 |
app/src/main/java/com/jiangdg/utils/imageloader/GlideLoader.kt | jiangdongguo | 105,255,685 | false | {"C": 5162979, "Assembly": 1351532, "C++": 812116, "HTML": 709927, "Kotlin": 553133, "Shell": 454771, "Java": 412491, "Makefile": 362115, "CMake": 49533, "CSS": 43589, "Roff": 37236, "M4": 35573, "JavaScript": 34594, "Batchfile": 8390, "GLSL": 3467, "Rich Text Format": 648} | /*
* Copyright 2017-2022 Jiangdg
*
* 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.jiangdg.utils.imageloader
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.view.View
import android.widget.ImageView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestManager
import com.bumptech.glide.integration.webp.decoder.WebpDrawable
import com.bumptech.glide.integration.webp.decoder.WebpDrawableTransformation
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.Transformation
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.jiangdg.demo.R
import java.lang.IllegalArgumentException
/**GlideImageLoader by glide
*
* @param target imageview owner
*
* @author Created by jiangdg on 2022/3/16
*/
class GlideLoader<T>(target: T) : ILoader<ImageView> {
private var mRequestManager: RequestManager? = null
init {
mRequestManager = when (target) {
is Fragment -> Glide.with(target)
is FragmentActivity -> Glide.with(target)
is Activity -> Glide.with(target)
is Context -> Glide.with(target)
is View -> Glide.with(target)
else -> throw IllegalArgumentException()
}
}
override fun load(imageView: ImageView, url: String?, placeHolder: Int) {
val centerCrop: Transformation<Bitmap> = CenterCrop()
mRequestManager!!.load(url).optionalTransform(centerCrop)
.optionalTransform(WebpDrawable::class.java, WebpDrawableTransformation(centerCrop))
.placeholder(placeHolder)
.into(imageView)
}
override fun load(imageView: ImageView, url: String?) {
val centerCrop: Transformation<Bitmap> = CenterCrop()
mRequestManager!!.load(url).optionalTransform(centerCrop)
.optionalTransform(WebpDrawable::class.java, WebpDrawableTransformation(centerCrop))
.placeholder(R.drawable.imageloader_default_cover_bg)
.into(imageView)
}
override fun load(imageView: ImageView, resId: Int) {
val centerCrop: Transformation<Bitmap> = CenterCrop()
mRequestManager!!.load(resId).optionalTransform(centerCrop)
.optionalTransform(WebpDrawable::class.java, WebpDrawableTransformation(centerCrop))
.placeholder(R.drawable.imageloader_default_cover_bg)
.into(imageView)
}
override fun load(
imageView: ImageView,
url: String?,
placeHolder: Int,
bitmapTransformation: BitmapTransformation?
) {
mRequestManager!!.load(url).optionalTransform(bitmapTransformation!!)
.optionalTransform(
WebpDrawable::class.java,
WebpDrawableTransformation(bitmapTransformation)
)
.placeholder(placeHolder).into(imageView)
}
@SuppressLint("CheckResult")
override fun loadRounded(imageView: ImageView, url: String?, placeHolder: Int, radius: Float) {
RequestOptions().apply {
if (radius >= 0) {
transform(CenterCrop(), RoundedCorners(dp2px(imageView.context, radius)))
} else {
transform(RoundedCorners(dp2px(imageView.context, radius)))
}
}.also { options ->
mRequestManager!!.load(url)
.placeholder(placeHolder)
.apply(options)
.into(imageView)
}
}
@SuppressLint("CheckResult")
override fun loadRounded(
imageView: ImageView,
url: String?,
placeHolder: Drawable?,
radius: Float
) {
RequestOptions().apply {
if (radius >= 0) {
transform(CenterCrop(), RoundedCorners(dp2px(imageView.context, radius)))
} else {
transform(RoundedCorners(dp2px(imageView.context, radius)))
}
}.also { options ->
mRequestManager!!.load(url)
.placeholder(placeHolder)
.apply(options)
.into(imageView)
}
}
override fun loadRounded(imageView: ImageView, url: String?, radius: Float) {
loadRounded(imageView, url, R.drawable.imageloader_default_cover_bg, radius)
}
override fun loadCircle(imageView: ImageView, url: String?, placeHolder: Int) {
mRequestManager?.apply {
this.load(url)
.placeholder(placeHolder)
.apply(RequestOptions.bitmapTransform(CircleCrop()))
.into(imageView)
}
}
override fun loadCircle(imageView: ImageView, url: String?) {
mRequestManager?.apply {
this.load(url)
.placeholder(R.drawable.imageloader_default_cover_bg)
.apply(RequestOptions.bitmapTransform(CircleCrop()))
.into(imageView)
}
}
override fun loadCircle(imageView: ImageView, resId: Int, placeHolder: Int) {
mRequestManager?.apply {
this.load(resId)
.placeholder(placeHolder)
.apply(RequestOptions.bitmapTransform(CircleCrop()))
.into(imageView)
}
}
override fun loadCircle(imageView: ImageView, resId: Int) {
mRequestManager?.apply {
this.load(resId)
.placeholder(R.drawable.imageloader_default_cover_bg)
.apply(RequestOptions.bitmapTransform(CircleCrop()))
.into(imageView)
}
}
override fun loadAsBitmap(
url: String?,
width: Int,
height: Int,
listener: ILoader.OnLoadedResultListener
) {
mRequestManager?.apply {
this.asBitmap()
.centerCrop()
.load(url)
.listener(object : RequestListener<Bitmap> {
override fun onLoadFailed(
e: GlideException?,
model: Any?,
target: Target<Bitmap>?,
isFirstResource: Boolean
): Boolean {
listener.onLoadedFailed(e)
return true
}
override fun onResourceReady(
resource: Bitmap?,
model: Any?,
target: Target<Bitmap>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
listener.onLoadedSuccess(resource)
return true
}
})
.submit(width, height)
}
}
private fun dp2px(context: Context, dpValue: Float): Int {
val scale: Float = context.resources.displayMetrics.density
return (dpValue * scale + 0.5f).toInt()
}
} | 396 | C | 708 | 2,038 | ebfd9437eb6e23e30f583a0151474b2fa6267fca | 7,978 | AndroidUSBCamera | Apache License 2.0 |
compiler/testData/diagnostics/tests/inference/upperBounds/useBoundsIfUnknownParameters.kt | android | 263,405,600 | true | null | // !WITH_NEW_INFERENCE
package Hello
open class Base<T>
class StringBase : Base<String>()
class Client<T, X: Base<T>>(<!UNUSED_PARAMETER!>x<!>: X)
fun test() {
val c = Client(StringBase()) // Type inference fails here for T.
val <!UNUSED_VARIABLE!>i<!> : Int = <!TYPE_MISMATCH!>c<!>
} | 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 295 | kotlin | Apache License 2.0 |
controls-core/src/commonMain/kotlin/space/kscience/controls/ports/phrases.kt | SciProgCentre | 240,888,288 | false | {"Kotlin": 260147, "Java": 1136} | package space.kscience.controls.ports
import io.ktor.utils.io.core.BytePacketBuilder
import io.ktor.utils.io.core.readBytes
import io.ktor.utils.io.core.reset
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.transform
/**
* Transform byte fragments into complete phrases using given delimiter. Not thread safe.
*/
public fun Flow<ByteArray>.withDelimiter(delimiter: ByteArray): Flow<ByteArray> {
require(delimiter.isNotEmpty()) { "Delimiter must not be empty" }
val output = BytePacketBuilder()
var matcherPosition = 0
return transform { chunk ->
chunk.forEach { byte ->
output.writeByte(byte)
//matching current symbol in delimiter
if (byte == delimiter[matcherPosition]) {
matcherPosition++
if (matcherPosition == delimiter.size) {
//full match achieved, sending result
val bytes = output.build()
emit(bytes.readBytes())
output.reset()
matcherPosition = 0
}
} else if (matcherPosition > 0) {
//Reset matcher since full match not achieved
matcherPosition = 0
}
}
}
}
/**
* Transform byte fragments into utf-8 phrases using utf-8 delimiter
*/
public fun Flow<ByteArray>.withStringDelimiter(delimiter: String): Flow<String> {
return withDelimiter(delimiter.encodeToByteArray()).map { it.decodeToString() }
}
/**
* A flow of delimited phrases
*/
public fun Port.delimitedIncoming(delimiter: ByteArray): Flow<ByteArray> = receiving().withDelimiter(delimiter)
/**
* A flow of delimited phrases with string content
*/
public fun Port.stringsDelimitedIncoming(delimiter: String): Flow<String> = receiving().withStringDelimiter(delimiter)
| 5 | Kotlin | 3 | 21 | 5b655a9354de5ddb4be25ee9e6be876f14f10b87 | 1,880 | controls-kt | Apache License 2.0 |
compiler/testData/codegen/box/properties/genericWithSameName.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // IGNORE_BACKEND: JVM, JVM_IR
package foo
class C<T>(val pp: T)
val <T: Any?> C<T>.p: String get() = pp?.toString() ?: "O"
val <T: Any> C<T>.p: String get() = pp.toString()
fun box(): String {
val c1 = C<String?>(null)
val c2 = C<String>("K")
return c1.p + c2.p
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 284 | kotlin | Apache License 2.0 |
app/src/main/kotlin/com/github/midros/istheapp/ui/widget/CustomNestedScrollView.kt | M1Dr05 | 134,190,446 | false | null | package com.github.midros.istheapp.ui.widget
import android.content.Context
import android.graphics.Rect
import android.os.Build
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.core.widget.NestedScrollView
import com.google.android.material.appbar.AppBarLayout
import kotlin.math.ceil
/**
* Created by <NAME> on 15/06/19.
*/
class CustomNestedScrollView : NestedScrollView {
private var appBar : AppBarLayout? =null
constructor(context: Context): super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet): super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int): super(context, attrs, defStyleAttr) {
init()
}
private fun init() {
fitsSystemWindows = true
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
requestApplyInsets()
}
override fun fitSystemWindows(insets: Rect): Boolean {
setPadding(insets.left,topView(),insets.right,insets.bottom)
return true
}
private fun topView() : Int = (if (appBar!=null) appBar!!.height else 0)
override fun onInterceptTouchEvent(e: MotionEvent?): Boolean {
isScrollable()
return super.onInterceptTouchEvent(e)
}
fun setAppBar(appBar: AppBarLayout){
this.appBar = appBar
}
private fun isScrollable(){
val childHeight = getChildAt(0).height
val isScroll = height < childHeight + paddingTop + paddingBottom
if (appBar != null) if (!isScroll) appBar!!.setExpanded(true)
}
} | 1 | Kotlin | 227 | 350 | b4dcfb64966e441ce27236f87644cf02970f036c | 1,634 | IsTheApp | Apache License 2.0 |
kotlin/src/com/daily/algothrim/trie/Trie.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.trie
/**
* Trie树,解决字符串查询
*/
class Trie {
companion object {
@JvmStatic
fun main(args: Array<String>) {
Trie().apply {
insert("hello".toCharArray())
insert("her".toCharArray())
insert("hi".toCharArray())
insert("how".toCharArray())
insert("so".toCharArray())
insert("see".toCharArray())
println(find("see".toCharArray()))
}
}
}
private val root = TrieNode('/')
class TrieNode(val data: Char) {
val children = Array<TrieNode?>(26) { null }
var isEndingChar = false
}
/**
* O(n)所有字符串的长度之和
*/
fun insert(text: CharArray) {
var p = root
text.forEach {
val index = it - 'a'
if (p.children[index] == null) {
p.children[index] = TrieNode(it)
}
p = p.children[index]!!
}
p.isEndingChar = true
}
/**
* O(k)查询的字符串长度
*/
fun find(text: CharArray): Boolean {
var p = root
text.forEach {
val index = it - 'a'
if (p.children[index] == null) return false
p = p.children[index]!!
}
return p.isEndingChar
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 1,384 | daily_algorithm | Apache License 2.0 |
app/src/main/java/com/app/skyss_companion/view/stop_place/StopPlaceListDivider.kt | martinheitmann | 339,335,251 | false | {"Kotlin": 624449} | package com.app.skyss_companion.view.stop_place
data class StopPlaceListDivider(
val text: String
) : StopPlaceListItem() | 0 | Kotlin | 0 | 0 | a4a79e658643731cd76617cdb9458aa1f742d4c3 | 126 | bus-companion | MIT License |
kotlin-browser/src/main/generated/dom/svg/SVGMPathElement.kt | stefanthaler | 440,580,782 | true | {"Kotlin": 8815376, "JavaScript": 528} | // Automatically generated - do not modify!
package dom.svg
sealed external class SVGMPathElement : SVGElement
| 0 | Kotlin | 0 | 0 | fc27a2b5d98423c8db24f8a28d1c3a95dc682b0a | 113 | kotlin-wrappers | Apache License 2.0 |
GreenHouseController/greenhousecommon/src/main/java/com/klnvch/greenhousecommon/ui/chart/ChartLine.kt | klnvch | 284,019,366 | false | {"Java": 116052, "Kotlin": 35169} | package com.klnvch.greenhousecommon.ui.chart
import android.util.Pair
class ChartLine(val data: List<Pair<Long, Float>>, val name: String, val color: Int)
| 0 | Java | 0 | 0 | 7041311084a82d92b6c3bb13917096a6ae2a7fc3 | 157 | Greenhouse | MIT License |
app/src/main/java/com/danefinlay/opengltesting/GLSLShaders.kt | shaulr | 177,291,695 | false | {"Java": 1627756, "C++": 76576, "Kotlin": 20433, "sed": 3113} | package com.example.myapplication
/**
* GLSL shaders as strings
* "//" Comments and new line characters in GLSL code are completely fine, no compilation errors.
* Created by dane on 4/11/16.
*/
val sampleVertexShaderCode =
"""
// This matrix member variable provides a hook to manipulate
// the coordinates of the objects that use this vertex shader
uniform mat4 uMVPMatrix;
attribute vec4 vPosition;
void main() {
// the matrix must be included as a modifier of gl_Position
// Note that the uMVPMatrix factor *must be first* in order
// for the matrix multiplication product to be correct.
gl_Position = uMVPMatrix * vPosition;
}
"""
val sampleFragmentShaderCode =
"""precision mediump float;
uniform vec4 vColor;
void main() {
gl_FragColor = vColor;
}
""" | 0 | Java | 1 | 0 | 30250e9fbf61eca9511b2858606d333e098024f4 | 959 | kotlinGL | MIT License |
backend/src/main/java/com/dopplertask/dopplertask/domain/action/connection/MySQLAction.kt | larbibaraka | 473,112,507 | true | {"JavaScript": 8342116, "Java": 191340, "Kotlin": 98486, "CSS": 43368, "HTML": 4584, "Dockerfile": 1229, "Shell": 315} | package com.dopplertask.dopplertask.domain.action.connection
import com.dopplertask.dopplertask.domain.ActionResult
import com.dopplertask.dopplertask.domain.StatusCode
import com.dopplertask.dopplertask.domain.TaskExecution
import com.dopplertask.dopplertask.domain.action.Action
import com.dopplertask.dopplertask.domain.action.Action.PropertyInformation.PropertyInformationType
import com.dopplertask.dopplertask.service.BroadcastListener
import com.dopplertask.dopplertask.service.ColumnEncryptor
import com.dopplertask.dopplertask.service.TaskService
import com.dopplertask.dopplertask.service.VariableExtractorUtil
import com.mysql.cj.jdbc.MysqlDataSource
import java.io.IOException
import java.sql.ResultSet
import java.sql.SQLException
import java.sql.Statement
import javax.persistence.*
@Entity
@Table(name = "MySQLAction")
@DiscriminatorValue("mysql_action")
class MySQLAction : Action() {
@Column
@Convert(converter = ColumnEncryptor::class)
var hostname: String? = null
@Column
@Convert(converter = ColumnEncryptor::class)
var username: String? = null
@Column
@Convert(converter = ColumnEncryptor::class)
var password: String? = null
@Column
@Convert(converter = ColumnEncryptor::class)
var port: String? = null
@Column
@Convert(converter = ColumnEncryptor::class)
var database: String? = null
@Column
@Convert(converter = ColumnEncryptor::class)
var timezone: String? = null
@Lob
@Column(columnDefinition = "TEXT")
var command: String? = null
@Throws(IOException::class)
override fun run(
taskService: TaskService,
execution: TaskExecution,
variableExtractorUtil: VariableExtractorUtil,
broadcastListener: BroadcastListener?
): ActionResult {
val localHostname = variableExtractorUtil.extract(hostname, execution, scriptLanguage)
val localUsername = variableExtractorUtil.extract(username, execution, scriptLanguage)
val localPassword = variableExtractorUtil.extract(password, execution, scriptLanguage)
val localPort = variableExtractorUtil.extract(port, execution, scriptLanguage)
val localDatabase = variableExtractorUtil.extract(database, execution, scriptLanguage)
val localCommand = variableExtractorUtil.extract(command, execution, scriptLanguage)
val localTimezone = variableExtractorUtil.extract(timezone, execution, scriptLanguage)
val dataSource = MysqlDataSource()
dataSource.user = localUsername
dataSource.password = <PASSWORD>
dataSource.serverName = localHostname
dataSource.databaseName = localDatabase
if (localPort != null && !localPort.isEmpty()) {
try {
dataSource.port = localPort.toInt()
} catch (e: NumberFormatException) {
e.printStackTrace()
}
}
if (localTimezone.isNotEmpty()) {
try {
dataSource.serverTimezone = localTimezone
} catch (e: SQLException) {
e.printStackTrace()
}
}
var stmt: Statement? = null
var rs: ResultSet? = null
val actionResult = ActionResult()
try {
dataSource.connection.use { conn ->
stmt = conn.createStatement()
if (stmt?.execute(localCommand) == true) {
rs = stmt?.resultSet;
val rsmd = rs?.metaData
val builder = StringBuilder()
builder.append("Quering: $localCommand\n")
builder.append("Result: \n\n")
val columnsNumber = rsmd?.columnCount
while (rs!!.next()) {
for (i in 1..columnsNumber!!) {
if (i > 1) {
builder.append(", ")
}
val columnValue = rs?.getString(i)
builder.append(rsmd.getColumnName(i) + ": " + columnValue)
}
builder.append("\n")
}
actionResult.output = builder.toString()
}
actionResult.statusCode = StatusCode.SUCCESS
return actionResult
}
} catch (e: SQLException) {
actionResult.errorMsg = e.toString()
actionResult.statusCode = StatusCode.FAILURE
return actionResult
} finally {
try {
if (stmt != null) {
stmt!!.close()
}
} catch (e: SQLException) {
}
try {
if (rs != null) {
rs!!.close()
}
} catch (e: SQLException) {
}
}
}
override val actionInfo: MutableList<PropertyInformation>
get() {
val actionInfo = super.actionInfo
actionInfo.add(
PropertyInformation(
"hostname", "Hostname", PropertyInformationType.STRING, "", "Hostname or IP", emptyList(),
PropertyInformation.PropertyInformationCategory.CREDENTIAL
)
)
actionInfo.add(
PropertyInformation(
"username", "Username", PropertyInformationType.STRING, "", "Username",
emptyList(),
PropertyInformation.PropertyInformationCategory.CREDENTIAL
)
)
actionInfo.add(
PropertyInformation(
"password", "<PASSWORD>", PropertyInformationType.STRING, "", "Password", emptyList(),
PropertyInformation.PropertyInformationCategory.CREDENTIAL
)
)
actionInfo.add(
PropertyInformation(
"database", "Database", PropertyInformationType.STRING, "", "Database name", emptyList(),
PropertyInformation.PropertyInformationCategory.CREDENTIAL
)
)
actionInfo.add(
PropertyInformation(
"port", "Port", PropertyInformationType.STRING, "3306", "Default is 3306", emptyList(),
PropertyInformation.PropertyInformationCategory.CREDENTIAL
)
)
actionInfo.add(
PropertyInformation(
"timezone",
"Timezone",
PropertyInformationType.STRING,
"",
"Specify timezone. Example CET",
emptyList(),
PropertyInformation.PropertyInformationCategory.CREDENTIAL
)
)
actionInfo.add(
PropertyInformation(
"command",
"MySQL Statement",
PropertyInformationType.MULTILINE,
"",
"Statement to execute"
)
)
return actionInfo
}
override val description: String
get() = "Creates a MySQL database connection and runs a command"
} | 0 | null | 0 | 1 | 92b80bd19f49e369b67c9dae560f1b15f06c9523 | 7,303 | dopplertask | MIT License |
compiler/testData/codegen/boxInline/suspend/stateMachine/lambdaTransformation.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // CHECK_STATE_MACHINE
// WITH_COROUTINES
// NO_CHECK_LAMBDA_INLINING
// WITH_STDLIB
// FILE: test.kt
import helpers.*
import kotlin.coroutines.*
const val DEBUG = false
inline fun inlineFun(b: () -> Unit) {
if (DEBUG) {
inlineFunReal(b)
}
}
inline fun inlineFunReal(b: () -> Unit) {
try {
b()
} finally {
}
}
fun builder(c: suspend () -> Unit) {
c.startCoroutine(CheckStateMachineContinuation)
}
// FILE: box.kt
import helpers.*
class Sample {
fun test() {
inlineFun {
builder {
inlineFun {
suspendFun()
suspendFun()
}
}
}
}
suspend fun suspendFun() = StateMachineChecker.suspendHere()
}
fun box(): String {
Sample().test()
StateMachineChecker.check(0, checkFinished = false)
return "OK"
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 875 | kotlin | Apache License 2.0 |
app/src/main/java/dadm/frba/utn/edu/ar/quehaceres/fragments/AvailableTasksFragment.kt | UTN-FRBA-Mobile | 148,959,761 | false | null | package dadm.frba.utn.edu.ar.quehaceres.fragments
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.google.android.gms.common.util.CollectionUtils.isEmpty
import dadm.frba.utn.edu.ar.quehaceres.OnTaskAssigned
import dadm.frba.utn.edu.ar.quehaceres.OnTaskCreated
import dadm.frba.utn.edu.ar.quehaceres.R
import dadm.frba.utn.edu.ar.quehaceres.api.Api
import dadm.frba.utn.edu.ar.quehaceres.services.Services
import kotlinx.android.synthetic.main.fragment_available_tasks.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.lang.IllegalStateException
class AvailableTasksFragment : BaseFragment() {
private val services by lazy { Services(context!!) }
private var listener: Listener? = null
private var groupId: Int? = null
private val eventBus = EventBus.getDefault()
// val taskTrucha: Api.Task = Api.Task(id = 200, name = "Esta tarea no es de verdad. Aca habria una tarea si hubieras creado una. Toca el icono con el simbolo '+'", )
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
groupId = it.getInt(ARG_GROUP_ID)
}
if (groupId == null) {
throw IllegalStateException("Group ID cannot be null")
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_available_tasks, container, false)
}
override fun onResume() {
super.onResume()
fetchTasks()
}
@SuppressLint("CheckResult")
private fun fetchTasks() {
compositeSubscription.add(
services.availableTasks(groupId!!)
.doOnSubscribe {
loading.visibility = View.VISIBLE
list.visibility = View.GONE
empty_state.visibility = View.GONE
}
.subscribe(
{
loading.visibility = View.GONE
list.visibility = View.VISIBLE
if (isEmpty(it)) {
list.visibility = View.GONE
empty_state.visibility = View.VISIBLE
} else {
list.adapter = AvailableTasksAdapter(it, listener)
}
},
{
loading.visibility = View.GONE
list.visibility = View.VISIBLE
Toast.makeText(context!!, "Hubo un error al cargar la lista de tareas disponibles", Toast.LENGTH_SHORT).show()
}
)
)
}
@Subscribe
fun onTaskCreated(event: OnTaskCreated) {
fetchTasks()
}
@Subscribe
fun onTaskAssigned(event: OnTaskAssigned) {
fetchTasks()
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is Listener) {
listener = context
} else {
throw RuntimeException(context.toString() + " must implement Listener")
}
}
override fun onDetach() {
super.onDetach()
listener = null
}
override fun onStart() {
super.onStart()
eventBus.register(this)
}
override fun onStop() {
super.onStop()
eventBus.unregister(this)
}
interface Listener {
fun onAvailableTaskClicked(item: Api.Task)
}
companion object {
const val ARG_GROUP_ID = "group-id"
@JvmStatic
fun newInstance(groupId: Int) =
AvailableTasksFragment().apply {
arguments = Bundle().apply {
putInt(ARG_GROUP_ID, groupId)
}
}
}
}
| 0 | Kotlin | 1 | 0 | 5c044042e6a209b4a090f12563b52a178fd9ad47 | 4,178 | Quehaceres | MIT License |
src/test/kotlin/ElevatorTest.kt | uorri | 606,729,920 | false | null | import building.Building
import building.ElevatorSystem
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.junit.jupiter.api.*
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
import passenger.Passenger
import emulator.PassengerEmulator
import passenger.PassengerGenerator
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit.MILLISECONDS
import kotlin.random.Random
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class ElevatorTest {
private val defaultScope = CoroutineScope(Dispatchers.Default)
private lateinit var passengerLatch: CountDownLatch
@BeforeEach
fun init() {
ElevatorSystem.start()
}
@AfterEach
fun shutdown() {
ElevatorSystem.shutdown()
}
@Test
fun `Creating a passenger on a non-existent floor`() {
assertThrows<IllegalArgumentException> {
getPassenger(Building.firstFloor - 1, 5)
}
assertThrows<IllegalArgumentException> {
getPassenger(Building.lastFloor + 1, 5)
}
}
@Test
fun `Creating a passenger with the target of a non-existent floor`() {
assertThrows<IllegalArgumentException> {
getPassenger(1, Building.firstFloor - 1)
}
assertThrows<IllegalArgumentException> {
getPassenger(1, Building.lastFloor + 1)
}
}
@ParameterizedTest
@CsvSource("1, 10", "7, 2", "3, 9", "25, 4")
fun `A passenger calls the elevator`(sourceFloor: Int, targetFloor: Int) {
val passenger = getPassenger(sourceFloor, targetFloor)
initPassengerLatch(1)
launchPassengerThread(passenger)
passengerLatch.await()
assertTrue { passenger.isArrived() }
}
@Test
fun `A passenger calls the elevator on the first floor and rides to the last`() {
val passenger = getPassenger(Building.firstFloor, Building.lastFloor)
initPassengerLatch(1)
launchPassengerThread(passenger)
passengerLatch.await()
assertTrue { passenger.isArrived() }
}
@ParameterizedTest
@CsvSource("3, 7, 8, 2", "1, 10, 4, 5", "4, 25, 3, 11")
fun `Passengers call the elevator`(
sourceFloor1: Int, sourceFloor2: Int,
targetFloor1: Int, targetFloor2: Int
) {
val passenger1 = getPassenger(sourceFloor1, targetFloor1)
val passenger2 = getPassenger(sourceFloor2, targetFloor2)
initPassengerLatch(2)
launchPassengerThread(passenger1)
launchPassengerThread(passenger2)
passengerLatch.await()
assertTrue { passenger1.isArrived() }
assertTrue { passenger2.isArrived() }
}
@Test
fun `Elevator is called on the same floor`() {
val sourceFloor = 18
val passenger1 = getPassenger(sourceFloor, 1)
val passenger2 = getPassenger(sourceFloor, 5)
val passenger3 = getPassenger(sourceFloor, 3)
initPassengerLatch(3)
launchPassengerThread(passenger1)
launchPassengerThread(passenger2)
launchPassengerThread(passenger3)
passengerLatch.await()
assertTrue { passenger1.isArrived() }
assertTrue { passenger2.isArrived() }
assertTrue { passenger3.isArrived() }
}
@Test
fun `Passengers call the elevator from same floor and ride different directions`() {
val sourceFloor = 18
val passenger1 = getPassenger(sourceFloor, 1)
val passenger2 = getPassenger(sourceFloor, 25)
initPassengerLatch(2)
launchPassengerThread(passenger1)
launchPassengerThread(passenger2)
passengerLatch.await()
assertTrue { passenger1.isArrived() }
assertTrue { passenger2.isArrived() }
}
@Test
fun `Passengers call the elevator from different floors and ride to the same floor`() {
val targetFloor = 5
val passenger1 = getPassenger(1, targetFloor)
val passenger2 = getPassenger(10, targetFloor)
initPassengerLatch(2)
launchPassengerThread(passenger1)
launchPassengerThread(passenger2)
passengerLatch.await()
assertTrue { passenger1.isArrived() }
assertTrue { passenger2.isArrived() }
}
@Test
fun `The elevator picks up passengers who called it during its movement`() {
ElevatorSystem.reset()
initPassengerLatch(3)
launchPassengerThread(getPassenger(1, 15))
MILLISECONDS.sleep(200)
launchPassengerThread(getPassenger(10, 4))
MILLISECONDS.sleep(200)
launchPassengerThread(getPassenger(4, 12))
passengerLatch.await()
assertEquals(listOf(1, 4, 12, 15, 10, 4), ElevatorSystem.getStopHistory())
}
@Test
fun `Passengers call the elevator from the same floor and ride to the same floor`() {
val sourceFloor = 10
val targetFloor = 1
val passenger1 = getPassenger(sourceFloor, targetFloor)
val passenger2 = getPassenger(sourceFloor, targetFloor)
val passenger3 = getPassenger(sourceFloor, targetFloor)
initPassengerLatch(3)
launchPassengerThread(passenger1)
launchPassengerThread(passenger2)
launchPassengerThread(passenger3)
passengerLatch.await()
assertTrue { passenger1.isArrived() }
assertTrue { passenger2.isArrived() }
assertTrue { passenger3.isArrived() }
}
@Test
fun `Elevator operates during rush hour`() {
val passengers = mutableListOf<Passenger>()
repeat(100) {
passengers.add(getPassenger(
sourceFloor = Random.nextInt(1, 25),
targetFloor = Random.nextInt(1, 25))
)
}
initPassengerLatch(passengers.size)
passengers.forEach { launchPassengerThread(it) }
passengerLatch.await()
passengers.forEach { assertTrue { it.isArrived() } }
}
private fun getPassenger(sourceFloor: Int, targetFloor: Int) =
PassengerGenerator.create(sourceFloor, targetFloor)
private fun launchPassengerThread(passenger: Passenger) {
defaultScope.launch {
PassengerEmulator.emulate(passenger)
passengerLatch.countDown()
}
}
private fun initPassengerLatch(count: Int) {
passengerLatch = CountDownLatch(count)
}
private fun Passenger.isArrived(): Boolean {
return Building.passengerIsOnTargetFloor(this)
}
} | 0 | Kotlin | 0 | 0 | 314d680f528e9174969d61c1e561a1098475d99a | 6,546 | elevator | Apache License 2.0 |
kcrypto/src/main/kotlin/org/bouncycastle/kcrypto/spec/PBKDFAlgSpec.kt | bcgit | 196,159,414 | false | null | package org.bouncycastle.kcrypto.spec
interface PBKDFAlgSpec<T>: AlgSpec<T>
{
} | 1 | Kotlin | 10 | 41 | 317868e703ddbf483b52718847a485f86a5d7903 | 81 | bc-kotlin | MIT License |
src/main/java/org/tokend/sdk/keyserver/WalletKeyDerivation.kt | tokend | 153,458,393 | false | null | package org.tokend.sdk.keyserver
import org.tokend.kdf.ScryptWithMasterKeyDerivation
import org.tokend.sdk.keyserver.models.KdfAttributes
import org.tokend.sdk.utils.extentions.encodeHexString
import java.nio.CharBuffer
import java.nio.charset.Charset
import java.security.SecureRandom
object WalletKeyDerivation {
@JvmStatic
fun deriveWalletEncryptionKey(login: String,
password: CharArray,
kdfAttributes: KdfAttributes): ByteArray {
val passwordCharBuffer = CharBuffer.wrap(password)
val passwordByteBuffer = Charset.defaultCharset().encode(passwordCharBuffer)
passwordCharBuffer.clear()
val passwordBytes = ByteArray(passwordByteBuffer.remaining())
passwordByteBuffer.get(passwordBytes).clear()
val result = deriveKey(login.toByteArray(), passwordBytes,
WALLET_KEY_MASTER_KEY.toByteArray(), kdfAttributes)
passwordBytes.fill(0)
return result
}
/**
* Derives wallet ID for given params
*
* @see deriveKey
*/
@JvmStatic
fun deriveWalletId(login: String,
password: CharArray,
kdfAttributes: KdfAttributes): ByteArray {
val passwordCharBuffer = CharBuffer.wrap(password)
val passwordByteBuffer = Charset.defaultCharset().encode(passwordCharBuffer)
passwordCharBuffer.clear()
val passwordBytes = ByteArray(passwordByteBuffer.remaining())
passwordByteBuffer.get(passwordBytes).clear()
val result = deriveKey(login.toByteArray(), passwordBytes,
WALLET_ID_MASTER_KEY.toByteArray(), kdfAttributes)
passwordBytes.fill(0)
return result
}
/**
* Derives wallet ID for given params and encodes it into HEX
*
* @see deriveKey
*/
@JvmStatic
fun deriveAndEncodeWalletId(login: String,
password: CharArray,
kdfAttributes: KdfAttributes): String {
return deriveWalletId(login, password, kdfAttributes).encodeHexString()
}
/**
* Derives wallet key for given params
*
* @see ScryptWithMasterKeyDerivation
* @see <a href="https://tokend.gitlab.io/docs/#wallet-id-derivation">Wallet key derivation docs</a>
*/
@JvmStatic
fun deriveKey(login: ByteArray,
password: ByteArray,
masterKey: ByteArray,
kdfAttributes: KdfAttributes): ByteArray {
val derivation = ScryptWithMasterKeyDerivation(kdfAttributes.n, kdfAttributes.r,
kdfAttributes.p, login, masterKey)
val salt = kdfAttributes.salt
?: throw IllegalArgumentException("KDF salt is required for derivation")
return derivation.derive(password, salt, kdfAttributes.bytes)
}
/**
* Generate salt for system KDF params.
*/
@JvmStatic
@JvmOverloads
fun generateKdfSalt(lengthBytes: Int = KDF_SALT_LENGTH_BYTES): ByteArray {
return SecureRandom().generateSeed(lengthBytes)
}
private const val WALLET_ID_MASTER_KEY = "WALLET_ID"
private const val WALLET_KEY_MASTER_KEY = "WALLET_KEY"
const val KDF_SALT_LENGTH_BYTES = 16
} | 0 | Kotlin | 1 | 14 | 5252e7441be26091a45c8dc8a87913bb0ebd1606 | 3,288 | kotlin-sdk | Apache License 2.0 |
bilgitesti/android/app/src/main/kotlin/com/example/bilgitesti/MainActivity.kt | symys | 443,495,927 | false | {"Dart": 61203, "Swift": 4040, "Kotlin": 1301, "Objective-C": 380} | package com.example.bilgitesti
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | Dart | 0 | 0 | 3498e6d6b49bd2c585caad1a0a9a294d0896b26c | 127 | flutter_kodplanet | MIT License |
ast-model/src/org/jetbrains/dukat/astModel/expressions/templates/ExpressionTemplateTokenModel.kt | Kotlin | 159,510,660 | false | {"Kotlin": 2656346, "WebIDL": 323681, "TypeScript": 135641, "JavaScript": 19475, "ANTLR": 11333} | package org.jetbrains.dukat.astModel.expressions.templates
import org.jetbrains.dukat.astModel.expressions.ExpressionModel
data class ExpressionTemplateTokenModel(
val expression: ExpressionModel
) : TemplateTokenModel | 242 | Kotlin | 43 | 508 | 55213ea607fb42ff13b6278613c8fbcced9aa418 | 224 | dukat | Apache License 2.0 |
src/commonMain/kotlin/model/ValidationResponseException.kt | hapifhir | 285,363,653 | false | {"Kotlin": 361881, "JavaScript": 97107, "HTML": 4570, "Dockerfile": 1410, "CSS": 202} | package model
class ValidationResponseException(val httpStatusCode: Int, message: String) : Exception(message) {
} | 23 | Kotlin | 11 | 17 | 9955214bf616a80958e3bd45637b27da44d4f6cb | 115 | org.hl7.fhir.validator-wrapper | Apache License 2.0 |
app/src/main/java/com/bso112/binder/example/util/paging/PagingExt.kt | bso112 | 646,378,583 | false | null | package com.bso112.binder.example.util.paging
import androidx.paging.CombinedLoadStates
import androidx.paging.LoadState
import androidx.paging.PagingData
import androidx.paging.flatMap
fun CombinedLoadStates.isEmpty(count: Int) =
source.refresh is LoadState.NotLoading && source.prepend.endOfPaginationReached && count < 1
fun CombinedLoadStates.hasError(): Boolean = allState.any { it is LoadState.Error }
fun CombinedLoadStates.getError(): Throwable? =
allState.firstNotNullOfOrNull { it as? LoadState.Error }?.error
fun CombinedLoadStates.isLoading(): Boolean = allState.any { it is LoadState.Loading }
val CombinedLoadStates.allState: List<LoadState>
get() = listOf(
refresh,
prepend,
append
)
fun <T : Any, R : Any> PagingData<T>.flatMapIndexed(block: (index: Int, item: T) -> List<R>): PagingData<R> {
var index = 0
return flatMap {
block(index, it).also {
index += 1
}
}
}
| 0 | Kotlin | 0 | 1 | 11f503e17807dc4eac02fd9b7349ed1e801c1964 | 971 | Binder | MIT License |
compiler/testData/codegen/box/directInvokeOptimization/contructorRef.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // CHECK_BYTECODE_TEXT
// JVM_IR_TEMPLATES
// 0 invoke\(
class C(x: String, y: String) {
val yx = y + x
}
fun box() =
::C.invoke("K", "O").yx
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 152 | kotlin | Apache License 2.0 |
idea/testData/quickfix/deprecatedSymbolUsage/classUsages/inAliasSimple.kt | android | 263,405,600 | true | null | // "Replace with 'NewClass'" "true"
@Deprecated("", ReplaceWith("NewClass"))
class OldClass
class NewClass
typealias Old = <caret>OldClass
val a: Old = Old() | 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 161 | kotlin | Apache License 2.0 |
app/src/main/java/com/hermanowicz/cv/di/common/view/View.kt | Szampi | 264,700,458 | false | null | package com.hermanowicz.cv.di.common.view
interface View
| 0 | Kotlin | 0 | 0 | b9cd553d3d1a97481f0a09bae8ca05ea01fa1d0c | 59 | Cv | MIT License |
compiler/backend.common.jvm/src/org/jetbrains/kotlin/codegen/signature/AsmTypeFactory.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* 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.codegen.signature
import org.jetbrains.kotlin.builtins.PrimitiveType
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.load.kotlin.JvmTypeFactory
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.org.objectweb.asm.Type
object AsmTypeFactory : JvmTypeFactory<Type> {
override fun boxType(possiblyPrimitiveType: Type): Type =
AsmUtil.boxType(possiblyPrimitiveType)
override fun createFromString(representation: String): Type =
Type.getType(representation)
override fun createPrimitiveType(primitiveType: PrimitiveType): Type =
AsmTypes.valueTypeForPrimitive(primitiveType)
override fun createObjectType(internalName: String): Type =
Type.getObjectType(internalName)
override fun toString(type: Type): String =
type.descriptor
override val javaLangClassType: Type
get() = AsmTypes.JAVA_CLASS_TYPE
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 1,548 | kotlin | Apache License 2.0 |
src/main/kotlin/Variables.kt | mustajab-ikram | 533,452,617 | false | {"Kotlin": 95245} | // Variable is a box where you store your data. It has a name by which you access this data or update this data.
// Let's take one example - you are playing a game where you have your score. Every time you do something in the game - your score increments.
// This score is stored as a variable in your application. So simply put - a variable is a place to store data that changes when your application runs.
// That's why it is named as variable - something that varies.
// Declaring values is done using either "var" or "val". "val" declarations cannot be reassigned, whereas "vars" can.
/*
Data Types In Kotlin
As said above, variables are simple boxes. Now we need to define the size of the box, and we need to define the type of data you will be storing in these boxes.
For this information, we have data types - Data Types define the type of the data you will be storing in a variable and also defines the size.
Kotlin has a variety of data types to store text data, numbers, and booleans. These are as follows -
Numbers - Superclass for all platform classes representing numeric values.
INTEGER (Byte, Short, Int, Long) - Numbers without decimals. E.g. 1, -5, 10, 224545
FLOATING POINT ( Float, Double) - Numbers with decimals. E.g. 11.23, 3.14 etc
CHAR - Stores single character E.g. M or F
Text Data -
String - Store multiple characters. E.g. Hello, Kotlin, etc.
Boolean
True/False
*/
fun main(args: Array<String>) {
/*
Kotlin has powerful type inference, which means that the Kotlin compiler can automatically identify the data type of the variable.
The compiler knows this from the initializer. So, if you’ve initialized the value of the variable on the declaration, you don’t need to define the data type explicitly because every primitive type has a default value.
The compiler will directly assume the size and type of the variable by that.
*/
val intNumber: Int = 10 // Declares an immutable variable of typr int and initializes it
var pi: Float = 3.14F // Declares a mutable variable and initializes it.
val precisePi: Double = 3.14159265359 // Declares an immutable variable and initializes it.
val bigNum = 20L // Declares an immutable variable and initializes it without specifying the type. The compiler infers the type Long.
var state: Byte // Declares a variable without initialization.
var myNumber: Number = 1903 // Superclass for all platform classes representing numeric values.
myNumber = 19.03 // Returns the value of this number as a Double, which may involve rounding.
myNumber = 1903F // Returns the value of this number as a Float, which may involve rounding.
myNumber = 1903L // Returns the value of this number as a Long, which may involve rounding or truncation.
// Same for Int, Char, Short, Byte
val simpleString = "Hello, World!"
// A raw string is delimited by a triple quote (""").
// Raw strings can contain newlines and any other characters.
val rawString = """
- Kotlin is a statically typed language. This means that a variable can only be assigned to objects of one fixed type, the type of variable.
- An advantage of statically typed language is that the compiler can catch the type errors during the compilation before the program is even run.
- A good compiler can also generate more efficient code for a statically typed language, as the type of objects is already known during the compilation.
- Consider the function to add two numbers:
fun test(a: Int, b: Int) {
println(a + b)
}
- Here, it is clear to the compiler that the + operator means integer addition and so the code for the function can immediately add two numbers.
One disadvantage of statically typed languages is that one has to write type names everywhere but kotlin saves us from that through its powerful type inference
"""
println(rawString)
}
| 0 | Kotlin | 0 | 4 | f3293e91212e973945a96f6ae90f2c442acb9298 | 4,084 | Kotlin_Tutorial | MIT License |
src/main/java/ink/anur/io/common/handler/EventDriverPoolHandler.kt | anurnomeru | 242,305,129 | false | null | package ink.anur.io.common.handler
import ink.anur.common.pool.EventDriverPool
import ink.anur.common.struct.Request
import ink.anur.pojo.common.AbstractStruct
import ink.anur.pojo.enumerate.RequestTypeEnum
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler
import org.slf4j.LoggerFactory
import java.nio.ByteBuffer
/**
* Created by <NAME> on 2020/3/1
*
* 将收到的消息扔进 EventDriverPool,再给到 CoordinateMessageService 消费
*/
class EventDriverPoolHandler : SimpleChannelInboundHandler<ByteBuffer>() {
private val logger = LoggerFactory.getLogger(this::class.java)
override fun channelRead0(ctx: ChannelHandlerContext?, msg: ByteBuffer?) {
if (ctx != null && msg != null) {
var sign = 0
try {
sign = msg.getInt(AbstractStruct.TypeOffset)
} catch (e: Exception) {
e.printStackTrace()
}
val typeEnum = RequestTypeEnum.parseByByteSign(sign)
if (typeEnum != RequestTypeEnum.HEAT_BEAT) {
logger.trace("<--- 收到了类型为 $typeEnum 的消息")
}
EventDriverPool.offer(Request(msg, typeEnum, ctx.channel()))
} else {
logger.error("Channel HandlerContext or its byte buffer in pipeline is null")
}
}
} | 1 | Kotlin | 1 | 5 | 27db6442ef9d4abc594d7e7719a8c772f03e61b6 | 1,374 | kanashi | MIT License |
adapters-threetenabp/src/main/kotlin/com/redissi/moshi/adapter/iso8601/threetenabp/LocalDateTimeAdapter.kt | IliasRedissi | 236,198,331 | false | null | package com.redissi.moshi.adapter.iso8601.threeten
import com.squareup.moshi.*
import org.threeten.bp.LocalDateTime
import org.threeten.bp.format.DateTimeFormatter
class LocalDateTimeAdapter {
private val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")
@ToJson fun toJson(localDateTime: LocalDateTime?): String {
if (localDateTime == null) {
return "null"
}
return localDateTime.format(formatter)
}
@FromJson fun fromJson(localDateTime: String): LocalDateTime? {
if (localDateTime == "null") {
return null
}
return LocalDateTime.parse(localDateTime)
}
} | 0 | Kotlin | 0 | 0 | 09fc0c92b4584f2b17e2a50e45ee6d93e44b3f47 | 672 | moshi-adapter-iso8601 | Apache License 2.0 |
wire4/src/commonTest/kotlin/mqtt/wire4/control/packet/ConnectionAcknowledgmentTests.kt | thebehera | 171,056,445 | false | null | @file:Suppress("EXPERIMENTAL_API_USAGE")
package mqtt.wire4.control.packet
import mqtt.buffer.BufferMemoryLimit
import mqtt.buffer.allocateNewBuffer
import mqtt.wire.control.packet.format.fixed.get
import mqtt.wire4.control.packet.ConnectionAcknowledgment.VariableHeader
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class ConnectionAcknowledgmentTests {
@Test
fun serializeDeserializeDefault() {
val buffer = allocateNewBuffer(4u, limits)
val actual = ConnectionAcknowledgment()
actual.serialize(buffer)
buffer.resetForRead()
val expected = ControlPacketV4.from(buffer)
assertEquals(expected, actual)
}
@Test
fun bit0SessionPresentFalseFlags() {
val buffer = allocateNewBuffer(4u, limits)
val model = ConnectionAcknowledgment()
model.header.serialize(buffer)
buffer.resetForRead()
val sessionPresentBit = buffer.readUnsignedByte().get(0)
assertFalse(sessionPresentBit)
val buffer2 = allocateNewBuffer(4u, limits)
model.serialize(buffer2)
buffer2.resetForRead()
val result = ControlPacketV4.from(buffer2) as ConnectionAcknowledgment
assertFalse(result.header.sessionPresent)
}
@Test
fun bit0SessionPresentFlags() {
val buffer = allocateNewBuffer(4u, limits)
val model = ConnectionAcknowledgment(VariableHeader(true))
model.header.serialize(buffer)
buffer.resetForRead()
assertTrue(buffer.readUnsignedByte().get(0))
}
}
val limits = object : BufferMemoryLimit {
override fun isTooLargeForMemory(size: UInt): Boolean = false
} | 2 | Kotlin | 1 | 32 | 2f2d176ca1d042f928fba3a9c49f4bc5ff39495f | 1,721 | mqtt | Apache License 2.0 |
test/regression/42.test.kt | nishtahir | 124,984,470 | false | {"Kotlin": 73919, "JavaScript": 12017} | // SYNTAX TEST "source.kotlin" "Camel cased variable declaration should not have class"
camelCased?.let { print(it) }
// ^^^^^ -entity.name.type.class.kotlin
// ^^ punctuation.accessor.dot.safe.kotlin
// ^^^ support.function.kotlin
// ^ meta.block.kotlin punctuation.section.group.begin.kotlin
// ^ meta.block.kotlin meta.group.kotlin punctuation.section.group.begin.kotlin
// ^ meta.block.kotlin meta.group.kotlin punctuation.section.group.end.kotlin
// ^ meta.block.kotlin punctuation.section.group.end.kotlin | 3 | Kotlin | 5 | 12 | b65a18d4c23eedcd2bc280cd04282d29d191721a | 611 | language-kotlin | Apache License 2.0 |
app/src/main/java/com/example/kotlin_jetpack/adpter/SongListAdapter.kt | zzm525465248 | 492,705,951 | false | {"Kotlin": 236095, "Java": 113} | package com.example.kotlin_jetpack.adpter
import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.kotlin_jetpack.R
import com.example.kotlin_jetpack.bean.Results
import com.example.kotlin_jetpack.ui.song_list.Song_list
class SongListAdapter :RecyclerView.Adapter<SongListAdapter.ViewHoldr>() {
private val mlist= arrayListOf<Results>()
class ViewHoldr(itemview:View) :RecyclerView.ViewHolder(itemview) {
val name: TextView = itemView.findViewById(R.id.tv_name)
val id: TextView = itemView.findViewById(R.id.textView3)
val imag: ImageView =itemView.findViewById(R.id.imag)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHoldr {
val itemview= LayoutInflater.from(parent.context).inflate(R.layout.rv_test,parent,false)
return ViewHoldr(itemview)
}
override fun onBindViewHolder(holder: ViewHoldr, position: Int) {
holder.itemView.apply {
with(mlist[position]){
holder.name.text=name
holder.id.text=(playCount/10000).toString()+"万"
Glide.with(context).load(picUrl).into(holder.imag)
holder.imag.setOnClickListener {
Log.d("sheet_id",id.toString())
val intent=Intent(context,Song_list::class.java)
intent.putExtra("id",id)
context.startActivity(intent)
}
}
}
}
override fun getItemCount(): Int {
return mlist.size
}
fun setData(it: List<Results>?) {
mlist.clear()
if (it != null) {
mlist.addAll(it)
}
notifyDataSetChanged()
}
} | 0 | Kotlin | 0 | 0 | ff8eddd25b68d671e4eb2de2bcfc67a1e81c48df | 1,943 | Ordinary_music | Apache License 2.0 |
kotlin-script-runner-server/src/main/kotlin/jetbrains/buildServer/runner/kotlinBuildStep/KotlinDowloadableToolVersion.kt | JetBrains | 347,072,032 | false | {"Kotlin": 32979, "Java": 3159} |
package jetbrains.buildServer.runner.kotlinBuildStep
import jetbrains.buildServer.tools.SimpleToolVersion
import jetbrains.buildServer.tools.ToolVersionIdHelper
import jetbrains.buildServer.tools.available.DownloadableToolVersion
class KotlinDowloadableToolVersion(val versionNumber: String): DownloadableToolVersion,
SimpleToolVersion(KotlinToolType.INSTANCE, versionNumber,
ToolVersionIdHelper.getToolId(KotlinToolType.INSTANCE, versionNumber),
"${KOTLIN_COMPILER_TOOL_DISPLAY_NAME} $versionNumber"
) {
override fun getDownloadUrl() = "https://github.com/JetBrains/kotlin/releases/download/v${version}/kotlin-compiler-${version}.zip"
override fun getDestinationFileName() = "kotlin-compiler-${version}.zip"
} | 5 | Kotlin | 7 | 2 | 3bcfbc92c4a791adb1d34fb381f1f0baf9f2782c | 772 | teamcity-kotlin-script-runner | Apache License 2.0 |
recyclerview-example/src/main/java/com/dwiariyanto/recyclerview/example/feature/singleitem/SingleItemActivity.kt | Cla1ty | 122,072,420 | false | null | /**************************************************************************************************
* *
* Created by <NAME> (<EMAIL>) *
* Copyright © 2018. All rights reserved. *
* *
* *
* Create On: *
* Sunday, February 18, 2018 at 21:25 *
* *
**************************************************************************************************/
package com.dwiariyanto.recyclerview.example.feature.singleitem
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import com.dwiariyanto.recyclerview.example.R
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.recyclerview.*
import javax.inject.Inject
class SingleItemActivity : AppCompatActivity(),
SingleItemView {
@Inject lateinit var presenter: SingleItemPresenter
@Inject lateinit var adapter: SingleItemAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AndroidInjection.inject(this)
setContentView(R.layout.recyclerview)
recyclerView.adapter = adapter
}
override fun onStart() {
super.onStart()
presenter.loadData()
}
override fun onPause() {
super.onPause()
presenter.removeCallback()
}
override fun showData(dataList: List<Any>) {
adapter.data = dataList
recyclerView.requestLayout()
}
override fun onItemClick(number: String) {
Toast.makeText(
this,
"Click $number",
Toast.LENGTH_SHORT
)
.show()
}
}
| 0 | Kotlin | 1 | 2 | 0dab419247e924717e0958a22ffbe2dbdaf8c3a3 | 2,132 | Recycler_View_Adapter_Wrapper | Apache License 2.0 |
sample/src/main/java/soup/animation/sample/SettingsFragment.kt | fornewid | 271,574,899 | false | null | package soup.animation.sample
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.core.app.ActivityOptionsCompat
import androidx.dynamicanimation.animation.DynamicAnimation
import androidx.dynamicanimation.animation.SpringAnimation
import androidx.dynamicanimation.animation.SpringForce
import androidx.dynamicanimation.animation.withSpringForceProperties
import androidx.fragment.app.Fragment
import soup.animation.sample.databinding.SettingsFragmentBinding
class SettingsFragment : Fragment(R.layout.settings_fragment) {
private lateinit var binding: SettingsFragmentBinding
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = SettingsFragmentBinding.bind(view).apply {
profileSection.setOnClickListener {
activity?.run {
if (GlobalData.isLogin) {
navigateToProfile(profileImage)
} else {
navigateToLogin(profileImage)
}
}
}
val panel = buttonPanel.springAnimationOf(DynamicAnimation.TRANSLATION_X)
val icon1 = icon01.springAnimationOf(DynamicAnimation.TRANSLATION_X)
val icon2 = icon02.springAnimationOf(DynamicAnimation.TRANSLATION_X)
val icon3 = icon03.springAnimationOf(DynamicAnimation.TRANSLATION_X)
arrow.setOnClickListener {
it.isSelected = it.isSelected.not()
if (it.isSelected) {
panel.animateToFinalPosition(0f)
icon1.animateToFinalPosition(0f)
icon2.animateToFinalPosition(0f)
icon3.animateToFinalPosition(0f)
} else {
panel.animateToFinalPosition(resources.getDimension(R.dimen.settings_button_panel_translation_x))
val transX = resources.getDimension(R.dimen.settings_button_icon_translation_x)
icon1.animateToFinalPosition(transX)
icon2.animateToFinalPosition(transX)
icon3.animateToFinalPosition(transX)
}
}
}
}
private fun View.springAnimationOf(viewProperty: DynamicAnimation.ViewProperty): SpringAnimation {
return SpringAnimation(this, viewProperty)
.withSpringForceProperties {
dampingRatio = SpringForce.DAMPING_RATIO_LOW_BOUNCY
stiffness = SpringForce.STIFFNESS_LOW
}
}
override fun onResume() {
super.onResume()
if (GlobalData.isLogin) {
binding.profileImage.setImageResource(R.drawable.user_icon)
}
}
private fun Activity.navigateToProfile(view: View) {
val intent = Intent(this, ProfileActivity::class.java)
val options = ActivityOptionsCompat
.makeSceneTransitionAnimation(this, view, view.transitionName)
ActivityCompat.startActivity(this, intent, options.toBundle())
}
private fun Activity.navigateToLogin(view: View) {
val intent = Intent(this, LoginActivity::class.java)
val options = ActivityOptionsCompat
.makeSceneTransitionAnimation(this, view, view.transitionName)
ActivityCompat.startActivity(this, intent, options.toBundle())
}
}
| 0 | null | 5 | 41 | d4b87fd7f307dc940a4086b18d287db2ceb64051 | 3,485 | android-animation-11p-more | Apache License 2.0 |
Basic/src/main/kotlin/classes/Constructor3.kt | fengzhizi715 | 137,714,143 | false | {"Kotlin": 118221, "Java": 6915} | package classes
/**
* Created by tony on 2018/8/10.
*/
class Constructor3(str:String) {
init {
println("$str")
}
constructor(str1: String, str2: String):this(str1) { // 调用主构造函数以及初始化块
println("$str1 $str2")
}
fun foo() = println("this is foo function")
}
fun main(args: Array<String>) {
val obj = Constructor3("hello","world")
obj.foo()
} | 0 | Kotlin | 15 | 60 | a46ce33b2efca69b5a6a42bba56407847b8521c1 | 417 | kotlin_tutorial | Apache License 2.0 |
oglHelper/src/main/java/com/dima6120/oglHelper/data/RGBA.kt | dima6120 | 298,513,503 | false | null | package com.dima6120.oglHelper.data
import android.graphics.Color
import androidx.core.graphics.ColorUtils
class RGBA {
private val EPSILON = 0.00001f
var r = 0f // red = 0..1
var g = 0f // green = 0..1
var b = 0f // blue = 0..1
var a = 0f // alpha = 0..1
constructor()
constructor(r: Float, g: Float, b: Float, a: Float) {
set(r, g, b, a)
}
constructor(rgba: RGBA) {
set(rgba)
}
constructor(rgb: RGB) {
set(rgb)
}
constructor(color: Int) {
set(color)
}
constructor(hsl: HSL) {
set(hsl)
}
fun set(r: Float, g: Float, b: Float, a: Float) {
this.r = r
this.g = g
this.b = b
this.a = a
}
fun set(rgb: RGB) {
set(rgb.r, rgb.g, rgb.b, 1f)
}
fun set(hsl: HSL) {
set(ColorUtils.HSLToColor(floatArrayOf(hsl.h, hsl.s, hsl.l)))
}
fun set(rgba: RGBA) {
set(rgba.r, rgba.g, rgba.b, rgba.a)
}
fun set(color: Int) {
set(Color.red(color) / 255f, Color.green(color) / 255f, Color.blue(color) / 255f, Color.alpha(color) / 255f)
}
} | 0 | Kotlin | 0 | 0 | d997580dd751d6ba82a6ad5ffbb56a7099aa63ba | 1,136 | OGLHelper | Apache License 2.0 |
core/network/imp/src/main/kotlin/com/vpopov/movie/now/core/network/imp/di/CoreNetworkComponentHolder.kt | Va1erii | 461,271,627 | false | {"Kotlin": 36823} | package com.vpopov.movie.now.core.network.imp.di
import com.vpopov.movienow.core.di.ComponentHolder
import com.vpopov.movienow.core.network.api.CoreNetworkApi
object CoreNetworkComponentHolder : ComponentHolder<CoreNetworkApi, CoreNetworkDependencies> {
@Volatile
private var coreNetworkComponent: CoreNetworkComponent? = null
override fun init(dependencies: CoreNetworkDependencies) {
if (coreNetworkComponent == null) {
synchronized(CoreNetworkComponentHolder::class.java) {
if (coreNetworkComponent == null) {
coreNetworkComponent = DaggerCoreNetworkComponent.factory()
.create(dependencies)
}
}
}
}
override fun get(): CoreNetworkApi {
return checkNotNull(coreNetworkComponent) { "CoreNetworkComponent was not initialized!" }
}
override fun reset() {
coreNetworkComponent = null
}
}
| 0 | Kotlin | 0 | 0 | ab03f4cc5484548b0d40486fac7b90c1c8e75470 | 956 | movie-now | MIT License |
core/photos/src/main/java/st/slex/csplashscreen/core/photos/ui/component/LazyListPhotoItem.kt | stslex | 413,161,718 | false | {"Kotlin": 332621, "Ruby": 1145} | package st.slex.csplashscreen.core.photos.ui.component
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import st.slex.csplashscreen.core.photos.ui.model.PhotoModel
import st.slex.csplashscreen.core.ui.components.base.MainUserAvatar
import st.slex.csplashscreen.core.ui.components.base.MediumText
import st.slex.csplashscreen.core.ui.components.base.PhotosBaseItem
import st.slex.csplashscreen.core.ui.theme.Dimen
@Composable
fun LazyListPhotoItem(
item: PhotoModel,
onUserClick: (username: String) -> Unit,
onImageClick: (imageId: String) -> Unit,
modifier: Modifier = Modifier,
) {
PhotosBaseItem(
modifier = modifier,
onContainerClick = remember(item.uuid) {
{ onImageClick(item.uuid) }
},
onHeaderClick = remember(item.username) {
{ onUserClick(item.username) }
},
url = item.urls.regular,
headerContent = {
MainUserAvatar(item.userUrl)
Spacer(modifier = Modifier.width(Dimen.medium))
MediumText(item.username)
}
)
}
| 2 | Kotlin | 0 | 3 | 94b3ee35d150cc907f23f37601bef8bb877b8d3d | 1,240 | CSplashScreen | Apache License 2.0 |
compiler/fir/tree/src/org/jetbrains/kotlin/fir/utils/exceptions/firExceptionUtils.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.utils.exceptions
import org.jetbrains.kotlin.KtSourceElement
import org.jetbrains.kotlin.fir.FirElement
import org.jetbrains.kotlin.fir.FirElementWithResolveState
import org.jetbrains.kotlin.fir.FirModuleData
import org.jetbrains.kotlin.fir.renderer.*
import org.jetbrains.kotlin.fir.symbols.ConeClassLikeLookupTag
import org.jetbrains.kotlin.fir.symbols.ConeClassifierLookupTag
import org.jetbrains.kotlin.fir.symbols.FirBasedSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirCallableSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirClassifierSymbol
import org.jetbrains.kotlin.fir.types.ConeKotlinType
import org.jetbrains.kotlin.utils.exceptions.ExceptionAttachmentBuilder
fun ExceptionAttachmentBuilder.withFirEntry(name: String, fir: FirElement) {
withEntry(name, fir) {
FirRenderer(
resolvePhaseRenderer = FirResolvePhaseRenderer(),
declarationRenderer = FirDeclarationRendererWithAttributes(),
fileAnnotationsContainerRenderer = FirFileAnnotationsContainerRenderer(),
).renderElementAsString(it)
}
withEntry("${name}ElementKind", fir.source?.kind?.let { it::class.simpleName })
if (fir is FirElementWithResolveState) {
withModuleDataEntry("${name}ModuleData", fir.moduleData)
}
withSourceEntry("${name}Source", fir.source)
}
fun ExceptionAttachmentBuilder.withFirSymbolIdEntry(name: String, symbol: FirBasedSymbol<*>?) {
when (symbol) {
is FirClassifierSymbol -> withFirLookupTagEntry(name, symbol.toLookupTag())
is FirCallableSymbol -> withEntry(name, symbol.callableId.toString())
else -> withEntry(name, symbol.toString())
}
}
fun ExceptionAttachmentBuilder.withFirLookupTagEntry(name: String, lookupTag: ConeClassifierLookupTag?) {
withEntry(name, lookupTag) { tag ->
when (tag) {
is ConeClassLikeLookupTag -> tag.classId.asString()
else -> tag.name.asString()
}
}
}
fun ExceptionAttachmentBuilder.withSourceEntry(name: String, source: KtSourceElement?) {
withEntry(name, source) { it.getElementTextInContextForDebug() }
}
fun ExceptionAttachmentBuilder.withModuleDataEntry(name: String, moduleData: FirModuleData?) {
withEntry(name, moduleData) { module ->
buildString {
append("Name: ${module.name}, ")
append("Platform: ${module.platform}")
}
}
}
fun ExceptionAttachmentBuilder.withFirSymbolEntry(name: String, symbol: FirBasedSymbol<*>) {
withFirEntry("${name}Fir", symbol.fir)
}
fun ExceptionAttachmentBuilder.withConeTypeEntry(name: String, coneType: ConeKotlinType?) {
withEntry(name, coneType) {
buildString { ConeTypeRendererForDebugging(this).render(it) }
}
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 2,978 | kotlin | Apache License 2.0 |
app/src/main/java/algo/kelvin373/banner/viewpager/TVShowInter.kt | kelvintandrio | 203,317,152 | false | null | package algo.kelvin373.banner.viewpager
import androidx.lifecycle.LiveData
import io.reactivex.disposables.CompositeDisposable
interface TVShowInter {
fun getTVShowAiringToday(
disposable: CompositeDisposable,
statusResponseTVShow: StatusResponseTVShow
): LiveData<List<DataTVShow>>
} | 0 | Kotlin | 0 | 0 | 57932705ef38381dce9f2e4a233863b89604624e | 310 | banner-pageadapter | Apache License 2.0 |
src/io/github/tozydev/fastmodule/modules/settings/PaperSettings.kt | TozyDev | 739,192,532 | false | {"Kotlin": 66630} | /*
* Copyright 2024 <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.tozydev.fastmodule.modules.settings
import org.gradle.api.provider.Property
abstract class PaperSettings {
abstract val version: Property<PaperVersion>
abstract val internal: Property<Boolean>
companion object {
val DEFAULT_VERSION = PaperVersion.V1_20_4
}
}
@Suppress("unused")
enum class PaperVersion {
V1_19_3,
V1_19_4,
V1_20,
V1_20_1,
V1_20_2,
V1_20_4;
val minecraftVersion get() = name.substring(1).replace('_', '.')
val artifactVersion get() = "$minecraftVersion-R0.1-SNAPSHOT"
}
| 11 | Kotlin | 0 | 1 | 16ed17ca0ff5a0c6d6028f2f8eeb36b7745a2938 | 1,166 | fast-module-gradle-plugin | Apache License 2.0 |
src/main/kotlin/no/nav/helse/flex/service/GjenapneSykmeldingService.kt | navikt | 475,306,289 | false | {"Kotlin": 1694951, "Dockerfile": 267} | package no.nav.helse.flex.service
import no.nav.helse.flex.domain.Arbeidssituasjon
import no.nav.helse.flex.domain.Soknadstatus
import no.nav.helse.flex.domain.Soknadstatus.AVBRUTT
import no.nav.helse.flex.domain.Soknadstatus.FREMTIDIG
import no.nav.helse.flex.domain.Soknadstatus.NY
import no.nav.helse.flex.domain.Soknadstatus.UTKAST_TIL_KORRIGERING
import no.nav.helse.flex.domain.Sykepengesoknad
import no.nav.helse.flex.kafka.consumer.SYKMELDINGSENDT_TOPIC
import no.nav.helse.flex.kafka.producer.SoknadProducer
import no.nav.helse.flex.logger
import no.nav.helse.flex.repository.SykepengesoknadDAO
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional(rollbackFor = [Throwable::class])
class GjenapneSykmeldingService(
private val soknadProducer: SoknadProducer,
private val sykepengesoknadDAO: SykepengesoknadDAO,
) {
val log = logger()
fun prosesserTombstoneSykmelding(
sykmeldingId: String,
topic: String,
) {
val soknaderTilSykmeldingSomKanSlettes =
sykepengesoknadDAO
.finnSykepengesoknaderForSykmelding(sykmeldingId)
.filter { listOf(NY, FREMTIDIG, AVBRUTT, UTKAST_TIL_KORRIGERING).contains(it.status) }
.filter { it.arbeidssituasjon != Arbeidssituasjon.ARBEIDSTAKER }
if (soknaderTilSykmeldingSomKanSlettes.isEmpty()) {
log.info("Mottok status åpen for sykmelding $sykmeldingId på kafka. Ingen tilhørende søknader.")
return
}
if (topic == SYKMELDINGSENDT_TOPIC) {
log.error("Prosesserte åpen melding for $sykmeldingId fra sendt topicet. Den kan ikke endres så dette skal ikke skje.")
return
}
soknaderTilSykmeldingSomKanSlettes.slettSoknader()
}
private fun List<Sykepengesoknad>.slettSoknader() {
this.map { it.copy(status = Soknadstatus.SLETTET) }
.forEach {
soknadProducer.soknadEvent(it, null, false)
sykepengesoknadDAO.slettSoknad(it)
}
}
}
| 3 | Kotlin | 0 | 4 | 46f4bc29cdc7631a26bf673f23c25ec208bc3fc3 | 2,120 | sykepengesoknad-backend | MIT License |
app/src/main/java/com/tomg/fiiok9control/eq/ui/EqAdapter.kt | Tommy-Geenexus | 422,602,254 | false | {"Java": 371833, "Kotlin": 305020} | /*
* Copyright (c) 2021-2023, <NAME> (<EMAIL>)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY,WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tomg.fiiok9control.eq.ui
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.tomg.fiiok9control.databinding.ItemEqBinding
import com.tomg.fiiok9control.eq.EqPreSet
import com.tomg.fiiok9control.eq.EqValue
class EqAdapter(
private val listener: Listener,
private val currentEqEnabled: () -> Boolean,
private val currentEqPreSet: () -> EqPreSet,
private val currentEqValues: () -> List<EqValue>,
private val currentIsLoading: () -> Boolean,
private val currentIsServiceConnected: () -> Boolean
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
interface Listener {
fun onEqEnabled(enabled: Boolean)
fun onEqPreSetRequested(eqPreSet: EqPreSet)
fun onUpdatePendingEqValues(value: EqValue)
fun onEqValueChanged(value: EqValue)
}
private companion object {
const val ITEM_CNT = 1
}
init {
setHasStableIds(true)
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): RecyclerView.ViewHolder {
return ItemEqViewHolder(
binding = ItemEqBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
),
listener = listener
)
}
override fun onBindViewHolder(
holder: RecyclerView.ViewHolder,
position: Int
) {
(holder as? ItemEqViewHolder)?.bindItemEq(
eqEnabled = currentEqEnabled(),
eqPreSet = currentEqPreSet(),
eqValues = currentEqValues(),
itemEnabled = currentIsServiceConnected() && !currentIsLoading()
)
}
override fun getItemViewType(position: Int) = position
override fun getItemId(position: Int) = position.toLong()
override fun getItemCount() = ITEM_CNT
}
| 1 | Java | 0 | 0 | cdb75ab15b5fa0d0bd2e1ce77a4bcb6ae0bb5e7c | 3,066 | fiio-k9-control | MIT License |
extensions/intellij/intellij_generator_plugin/src/main/java/com/bloc/intellij_generator_plugin/generator/components/BlocEventGenerator.kt | rahulmanthena | 271,642,479 | true | {"Dart": 101149, "Kotlin": 7737, "Objective-C": 2259, "Java": 2048, "Shell": 156} | package com.bloc.intellij_generator_plugin.generator.components
import com.bloc.intellij_generator_plugin.generator.Generator
class BlocEventGenerator(
blocName: String,
blocShouldUseEquatable: Boolean
) : Generator(blocName, blocShouldUseEquatable, templateName = "bloc_event") {
override fun fileName() = "${snakeCase()}_event.${fileExtension()}"
} | 0 | Dart | 1 | 0 | b895443508ead65ba01142c9b3a6b8025e4db016 | 365 | intellij_bloc_generator | MIT License |
app/src/main/java/com/example/myapplication/recipes/domain/util/OrderType.kt | violinyanev | 714,727,270 | false | {"Kotlin": 59205} | package com.example.myapplication.recipes.domain.util
sealed class OrderType {
object Ascending : OrderType()
object Descending : OrderType()
}
| 4 | Kotlin | 0 | 0 | bec06daa5be256235fd1c6c283ad79ea1dc8b5ff | 153 | my-app | Apache License 2.0 |
src/38_it_keyword_lambdas.kt | elboyev | 430,117,951 | false | {"Kotlin": 40960, "Java": 297} |
/*
* 1. 'it' keyword
* */
fun main(args: Array<String>) {
val program = Programs()
program.reverseAndDisplay("hello", { it.reversed() })
}
class Programs {
fun reverseAndDisplay(str: String, myFunc: (String) -> String) { // High Level Function with Lambda as Parameter
val result = myFunc(str) // it.reversed() ==> str.reversed() ==> "hello".reversed() = "olleh"
println(result)
}
}
| 0 | Kotlin | 4 | 7 | 752615afe8e5c3564bed86481c9a8b066a330404 | 427 | Kotlin_Tutorials | MIT License |
android/app/src/main/kotlin/com/geekflow/home_automation/MainActivity.kt | JobinBiju | 362,675,501 | false | {"Dart": 47687, "C++": 3590, "Swift": 404, "Kotlin": 125, "Objective-C": 38} | package com.geekflow.home_fi
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 5 | Dart | 39 | 107 | 82b6693bd1f72a556c8d1ae9c05c515b4980cbfd | 125 | Home-Fi | MIT License |
QRStoringHelper/app/src/main/java/studios/devs/mobi/qrstoringhelper/MainApplication.kt | ValeriJordanov | 321,771,563 | false | null | package studios.devs.mobi.qrstoringhelper
import android.app.Application
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.HasAndroidInjector
import studios.devs.mobi.qrstoringhelper.di.AppComponent
import studios.devs.mobi.qrstoringhelper.di.DaggerAppComponent
import studios.devs.mobi.qrstoringhelper.di.modules.AppModule
import javax.inject.Inject
class MainApplication: Application(), HasAndroidInjector {
companion object{
lateinit var appComponent: AppComponent
const val QR_STORING_HELPER_LOCAL_STORE = "QRStoringHelperLocalStore"
}
@Inject lateinit var androidInjector : DispatchingAndroidInjector<Any>
override fun androidInjector(): AndroidInjector<Any> = androidInjector
override fun onCreate() {
super.onCreate()
appComponent = DaggerAppComponent.builder().appModule(AppModule(this, this)).build()
appComponent.inject(this)
}
} | 0 | Kotlin | 0 | 0 | 71d8ecd7c3429157b72de94d096d36208b13b491 | 968 | QR-Storing-Helper | Apache License 2.0 |
web3walletcore/src/commonMain/kotlin/com/sonsofcrypto/web3walletcore/modules/authenticate/AuthenticateInteractor.kt | sonsofcrypto | 454,978,132 | false | {"Kotlin": 1509902, "Swift": 1165953, "Jupyter Notebook": 183824, "Objective-C": 77663, "Python": 39465, "Go": 20697, "C": 15793, "Java": 12789, "Shell": 4516} | package com.sonsofcrypto.web3walletcore.modules.authenticate
import com.sonsofcrypto.web3lib.services.keyStore.SignerStoreItem
import com.sonsofcrypto.web3lib.services.keyStore.SignerStoreService
interface AuthenticateInteractor {
fun keyStoreItem(): SignerStoreItem?
fun canUnlockWithBio(signerStoreItem: SignerStoreItem): Boolean
fun unlockWithBiometrics(
item: SignerStoreItem,
title: String,
handler: (AuthenticateData?, Error?) -> Unit
)
fun isValid(item: SignerStoreItem, password: String, salt: String): Boolean
}
class DefaultAuthenticateInteractor(
private val signerStoreService: SignerStoreService
): AuthenticateInteractor {
override fun keyStoreItem(): SignerStoreItem? = signerStoreService.selected
override fun canUnlockWithBio(signerStoreItem: SignerStoreItem): Boolean =
signerStoreItem.canUnlockWithBio() && signerStoreService.biometricsSupported()
override fun unlockWithBiometrics(
item: SignerStoreItem,
title: String,
handler: (AuthenticateData?, Error?) -> Unit
) {
signerStoreService.biometricAuthenticate(title) { success: Boolean, error: Error? ->
if (success) {
val password = signerStoreService.password(item) ?: ""
handler(AuthenticateData(password, ""), null)
} else {
handler(null, error ?: Error("Unknown error"))
}
}
}
override fun isValid(item: SignerStoreItem, password: String, salt: String): Boolean {
return try {
val secretStorage = signerStoreService.secretStorage(item, password) ?: return false
secretStorage.decrypt(password)
true
} catch (error: Throwable) {
false
}
}
}
| 1 | Kotlin | 2 | 6 | 16fd656b1570b7744fd7fa6339d1dd607573d121 | 1,802 | web3wallet | MIT License |
src/cypress/lexer/TokenType.kt | Shom770 | 537,689,516 | false | {"Kotlin": 20746, "Cypher": 17} | package cypress.lexer
enum class TokenType(val precedence: Int = 0){
// symbols
OPEN_PAREN,
CLOSE_PAREN,
OPEN_BRACE,
CLOSE_BRACE,
COMMA,
ASSIGN,
ARROW,
// operators
PLUS(3),
MINUS(3),
ASTERISK(5),
FORWARD_SLASH(5),
DOUBLE_ASTERISK(7),
LESS_THAN(1),
GREATER_THAN(1),
LESS_THAN_OR_EQUAL(1),
GREATER_THAN_OR_EQUAL(1),
EQUALS(1),
// identifiers and literals
INT,
FLOAT,
IDENTIFIER,
// keywords
NOT,
AND(11),
OR(9),
IF,
ELSE,
FOR,
PROC,
// delimiters for end of line/file
NEWLINE,
EOF;
companion object {
val conditionalTokens = hashSetOf(
LESS_THAN,
LESS_THAN_OR_EQUAL,
GREATER_THAN,
GREATER_THAN_OR_EQUAL,
EQUALS,
AND,
OR
)
}
} | 0 | Kotlin | 0 | 0 | 84c7b271972c0d7538ed25038a453f979bf6eaaf | 874 | cypress | MIT License |
app/src/main/java/com/sinthoras/randograf/cards/covers/CardGameStart.kt | SinTh0r4s | 444,149,281 | false | {"Java": 18033, "Kotlin": 17451} | package com.sinthoras.randograf.cards.covers
import com.sinthoras.randograf.R
class CardGameStart : CardCover() {
override fun getTitle(): Int {
return R.string.card_title_game_start
}
}
| 1 | Java | 0 | 0 | 5319ccb2ebbb9e90f957a065794ad5aebff20459 | 206 | Randograf | MIT License |
src/main/kotlin/com/corradowaver/bot/tts/yandex/YandexAuth.kt | corradowaver | 354,381,983 | false | null | package com.corradowaver.bot.tts.yandex
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
@Component
class YandexAuth(yandexCloudProperties: YandexCloudProperties) {
val yandexIamTokenUrl = "https://iam.api.cloud.yandex.net/iam/v1/tokens"
var folder = yandexCloudProperties.folder
var iamToken: String = ""
private var yandexPassportOAuthToken = yandexCloudProperties.token
@Scheduled(fixedRate = 6 * 60 * 60 * 1000, initialDelay = 1000)
fun scheduleMe() {
iamToken = requestIamToken()
}
private fun requestIamToken(): String =
khttp.get(
url = yandexIamTokenUrl,
data = "{\"yandexPassportOauthToken\":\"$yandex<PASSWORD>OAuthToken\"}"
)
.jsonObject.get("iamToken")
.toString()
}
| 0 | Kotlin | 0 | 4 | dba7145d7ce252a20d8982cc912f1ee4cd3d6779 | 796 | discord-bot-guild-girl-kt | MIT License |
director-core/src/main/kotlin/pw/dotdash/director/core/lexer/InputTokenizer.kt | TheFrontier | 240,782,509 | false | null | package pw.dotdash.director.core.lexer
import pw.dotdash.director.core.exception.ArgumentParseException
interface InputTokenizer {
@Throws(ArgumentParseException::class)
fun tokenize(arguments: String, lenient: Boolean): Sequence<Token>
} | 0 | Kotlin | 0 | 1 | fb3febc6e83d622a7dd32e2434b43b23a49cc36a | 249 | director | MIT License |
MapboxSearch/discover/src/test/java/com/mapbox/search/discover/DiscoverResultTest.kt | mapbox | 438,355,708 | false | {"Kotlin": 1983845, "Java": 42091, "Python": 18979, "Shell": 16647} | package com.mapbox.search.discover
import com.mapbox.geojson.Point
import com.mapbox.search.base.core.countryIso1
import com.mapbox.search.base.core.countryIso2
import com.mapbox.search.base.result.BaseSearchResultType
import com.mapbox.search.base.result.BaseServerSearchResultImpl
import com.mapbox.search.base.result.mapToBase
import com.mapbox.search.base.utils.extension.mapToPlatform
import com.mapbox.search.common.tests.CommonSdkTypeObjectCreators
import com.mapbox.search.common.tests.ReflectionObjectsFactory
import com.mapbox.search.common.tests.ToStringVerifier
import com.mapbox.search.common.tests.createCoreSearchAddress
import com.mapbox.search.common.tests.createCoreSearchAddressCountry
import com.mapbox.search.common.tests.createCoreSearchAddressRegion
import com.mapbox.search.common.tests.createTestCoreRoutablePoint
import com.mapbox.search.common.tests.createTestCoreSearchResult
import com.mapbox.search.common.tests.createTestResultMetadata
import com.mapbox.search.common.tests.withPrefabTestPoint
import io.mockk.mockk
import nl.jqno.equalsverifier.EqualsVerifier
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
internal class DiscoverResultTest {
@Test
fun `equals() and hashCode() functions are correct`() {
EqualsVerifier.forClass(DiscoverResult::class.java)
.withPrefabTestPoint()
.verify()
}
@Test
fun `toString() function is correct`() {
ToStringVerifier(
clazz = DiscoverResult::class,
objectsFactory = ReflectionObjectsFactory(
extraCreators = CommonSdkTypeObjectCreators.ALL_CREATORS
),
includeAllProperties = false
).verify()
}
@Test
fun `Check DiscoverApiResult`() {
val coreMetadata = createTestResultMetadata(
data = hashMapOf("iso_3166_1" to "fra", "iso_3166_2" to "fr")
)
val coreAddress = createCoreSearchAddress(
houseNumber = "test-house-number",
street = "test-street",
neighborhood = "test-neighborhood",
locality = "test-locality",
postcode = "test-postcode",
place = "test-place",
district = "test-district",
region = createCoreSearchAddressRegion("test-region"),
country = createCoreSearchAddressCountry("test-country"),
)
val coreResult = createTestCoreSearchResult(
names = listOf("<NAME>"),
addresses = listOf(coreAddress),
center = Point.fromLngLat(123.0, 456.0),
routablePoints = listOf(createTestCoreRoutablePoint()),
categories = listOf("restaurant", "cafe"),
categoryIds = listOf("restaurant-id", "cafe-id"),
brand = listOf("test-brand"),
brandId = "test-brand-id",
icon = "cafe",
metadata = coreMetadata
)
val baseResult = BaseServerSearchResultImpl(
listOf(BaseSearchResultType.POI),
coreResult.mapToBase(),
mockk(),
)
val discoverResult = DiscoverResult.createFromSearchResult(baseResult)
assertEquals(coreResult.names.first(), discoverResult.name)
assertEquals(coreResult.center, discoverResult.coordinate)
assertEquals(coreResult.routablePoints?.map { it.mapToPlatform() }, discoverResult.routablePoints)
assertEquals(coreResult.categories, discoverResult.categories)
assertEquals(coreResult.icon, discoverResult.makiIcon)
assertEquals(coreAddress.houseNumber, discoverResult.address.houseNumber)
assertEquals(coreAddress.street, discoverResult.address.street)
assertEquals(coreAddress.neighborhood, discoverResult.address.neighborhood)
assertEquals(coreAddress.locality, discoverResult.address.locality)
assertEquals(coreAddress.postcode, discoverResult.address.postcode)
assertEquals(coreAddress.place, discoverResult.address.place)
assertEquals(coreAddress.district, discoverResult.address.district)
assertEquals(coreAddress.region?.name, discoverResult.address.region)
assertEquals(coreAddress.country?.name, discoverResult.address.country)
assertEquals(coreMetadata.countryIso1, discoverResult.address.countryIso1)
assertEquals(coreMetadata.countryIso2, discoverResult.address.countryIso2)
}
}
| 15 | Kotlin | 9 | 22 | e79156c404231c78699a2f7cfc182e3c148bfc06 | 4,444 | mapbox-search-android | Apache License 2.0 |
src/main/kotlin/fp/kotlin/example/chapter05/solution/5-14-associate.kt | funfunStory | 101,662,895 | false | null | package fp.kotlin.example.chapter05.solution
import fp.kotlin.example.chapter05.FunList
import fp.kotlin.example.chapter05.foldRight
import fp.kotlin.example.chapter05.funListOf
/**
*
* 연습문제 5-14
*
* zip 함수는 리스트와 리스트를 조합해서 리스트를 생성하는 함수이다.
* 여기서는 리스트의 값을 입력받은 조합 함수에 의해서 연관 자료구조인 맵을 생성하는 associate 함수를 작성해보자.
*
* 힌트: 함수의 선언 타입은 아래와 같다.
*
*/
fun main() {
require(
funListOf(1, 2, 3, 4, 5).associate { it to it * 10 } == mapOf(1 to 10, 2 to 20, 3 to 30, 4 to 40, 5 to 50))
}
fun <T, R> FunList<T>.associate(f: (T) -> Pair<T, R>): Map<T, R> = foldRight(mapOf()) { value, acc -> acc.plus(f(value)) }
| 1 | Kotlin | 23 | 39 | bb10ea01d9f0e1b02b412305940c1bd270093cb6 | 799 | fp-kotlin-example | MIT License |
sphinx/activity/main/activitymain/src/main/java/chat/sphinx/activitymain/navigation/navigators/detail/QRCodeNavigatorImpl.kt | stakwork | 340,103,148 | false | {"Kotlin": 4002503, "Java": 403469, "JavaScript": 4745, "HTML": 4706, "Shell": 2453} | package chat.sphinx.activitymain.navigation.navigators.detail
import chat.sphinx.activitymain.navigation.drivers.DetailNavigationDriver
import chat.sphinx.qr_code.navigation.QRCodeNavigator
import javax.inject.Inject
internal class QRCodeNavigatorImpl @Inject constructor(
detailDriver: DetailNavigationDriver,
): QRCodeNavigator(detailDriver) {
override suspend fun closeDetailScreen() {
(navigationDriver as DetailNavigationDriver).closeDetailScreen()
}
}
| 96 | Kotlin | 8 | 18 | 4fd9556a4a34f14126681535558fe1e39747b323 | 480 | sphinx-kotlin | MIT License |
idea/testData/inspectionsLocal/collections/convertCallChainIntoSequence/flatten2.kt | android | 263,405,600 | true | null | // WITH_RUNTIME
fun test() {
listOf(listOf(1), listOf(2, 3)).<caret>filter { it.size > 1 }.flatten()
} | 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 106 | kotlin | Apache License 2.0 |
app/src/main/java/com/nosoproject/nosowallet/model/NOSObjects.kt | Noso-Project | 440,352,953 | false | {"Kotlin": 236273} | package com.nosoproject.nosowallet.model
import io.realm.kotlin.types.RealmObject
import io.realm.kotlin.types.annotations.PrimaryKey
import java.io.Serializable
class ConcensusResult {
var LastBlock:Long = 0
var LastBranch:String = ""
var Address:String = ""
var Port:Int = 8080
}
class ConcensusData {
var Value:String = ""
var Count:Int = 0
}
class NodeInfo {
var Address:String = ""
var Port:Int = 8080
var Connections:Long = 0L
var Lastblock:Long = 0L
var Pendings:Long = 0L
var Delta:Long = 0L
var Branch:String = ""
var Version:String = ""
var UTCTime:Long = 0
}
class PoolData {
var Address:String = ""
var Port:Int = 8080
var MinerID:String = ""
var NosoAddress:String = ""
var Connected:Boolean = false
var Invalid: Boolean = false
var CurrentBlock:Long = 0
var TargetHash:String = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
var TargetDiff:String = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
var PoolBalance:Long = 0L
var PoolTilPayment:Int = 30
var PoolPayStr:String = ""
}
class PoolPayData{
var Block = 0L
var Amount = 0L
var OrderID = ""
}
class SumaryData: RealmObject {
@PrimaryKey
var Hash = ""
var Custom = ""
var Balance: Long = -1
var Score: Long = -1
var LastOP: Long = -1
}
class ServerObject:RealmObject {
@PrimaryKey var Address:String = "localhost"
var Port:Int = 8080
var NosoAddress:String = ""
var Count:Int = 0
}
class OrderObject: RealmObject {
@PrimaryKey var OrderID: String = "-1"
var Destination:String? = null
var Amount:Long = 0L
var Timestamp:Long = 0L
}
class PendingInfo {
var TO_Type:String = ""
var TO_Sender:String = ""
var TO_Receiver:String = ""
var TO_Amount:Long = 0
var TO_Fee:Long = 0
}
class OrderData : Serializable {
var Block:Int = -1
var OrderID:String? = null
var OrderLines:Int = -1
var OrderType: String? = ""
var TimeStamp:Long = -1L
var Reference:String? = null
var TrxLine:Int = -1
var Sender:String? = null // Public Key of who is sending the noso
var Address:String? = null
var Receiver:String? = null
var AmountFee:Long = -1
var AmountTrf:Long = -1
var Signature:String? = null
var TrfrID:String? = null
}
class WalletObject : Serializable {
var Hash:String? = null
var Custom:String? = null
var PublicKey:String? = null
var PrivateKey:String? = null
var Balance:Long = 0
var Pending:Long = 0
var Score:Long = 0
var LastOP:Long = 0
var isLocked:Boolean = false
var Incoming:Long = 0L
var Outgoing:Long = 0L
fun copy(
hash:String? = Hash,
custom:String? = Custom,
publicKey:String? = PublicKey,
privateKey:String? = PrivateKey,
balance:Long = Balance,
pending:Long = Pending,
score:Long = Score,
lastOP:Long = LastOP,
locked:Boolean = isLocked,
incoming:Long = Incoming,
outgoing:Long = Outgoing
): WalletObject {
return WalletObject().apply {
Hash = hash
Custom = custom
PublicKey = publicKey
PrivateKey = privateKey
Balance = balance
Pending = pending
Score = score
LastOP = lastOP
isLocked = locked
Incoming = incoming
Outgoing = outgoing
}
}
}
class KeyPair : Serializable {
var PublicKey:String? = null
var PrivateKey:String? = null
}
enum class KeyType {
SECP256K1,
SECP384R1,
SECP521R1,
SECT283K1
}
class DivResult {
var Cociente:String? = null
var Residuo:String? = null
}
| 6 | Kotlin | 1 | 13 | fc3c4b2299903703b138729a650c84b31dc0e1ca | 3,721 | NosoWallet-Android | The Unlicense |
settings.gradle.kts | MohFahmi27 | 535,535,970 | false | {"Kotlin": 147264} | @file:Suppress("UnstableApiUsage")
pluginManagement {
repositories {
gradlePluginPortal()
google()
mavenCentral()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
maven { url = uri("https://jitpack.io") }
}
}
rootProject.name = "StoryApp"
include(":app")
include(":features:auth")
include(":core")
include(":features:home")
include(":features:detail")
include(":features:map-story")
include(":features:add-story")
| 0 | Kotlin | 0 | 3 | 33e94844c52da1ad24f68e204dc0e220d564c4c4 | 573 | MyIntermediateAndroidSubmission | Apache License 2.0 |
data-local/src/main/java/com/github/odaridavid/data/local/dao/FavoritesDao.kt | odaridavid | 227,998,628 | false | null | /**
*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
**/
package com.github.odaridavid.data.local.dao
import androidx.room.*
import com.github.odaridavid.data.local.mappers.toEntity
import com.github.odaridavid.data.local.models.FavoriteEntity
import com.github.odaridavid.data.local.models.FavoriteWithFilms
import com.github.odaridavid.data.local.models.FilmEntity
import com.k0d4black.theforce.domain.models.Favorite
import com.k0d4black.theforce.domain.models.Result
@Dao
interface FavoritesDao {
@Query("DELETE FROM favorites")
suspend fun deleteAll(): Int
@Query("DELETE FROM favorites WHERE name=:name")
suspend fun deleteByName(name: String): Int
@Transaction
@Query("SELECT * FROM favorites WHERE name=:name")
suspend fun getByName(name: String): FavoriteWithFilms
@Transaction
@Query("SELECT * FROM favorites")
suspend fun getAll(): List<FavoriteWithFilms>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(favoriteEntity: FavoriteEntity): Long
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(filmEntity: FilmEntity): Long
@Transaction
suspend fun insert(favorite: Favorite):Result {
val favId = insert(favorite.toEntity())
for (film in favorite.films) {
val filmEntity = film.toEntity(favId)
insert(filmEntity)
return Result.SUCCESS
}
return Result.FAILURE
}
} | 23 | Kotlin | 109 | 635 | 641213f53fc148b154465727d4c3246194a11542 | 1,996 | Clean-MVVM-ArchComponents | Apache License 2.0 |
src/main/kotlin/eZmaxApi/models/CommonMinusReportgroup.kt | eZmaxinc | 271,950,932 | false | {"Kotlin": 3232090} | /**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package eZmaxApi.models
import eZmaxApi.models.CommonMinusReport
import eZmaxApi.models.CommonMinusReportcellstyle
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* A group of reports Each Reportgroup is for a specific recipient or for a specific context.
*
* @param aObjReport
* @param aObjReportcellstyleCustom
*/
data class CommonMinusReportgroup (
@Json(name = "a_objReport")
val aObjReport: kotlin.collections.List<CommonMinusReport>,
@Json(name = "a_objReportcellstyleCustom")
val aObjReportcellstyleCustom: kotlin.collections.List<CommonMinusReportcellstyle>
)
| 0 | Kotlin | 0 | 0 | 775bfa1e6452d8ba1c6c4d7e1781b0977f5301b0 | 896 | eZmax-SDK-kotlin | MIT License |
kotlin-antd/antd-samples/src/main/kotlin/samples/treeselect/Suffix.kt | xlj44400 | 248,655,590 | true | {"Kotlin": 1516065, "HTML": 1503} | package samples.treeselect
import antd.icon.*
import antd.treeselect.*
import kotlinext.js.*
import react.*
import react.dom.*
import styled.*
private val icon = buildElement {
smileOutlined {}
}
interface SuffixDemoState : RState {
var value: String?
}
class SuffixDemo : RComponent<RProps, SuffixDemoState>() {
private val handleChange = fun(newValue: String, _: Any, _: Any) {
console.log(newValue)
setState {
value = newValue
}
}
override fun SuffixDemoState.init() {
value = null
}
override fun RBuilder.render() {
treeSelect<String, TreeSelectComponent<String>> {
attrs {
showSearch = true
suffixIcon = suffixIcon
style = js { width = 300 }
value = state.value
dropdownStyle = js {
maxHeight = 400
overflow = "auto"
}
placeholder = "Please select"
allowClear = true
treeDefaultExpandAll = true
onChange = handleChange
}
treeNode {
attrs {
value = "parent 1"
title = "parent 1"
key = "0-1"
}
treeNode {
attrs {
value = "parent 1-0"
title = "parent 1-0"
key = "0-1-1"
}
treeNode {
attrs {
value = "leaf1"
title = "my leaf"
key = "random"
}
}
treeNode {
attrs {
value = "leaf2"
title = "your leaf"
key = "random1"
}
}
}
treeNode {
attrs {
value = "parent 1-1"
title = "parent 1-1"
key = "random2"
}
treeNode {
attrs {
value = "sss"
title = buildElement {
b {
attrs.jsStyle = js { color = "#08c" }
+"sss"
}
}
key = "random3"
}
}
}
}
}
}
}
fun RBuilder.suffixMultipleDemo() = child(SuffixDemo::class) {}
fun RBuilder.suffix() {
styledDiv {
css { +TreeSelectStyles.suffix }
suffixMultipleDemo()
}
}
| 0 | Kotlin | 0 | 0 | ce8216c0332abdfefcc0a06cf5fbbbf24e669931 | 2,932 | kotlin-js-wrappers | Apache License 2.0 |