path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/example/game3/PlayPage.kt
Ezzy1012
796,705,547
false
{"Kotlin": 11498}
package com.example.game3 import android.annotation.SuppressLint import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.ImageView import android.widget.TextView class PlayPage : AppCompatActivity() { @SuppressLint("MissingInflatedId") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_play_page) //this button (play) will take us to the play-end page which will then have a button to make daffy happy// val play_page_btn = findViewById<Button>(R.id.play_page_btn) play_page_btn.setOnClickListener { intent = Intent(this, Playend::class.java) startActivity(intent) } //this button (back) will take us back to the second page// val play_page_btn_back_btn = findViewById<Button>(R.id.play_page_btn_back_btn) play_page_btn_back_btn.setOnClickListener { intent = Intent(this, SecondPage::class.java) startActivity(intent) } //Done with the first phase// //Declaring the components val imageView = findViewById<ImageView>(R.id.imageView) imageView.setOnClickListener { } val textView = findViewById<TextView>(R.id.textView) textView.setOnClickListener { } } }
0
Kotlin
0
0
bb71996765ff31c72627b77cd697c0ab04369136
1,392
Game3
MIT License
ui/src/test/kotlin/team/duckie/quackquack/ui/snapshot/TextFieldSnapshot.kt
duckie-team
523,387,054
false
{"Kotlin": 901061, "MDX": 51559, "JavaScript": 6871, "CSS": 1060}
/* * Designed and developed by Duckie Team 2023. * * Licensed under the MIT. * Please see full license: https://github.com/duckie-team/quack-quack-android/blob/main/LICENSE */ @file:Suppress("LargeClass", "LongMethod") @file:OptIn(ExperimentalDesignToken::class, ExperimentalQuackQuackApi::class) package team.duckie.quackquack.ui.snapshot import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.test.ext.junit.runners.AndroidJUnit4 import com.github.takahirom.roborazzi.captureRoboImage import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.annotation.Config import team.duckie.quackquack.material.QuackColor import team.duckie.quackquack.material.icon.QuackIcon import team.duckie.quackquack.material.icon.quackicon.Outlined import team.duckie.quackquack.material.icon.quackicon.outlined.Heart import team.duckie.quackquack.ui.QuackDefaultTextField import team.duckie.quackquack.ui.QuackFilledTextField import team.duckie.quackquack.ui.QuackTextFieldStyle import team.duckie.quackquack.ui.TextFieldPlaceholderStrategy import team.duckie.quackquack.ui.TextFieldValidationState import team.duckie.quackquack.ui.counter import team.duckie.quackquack.ui.defaultTextFieldIcon import team.duckie.quackquack.ui.defaultTextFieldIndicator import team.duckie.quackquack.ui.filledTextFieldIcon import team.duckie.quackquack.ui.optin.ExperimentalDesignToken import team.duckie.quackquack.ui.snapshot.util.LargestFontScale import team.duckie.quackquack.ui.snapshot.util.MultilinesSnapshotQualifier import team.duckie.quackquack.ui.snapshot.util.SnapshotPathGeneratorRule import team.duckie.quackquack.ui.snapshot.util.TestColumn import team.duckie.quackquack.ui.snapshot.util.WithLabel import team.duckie.quackquack.ui.token.HorizontalDirection import team.duckie.quackquack.ui.token.VerticalDirection import team.duckie.quackquack.ui.util.ExperimentalQuackQuackApi private const val MediumText = "가나다라마바사아자차카타파하" private const val LongText = "그러므로 주며, 없으면 우리 보라. 이것은 온갖 안고, 거선의 황금시대다." private const val MultilineText = "$MediumText\n$MediumText\n$MediumText\n$MediumText\n$MediumText" private const val SuccessText = "성공!" private const val ErrorText = "실패!" // TODO: parameterized test @Config(qualifiers = MultilinesSnapshotQualifier) @RunWith(AndroidJUnit4::class) class TextFieldSnapshot { @get:Rule val snapshotPath = SnapshotPathGeneratorRule("textfield") @Test fun QuackDefaultTextFields() { captureRoboImage(snapshotPath()) { TestColumn { WithLabel("[Default]", isTitle = true) { QuackDefaultTextField( value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.Default, ) } WithLabel("[DefaultLarge]", isTitle = true) { QuackDefaultTextField( value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.DefaultLarge, ) } } } } @Test fun QuackDefaultTextFields_placeholders() { captureRoboImage(snapshotPath()) { TestColumn(contentGap = 30.dp) { WithLabel("[Default]", isTitle = true) { WithLabel("Hidable") { QuackDefaultTextField( value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.Default, placeholderText = MediumText, placeholderStrategy = TextFieldPlaceholderStrategy.Hidable, ) } WithLabel("Always") { QuackDefaultTextField( value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.Default, placeholderText = MediumText, placeholderStrategy = TextFieldPlaceholderStrategy.Always, ) } } WithLabel("[DefaultLarge]", isTitle = true) { WithLabel("Hidable") { QuackDefaultTextField( value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.DefaultLarge, placeholderText = MediumText, placeholderStrategy = TextFieldPlaceholderStrategy.Hidable, ) } WithLabel("Always") { QuackDefaultTextField( value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.DefaultLarge, placeholderText = MediumText, placeholderStrategy = TextFieldPlaceholderStrategy.Always, ) } } } } } @Test fun QuackDefaultTextFields_validations() { captureRoboImage(snapshotPath()) { TestColumn(contentGap = 30.dp) { WithLabel("[Default]", isTitle = true) { WithLabel("default") { QuackDefaultTextField( value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.Default, validationState = TextFieldValidationState.Default, ) } WithLabel("success") { QuackDefaultTextField( value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.Default, validationState = TextFieldValidationState.Success(SuccessText), ) } WithLabel("error") { QuackDefaultTextField( value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.Default, validationState = TextFieldValidationState.Error(ErrorText), ) } } WithLabel("[DefaultLarge]", isTitle = true) { WithLabel("default") { QuackDefaultTextField( value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.DefaultLarge, validationState = TextFieldValidationState.Default, ) } WithLabel("success") { QuackDefaultTextField( value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.DefaultLarge, validationState = TextFieldValidationState.Success(SuccessText), ) } WithLabel("error") { QuackDefaultTextField( value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.DefaultLarge, validationState = TextFieldValidationState.Error(ErrorText), ) } } } } } @Test fun QuackDefaultTextFields_indicators() { captureRoboImage(snapshotPath()) { TestColumn(contentGap = 30.dp) { WithLabel("[Default]", isTitle = true) { WithLabel("top / default") { QuackDefaultTextField( modifier = Modifier.defaultTextFieldIndicator(direction = VerticalDirection.Top), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.Default, ) } WithLabel("bottom / default") { QuackDefaultTextField( modifier = Modifier.defaultTextFieldIndicator(), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.Default, ) } WithLabel("bottom / success") { QuackDefaultTextField( modifier = Modifier.defaultTextFieldIndicator(), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.Default, validationState = TextFieldValidationState.Success(SuccessText), ) } WithLabel("bottom / error") { QuackDefaultTextField( modifier = Modifier.defaultTextFieldIndicator(), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.Default, validationState = TextFieldValidationState.Error(ErrorText), ) } } WithLabel("[DefaultLarge]", isTitle = true) { WithLabel("top / default") { QuackDefaultTextField( modifier = Modifier.defaultTextFieldIndicator(direction = VerticalDirection.Top), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.DefaultLarge, ) } WithLabel("bottom / default") { QuackDefaultTextField( modifier = Modifier.defaultTextFieldIndicator(), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.DefaultLarge, ) } WithLabel("bottom / success") { QuackDefaultTextField( modifier = Modifier.defaultTextFieldIndicator(), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.DefaultLarge, validationState = TextFieldValidationState.Success(SuccessText), ) } WithLabel("bottom / error") { QuackDefaultTextField( modifier = Modifier.defaultTextFieldIndicator(), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.DefaultLarge, validationState = TextFieldValidationState.Error(ErrorText), ) } } } } } @Test fun QuackDefaultTextFields_icons() { captureRoboImage(snapshotPath()) { TestColumn(contentGap = 30.dp) { WithLabel("[Default]", isTitle = true) { WithLabel("both") { QuackDefaultTextField( modifier = Modifier .defaultTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Left, ) .defaultTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Right, ), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.Default, ) } WithLabel("leading") { QuackDefaultTextField( modifier = Modifier.defaultTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Left, ), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.Default, ) } WithLabel("trailing") { QuackDefaultTextField( modifier = Modifier.defaultTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Right, ), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.Default, ) } } WithLabel("[DefaultLarge]", isTitle = true) { WithLabel("both") { QuackDefaultTextField( modifier = Modifier .defaultTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Left, ) .defaultTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Right, ), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.DefaultLarge, ) } WithLabel("leading") { QuackDefaultTextField( modifier = Modifier.defaultTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Left, ), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.DefaultLarge, ) } WithLabel("trailing") { QuackDefaultTextField( modifier = Modifier.defaultTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Right, ), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.DefaultLarge, ) } } } } } @Test fun QuackDefaultTextFields_counters() { captureRoboImage(snapshotPath()) { TestColumn(contentGap = 30.dp) { WithLabel("[Default]", isTitle = true) { WithLabel("default") { QuackDefaultTextField( modifier = Modifier.counter(maxLength = 10), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.Default, ) } WithLabel("over") { QuackDefaultTextField( modifier = Modifier.counter(maxLength = 10), value = LongText, onValueChange = {}, singleLine = true, style = QuackTextFieldStyle.Default, ) } } WithLabel("[DefaultLarge]", isTitle = true) { WithLabel("default") { QuackDefaultTextField( modifier = Modifier.counter(maxLength = 10), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.DefaultLarge, ) } WithLabel("over") { QuackDefaultTextField( modifier = Modifier.counter(maxLength = 10), value = LongText, onValueChange = {}, singleLine = true, style = QuackTextFieldStyle.DefaultLarge, ) } } } } } @Test fun QuackDefaultTextFields_multilines() { QuackDefaultTextFields_multilines_capturer(fillMaxWidth = false) } @Config(fontScale = LargestFontScale) @Test fun QuackDefaultTextFields_multilines_x2() { QuackDefaultTextFields_multilines_capturer(fillMaxWidth = true) } private fun QuackDefaultTextFields_multilines_capturer(fillMaxWidth: Boolean) { val widthModifier = if (fillMaxWidth) Modifier.fillMaxWidth() else Modifier captureRoboImage(snapshotPath()) { TestColumn(contentGap = 30.dp) { WithLabel("[Default]", isTitle = true) { WithLabel("default") { QuackDefaultTextField( modifier = Modifier.then(widthModifier), value = MultilineText, onValueChange = {}, style = QuackTextFieldStyle.Default, ) } WithLabel("placeholder") { QuackDefaultTextField( modifier = Modifier.then(widthModifier), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.Default, placeholderText = MultilineText, placeholderStrategy = TextFieldPlaceholderStrategy.Always, ) } WithLabel("indicator") { QuackDefaultTextField( modifier = Modifier .then(widthModifier) .defaultTextFieldIndicator(), value = MultilineText, onValueChange = {}, style = QuackTextFieldStyle.Default, placeholderText = MultilineText, validationState = TextFieldValidationState.Success(SuccessText), ) } WithLabel("icons") { QuackDefaultTextField( modifier = Modifier .then(widthModifier) .defaultTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Left, ) .defaultTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Right, ), value = MultilineText, onValueChange = {}, style = QuackTextFieldStyle.Default, ) } WithLabel("counter") { QuackDefaultTextField( modifier = Modifier .then(widthModifier) .counter(maxLength = 10), value = MultilineText, onValueChange = {}, style = QuackTextFieldStyle.Default, ) } } WithLabel("[DefaultLarge]", isTitle = true) { WithLabel("default") { QuackDefaultTextField( modifier = Modifier.then(widthModifier), value = MultilineText, onValueChange = {}, style = QuackTextFieldStyle.DefaultLarge, ) } WithLabel("placeholder") { QuackDefaultTextField( modifier = Modifier.then(widthModifier), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.DefaultLarge, placeholderText = MultilineText, placeholderStrategy = TextFieldPlaceholderStrategy.Always, ) } WithLabel("indicator") { QuackDefaultTextField( modifier = Modifier .then(widthModifier) .defaultTextFieldIndicator(), value = MultilineText, onValueChange = {}, style = QuackTextFieldStyle.DefaultLarge, placeholderText = MultilineText, validationState = TextFieldValidationState.Success(SuccessText), ) } WithLabel("icons") { QuackDefaultTextField( modifier = Modifier .then(widthModifier) .defaultTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Left, ) .defaultTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Right, ), value = MultilineText, onValueChange = {}, style = QuackTextFieldStyle.DefaultLarge, ) } WithLabel("counter") { QuackDefaultTextField( modifier = Modifier .then(widthModifier) .counter(maxLength = 10), value = MultilineText, onValueChange = {}, style = QuackTextFieldStyle.DefaultLarge, ) } } } } } // QuackDefaultTextField // -------------------------------------------------- // // QuackFilledTextField @Test fun QuackFilledTextFields() { captureRoboImage(snapshotPath()) { TestColumn { WithLabel("[FilledLarge]", isTitle = true) { QuackFilledTextField( value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.FilledLarge, ) } WithLabel("[FilledFlat]", isTitle = true) { QuackFilledTextField( value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.FilledFlat, ) } } } } @Test fun QuackFilledTextField_FilledLarge_placeholders() { captureRoboImage(snapshotPath()) { TestColumn(contentGap = 30.dp) { WithLabel("[FilledLarge]", isTitle = true) { WithLabel("Hidable") { QuackFilledTextField( value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.FilledLarge, placeholderText = MediumText, placeholderStrategy = TextFieldPlaceholderStrategy.Hidable, ) } WithLabel("Always") { QuackFilledTextField( value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.FilledLarge, placeholderText = MediumText, placeholderStrategy = TextFieldPlaceholderStrategy.Always, ) } } WithLabel("[FilledFlat]", isTitle = true) { WithLabel("Hidable") { QuackFilledTextField( value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.FilledFlat, placeholderText = MediumText, placeholderStrategy = TextFieldPlaceholderStrategy.Hidable, ) } WithLabel("Always") { QuackFilledTextField( value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.FilledFlat, placeholderText = MediumText, placeholderStrategy = TextFieldPlaceholderStrategy.Always, ) } } } } } @Test fun QuackFilledTextField_FilledLarge_icons() { captureRoboImage(snapshotPath()) { TestColumn(contentGap = 30.dp) { WithLabel("[FilledLarge]", isTitle = true) { WithLabel("both") { QuackFilledTextField( modifier = Modifier .filledTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Left, ) .filledTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Right, ), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.FilledLarge, ) } WithLabel("leading") { QuackFilledTextField( modifier = Modifier.filledTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Left, ), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.FilledLarge, ) } WithLabel("trailing") { QuackFilledTextField( modifier = Modifier.filledTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Right, ), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.FilledLarge, ) } } WithLabel("[FilledFlat]", isTitle = true) { WithLabel("both") { QuackFilledTextField( modifier = Modifier .filledTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Left, ) .filledTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Right, ), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.FilledFlat, ) } WithLabel("leading") { QuackFilledTextField( modifier = Modifier.filledTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Left, ), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.FilledFlat, ) } WithLabel("trailing") { QuackFilledTextField( modifier = Modifier.filledTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Right, ), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.FilledFlat, ) } } } } } @Test fun QuackFilledTextField_FilledLarge_counters() { captureRoboImage(snapshotPath()) { TestColumn(contentGap = 30.dp) { WithLabel("[FilledLarge]", isTitle = true) { WithLabel("Filled") { QuackFilledTextField( modifier = Modifier.counter(maxLength = 10), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.FilledLarge, ) } WithLabel("over") { QuackFilledTextField( modifier = Modifier.counter(maxLength = 10), value = LongText, onValueChange = {}, singleLine = true, style = QuackTextFieldStyle.FilledLarge, ) } } WithLabel("[FilledFlat]", isTitle = true) { WithLabel("Filled") { QuackFilledTextField( modifier = Modifier.counter(maxLength = 10), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.FilledFlat, ) } WithLabel("over") { QuackFilledTextField( modifier = Modifier.counter(maxLength = 10), value = LongText, onValueChange = {}, singleLine = true, style = QuackTextFieldStyle.FilledFlat, ) } } } } } @Test fun QuackFilledTextField_FilledLarge_multilines() { QuackFilledTextField_FilledLarge_multilines_capturer(fillMaxWidth = false) } @Config(fontScale = LargestFontScale) @Test fun QuackFilledTextField_FilledLarge_multilines_x2() { QuackFilledTextField_FilledLarge_multilines_capturer(fillMaxWidth = true) } private fun QuackFilledTextField_FilledLarge_multilines_capturer(fillMaxWidth: Boolean) { val widthModifier = if (fillMaxWidth) Modifier.fillMaxWidth() else Modifier captureRoboImage(snapshotPath()) { TestColumn(contentGap = 30.dp) { WithLabel("[FilledLarge]", isTitle = true) { WithLabel("Filled") { QuackFilledTextField( modifier = Modifier.then(widthModifier), value = MultilineText, onValueChange = {}, style = QuackTextFieldStyle.FilledLarge, ) } WithLabel("placeholder") { QuackFilledTextField( modifier = Modifier.then(widthModifier), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.FilledLarge, placeholderText = MultilineText, placeholderStrategy = TextFieldPlaceholderStrategy.Always, ) } WithLabel("icons") { QuackFilledTextField( modifier = Modifier .then(widthModifier) .filledTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Left, ) .filledTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Right, ), value = MultilineText, onValueChange = {}, style = QuackTextFieldStyle.FilledLarge, ) } WithLabel("counter") { QuackFilledTextField( modifier = Modifier .then(widthModifier) .counter(maxLength = 10), value = MultilineText, onValueChange = {}, style = QuackTextFieldStyle.FilledLarge, ) } } WithLabel("[FilledFlat]", isTitle = true) { WithLabel("Filled") { QuackFilledTextField( modifier = Modifier.then(widthModifier), value = MultilineText, onValueChange = {}, style = QuackTextFieldStyle.FilledFlat, ) } WithLabel("placeholder") { QuackFilledTextField( modifier = Modifier.then(widthModifier), value = MediumText, onValueChange = {}, style = QuackTextFieldStyle.FilledFlat, placeholderText = MultilineText, placeholderStrategy = TextFieldPlaceholderStrategy.Always, ) } WithLabel("icons") { QuackFilledTextField( modifier = Modifier .then(widthModifier) .filledTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Left, ) .filledTextFieldIcon( icon = QuackIcon.Outlined.Heart, tint = QuackColor.Unspecified, direction = HorizontalDirection.Right, ), value = MultilineText, onValueChange = {}, style = QuackTextFieldStyle.FilledFlat, ) } WithLabel("counter") { QuackFilledTextField( modifier = Modifier .then(widthModifier) .counter(maxLength = 10), value = MultilineText, onValueChange = {}, style = QuackTextFieldStyle.FilledFlat, ) } } } } } }
45
Kotlin
8
99
24d44663cf5bea29fc73595b5f60be03b08e162b
30,692
quack-quack-android
MIT License
android/app/src/main/kotlin/com/example/neumorphic_calculator/MainActivity.kt
mllrr96
825,123,377
false
{"Dart": 142064, "Swift": 689, "Kotlin": 133, "Objective-C": 38}
package com.ragheb.neumorphic_calculator import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity()
1
Dart
3
13
c21173fe544f74de370694a157768b99ce3abbea
133
Neumorphic-Calculator
MIT License
Samples/Android-Advanced-Kotlin/app/src/main/java/com/pushwoosh/sample/customcontent/NotificationButtonReceiver.kt
Pushwoosh
15,434,764
false
{"Java": 2695318, "Kotlin": 92394}
package com.pushwoosh.sample.customcontent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.net.Uri import android.support.v4.app.NotificationManagerCompat import android.util.Log class NotificationButtonReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { Log.d("Pushwoosh", "notification button clicked") val managerCompat = NotificationManagerCompat.from(context) managerCompat.cancelAll() val actionIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.pushwoosh.com/")) actionIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(actionIntent) } }
2
Java
44
55
aa77bc545944ae509186dab810707e26f2d9f7c5
741
pushwoosh-android-sdk
MIT License
src/com/hxz/mpxjs/libraries/nuxt/model/NuxtComponentProvider.kt
wuxianqiang
508,329,768
false
{"Kotlin": 1447881, "Vue": 237479, "TypeScript": 106023, "JavaScript": 93869, "HTML": 17163, "Assembly": 12226, "Lex": 11227, "Java": 2846, "Shell": 1917, "Pug": 338}
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.hxz.mpxjs.libraries.nuxt.model import com.intellij.webpack.WebpackConfigManager import com.intellij.webpack.WebpackReferenceContributor import com.intellij.lang.javascript.library.JSLibraryUtil import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiFile import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.asSafely import com.intellij.util.containers.MultiMap import com.hxz.mpxjs.codeInsight.fromAsset import com.hxz.mpxjs.libraries.nuxt.NUXT_COMPONENTS_DEFS import com.hxz.mpxjs.libraries.nuxt.NUXT_OUTPUT_FOLDER import com.hxz.mpxjs.model.VueComponent import com.hxz.mpxjs.model.source.VueContainerInfoProvider /** * @see com.hxz.mpxjs.model.typed.VueTypedGlobal.typedGlobalComponents */ class NuxtComponentProvider : VueContainerInfoProvider { private val LAZY = "lazy" // https://nuxtjs.org/docs/directory-structure/components#dynamic-imports override fun getAdditionalComponents(scope: GlobalSearchScope, sourceComponents: VueContainerInfoProvider.ComponentsInfo): VueContainerInfoProvider.ComponentsInfo? = NuxtModelManager.getApplication(scope) ?.config ?.takeIf { config -> config.file.let { // Ensure we have a config, and ensure we don't have the auto-generated list of components in .nuxt folder it != null && it.parent?.findSubdirectory(NUXT_OUTPUT_FOLDER)?.findFile(NUXT_COMPONENTS_DEFS) == null} } ?.let { config -> // alternative idea: there's .nuxt/components/index.js that contains named exports with components, // although it looks like it handles Lazy prefix incorrectly // there's also .nuxt/components/plugin.js that contains object literal with correctly generated component names val resolvedDirs = config.components.asSequence() .mapNotNull { componentDir -> resolvePath(config.file!!, componentDir)?.let { Pair(it, componentDir) } } .sortedWith( Comparator.comparingInt<Pair<VirtualFile, NuxtConfig.ComponentsDirectoryConfig>> { it.second.level } .thenComparingInt { dir -> -dir.first.path.count { it == '\\' || it == '/' } }) .toList() sourceComponents.local.entrySet() .asSequence() .flatMap { it.value } .flatMap { component -> val componentFile = component.source?.containingFile?.virtualFile ?: return@flatMap emptySequence() val index = resolvedDirs.indexOfFirst { VfsUtil.isAncestor(it.first, componentFile, true) } if (index < 0) return@flatMap emptySequence() val componentDirConfig = resolvedDirs[index].second if (componentFile.extension.let { componentDirConfig.extensions.contains(it) }) { val dirPrefix = if (componentDirConfig.pathPrefix) { VfsUtil.getRelativePath(componentFile.parent, resolvedDirs[index].first, '-') ?.takeIf { it.isNotEmpty() } ?.let { fromAsset(it).replace(MULTI_HYPHEN_REGEX, "-") } ?: "" } else { "" } val configuredPrefix = componentDirConfig.prefix.let { if (it.isNotEmpty()) "$it-" else it } val mergedPrefixParts = (configuredPrefix + dirPrefix).split('-').filter { it.isNotEmpty() } val baseName = fromAsset(componentFile.nameWithoutExtension) val baseNameParts = baseName.split('-') var commonIndex = 0 while (commonIndex < mergedPrefixParts.size) { if (mergedPrefixParts[commonIndex] == baseNameParts[0]) { break } commonIndex += 1 } val parts = mergedPrefixParts.subList(0, commonIndex) + baseNameParts val partsWithoutLazy = if (parts.firstOrNull() == LAZY) parts.drop(1) else parts val name = partsWithoutLazy.joinToString("-") sequenceOf( Triple(name, component, index), Triple("$LAZY-$name", component, index) ) } else { emptySequence() } } .sortedBy { it.third } .distinctBy { it.first } .fold(MultiMap.create<String, VueComponent>()) { map, (name, component) -> map.also { it.putValue(name, component) } } .let { VueContainerInfoProvider.ComponentsInfo(MultiMap.empty(), it) } } private fun resolvePath(configFile: PsiFile, componentDir: NuxtConfig.ComponentsDirectoryConfig): VirtualFile? = if (componentDir.path.startsWith("~") || componentDir.path.startsWith("@")) { WebpackConfigManager.getInstance(configFile.project) .resolveConfig(configFile) .takeIf { !it.isEmpty() } ?.let { webpackReferenceProvider.getAliasedReferences(componentDir.path.trimEnd('/'), configFile, 0, it, true) } ?.lastOrNull() ?.resolve() ?.asSafely<PsiDirectory>() ?.virtualFile } else { configFile.virtualFile.parent?.findFileByRelativePath(componentDir.path) } ?.takeIf { it.isDirectory && it.name != JSLibraryUtil.NODE_MODULES } companion object { val webpackReferenceProvider = WebpackReferenceContributor() private val MULTI_HYPHEN_REGEX = Regex("-{2,}") } }
2
Kotlin
0
4
e069e8b340ab04780ac13eab375d900f21bc7613
5,624
intellij-plugin-mpx
Apache License 2.0
core/src/test/kotlin/net/kotlinx/core/number/LongSupportKtTest.kt
mypojo
565,799,715
false
{"Kotlin": 1022025, "Jupyter Notebook": 2068}
package net.kotlinx.core.number import net.kotlinx.core.time.toKr01 import net.kotlinx.test.TestRoot import org.junit.jupiter.api.Test import kotlin.time.Duration.Companion.seconds class LongSupportKtTest : TestRoot(){ @Test fun test() { println(1681869805.seconds.inWholeMilliseconds.toLocalDateTime().toKr01()) } }
0
Kotlin
0
1
47b8c26ec432cba214fb37a3e90bebfc1eb6a611
343
kx_kotlin_support
MIT License
LiveDataExt/src/main/java/com/architect/livedataext/LiveDataBindExt.kt
TheArchitect123
823,072,221
false
{"Kotlin": 7980}
package com.architect.livedataext import android.view.View import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import androidx.lifecycle.map fun <T> LiveData<T>.bind(lifecycleOwner: LifecycleOwner, observer: (T?) -> Unit): Closeable { observer(value) val androidObserver = Observer<T> { value -> observer(value) } this.observe(lifecycleOwner, androidObserver) return Closeable { this.removeObserver(androidObserver) } } fun <T> LiveData<T>.bindNotNull(lifecycleOwner: LifecycleOwner, observer: (T) -> Unit): Closeable { return bind(lifecycleOwner) { value -> if (value == null) return@bind observer(value) } } fun View.bindVisibleOrGone( lifecycleOwner: LifecycleOwner, liveData: LiveData<Boolean> ): Closeable { return liveData.bindNotNull(lifecycleOwner) { value -> this.visibility = if (value) View.VISIBLE else View.GONE } } fun View.bindVisibleOrInvisible( lifecycleOwner: LifecycleOwner, liveData: LiveData<Boolean> ): Closeable { return liveData.bindNotNull(lifecycleOwner) { value -> this.visibility = if (value) View.VISIBLE else View.INVISIBLE } } fun View.bindEnabled( lifecycleOwner: LifecycleOwner, liveData: LiveData<Boolean> ): Closeable { return liveData.bindNotNull(lifecycleOwner) { this.isEnabled = it } } fun <T> MutableLiveData<T>.readOnly(): LiveData<T> = this fun <T : Throwable> LiveData<T>.throwableMessage( mapper: (Throwable) -> String = { it.message.orEmpty() } ): LiveData<String> = map(mapper)
0
Kotlin
0
0
cc746f4029155dcf6a93cf7d4346fe257dcd4d04
1,665
LiveDataExt
MIT License
src/main/kotlin/com/github/ivan_osipov/clabo/api/model/UserProfilePhotos.kt
ivan-osipov
92,181,671
false
null
package com.github.ivan_osipov.clabo.api.model import com.google.gson.annotations.SerializedName class UserProfilePhotos { @SerializedName("total_count") private var _totalCount: Int? = null val totalCount: Int get() = _totalCount!! @SerializedName("photos") var photos: List<List<PhotoSize>> = ArrayList() }
31
Kotlin
3
6
943583bce73aad8479c1be8d7e6f6fe74807058e
342
Clabo
Apache License 2.0
app/src/main/java/com/example/lengary_l/wanandroidtodo/data/Status.kt
CoderLengary
145,677,373
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 52, "XML": 38, "Java": 2, "HTML": 1}
package com.example.lengary_l.wanandroidtodo.data import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName /** * Created by CoderLengary */ data class Status ( @SerializedName("data") @Expose val data: TodoDetailData, @SerializedName("errorCode") @Expose val errorCode: Int, @SerializedName("errorMsg") @Expose val errorMsg: String )
0
Kotlin
0
5
6c9499d52f63be76b14ca0a69c84cf6fa279bd2c
449
WanAndroidTodo
Apache License 2.0
nebulosa-adql/src/main/kotlin/nebulosa/adql/Contains.kt
tiagohm
568,578,345
false
{"Kotlin": 2747666, "TypeScript": 509060, "HTML": 243311, "JavaScript": 120539, "SCSS": 11332, "Python": 2817, "Makefile": 355}
package nebulosa.adql import adql.query.constraint.ADQLConstraint import adql.query.constraint.Comparison import adql.query.constraint.ComparisonOperator import adql.query.operand.NumericConstant import adql.query.operand.function.geometry.ContainsFunction import adql.query.operand.function.geometry.GeometryFunction data class Contains(override val constraint: ADQLConstraint) : WhereConstraint { private constructor(left: GeometryFunction.GeometryValue<GeometryFunction>, right: GeometryFunction.GeometryValue<GeometryFunction>) : this( Comparison(ContainsFunction(left, right), ComparisonOperator.EQUAL, NumericConstant(1L)) ) constructor(left: Column, right: Region) : this(GeometryFunction.GeometryValue(left.operand), GeometryFunction.GeometryValue(right.operand)) constructor(left: Region, right: Region) : this(GeometryFunction.GeometryValue(left.operand), GeometryFunction.GeometryValue(right.operand)) override operator fun not(): NotContains { val comparison = constraint as Comparison return NotContains(Comparison(comparison.leftOperand, ComparisonOperator.EQUAL, NumericConstant(0L))) } }
21
Kotlin
2
4
e144290464c5e6e2e18ad23a036526800428e7f9
1,158
nebulosa
MIT License
shared/src/commonMain/kotlin/theme/Color.kt
HaniFakhouri
732,515,661
false
{"Kotlin": 76383, "Swift": 592, "Shell": 228}
package theme import androidx.compose.ui.graphics.Color /** * Created by hani.fakhouri on 2023-12-19. */ val AppRed = Color(0xFFB9261C) val AppGreen = Color(0xFF009736) val AppBlack = Color.Black val AppWhite = Color.White
0
Kotlin
0
0
41543c96abc988ced153d82ac9cbcd00b4f7666c
227
Boycotz
Apache License 2.0
app/src/main/java/com/example/test/ui/ProductsScreen.kt
cheesecode
794,265,006
false
{"Kotlin": 39142}
package com.example.test.ui import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import coil.compose.AsyncImage import coil.request.ImageRequest import com.example.test.viewmodel.ProductViewModel @Composable fun ProductsScreen(amount: Int, productViewModel : ProductViewModel) { //val productState by productViewModel.productFlow.collectAsState(null) productViewModel.fetchProducts(amount) val productsState = productViewModel.productsFlow.collectAsState() LazyColumn( // modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(16.dp) ) { productsState.value?.let { products -> itemsIndexed(products) { index, product -> Card( modifier = Modifier .fillMaxWidth() .padding(vertical = 16.dp) ) { Column( modifier = Modifier.padding(16.dp) ) { Text(text = "Product ID: ${product.id}") Text(text = "Title: ${product.title}") Spacer(modifier = Modifier.height(8.dp)) Text(text = "Description: ${product.description}") Spacer(modifier = Modifier.height(8.dp)) Row(verticalAlignment = Alignment.CenterVertically) { Text(text = "Price: $${product.price}") Spacer(modifier = Modifier.width(16.dp)) Text(text = "Discount: ${product.discountPercentage}% off") } Spacer(modifier = Modifier.height(8.dp)) Row(verticalAlignment = Alignment.CenterVertically) { Text(text = "Rating: ${product.rating}") Spacer(modifier = Modifier.width(16.dp)) Text(text = "Stock: ${product.stock}") } Spacer(modifier = Modifier.height(8.dp)) Box( modifier = Modifier .fillMaxWidth() .height(200.dp) .clip(RoundedCornerShape(8.dp)) .background(color = Color.LightGray) ) { AsyncImage( model = ImageRequest.Builder(LocalContext.current) .data(product.thumbnail) .crossfade(true) .build(), contentDescription = null, modifier = Modifier.fillMaxSize(), ) } Spacer(modifier = Modifier.height(8.dp)) LazyRow( contentPadding = PaddingValues(horizontal = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp) ) { product.images.forEach { imageUrl -> item { Box( modifier = Modifier .size(100.dp) .clip(RoundedCornerShape(8.dp)) .background(Color.LightGray) ) { AsyncImage( model = ImageRequest.Builder(LocalContext.current) .data(imageUrl) .crossfade(true) .build(), contentDescription = null, modifier = Modifier.fillMaxSize(), ) } } } } } } } } // Placeholder for loading state if (productsState.value == null) { item { Box( modifier = Modifier .fillMaxWidth() .padding(16.dp) .wrapContentHeight() ) { Text(text = "Loading...", modifier = Modifier.align(Alignment.Center)) } } } } }
0
Kotlin
0
0
50426426ff50d9d7a83b2f3e3cb673f2b515e441
6,110
Compose_Hilt_Repository_Cache
MIT License
saved-sites/saved-sites-impl/src/main/java/com/duckduckgo/savedsites/impl/sync/SavedSiteInvalidItemsViewModel.kt
hojat72elect
822,396,044
false
{"Kotlin": 11626231, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784}
package com.duckduckgo.savedsites.impl.sync import android.annotation.SuppressLint import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.duckduckgo.anvil.annotations.ContributesViewModel import com.duckduckgo.common.utils.DispatcherProvider import com.duckduckgo.di.scopes.ViewScope import com.duckduckgo.savedsites.impl.sync.SavedSiteInvalidItemsViewModel.Command.NavigateToBookmarks import javax.inject.Inject import kotlinx.coroutines.channels.BufferOverflow.DROP_OLDEST import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.launch @SuppressLint("NoLifecycleObserver") // we don't observe app lifecycle @ContributesViewModel(ViewScope::class) class SavedSiteInvalidItemsViewModel @Inject constructor( private val dispatcherProvider: DispatcherProvider, private val syncSavedSitesRepository: SyncSavedSitesRepository, ) : ViewModel(), DefaultLifecycleObserver { data class ViewState( val warningVisible: Boolean = false, val invalidItemsSize: Int = 0, val hint: String = "", ) sealed class Command { data object NavigateToBookmarks : Command() } private val command = Channel<Command>(1, DROP_OLDEST) private val _viewState = MutableStateFlow(ViewState()) fun viewState(): Flow<ViewState> = _viewState.onStart { viewModelScope.launch(dispatcherProvider.io()) { emitNewViewState() } } override fun onResume(owner: LifecycleOwner) { viewModelScope.launch(dispatcherProvider.io()) { emitNewViewState() } } fun commands(): Flow<Command> = command.receiveAsFlow() private suspend fun emitNewViewState() { val invalidItems = syncSavedSitesRepository.getInvalidSavedSites() _viewState.emit( ViewState( warningVisible = invalidItems.isNotEmpty(), hint = invalidItems.firstOrNull()?.title?.shortenString(15) ?: "", invalidItemsSize = invalidItems.size, ), ) } fun onWarningActionClicked() { viewModelScope.launch { command.send(NavigateToBookmarks) } } private fun String.shortenString(maxLength: Int): String { return this.takeIf { it.length <= maxLength } ?: (this.take(maxLength - 3) + "...") } }
0
Kotlin
0
0
b89591136b60933d6a03fac43a38ee183116b7f8
2,611
DuckDuckGo
Apache License 2.0
app/src/androidTest/java/com/sergeyrodin/matchesboxes/component/list/RadioComponentsListFragmentTest.kt
rodins
340,269,974
false
null
package com.sergeyrodin.matchesboxes.component.list import android.content.Context import android.os.Bundle import androidx.appcompat.view.menu.ActionMenuItem import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.fragment.app.Fragment import androidx.navigation.NavController import androidx.navigation.Navigation import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import com.sergeyrodin.matchesboxes.* import com.sergeyrodin.matchesboxes.component.addeditdelete.NO_ID_SET import com.sergeyrodin.matchesboxes.component.addeditdelete.RadioComponentManipulatorReturns import com.sergeyrodin.matchesboxes.data.* import com.sergeyrodin.matchesboxes.di.RadioComponentsDataSourceModule import dagger.hilt.android.testing.HiltAndroidRule import dagger.hilt.android.testing.HiltAndroidTest import dagger.hilt.android.testing.UninstallModules import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito import org.mockito.Mockito.verify import javax.inject.Inject @RunWith(AndroidJUnit4::class) @MediumTest @HiltAndroidTest @UninstallModules(RadioComponentsDataSourceModule::class) class RadioComponentsListFragmentTest { @get:Rule(order = 1) val hiltRule = HiltAndroidRule(this) @get:Rule(order = 2) val composeTestRule = createAndroidComposeRule<HiltTestActivity>() @get:Rule(order = 3) var instantExecutorRule = InstantTaskExecutorRule() @Inject lateinit var dataSource: FakeDataSource @Before fun initDataSource() { hiltRule.inject() } @Test fun noItems_noItemsTextDisplayed() { val bag = Bag(1, "Bag") val set = MatchesBoxSet(1, "Set", bag.id) val box = MatchesBox(1, "Box", set.id) dataSource.addRadioComponents() launchFragment(box) composeTestRule.onNodeWithTextResource(R.string.no_components_added).assertIsDisplayed() } @Test fun fewItems_noItemsTextNotDisplayed() { val bag = Bag(1, "Bag") val set = MatchesBoxSet(1, "Set", bag.id) val box = MatchesBox(1, "Box", set.id) dataSource.addRadioComponents( RadioComponent(1, "Component1", 1, box.id), RadioComponent(2, "Component2", 1, box.id), RadioComponent(3, "Component3", 1, box.id) ) launchFragment(box) composeTestRule.onNodeWithTextResource(R.string.no_components_added).assertDoesNotExist() } @Test fun fewItems_textEquals() { val bag = Bag(1, "Bag") val set = MatchesBoxSet(1, "Set", bag.id) val box = MatchesBox(1, "Box", set.id) val component1 = RadioComponent(1, "Component1", 1, box.id) val component2 = RadioComponent(2, "Component2", 1, box.id) val component3 = RadioComponent(3, "Component3", 1, box.id) dataSource.addRadioComponents(component1, component2, component3) launchFragment(box) composeTestRule.onNodeWithText(component1.name).assertIsDisplayed() composeTestRule.onNodeWithText(component2.name).assertIsDisplayed() composeTestRule.onNodeWithText(component3.name).assertIsDisplayed() } @Test fun oneItem_quantityDisplayed() { val bag = Bag(1, "Bag") val set = MatchesBoxSet(1, "Set", bag.id) val box = MatchesBox(1, "Box", set.id) val component = RadioComponent(1, "Component", 12, box.id) dataSource.addRadioComponents(component) launchFragment(box) val result = composeTestRule.activity.resources.getQuantityString( R.plurals.components_quantity, component.quantity, component.quantity.toString() ) composeTestRule.onNodeWithText(result).assertIsDisplayed() } @Test fun addItem_navigationCalled() { val bag = Bag(1, "Bag") val set = MatchesBoxSet(1, "Set", bag.id) val box = MatchesBox(1, "Box", set.id) dataSource.addRadioComponents() val bundle = createBundle(box) val navController = Mockito.mock(NavController::class.java) var title = "" launchFragment<RadioComponentsListFragment>(composeTestRule.activityRule.scenario, bundle) { Navigation.setViewNavController(view!!, navController) title = getString(R.string.add_component) } composeTestRule.onNodeWithContentDescriptionResource(R.string.add_component).performClick() verify(navController).navigate( RadioComponentsListFragmentDirections .actionRadioComponentsListFragmentToAddEditDeleteRadioComponentFragment( ADD_NEW_ITEM_ID, box.id, title, "", RadioComponentManipulatorReturns.TO_COMPONENTS_LIST ) ) } @Test fun selectItem_navigationCalled() { val bag = Bag(1, "Bag") val set = MatchesBoxSet(1, "Set", bag.id) val box = MatchesBox(1, "Box", set.id) val component = RadioComponent(1, "Component", 3, box.id) dataSource.addRadioComponents(component) val navController = Mockito.mock(NavController::class.java) val bundle = createBundle(box) launchFragment<RadioComponentsListFragment>(composeTestRule.activityRule.scenario, bundle) { Navigation.setViewNavController(requireView(), navController) } composeTestRule.onNodeWithText(component.name).performClick() verify(navController).navigate( RadioComponentsListFragmentDirections .actionRadioComponentsListFragmentToRadioComponentDetailsFragment( component.id, "", RadioComponentManipulatorReturns.TO_COMPONENTS_LIST ) ) } @Test fun boxEditClick_navigationCalled() { val setId = 1 val box = MatchesBox(1, "Box", setId) dataSource.addRadioComponents() val navController = Mockito.mock(NavController::class.java) var title = "" val bundle = createBundle(box) launchFragment<RadioComponentsListFragment>(composeTestRule.activityRule.scenario, bundle) { Navigation.setViewNavController(view!!, navController) title = getString(R.string.update_box) clickEditAction(this) } verify(navController).navigate( RadioComponentsListFragmentDirections .actionRadioComponentsListFragmentToAddEditDeleteMatchesBoxFragment( NO_ID_SET, box.id, title ) ) } private fun launchFragment(box: MatchesBox) { val bundle = createBundle(box) launchFragment(bundle) } private fun launchFragment(bundle: Bundle){ launchFragment<RadioComponentsListFragment>(composeTestRule.activityRule.scenario, bundle) } private fun createBundle(box: MatchesBox): Bundle { return RadioComponentsListFragmentArgs.Builder(box.id, "Title").build().toBundle() } private fun clickEditAction(fragment: Fragment) { // Create dummy menu item with the desired item id val context = ApplicationProvider.getApplicationContext<Context>() val editMenuItem = ActionMenuItem(context, 0, R.id.action_edit, 0, 0, null) fragment.onOptionsItemSelected(editMenuItem) } }
0
Kotlin
0
0
719cec50f4e6129d0628598e20e21018b79bb8f6
7,746
matches-boxes
Apache License 2.0
app/src/main/java/com/realestate/model/DeviceFilterModel.kt
ChandanJana
810,743,284
false
{"Kotlin": 682645, "Java": 1802}
package com.realestate.model import android.os.Parcelable import kotlinx.android.parcel.Parcelize /** * Created by Chandan on 21/06/21 * Company: Endue Technologies Pvt. LTD * Email: <EMAIL> */ @Parcelize data class DeviceFilterModel ( val details: List<DeviceDetailsModel> ):Parcelable
0
Kotlin
0
0
ef6c30983cdd9eb0534b4d59d0e99a47c27c5cd9
296
android-Realstate
MIT License
ExamplesKotlin/BcastRecCompOrdBcastWithResRec/app/src/main/java/course/examples/broadcastreceiver/resultreceiver/Receiver3.kt
aporter
15,648,899
false
null
package course.examples.broadcastreceiver.resultreceiver import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.util.Log class Receiver3 : BroadcastReceiver() { companion object { private const val TAG = "Receiver3" } override fun onReceive(context: Context, intent: Intent) { Log.i(TAG, "INTENT RECEIVED by Receiver3") val tmp = if (resultData == null) "" else resultData resultData = "$tmp:Receiver 3" } }
65
Java
5469
4,289
157373885fbfa18b83fa97cd46f6a003905970ea
527
coursera-android
MIT License
src/main/kotlin/com/cn/tg/flooow/service/GraphService.kt
return764
661,601,356
false
null
package com.cn.tg.flooow.service import com.cn.tg.flooow.entity.ActionOptionPO import com.cn.tg.flooow.entity.EdgePO import com.cn.tg.flooow.entity.vo.ActionOptionVO import com.cn.tg.flooow.entity.vo.ActionTemplateVO import com.cn.tg.flooow.entity.vo.ActionVO import com.cn.tg.flooow.repository.ActionRepository import com.cn.tg.flooow.model.Edge import com.cn.tg.flooow.entity.vo.GraphDataVO import com.cn.tg.flooow.enums.OptionInputType import com.cn.tg.flooow.entity.vo.MoveNodeEvent import com.cn.tg.flooow.model.Node import com.cn.tg.flooow.repository.ActionOptionRepository import com.cn.tg.flooow.repository.ActionTemplateOptionRepository import com.cn.tg.flooow.repository.ActionTemplateRepository import com.cn.tg.flooow.repository.EdgeRepository import com.cn.tg.flooow.repository.NodeRepository import com.cn.tg.flooow.repository.PortRepository import jakarta.transaction.Transactional import org.springframework.stereotype.Service @Service class GraphService( private val actionRepository: ActionRepository, private val actionOptionRepository: ActionOptionRepository, private val nodeRepository: NodeRepository, private val portRepository: PortRepository, private val edgeRepository: EdgeRepository, private val actionTemplateRepository: ActionTemplateRepository, private val actionTemplateOptionRepository: ActionTemplateOptionRepository ) { fun getGraphData(graphId: String): GraphDataVO { val listNodes = nodeRepository.findAll() .filter { !it.isDeleted } .map { it.toModel(portRepository.findAllByNodeId(it.id), actionOptionRepository.findAllByNodeId(it.id)) } val listEdges = edgeRepository.findAll() .filter { !it.isDeleted } .map { it.toModel() } return GraphDataVO(listNodes, listEdges) } fun getAction(nodeId: String): ActionVO { return actionRepository.findByNodeId(nodeId).map { val template = actionTemplateRepository.findById(it.templateId!!).get() ActionVO( id = it.id!!, templateName = template.templateName, className = template.className, status = it.status, value = it.value ) }.get() } @Transactional fun addNode(node: Node): Node { return with(node) { val template = actionTemplateRepository.findByTemplateName(data["template"]) val action = actionRepository.save(toActionPO(template)) val ports = portRepository.saveAll(buildPortsPOs()) val templateOptions = actionTemplateOptionRepository.findAllByTemplateId(template?.id) val options = templateOptions.map { val value = data[it.key] ActionOptionPO( actionId = action.id!!, nodeId = node.id, key = it.key, value = value ?: it.defaultValue, type = it.type, inputType = OptionInputType.DEFAULT, visible = it.visible ) }.let { actionOptionRepository.saveAll(it) } nodeRepository.save(toPO(data["label"])).toModel(ports, options) } } fun addEdge(edge: Edge): Edge { with(edge) { EdgePO( id = id, shape = shape, sourceCellId = source.cell, sourcePortId = source.port, targetCellId = target.cell, targetPortId = target.port ).let { edgeRepository.save(it) } } return edge } fun retrieveAllTemplates(): List<ActionTemplateVO> { return actionTemplateRepository.findAll() .map { val options = actionTemplateOptionRepository.findAllByTemplateId(it.id) ActionTemplateVO( shape = it.shape, data = options.associate { opt -> opt.key to opt.defaultValue } ) } } fun moveNode(event: MoveNodeEvent): MoveNodeEvent { nodeRepository.findById(event.id) .ifPresent { nodeRepository.save(it.copy( x = event.postX, y = event.postY )) } return event } fun getActionOptions(nodeId: String): List<ActionOptionVO> { return actionOptionRepository.findAllByNodeId(nodeId) .filter { it.visible } .filter { !it.isDeleted } .map { it.toVO() } } @Transactional fun deleteNode(nodeId: String): Boolean { nodeRepository.findById(nodeId).ifPresent { nodeRepository.save(it.copy(isDeleted = true)) } portRepository.findAllByNodeId(nodeId).forEach { portRepository.save(it.copy(isDeleted = true)) } actionRepository.findByNodeId(nodeId).ifPresent { actionRepository.save(it.copy(isDeleted = true)) } actionOptionRepository.findAllByNodeId(nodeId).forEach { actionOptionRepository.save(it.copy(isDeleted = true)) } return true } fun deleteEdge(edgeId: String): Boolean { edgeRepository.findById(edgeId).ifPresent { edgeRepository.save(it.copy(isDeleted = true)) } return true } fun updateActionOptions(nodeId: String, listActionOptions: List<ActionOptionVO>): List<ActionOptionVO> { val actionOptions = actionOptionRepository.findAllByNodeId(nodeId) val mappedActionOptions = listActionOptions.associateBy { it.id } val changedActionOptions = actionOptions.map { it.copy( inputType = mappedActionOptions[it.id]?.inputType ?: it.inputType, value = mappedActionOptions[it.id]?.value ?: it.value ) } return actionOptionRepository.saveAll(changedActionOptions).map { it.toVO() } } }
0
Kotlin
0
0
ccd0494b487dc23c8d7cb4c103003fffc301be2f
6,077
flooow-api
MIT License
spring-data-graphql-r2dbc/src/main/kotlin/io/github/wickedev/graphql/spring/data/r2dbc/query/redefine/RedefineConnectionNextMethod.kt
wickedev
439,584,762
false
{"Kotlin": 269467, "JavaScript": 6748, "Java": 2439, "CSS": 1699}
package io.github.wickedev.graphql.spring.data.r2dbc.query.redefine import graphql.schema.DataFetchingEnvironment import io.github.wickedev.graphql.types.Backward import io.github.wickedev.graphql.types.ConnectionParam import io.github.wickedev.graphql.types.ID import net.bytebuddy.description.type.TypeDefinition import net.bytebuddy.description.type.TypeDescription import org.springframework.data.domain.Pageable import org.springframework.data.repository.core.RepositoryMetadata import reactor.core.publisher.Flux import java.lang.reflect.Method fun redefineConnectionNextMethod(method: Method, metadata: RepositoryMetadata): Method { val interfaceName = redefineInterfaceName(method) val methodName = redefineMethodName(method) val parameters = redefineParameters(method) val returnType = redefineReturnType(metadata) val unloadedType = makeType(interfaceName, methodName, parameters, returnType) ?: throw Error("unloaded type is null") val type = loadType(unloadedType) ?: throw Error("loaded type is null") return type.getMethod(methodName, *parametersForGetMethod(method)) } private fun redefineMethodName(method: Method): String { val backward = method.parameters.find { it.type == Backward::class.java } != null return if (backward) { method.name .replace("connection", "findAll") .replace("By", "ByIdLessThanAnd") } else { method.name .replace("connection", "findAll") .replace("By", "ByIdGreaterThanAnd") } } private fun redefineParameters(method: Method): List<TypeDescription.Generic> { return listOf( TypeDescription.Generic.Builder .rawType(ID::class.java) .build(), ) + method.parameters.filter { p -> p.type != DataFetchingEnvironment::class.java && !ConnectionParam::class.java.isAssignableFrom(p.type) } .map { TypeDescription.Generic.Builder .rawType(it.type) .build() } + listOf( TypeDescription.Generic.Builder .rawType(Pageable::class.java) .build() ) } private fun redefineReturnType(metadata: RepositoryMetadata): TypeDefinition { val returnObjectType = metadata.domainType return TypeDescription.Generic.Builder .parameterizedType(Flux::class.java, returnObjectType).build() } private fun parametersForGetMethod(method: Method): Array<Class<*>> { return (listOf(ID::class.java) + (method.parameters.filter { p -> p.type != DataFetchingEnvironment::class.java && !ConnectionParam::class.java.isAssignableFrom(p.type) } .map { it.type }) + listOf(Pageable::class.java)) .toTypedArray() }
0
Kotlin
0
19
d6913beaecf9e7ef065acdb1805794a10b07d55e
2,775
graphql-jetpack
The Unlicense
spring-data-graphql-r2dbc/src/main/kotlin/io/github/wickedev/graphql/spring/data/r2dbc/query/redefine/RedefineConnectionNextMethod.kt
wickedev
439,584,762
false
{"Kotlin": 269467, "JavaScript": 6748, "Java": 2439, "CSS": 1699}
package io.github.wickedev.graphql.spring.data.r2dbc.query.redefine import graphql.schema.DataFetchingEnvironment import io.github.wickedev.graphql.types.Backward import io.github.wickedev.graphql.types.ConnectionParam import io.github.wickedev.graphql.types.ID import net.bytebuddy.description.type.TypeDefinition import net.bytebuddy.description.type.TypeDescription import org.springframework.data.domain.Pageable import org.springframework.data.repository.core.RepositoryMetadata import reactor.core.publisher.Flux import java.lang.reflect.Method fun redefineConnectionNextMethod(method: Method, metadata: RepositoryMetadata): Method { val interfaceName = redefineInterfaceName(method) val methodName = redefineMethodName(method) val parameters = redefineParameters(method) val returnType = redefineReturnType(metadata) val unloadedType = makeType(interfaceName, methodName, parameters, returnType) ?: throw Error("unloaded type is null") val type = loadType(unloadedType) ?: throw Error("loaded type is null") return type.getMethod(methodName, *parametersForGetMethod(method)) } private fun redefineMethodName(method: Method): String { val backward = method.parameters.find { it.type == Backward::class.java } != null return if (backward) { method.name .replace("connection", "findAll") .replace("By", "ByIdLessThanAnd") } else { method.name .replace("connection", "findAll") .replace("By", "ByIdGreaterThanAnd") } } private fun redefineParameters(method: Method): List<TypeDescription.Generic> { return listOf( TypeDescription.Generic.Builder .rawType(ID::class.java) .build(), ) + method.parameters.filter { p -> p.type != DataFetchingEnvironment::class.java && !ConnectionParam::class.java.isAssignableFrom(p.type) } .map { TypeDescription.Generic.Builder .rawType(it.type) .build() } + listOf( TypeDescription.Generic.Builder .rawType(Pageable::class.java) .build() ) } private fun redefineReturnType(metadata: RepositoryMetadata): TypeDefinition { val returnObjectType = metadata.domainType return TypeDescription.Generic.Builder .parameterizedType(Flux::class.java, returnObjectType).build() } private fun parametersForGetMethod(method: Method): Array<Class<*>> { return (listOf(ID::class.java) + (method.parameters.filter { p -> p.type != DataFetchingEnvironment::class.java && !ConnectionParam::class.java.isAssignableFrom(p.type) } .map { it.type }) + listOf(Pageable::class.java)) .toTypedArray() }
0
Kotlin
0
19
d6913beaecf9e7ef065acdb1805794a10b07d55e
2,775
graphql-jetpack
The Unlicense
harmony-kotlin/src/commonTest/kotlin/com/harmony/kotlin/data/datasource/validator/vastra/strategies/timestamp/TimestampValidationStrategyTest.kt
mobilejazz
193,985,847
false
null
package com.harmony.kotlin.data.datasource.validator.vastra.strategies.timestamp import com.harmony.kotlin.common.BaseTest import com.harmony.kotlin.common.date.Millis import com.harmony.kotlin.common.date.Seconds import com.harmony.kotlin.data.validator.vastra.ValidationService import com.harmony.kotlin.data.validator.vastra.ValidationServiceManager import com.harmony.kotlin.data.validator.vastra.strategies.timestamp.TimestampValidationEntity import com.harmony.kotlin.data.validator.vastra.strategies.timestamp.TimestampValidationStrategy import kotlinx.datetime.Clock import kotlin.test.Test import kotlin.test.assertFalse import kotlin.test.assertTrue import kotlin.time.Duration.Companion.days import kotlin.time.Duration.Companion.minutes import kotlin.time.DurationUnit import kotlin.time.ExperimentalTime @ExperimentalTime class TimestampValidationStrategyTest : BaseTest() { private data class Foo(val id: String, override val lastUpdatedAt: Millis, override val expireIn: Seconds) : TimestampValidationEntity @Test fun should_value_be_valid_if_value_is_not_expired() { val foo = Foo("bar", lastUpdatedAt = Clock.System.now().toEpochMilliseconds(), expireIn = 1.minutes.toLong(DurationUnit.MILLISECONDS)) val timestampValidationStrategy = TimestampValidationStrategy() val validationServiceManager = ValidationServiceManager(listOf(timestampValidationStrategy)) val isValid = validationServiceManager.isValid(foo) assertTrue(actual = isValid) } @Test fun should_values_be_valid_if_value_are_not_expired() { val values = listOf( Foo("bar", lastUpdatedAt = Clock.System.now().toEpochMilliseconds(), expireIn = 1.minutes.toLong(DurationUnit.MILLISECONDS)), Foo("bar", lastUpdatedAt = Clock.System.now().toEpochMilliseconds(), expireIn = 1.minutes.toLong(DurationUnit.MILLISECONDS)) ) val timestampValidationStrategy = TimestampValidationStrategy() val validationServiceManager = ValidationServiceManager(listOf(timestampValidationStrategy)) val isValid = validationServiceManager.isValid(values) assertTrue(actual = isValid) } @Test fun should_value_be_invalid_if_value_is_expired() { val yesterday = Clock.System.now().minus(1.days).toEpochMilliseconds() val foo = Foo("bar", lastUpdatedAt = yesterday, expireIn = 1.minutes.toLong(DurationUnit.MILLISECONDS)) val timestampValidationStrategy = TimestampValidationStrategy() val validationServiceManager = ValidationServiceManager(listOf(timestampValidationStrategy)) val isValid = validationServiceManager.isValid(foo) assertFalse(isValid) } @Test fun should_values_be_invalid_if_values_are_expired() { runTest { val yesterday = Clock.System.now().minus(1.days).toEpochMilliseconds() val values = listOf( Foo("bar", lastUpdatedAt = yesterday, expireIn = 1.minutes.toLong(DurationUnit.MILLISECONDS)), Foo("bar", lastUpdatedAt = yesterday, expireIn = 1.minutes.toLong(DurationUnit.MILLISECONDS)) ) val timestampValidationStrategy = TimestampValidationStrategy() val validationServiceManager: ValidationService = ValidationServiceManager(listOf(timestampValidationStrategy)) val isValid = validationServiceManager.isValid(values) assertFalse(isValid) } } }
1
Kotlin
1
12
9ad0e00b2f76cc0db756bc05b83775a82c5db8f2
3,304
harmony-kotlin
Apache License 2.0
aesi-intellij/src/main/kotlin/com/virtlink/editorservices/intellij/psi/AesiFile2.kt
Virtlink
90,153,785
false
{"Git Config": 1, "Diff": 1, "Markdown": 1139, "Text": 2, "Ignore List": 19, "Makefile": 3, "YAML": 3, "Gradle": 21, "INI": 6, "Kotlin": 221, "Handlebars": 1, "Shell": 1, "ANTLR": 2, "XML": 5, "Maven POM": 7, "JAR Manifest": 4, "Java": 60, "Gemfile.lock": 1, "Ruby": 1, "SCSS": 1, "JSON with Comments": 2, "JSON": 6}
package com.virtlink.editorservices.intellij.psi import com.intellij.extapi.psi.PsiFileBase import com.intellij.openapi.fileTypes.LanguageFileType import com.intellij.psi.FileViewProvider class AesiFile2(viewProvider: FileViewProvider, private val fileType: LanguageFileType) : PsiFileBase(viewProvider, fileType.language) { override fun getFileType(): LanguageFileType = this.fileType }
1
null
1
1
f7af2531913d9809f3429c0d8e3a82fb695d5ba4
398
aesi
Apache License 2.0
app/src/main/java/asada0/android/brighterbigger/TwoFingerDoubleTapDetector.kt
asada0
205,814,543
false
null
// // TwoFingerDoubleTapDetector.kt // Brighter and Bigger // // Created by <NAME>, <NAME> and <NAME> on 2019/08/05. // // Copyright 2010-2019 <NAME>. All rights reserved. // //  This is based on the code of the following site. //  https://stackoverflow.com/questions/12414680/how-to-implement-a-two-finger-double-click-in-android // package asada0.android.brighterbigger import android.view.MotionEvent import android.view.ViewConfiguration abstract class TwoFingerDoubleTapDetector { private var mFirstDownTime: Long = 0L private var mSeparateTouches = false private var mTwoFingerTapCount: Int = 0 companion object { private val TIMEOUT = ViewConfiguration.getDoubleTapTimeout() + 100L } fun onTouchEvent(event: MotionEvent): Boolean { when (event.actionMasked) { MotionEvent.ACTION_DOWN -> if (mFirstDownTime == 0L || (event.eventTime - mFirstDownTime) > TIMEOUT) { reset(event.downTime) } MotionEvent.ACTION_POINTER_UP -> if (event.pointerCount == 2) { mTwoFingerTapCount++ } else { mFirstDownTime = 0L } MotionEvent.ACTION_UP -> if (!mSeparateTouches) { mSeparateTouches = true } else if (mTwoFingerTapCount == 2 && (event.eventTime - mFirstDownTime) < TIMEOUT) { onTwoFingerDoubleTap() mFirstDownTime = 0L return true } } return false } abstract fun onTwoFingerDoubleTap() private fun reset(time: Long) { mFirstDownTime = time mSeparateTouches = false mTwoFingerTapCount = 0 } }
0
Kotlin
0
1
256208c4bc2f1e9732a37b6ed2eb94e71b1564fb
1,797
BrighterAndBigger
MIT License
js/js.translator/testData/multiModuleOrder/umd.kt
JakeWharton
99,388,807
true
null
// MODULE: lib // FILE: lib.kt // MODULE_KIND: UMD package lib fun bar() = "OK" // MODULE: main(lib) // FILE: main.kt // MODULE_KIND: UMD package foo import lib.bar fun box() = bar()
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
187
kotlin
Apache License 2.0
app/src/main/java/com/flamyoad/tsukiviewer/db/dao/CollectionDoujinDao.kt
flamyoad
286,064,194
false
null
package com.flamyoad.tsukiviewer.db.dao import androidx.room.Dao import androidx.room.Query import com.flamyoad.tsukiviewer.model.DoujinDetails @Dao interface CollectionDoujinDao { // Search with Included Tags (OR) @Query(""" SELECT * FROM doujin_details as details INNER JOIN doujin_tags ON details.id = doujin_tags.doujinId WHERE tagId IN (:includedTagsId) GROUP BY details.id """) suspend fun searchIncludedOr(includedTagsId: List<Long>): List<DoujinDetails> // Search with Included Tags (AND) @Query(""" SELECT * FROM doujin_tags INNER JOIN doujin_details ON doujin_tags.doujinId = doujin_details.id WHERE doujin_tags.tagId IN (:includedTagsId) ----> Replace with list args GROUP BY doujin_tags.doujinId HAVING COUNT(*) = :includedTagsCount """) suspend fun searchIncludedAnd(includedTagsId: List<Long>, includedTagsCount: Int): List<DoujinDetails> // Search with Excluded Tags (OR) @Query(""" SELECT * FROM doujin_details WHERE id IN ( SELECT doujinId FROM doujin_tags EXCEPT SELECT doujinId FROM doujin_tags WHERE doujin_tags.tagId IN (:excludedTagsId) GROUP BY doujin_tags.doujinId ) """) suspend fun searchExcludedOr(excludedTagsId: List<Long>): List<DoujinDetails> // Search with Excluded Tags (AND) @Query(""" SELECT * FROM doujin_details WHERE id IN ( SELECT doujinId FROM doujin_tags EXCEPT SELECT doujinId FROM doujin_tags INNER JOIN doujin_details ON doujin_tags.doujinId = doujin_details.id WHERE doujin_tags.tagId IN (:excludedTagsId) GROUP BY doujin_tags.doujinId HAVING COUNT(*) = :excludedTagsCount ) """) suspend fun searchExcludedAnd(excludedTagsId: List<Long>, excludedTagsCount: Int): List<DoujinDetails> // Search with Included Tags (OR) + Excluded Tags (OR) @Query( """ SELECT * FROM doujin_details WHERE id IN ( SELECT doujinId FROM doujin_tags WHERE doujin_tags.tagId IN (:includedTagsId) GROUP BY doujinId EXCEPT SELECT doujinId FROM doujin_tags WHERE doujin_tags.tagId IN (:excludedTagsId) GROUP BY doujin_tags.doujinId) """ ) suspend fun searchIncludedOrExcludedOr( includedTagsId: List<Long>, excludedTagsId: List<Long> ): List<DoujinDetails> // Search with Included Tags (OR) + Excluded Tags (AND) @Query( """ SELECT * FROM doujin_details WHERE id IN ( SELECT doujinId FROM doujin_tags WHERE doujin_tags.tagId IN (:includedTagsId) GROUP BY doujinId EXCEPT SELECT doujinId FROM doujin_tags WHERE doujin_tags.tagId IN (:excludedTagsId) GROUP BY doujinId HAVING COUNT(*) = :excludedTagsCount) -----> Replace with list size """ ) suspend fun searchIncludedOrExcludedAnd( includedTagsId: List<Long>, excludedTagsId: List<Long>, excludedTagsCount: Int ): List<DoujinDetails> // Search with Included Tags (AND) + Excluded Tags (OR) @Query( """ SELECT * FROM doujin_details WHERE id IN ( SELECT doujinId FROM doujin_tags WHERE doujin_tags.tagId IN (:includedTagsId) GROUP BY doujinId HAVING COUNT(*) = :includedTagsCount EXCEPT SELECT doujinId FROM doujin_tags WHERE doujin_tags.tagId IN (:excludedTagsId) GROUP BY doujinId) """ ) suspend fun searchIncludedAndExcludedOr( includedTagsId: List<Long>, excludedTagsId: List<Long>, includedTagsCount: Int ): List<DoujinDetails> // Search with Included Tags (AND) + Excluded Tags (AND) @Query( """ SELECT * FROM doujin_details WHERE id IN ( SELECT doujinId FROM doujin_tags WHERE doujin_tags.tagId IN (:includedTagsId) GROUP BY doujinId HAVING COUNT(*) = :includedTagsCount EXCEPT SELECT doujinId FROM doujin_tags WHERE doujin_tags.tagId IN (:excludedTagsId) GROUP BY doujinId HAVING COUNT(*) = :excludedTagsCount ) """ ) suspend fun searchIncludedAndExcludedAnd( includedTagsId: List<Long>, excludedTagsId: List<Long>, includedTagsCount: Int, excludedTagsCount: Int ): List<DoujinDetails> }
3
null
1
6
2ad5060d52b758c5c60ab133f1cc7aed49ccca9b
4,554
TsukiViewer
Apache License 2.0
sphinx/application/data/features/feature-coredb/src/main/java/chat/sphinx/feature_coredb/CoreDBImpl.kt
kevkevinpal
385,406,512
true
{"Kotlin": 1368824, "Java": 357402, "JavaScript": 4745, "Shell": 2453}
package chat.sphinx.feature_coredb import chat.sphinx.concept_coredb.CoreDB import chat.sphinx.concept_coredb.SphinxDatabase import chat.sphinx.conceptcoredb.* import chat.sphinx.feature_coredb.adapters.chat.* import chat.sphinx.feature_coredb.adapters.common.* import chat.sphinx.feature_coredb.adapters.contact.* import chat.sphinx.feature_coredb.adapters.contact.ContactAliasAdapter import chat.sphinx.feature_coredb.adapters.contact.ContactOwnerAdapter import chat.sphinx.feature_coredb.adapters.contact.LightningNodeAliasAdapter import chat.sphinx.feature_coredb.adapters.contact.LightningRouteHintAdapter import chat.sphinx.feature_coredb.adapters.contact.PrivatePhotoAdapter import chat.sphinx.feature_coredb.adapters.invite.InviteStringAdapter import chat.sphinx.feature_coredb.adapters.media.* import chat.sphinx.feature_coredb.adapters.message.* import com.squareup.moshi.Moshi import com.squareup.sqldelight.db.SqlDriver import io.matthewnelson.concept_encryption_key.EncryptionKey import kotlinx.coroutines.* import kotlinx.coroutines.flow.* abstract class CoreDBImpl(private val moshi: Moshi): CoreDB() { companion object { const val DB_NAME = "sphinx.db" } private val sphinxDatabaseQueriesStateFlow: MutableStateFlow<SphinxDatabaseQueries?> = MutableStateFlow(null) override val isInitialized: Boolean get() = sphinxDatabaseQueriesStateFlow.value != null override fun getSphinxDatabaseQueriesOrNull(): SphinxDatabaseQueries? { return sphinxDatabaseQueriesStateFlow.value } protected abstract fun getSqlDriver(encryptionKey: EncryptionKey): SqlDriver private val initializationLock = Object() fun initializeDatabase(encryptionKey: EncryptionKey) { if (isInitialized) { return } synchronized(initializationLock) { if (isInitialized) { return } sphinxDatabaseQueriesStateFlow.value = SphinxDatabase( driver = getSqlDriver(encryptionKey), chatDboAdapter = ChatDbo.Adapter( idAdapter = ChatIdAdapter.getInstance(), uuidAdapter = ChatUUIDAdapter(), nameAdapter = ChatNameAdapter(), photo_urlAdapter = PhotoUrlAdapter.getInstance(), typeAdapter = ChatTypeAdapter(), statusAdapter = ChatStatusAdapter(), contact_idsAdapter = ContactIdsAdapter.getInstance(), is_mutedAdapter = ChatMutedAdapter.getInstance(), created_atAdapter = DateTimeAdapter.getInstance(), group_keyAdapter = ChatGroupKeyAdapter(), hostAdapter = ChatHostAdapter(), price_per_messageAdapter = SatAdapter.getInstance(), escrow_amountAdapter = SatAdapter.getInstance(), unlistedAdapter = ChatUnlistedAdapter(), private_tribeAdapter = ChatPrivateAdapter(), owner_pub_keyAdapter = LightningNodePubKeyAdapter.getInstance(), seenAdapter = SeenAdapter.getInstance(), meta_dataAdapter = ChatMetaDataAdapter(moshi), my_photo_urlAdapter = PhotoUrlAdapter.getInstance(), my_aliasAdapter = ChatAliasAdapter(), pending_contact_idsAdapter = ContactIdsAdapter.getInstance(), latest_message_idAdapter = MessageIdAdapter.getInstance(), ), contactDboAdapter = ContactDbo.Adapter( idAdapter = ContactIdAdapter.getInstance(), route_hintAdapter = LightningRouteHintAdapter(), node_pub_keyAdapter = LightningNodePubKeyAdapter.getInstance(), node_aliasAdapter = LightningNodeAliasAdapter(), aliasAdapter = ContactAliasAdapter(), photo_urlAdapter = PhotoUrlAdapter.getInstance(), private_photoAdapter = PrivatePhotoAdapter(), ownerAdapter = ContactOwnerAdapter(), statusAdapter = ContactStatusAdapter(), public_keyAdapter = ContactPublicKeyAdapter(), device_idAdapter = DeviceIdAdapter(), created_atAdapter = DateTimeAdapter.getInstance(), updated_atAdapter = DateTimeAdapter.getInstance(), notification_soundAdapter = NotificationSoundAdapter(), tip_amountAdapter = SatAdapter.getInstance(), invite_idAdapter = InviteIdAdapter.getInstance(), invite_statusAdapter = InviteStatusAdapter.getInstance(), ), inviteDboAdapter = InviteDbo.Adapter( idAdapter = InviteIdAdapter.getInstance(), invite_stringAdapter = InviteStringAdapter(), invoiceAdapter = LightningPaymentRequestAdapter.getInstance(), contact_idAdapter = ContactIdAdapter.getInstance(), statusAdapter = InviteStatusAdapter.getInstance(), priceAdapter = SatAdapter.getInstance(), created_atAdapter = DateTimeAdapter.getInstance(), ), dashboardDboAdapter = DashboardDbo.Adapter( idAdapter = DashboardIdAdapter(), contact_idAdapter = ContactIdAdapter.getInstance(), dateAdapter = DateTimeAdapter.getInstance(), mutedAdapter = ChatMutedAdapter.getInstance(), seenAdapter = SeenAdapter.getInstance(), photo_urlAdapter = PhotoUrlAdapter.getInstance(), latest_message_idAdapter = MessageIdAdapter.getInstance() ), messageDboAdapter = MessageDbo.Adapter( idAdapter = MessageIdAdapter.getInstance(), uuidAdapter = MessageUUIDAdapter(), chat_idAdapter = ChatIdAdapter.getInstance(), typeAdapter = MessageTypeAdapter(), senderAdapter = ContactIdAdapter.getInstance(), receiver_Adapter = ContactIdAdapter.getInstance(), amountAdapter = SatAdapter.getInstance(), payment_hashAdapter = LightningPaymentHashAdapter.getInstance(), payment_requestAdapter = LightningPaymentRequestAdapter.getInstance(), dateAdapter = DateTimeAdapter.getInstance(), expiration_dateAdapter = DateTimeAdapter.getInstance(), message_contentAdapter = MessageContentAdapter(), message_content_decryptedAdapter = MessageContentDecryptedAdapter(), statusAdapter = MessageStatusAdapter(), seenAdapter = SeenAdapter.getInstance(), sender_aliasAdapter = SenderAliasAdapter(), sender_picAdapter = PhotoUrlAdapter.getInstance(), original_muidAdapter = MessageMUIDAdapter(), reply_uuidAdapter = ReplyUUIDAdapter(), ), messageMediaDboAdapter = MessageMediaDbo.Adapter( idAdapter = MessageIdAdapter.getInstance(), chat_idAdapter = ChatIdAdapter.getInstance(), media_keyAdapter = MediaKeyAdapter(), media_key_decryptedAdapter = MediaKeyDecryptedAdapter(), media_typeAdapter = MediaTypeAdapter(), media_tokenAdapter = MediaTokenAdapter(), local_fileAdapter = FileAdapter.getInstance(), ), ).sphinxDatabaseQueries } } private class Hackery(val hack: SphinxDatabaseQueries): Exception() override suspend fun getSphinxDatabaseQueries(): SphinxDatabaseQueries { sphinxDatabaseQueriesStateFlow.value?.let { queries -> return queries } var queries: SphinxDatabaseQueries? = null try { sphinxDatabaseQueriesStateFlow.collect { queriesState -> if (queriesState != null) { queries = queriesState throw Hackery(queriesState) } } } catch (e: Hackery) { return e.hack } // Will never make it here, but to please the IDE just in case... delay(25L) return queries!! } }
0
null
0
0
5a5f316654ada1171270e28bf4d72d96182afd80
8,603
sphinx-kotlin
MIT License
app/src/main/java/com/jobscolin/wanandroid/base/adapter/BaseBindingViewHolder.kt
jobscolin
209,723,566
false
null
package com.jobscolin.wanandroid.base.adapter import android.view.View import androidx.recyclerview.widget.RecyclerView /** * @author : xdl * @time : 2019/08/09 * @describe : */ abstract class BaseBindingViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { abstract fun bind(iItem: IItem) }
0
Kotlin
0
0
3bed6d8a83f969a2a91ef039946d0f8d0a7c5c03
326
wanandroid
Apache License 2.0
app/src/main/java/com/calberto_barbosa_jr/fireconnectkotlinmvvm/model/ImageModel.kt
calbertobarbosajr
749,207,646
false
{"Kotlin": 61653}
package com.calberto_barbosa_jr.fireconnectkotlinmvvm.model data class ImageModel(val imageUrl: String)
0
Kotlin
0
0
6c15e3a796948c990f9f694b9a0168fc7bcd44a9
105
FireConnectKotlinMVVM
MIT License
viewlib/src/main/java/it/codingjam/github/util/ViewModelFactory.kt
linga103
144,549,273
true
{"Kotlin": 100830}
package it.codingjam.github.util import android.arch.lifecycle.ViewModel import android.arch.lifecycle.ViewModelProvider import android.arch.lifecycle.ViewModelProviders import android.support.v4.app.Fragment import android.support.v4.app.FragmentActivity import javax.inject.Provider class ViewModelFactory(val testProvider: (() -> ViewModel)? = null) { inline fun <reified VM : ViewModel> factory( provider: Provider<VM>, crossinline init: (VM) -> Unit ): ViewModelProvider.Factory { return object : ViewModelProvider.Factory { override fun <T1 : ViewModel> create(aClass: Class<T1>): T1 { val viewModel = testProvider?.invoke() as VM? ?: provider.get() return viewModel.also(init) as T1 } } } inline operator fun <reified VM : ViewModel> invoke( fragment: Fragment, provider: Provider<VM>, crossinline init: (VM) -> Unit = {} ): VM { return ViewModelProviders.of(fragment, factory(provider, init)).get(VM::class.java) } inline operator fun <reified VM : ViewModel> invoke( activity: FragmentActivity, provider: Provider<VM>, crossinline init: (VM) -> Unit = {} ): VM { return ViewModelProviders.of(activity, factory(provider, init)).get(VM::class.java) } }
0
Kotlin
0
0
53747df9a4029c09e4f312e7d8bb947854f90128
1,324
ArchitectureComponentsDemo
Apache License 2.0
app/src/main/java/com/convidados/viewModel/AbsentsViewModel.kt
agathaappb
648,808,159
false
null
package com.convidados.viewModel import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.convidados.model.GuestModel import com.convidados.repository.GuestRepository class AbsentsViewModel(application: Application) : AndroidViewModel(application) { private val repository = GuestRepository.getInstance(application.applicationContext) private val listGuestAbsent = MutableLiveData<List<GuestModel>>() val guestsAbsents: LiveData<List<GuestModel>> = listGuestAbsent fun getAbsent(presence:Int){ listGuestAbsent.value = repository.getPresence(presence) } }
0
Kotlin
0
0
e24bbee4e2787bb340b61ca781b80a2940978c3e
730
convidados
Apache License 2.0
src/commonMain/kotlin/org/guiVista/gui/window/scrolled_window_base.kt
gui-vista
331,127,836
false
null
package org.guiVista.gui.window import org.guiVista.gui.layout.Container /** Base interface for a scrolled window (a window that adds scrollbars to its child widget). */ public expect interface ScrolledWindowBase : Container
0
Kotlin
0
0
484e1e8437a3d57faaf5667489d622402fe7be01
227
guivista-gui
Apache License 2.0
library/kotlin/io/envoyproxy/envoymobile/mocks/MockEnvoyHTTPStream.kt
zyshi
383,876,459
true
{"Ruby": 1, "Starlark": 81, "YAML": 19, "CODEOWNERS": 2, "Markdown": 12, "EditorConfig": 1, "Git Attributes": 1, "Text": 8, "Ignore List": 1, "Git Config": 1, "Objective-C": 22, "C++": 138, "Python": 26, "Swift": 101, "Kotlin": 96, "Java": 102, "HTML": 7, "Shell": 6, "reStructuredText": 28, "CSS": 1, "XML": 16, "Diff": 3, "C": 9, "Protocol Buffer": 7, "OpenStep Property List": 2}
package io.envoyproxy.envoymobile import io.envoyproxy.envoymobile.engine.EnvoyHTTPStream import io.envoyproxy.envoymobile.engine.types.EnvoyHTTPCallbacks import java.nio.ByteBuffer /** * Internal no-op mock implementation of the engine's `EnvoyHTTPStream`. * * @param callbacks Callbacks associated with the stream. */ internal class MockEnvoyHTTPStream(val callbacks: EnvoyHTTPCallbacks) : EnvoyHTTPStream(0, callbacks) { override fun sendHeaders(headers: MutableMap<String, MutableList<String>>?, endStream: Boolean) {} override fun sendData(data: ByteBuffer?, endStream: Boolean) {} override fun sendTrailers(trailers: MutableMap<String, MutableList<String>>?) {} override fun cancel(): Int { return 0 } }
0
null
0
0
b58e973c7aad805d938603276e10d8a9543b6364
733
envoy-mobile
Apache License 2.0
src/test/kotlin/utils/TestUtils.kt
mr3y-the-programmer
390,104,276
false
null
package utils import java.io.File import java.nio.file.Path import java.nio.file.Paths import kotlin.io.path.div internal val root = Paths.get("").toAbsolutePath() / "src" / "test" / "fakeproject" internal val srcMainPath: (String) -> Path = { module -> root / module / "src" / "main" } internal val srcTestPath: (String) -> Path = { module -> root / module / "src" / "test" } internal fun getModuleMainFiles(module: String): Sequence<File> { return File(srcMainPath(module).toString()).walkBottomUp().filter { it.isFile } } internal fun getModuleMainDirs(module: String): Sequence<File> { return File(srcMainPath(module).toString()).walkBottomUp().filter { it.isDirectory } } internal fun getModuleTestDirs(module: String): Sequence<File> { return File(srcTestPath(module).toString()).walkBottomUp().filter { it.isDirectory } }
2
Kotlin
1
1
438853e732ee82081788f74d259e78d3687bcec9
847
chpkg
Apache License 2.0
src/test/kotlin/utils/TestUtils.kt
mr3y-the-programmer
390,104,276
false
null
package utils import java.io.File import java.nio.file.Path import java.nio.file.Paths import kotlin.io.path.div internal val root = Paths.get("").toAbsolutePath() / "src" / "test" / "fakeproject" internal val srcMainPath: (String) -> Path = { module -> root / module / "src" / "main" } internal val srcTestPath: (String) -> Path = { module -> root / module / "src" / "test" } internal fun getModuleMainFiles(module: String): Sequence<File> { return File(srcMainPath(module).toString()).walkBottomUp().filter { it.isFile } } internal fun getModuleMainDirs(module: String): Sequence<File> { return File(srcMainPath(module).toString()).walkBottomUp().filter { it.isDirectory } } internal fun getModuleTestDirs(module: String): Sequence<File> { return File(srcTestPath(module).toString()).walkBottomUp().filter { it.isDirectory } }
2
Kotlin
1
1
438853e732ee82081788f74d259e78d3687bcec9
847
chpkg
Apache License 2.0
src/main/kotlin/org/jetbrains/fortran/ide/annotator/FortranErrorAnnotator.kt
satamas
60,362,183
false
null
package org.jetbrains.fortran.ide.annotator import com.intellij.codeInsight.daemon.impl.HighlightRangeExtension import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.Annotator import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.fortran.lang.psi.* import org.jetbrains.fortran.lang.psi.impl.FortranConstructNameDeclImpl import org.jetbrains.fortran.lang.psi.impl.FortranLabelDeclImpl class FortranErrorAnnotator : Annotator, HighlightRangeExtension { override fun isForceHighlightParents(file: PsiFile): Boolean = file is FortranFile || file is FortranFixedFormFile override fun annotate(element: PsiElement, holder: AnnotationHolder) { val visitor = object : FortranVisitor() { override fun visitLabelDecl(labelDecl: FortranLabelDecl) { val programUnit = PsiTreeUtil.getParentOfType(element, FortranProgramUnit::class.java) ?: return val declarations = PsiTreeUtil.findChildrenOfType(programUnit, FortranLabelDeclImpl::class.java) .filter { (labelDecl as FortranLabelDeclImpl).getLabelValue() == it.getLabelValue() } if (declarations.size > 1) { holder.createErrorAnnotation( labelDecl, "Duplicated label `${(labelDecl as FortranLabelDeclImpl).getLabelValue()}` declaration" ) } } override fun visitConstructNameDecl(decl: FortranConstructNameDecl) { val programUnit = PsiTreeUtil.getParentOfType(element, FortranProgramUnit::class.java) ?: return val declarations = PsiTreeUtil.findChildrenOfType(programUnit, FortranConstructNameDeclImpl::class.java) .filter { decl.name.equals(it.name, true) } if (declarations.size > 1) { holder.createErrorAnnotation( decl, "Duplicated construct name `${decl.name}` declaration" ) } } } element.accept(visitor) } }
28
null
17
63
df108ce24b41de9ef7f905408f2792e2cde27056
2,165
fortran-plugin
Apache License 2.0
libraries/kotlinx-metadata/jvm/src/kotlinx/metadata/jvm/KotlinModuleMetadata.kt
JetBrains
3,432,266
false
{"Kotlin": 73228872, "Java": 6651359, "Swift": 4257359, "C": 2624202, "C++": 1891343, "Objective-C": 639940, "Objective-C++": 165521, "JavaScript": 135764, "Python": 43529, "Shell": 31554, "TypeScript": 22854, "Lex": 18369, "Groovy": 17190, "Batchfile": 11693, "CSS": 11368, "Ruby": 6922, "EJS": 5241, "HTML": 5073, "Dockerfile": 4705, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "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. */ @file:Suppress( "MemberVisibilityCanBePrivate", "DEPRECATION", // For KmModule.annotations — remove reading when deprecation is raised to error "DEPRECATION_ERROR", // deprecated .accept implementation "INVISIBLE_MEMBER", // InconsistentKotlinMetadataException "INVISIBLE_REFERENCE", "UNUSED_PARAMETER" // For deprecated Writer.write ) package kotlinx.metadata.jvm import kotlinx.metadata.* import kotlinx.metadata.internal.toKmClass import kotlinx.metadata.jvm.KotlinClassMetadata.Companion.COMPATIBLE_METADATA_VERSION import kotlinx.metadata.jvm.KotlinClassMetadata.Companion.throwIfNotCompatible import kotlinx.metadata.jvm.internal.wrapIntoMetadataExceptionWhenNeeded import kotlinx.metadata.jvm.internal.wrapWriteIntoIAE import org.jetbrains.kotlin.metadata.jvm.JvmModuleProtoBuf import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmMetadataVersion import org.jetbrains.kotlin.metadata.jvm.deserialization.ModuleMapping import org.jetbrains.kotlin.metadata.jvm.deserialization.PackageParts import org.jetbrains.kotlin.metadata.jvm.deserialization.serializeToByteArray /** * Represents the parsed metadata of a Kotlin JVM module file. * * To create an instance of [KotlinModuleMetadata], load the contents of the `.kotlin_module` file into a byte array * and call [KotlinModuleMetadata.read]. Then it is possible to transform the result into [KmModule] with [KotlinModuleMetadata.toKmModule]. * * `.kotlin_module` file is produced per Kotlin compilation, and contains auxiliary information, such as a map of all single- and multi-file facades ([KmModule.packageParts]), * `@OptionalExpectation` declarations ([KmModule.optionalAnnotationClasses]), and module annotations ([KmModule.annotations). * * @property bytes the byte array representing the contents of a `.kotlin_module` file */ @UnstableMetadataApi public class KotlinModuleMetadata private constructor( private val bytes: ByteArray, private val data: ModuleMapping, ) { /** * Returns the [KmModule] representation of this metadata. * * Returns the same (mutable) [KmModule] instance every time. */ public val kmModule: KmModule = readImpl() /** * Visits metadata of this module with a new [KmModule] instance and returns that instance. */ @Deprecated( "To avoid excessive copying, use .kmModule property instead. Note that it returns a view and not a copy.", ReplaceWith("kmModule"), DeprecationLevel.WARNING ) public fun toKmModule(): KmModule = KmModule().apply { kmModule.accept(this) } /** * A [KmModuleVisitor] that generates the metadata of a Kotlin JVM module file. */ @Deprecated( "Writer API is deprecated as excessive and cumbersome. Please use KotlinModuleMetadata.write(kmModule, metadataVersion)", level = DeprecationLevel.ERROR ) public class Writer { private val b = JvmModuleProtoBuf.Module.newBuilder() private fun writeModule(kmModule: KmModule) { kmModule.packageParts.forEach { (fqName, packageParts) -> PackageParts(fqName).apply { for (fileFacade in packageParts.fileFacades) { addPart(fileFacade, null) } for ((multiFileClassPart, multiFileFacade) in packageParts.multiFileClassParts) { addPart(multiFileClassPart, multiFileFacade) } addTo(b) } } // visitAnnotation /* // TODO: move StringTableImpl to module 'metadata' and support module annotations here b.addAnnotation(ProtoBuf.Annotation.newBuilder().apply { id = annotation.className.name // <-- use StringTableImpl here }) */ // visitOptionalAnnotationClass /* return object : ClassWriter(TODO() /* use StringTableImpl here */) { override fun visitEnd() { b.addOptionalAnnotationClass(t) } } */ } /** * Returns the metadata of the module file that was written with this writer. * * @param metadataVersion metadata version to be written to the metadata (see [Metadata.metadataVersion]), * [KotlinClassMetadata.COMPATIBLE_METADATA_VERSION] by default */ @Deprecated( "Writer API is deprecated as excessive and cumbersome. Please use KotlinModuleMetadata.write(kmModule, metadataVersion)", level = DeprecationLevel.ERROR ) public fun write(metadataVersion: IntArray = COMPATIBLE_METADATA_VERSION): ByteArray { error("This method is no longer implemented. Migrate to KotlinModuleMetadata.write.") } } /** * Makes the given visitor visit the metadata of this module file. * * @param v the visitor that must visit this module file */ @Deprecated(VISITOR_API_MESSAGE, level = DeprecationLevel.ERROR) public fun accept(v: KmModuleVisitor): Unit = kmModule.accept(v) private fun readImpl(): KmModule { val v = KmModule() for ((fqName, parts) in data.packageFqName2Parts) { val (fileFacades, multiFileClassParts) = parts.parts.partition { parts.getMultifileFacadeName(it) == null } v.packageParts[fqName] = KmPackageParts( fileFacades.toMutableList(), multiFileClassParts.associateWith { parts.getMultifileFacadeName(it)!! }.toMutableMap() ) } for (annotation in data.moduleData.annotations) { v.annotations.add(KmAnnotation(annotation, emptyMap())) } for (classProto in data.moduleData.optionalAnnotations) { v.optionalAnnotationClasses.add(classProto.toKmClass(data.moduleData.nameResolver)) } return v } /** * Collection of methods for reading and writing [KotlinModuleMetadata]. */ public companion object { /** * Parses the given byte array with the .kotlin_module file content and returns the [KotlinModuleMetadata] instance, * or `null` if this byte array encodes a module with an unsupported metadata version. * * @throws IllegalArgumentException if an error happened while parsing the given byte array, * which means that it is either not the content of a `.kotlin_module` file, or it has been corrupted. */ @JvmStatic @UnstableMetadataApi public fun read(bytes: ByteArray): KotlinModuleMetadata { return wrapIntoMetadataExceptionWhenNeeded { val result = dataFromBytes(bytes) when (result) { ModuleMapping.EMPTY, ModuleMapping.CORRUPTED -> throw InconsistentKotlinMetadataException("Data is not the content of a .kotlin_module file, or it has been corrupted.") } KotlinModuleMetadata(bytes, result) } } /** * Writes the metadata of the Kotlin module file. * * @param metadataVersion metadata version to be written to the metadata (see [Metadata.metadataVersion]), * [KotlinClassMetadata.COMPATIBLE_METADATA_VERSION] by default * * @throws IllegalArgumentException if [kmModule] is not correct and cannot be written or if [metadataVersion] is not supported for writing. */ @UnstableMetadataApi @JvmStatic @JvmOverloads public fun write(kmModule: KmModule, metadataVersion: IntArray = COMPATIBLE_METADATA_VERSION): ByteArray = wrapWriteIntoIAE { val w = Writer().also { it.writeModule(kmModule) } return w.b.build().serializeToByteArray(JvmMetadataVersion(*metadataVersion), 0) } private fun dataFromBytes(bytes: ByteArray): ModuleMapping { return ModuleMapping.loadModuleMapping( bytes, "KotlinModuleMetadata", skipMetadataVersionCheck = false, isJvmPackageNameSupported = true, reportIncompatibleVersionError = ::throwIfNotCompatible ) } } } /** * A visitor to visit Kotlin JVM module files. * * When using this class, [visitEnd] must be called exactly once and after calls to all other visit* methods. */ @Deprecated(VISITOR_API_MESSAGE, level = DeprecationLevel.ERROR) @UnstableMetadataApi public abstract class KmModuleVisitor(private val delegate: KmModuleVisitor? = null) { /** * Visits the table of all single- and multi-file facades declared in some package of this module. * * Packages are separated by '/' in the names of file facades. * * @param fqName the fully qualified name of the package, separated by '.' * @param fileFacades the list of single-file facades in this package * @param multiFileClassParts the map of multi-file classes where keys are names of multi-file class parts, * and values are names of the corresponding multi-file facades */ public open fun visitPackageParts(fqName: String, fileFacades: List<String>, multiFileClassParts: Map<String, String>) { delegate?.visitPackageParts(fqName, fileFacades, multiFileClassParts) } /** * Visits the annotation on the module. * * @param annotation annotation on the module */ public open fun visitAnnotation(annotation: KmAnnotation) { delegate?.visitAnnotation(annotation) } /** * Visits an `@OptionalExpectation`-annotated annotation class declared in this module. * Such classes are not materialized to bytecode on JVM, but the Kotlin compiler stores their metadata in the module file on JVM, * and loads it during compilation of dependent modules, in order to avoid reporting "unresolved reference" errors on usages. * * Multiplatform projects are an experimental feature of Kotlin, and their behavior and/or binary format * may change in a subsequent release. */ public open fun visitOptionalAnnotationClass(): KmClassVisitor? = delegate?.visitOptionalAnnotationClass() /** * Visits the end of the module. */ public open fun visitEnd() { delegate?.visitEnd() } // TODO: JvmPackageName } /** * Represents a Kotlin JVM module file (`.kotlin_module` extension). */ @UnstableMetadataApi public class KmModule : KmModuleVisitor() { /** * Table of all single- and multi-file facades declared in some package of this module, where keys are '.'-separated package names. */ public val packageParts: MutableMap<String, KmPackageParts> = LinkedHashMap() /** * Annotations on the module. * * Currently, Kotlin does not provide functionality to specify annotations on modules. */ @Deprecated("This list is always empty and will be removed", level = DeprecationLevel.WARNING) public val annotations: MutableList<KmAnnotation> = ArrayList(0) /** * `@OptionalExpectation`-annotated annotation classes declared in this module. * Such classes are not materialized to bytecode on JVM, but the Kotlin compiler stores their metadata in the module file on JVM, * and loads it during compilation of dependent modules, in order to avoid reporting "unresolved reference" errors on usages. * * Multiplatform projects are an experimental feature of Kotlin, and their behavior and/or binary format * may change in a subsequent release. */ public val optionalAnnotationClasses: MutableList<KmClass> = ArrayList(0) @Deprecated(VISITOR_API_MESSAGE, level = DeprecationLevel.ERROR) override fun visitPackageParts(fqName: String, fileFacades: List<String>, multiFileClassParts: Map<String, String>) { packageParts[fqName] = KmPackageParts(fileFacades.toMutableList(), multiFileClassParts.toMutableMap()) } @Deprecated(VISITOR_API_MESSAGE, level = DeprecationLevel.ERROR) override fun visitAnnotation(annotation: KmAnnotation) { annotations.add(annotation) } @Deprecated(VISITOR_API_MESSAGE, level = DeprecationLevel.ERROR) override fun visitOptionalAnnotationClass(): KmClass = KmClass().also(optionalAnnotationClasses::add) /** * Populates the given visitor with data in this module. * * @param visitor the visitor which will visit data in this module. */ @Deprecated(VISITOR_API_MESSAGE, level = DeprecationLevel.ERROR) public fun accept(visitor: KmModuleVisitor) { for ((fqName, parts) in packageParts) { visitor.visitPackageParts(fqName, parts.fileFacades, parts.multiFileClassParts) } annotations.forEach(visitor::visitAnnotation) optionalAnnotationClasses.forEach { visitor.visitOptionalAnnotationClass()?.let(it::accept) } } } /** * Collection of all single- and multi-file facades in a package of some module. * * Packages are separated by '/' in the names of file facades. * * @property fileFacades the list of single-file facades in this package * @property multiFileClassParts the map of multi-file classes where keys are names of multi-file class parts, * and values are names of the corresponding multi-file facades */ @UnstableMetadataApi public class KmPackageParts( public val fileFacades: MutableList<String>, public val multiFileClassParts: MutableMap<String, String> )
163
Kotlin
5686
46,039
f98451e38169a833f60b87618db4602133e02cf2
13,741
kotlin
Apache License 2.0
leetcode/p1630/Solution.kt
suhwanhwang
199,259,343
false
{"Text": 138, "Ignore List": 2, "Markdown": 1, "Makefile": 2, "Java": 638, "C++": 118, "YAML": 15, "JSON": 311, "Shell": 56, "Gradle": 12, "Python": 6, "Jupyter Notebook": 10, "XML": 4, "Kotlin": 232, "Swift": 67, "INI": 1}
class Solution { fun checkArithmeticSubarrays(nums: IntArray, l: IntArray, r: IntArray): List<Boolean> { val ans = mutableListOf<Boolean>() for (i in 0 until l.size) { val left = l[i] val right = r[i] val sorted = nums.filterIndexed { index, _ -> left <= index && index <= right }.sorted() var isOk = true val diff = sorted[1] - sorted[0] for (j in 2 until sorted.size) { if (sorted[j] - sorted[j - 1] != diff) { isOk = false break } } ans.add(isOk) } return ans } }
0
Java
0
0
0cc37fd7b9350a2a9f01f4828e3f4a22cf2121e5
725
problem-solving
MIT License
server/src/main/java/de/zalando/zally/rule/RulesValidator.kt
upasanachatterjee
142,311,308
true
{"YAML": 17, "Text": 2, "Ignore List": 6, "Shell": 5, "Markdown": 6, "CODEOWNERS": 1, "Gradle": 4, "JSON": 36, "Dockerfile": 3, "Batchfile": 2, "Java Properties": 2, "Kotlin": 146, "Java": 59, "OASv2-json": 19, "OASv2-yaml": 26, "OASv3-json": 3, "OASv3-yaml": 1, "INI": 1, "SQL": 7, "HTML": 2, "NPM Config": 1, "JavaScript": 74, "EditorConfig": 1, "JSON with Comments": 1, "Pug": 1, "SCSS": 1, "Go": 38, "TOML": 2}
package de.zalando.zally.rule import com.fasterxml.jackson.core.JsonPointer import de.zalando.zally.rule.api.Violation import de.zalando.zally.util.ast.JsonPointers import org.slf4j.LoggerFactory abstract class RulesValidator<RootT>(val rules: RulesManager) : ApiValidator { private val log = LoggerFactory.getLogger(RulesValidator::class.java) private val reader = ObjectTreeReader() override fun validate(content: String, policy: RulesPolicy): List<Result> { val root = parse(content) ?: return emptyList() return rules .checks(policy) .filter { details -> isCheckMethod(details, root) } .flatMap { details -> invoke(details, root) } .sortedBy(Result::violationType) } abstract fun parse(content: String): RootT? private fun isCheckMethod(details: CheckDetails, root: Any) = when (details.method.parameters.size) { 1 -> isRootParameterNeeded(details, root) else -> false } private fun isRootParameterNeeded(details: CheckDetails, root: Any) = details.method.parameters.isNotEmpty() && details.method.parameters[0].type.isAssignableFrom(root::class.java) private fun invoke(details: CheckDetails, root: RootT): Iterable<Result> { log.debug("validating ${details.method.name} of ${details.instance.javaClass.simpleName} rule") val result = details.method.invoke(details.instance, root) val violations = when (result) { null -> emptyList() is Violation -> listOf(result) is Iterable<*> -> result.filterIsInstance(Violation::class.java) else -> throw Exception("Unsupported return type for a @Check method!: ${result::class.java}") } log.debug("${violations.count()} violations identified") // TODO: make pointer not-null and remove usage of `paths` return violations .filterNot { ignore(root, it.pointer ?: JsonPointers.empty(), details.rule.id) } .map { if (it.pointer != null) { Result(details.ruleSet, details.rule, it.description, details.check.severity, it.paths, it.pointer) } else { Result(details.ruleSet, details.rule, it.description, details.check.severity, it.paths) } } } abstract fun ignore(root: RootT, pointer: JsonPointer, ruleId: String): Boolean }
0
Kotlin
0
0
a4c548a0a31b98b4188625feda7539fd8c6aae6a
2,498
zally-edits
MIT License
core/src/main/kotlin/tech/openEdgn/test/component/FXCanvas.kt
ExplodingFKL
316,875,411
false
{"Kotlin": 66578, "CSS": 2990, "Java": 917}
package tech.openEdgn.test.component import javafx.scene.canvas.Canvas import javafx.scene.canvas.GraphicsContext import javafx.scene.layout.VBox abstract class FXCanvas : VBox() { private val canvas = Canvas() private val graphics: GraphicsContext = canvas.graphicsContext2D init { val mWidth = 200.0 val mHeight = 100.0 prefWidth = mWidth maxWidth = Double.MAX_VALUE minWidth = mWidth prefHeight = mHeight maxHeight = Double.MAX_VALUE minWidth = mWidth children.add(canvas) widthProperty().addListener { _, _, newValue -> canvas.widthProperty().set(newValue.toDouble()- (padding.left + padding.right)) draw() } heightProperty().addListener { _, _, newValue -> canvas.heightProperty().set(newValue.toDouble() - (padding.top + padding.bottom)) draw() } } abstract fun draw(graphics: GraphicsContext) protected fun draw() { graphics.clearRect(0.0, 0.0, canvas.width, canvas.height) draw(graphics) } protected val drawWidth: Double get() { return canvas.width } protected val drawHeight: Double get() { return canvas.height } }
0
Kotlin
0
0
7aeca46864590e305c5cc76c01ce2f95d4baea85
1,293
SystemOperation
MIT License
app/src/androidTest/java/com/gigigo/orchextrasdk/demo/test/screen/LoginScreen.kt
Orchextra
44,963,670
false
null
package com.gigigo.orchextrasdk.demo.test.screen import com.agoda.kakao.KButton import com.agoda.kakao.KEditText import com.agoda.kakao.KTextView import com.agoda.kakao.KView import com.agoda.kakao.Screen import com.gigigo.orchextrasdk.demo.R import com.gigigo.orchextrasdk.demo.R.id open class LoginScreen : Screen<LoginScreen>() { val logoLayout: KView = KView { withId(R.id.logo_layout) } val startButton: KButton = KButton { withId(R.id.start_button) } val projectNameEditText: KEditText = KEditText { withId(id.projectName_editText) } val apiKeyEditText: KEditText = KEditText { withId(id.apiKey_editText) } val apiSecretEditText: KEditText = KEditText { withId(id.apiSecret_editText) } val errorTextView: KTextView = KTextView { withId(id.errorTextView) } }
4
Kotlin
8
18
e17c0d362800a903845454f2d01179fec22765ab
784
orchextra-android-sdk
Apache License 2.0
qchatkit/src/main/java/com/netease/yunxin/kit/qchatkit/repo/QChatRoleRepo.kt
shine2008
608,936,203
true
{"Java Properties": 2, "Gradle Kotlin DSL": 5, "Shell": 1, "Markdown": 1, "Batchfile": 1, "INI": 2, "Proguard": 3, "Kotlin": 52, "Java": 206}
/* * Copyright (c) 2022 NetEase, Inc. All rights reserved. * Use of this source code is governed by a MIT license that can be * found in the LICENSE file. */ package com.netease.yunxin.kit.qchatkit.repo import com.netease.nimlib.sdk.qchat.enums.QChatRoleOption import com.netease.nimlib.sdk.qchat.enums.QChatRoleResource import com.netease.nimlib.sdk.qchat.enums.QChatRoleType import com.netease.nimlib.sdk.qchat.model.QChatMemberRole import com.netease.nimlib.sdk.qchat.result.QChatCreateServerRoleResult import com.netease.nimlib.sdk.qchat.result.QChatRemoveMembersFromServerRoleResult import com.netease.yunxin.kit.alog.ALog import com.netease.yunxin.kit.corekit.im.provider.FetchCallback import com.netease.yunxin.kit.corekit.im.utils.toInform import com.netease.yunxin.kit.corekit.model.ResultInfo import com.netease.yunxin.kit.corekit.qchat.provider.QChatRoleProvider import com.netease.yunxin.kit.qchatkit.repo.model.QChatChannelMember import com.netease.yunxin.kit.qchatkit.repo.model.QChatChannelRoleInfo import com.netease.yunxin.kit.qchatkit.repo.model.QChatRoleOptionEnum import com.netease.yunxin.kit.qchatkit.repo.model.QChatRoleResourceEnum import com.netease.yunxin.kit.qchatkit.repo.model.QChatServerRoleInfo import com.netease.yunxin.kit.qchatkit.repo.model.QChatServerRoleMemberInfo import com.netease.yunxin.kit.qchatkit.repo.model.ServerRoleResult import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch object QChatRoleRepo { const val MAX_ROLE_PAGE_SIZE = 200 /** * Q chat role repo * * @constructor Create empty Q chat role repo */ private const val LOG_TAG = "QChatRoleRepo" /** * 新增服务器身份组,并将成员加入 */ @JvmStatic @JvmOverloads fun createRoleWithMember( serverId: Long, name: String, type: QChatRoleType = QChatRoleType.CUSTOM, members: List<String>, icon: String? = null, extension: String? = null, inform: ((ResultInfo<QChatCreateServerRoleResult>) -> Unit) ) { CoroutineScope(Dispatchers.Main).launch { val result = QChatRoleProvider.createServerRole(serverId, name, type, icon, extension) ALog.e(LOG_TAG, result.toString()) if (result.success) { QChatRoleProvider.addMembersToServerRole( serverId, result.value!!.role.roleId, members ) } inform.invoke(result) } } /** * 新增服务器身份组 */ @JvmStatic @JvmOverloads fun createRole( serverId: Long, name: String, type: QChatRoleType = QChatRoleType.CUSTOM, icon: String? = null, extension: String? = null, inform: ((ResultInfo<QChatCreateServerRoleResult>) -> Unit) ) { CoroutineScope(Dispatchers.Main).launch { val result = QChatRoleProvider.createServerRole(serverId, name, type, icon, extension) ALog.e(LOG_TAG, result.toString()) inform.invoke(result) } } /** * 查询某服务器下某身份组下的成员列表 */ @JvmStatic @JvmOverloads fun fetchServerRoleMember( serverId: Long, roleId: Long, timeTag: Long, limit: Int, accId: String? = null, callback: FetchCallback<List<QChatServerRoleMemberInfo>> ) { CoroutineScope((Dispatchers.Main)).launch { QChatRoleProvider.getServerRoleMembers(serverId, roleId, timeTag, limit, accId) .toInform(callback) { it?.roleMemberList?.map { qChatServerRoleMember -> qChatServerRoleMember.toInfo() } } } } /** * 将某些人移出某服务器身份组 */ @JvmStatic fun removeServerRoleMember( serverId: Long, roleId: Long, accIds: List<String>, callback: FetchCallback<List<String>> ) { CoroutineScope(Dispatchers.Main).launch { QChatRoleProvider.removeMembersFromServerRole(serverId, roleId, accIds) .toInform(callback) { it?.successAccids } } } /** * 将某些人移出某服务器身份组 */ @JvmStatic fun removeServerRoleMemberForResult( serverId: Long, roleId: Long, accIds: List<String>, callback: FetchCallback<QChatRemoveMembersFromServerRoleResult> ) { CoroutineScope(Dispatchers.Main).launch { QChatRoleProvider.removeMembersFromServerRole(serverId, roleId, accIds) .toInform(callback) { it } } } /** * 将某些人加入某服务器身份组 */ @JvmStatic fun addServerRoleMember( serverId: Long, roleId: Long, accIds: List<String>, callback: FetchCallback<List<String>> ) { CoroutineScope(Dispatchers.Main).launch { QChatRoleProvider.addMembersToServerRole(serverId, roleId, accIds).toInform(callback) { it?.successAccids } } } /** * 新增Channel身份组 */ @JvmStatic fun addChannelRole( serverId: Long, channelId: Long, parentRoleId: Long, callback: FetchCallback<QChatChannelRoleInfo> ) { CoroutineScope(Dispatchers.Main).launch { val result = QChatRoleProvider.addChannelRole(serverId, channelId, parentRoleId) callback.run { result.toInform(this) { it?.role?.toInfo() } } } } /** * 修改频道下某身份组的权限 */ @JvmStatic fun updateChannelRole( serverId: Long, channelId: Long, roleId: Long, option: Map<QChatRoleResourceEnum, QChatRoleOptionEnum>, callback: FetchCallback<QChatChannelRoleInfo> ) { CoroutineScope(Dispatchers.Main).launch { val optionMap = mutableMapOf<QChatRoleResource, QChatRoleOption>() option.map { optionMap.put( QChatConvert.convertToRoleResource(it.key), QChatConvert.convertToRoleOption(it.value) ) } val result = QChatRoleProvider.updateChannelRole(serverId, channelId, roleId, optionMap) callback.run { result.toInform(this) { it?.role?.toInfo() } } } } /** * 删除频道身份组 */ @JvmStatic fun deleteChannelRole( serverId: Long, channelId: Long, roleId: Long, callback: FetchCallback<Void> ) { CoroutineScope(Dispatchers.Main).launch { val result = QChatRoleProvider.deleteChannelRole(serverId, channelId, roleId) callback.run { result.toInform(this) { it } } } } /** * 为某个人定制某频道的权限 */ @JvmStatic fun addChannelMemberRole( serverId: Long, channelId: Long, accId: String, callback: FetchCallback<QChatChannelMember> ) { CoroutineScope(Dispatchers.Main).launch { val result = QChatRoleProvider.addChannelMemberRole(serverId, channelId, accId) callback.run { result.toInform(this) { it?.role?.toInfo() } } } } /** * 修改某人的定制权限 */ @JvmStatic fun updateChannelMember( serverId: Long, channelId: Long, accId: String, option: Map<QChatRoleResourceEnum, QChatRoleOptionEnum>, callback: FetchCallback<QChatChannelMember> ) { CoroutineScope(Dispatchers.Main).launch { val optionMap = mutableMapOf<QChatRoleResource, QChatRoleOption>() option.map { optionMap.put( QChatConvert.convertToRoleResource(it.key), QChatConvert.convertToRoleOption(it.value) ) } val result = QChatRoleProvider.updateChannelMemberRole(serverId, channelId, accId, optionMap) callback.run { result.toInform(this) { it?.role?.toInfo() } } } } /** * 删除频道下某人的定制权限 */ @JvmStatic fun deleteChannelMemberRole( serverId: Long, channelId: Long, accId: String, callback: FetchCallback<Void> ) { CoroutineScope(Dispatchers.Main).launch { val result = QChatRoleProvider.deleteChannelMemberRole(serverId, channelId, accId) callback.run { result.toInform(this) { it } } } } /** * 修改服务器身份组信息 */ @JvmStatic @JvmOverloads fun updateRole( serverId: Long, roleId: Long, name: String? = null, icon: String? = null, extension: String? = null, auths: Map<QChatRoleResourceEnum, QChatRoleOptionEnum>? = null, inform: FetchCallback<Void> ) { CoroutineScope(Dispatchers.Main).launch { val optionMap = mutableMapOf<QChatRoleResource, QChatRoleOption>() auths?.map { optionMap.put( QChatConvert.convertToRoleResource(it.key), QChatConvert.convertToRoleOption(it.value) ) } QChatRoleProvider.updateServerRole(serverId, roleId, name, icon, extension, optionMap) .toInform(inform) { ALog.e(LOG_TAG, it.toString()) null } } } /** * 查询服务器下身份组列表,第一页返回结果额外包含everyone身份组,自定义身份组数量充足的情况下会返回limit+1个身份组 */ @JvmStatic @JvmOverloads fun fetchServerRoles( serverId: Long, timeTag: Long, limit: Int, inform: FetchCallback<ServerRoleResult> ) { CoroutineScope((Dispatchers.Main)).launch { QChatRoleProvider.fetchServerRoles(serverId, timeTag, limit) .toInform(inform) { qChatGetServerRolesResult -> ServerRoleResult( qChatGetServerRolesResult?.roleList?.map { qChatServerRole -> qChatServerRole.toInfo() }, qChatGetServerRolesResult?.isMemberSet ) } } } /** * 查询服务器下身份组列表,第一页返回结果额外包含everyone身份组,并移除频道下身份组 */ @JvmStatic @JvmOverloads fun fetchServerRolesWithoutChannel( serverId: Long, channelId: Long, timeTag: Long, limit: Int, inform: FetchCallback<List<QChatServerRoleInfo>> ) { CoroutineScope((Dispatchers.Main)).launch { QChatRoleProvider.fetchServerRoles(serverId, timeTag, limit) .toInform(inform) { qChatGetServerRolesResult -> val hasRoleSet = mutableSetOf<Long>() qChatGetServerRolesResult?.roleList?.apply { val roleList = map { serverRole -> serverRole.roleId } queryChannelRole(serverId, channelId, roleList).also { resultSet -> hasRoleSet.addAll(resultSet) } }?.filterNot { hasRoleSet.contains(it.roleId) }?.map { qChatServerRole -> qChatServerRole.toInfo() } } } } private suspend fun queryChannelRole( serverId: Long, channelId: Long, roleIdList: List<Long> ): Set<Long> { val result = QChatRoleProvider.queryExistingChannelRoles(serverId, channelId, roleIdList) return mutableSetOf<Long>().apply { result.value?.roleList?.map { this.add(it.parentRoleId) } } } /** * 查询ACCID用户加入的身份组列表,结果只有自定义身份组,不包含everyone身份组 */ @JvmStatic @JvmOverloads fun fetchMemberJoinedRoles( serverId: Long, accId: String, inform: FetchCallback<List<QChatServerRoleInfo>> ) { CoroutineScope((Dispatchers.Main)).launch { QChatRoleProvider.getExistingServerRolesByAccids( serverId, listOf(accId) ).toInform(inform) { qChatGetServerRolesByAccidResult -> qChatGetServerRolesByAccidResult?.accidServerRolesMap?.get(accId) ?.map { qChatServerRole -> qChatServerRole.toInfo() } } } } /** * 移除服务器身份组 */ @JvmStatic fun deleteServerRole( serverId: Long, roleId: Long, callback: FetchCallback<Void> ) { CoroutineScope(Dispatchers.Main).launch { val result = QChatRoleProvider.deleteServerRole(serverId, roleId) callback.run { result.toInform(this) { it } } } } /** * 批量修改服务器身份组优先级 */ @JvmStatic fun updateRolesPriorities( serverId: Long, topPriority: Long, rolesList: List<QChatServerRoleInfo>, callback: FetchCallback<Void> ) { CoroutineScope(Dispatchers.Main).launch { val map = mutableMapOf<Long, Long>() var top = topPriority rolesList.map { map[it.roleId] = top++ } QChatRoleProvider.updateServerRolePriorities(serverId, map).toInform(callback) { null } } } /** * 查询自己是否拥有某个权限 */ @JvmStatic @JvmOverloads fun checkPermission( serverId: Long, channelId: Long? = null, resource: QChatRoleResource, callback: FetchCallback<Boolean> ) { CoroutineScope(Dispatchers.Main).launch { QChatRoleProvider.checkPermission(serverId, channelId, resource).toInform(callback) { it?.isHasPermission } } } /** * 查询自己是否拥有某些权限 */ @JvmStatic @JvmOverloads fun checkPermissions( serverId: Long, channelId: Long? = null, resourceList: List<QChatRoleResource>, callback: FetchCallback<Map<QChatRoleResource, QChatRoleOption>> ) { CoroutineScope(Dispatchers.Main).launch { QChatRoleProvider.checkPermissions(serverId, channelId, resourceList) .toInform(callback) { it?.permissions } } } /** * 查询channel下某人的定制权限 */ @JvmStatic fun getMemberRoles( serverId: Long, channelId: Long, timeTag: Long, limit: Int, callback: FetchCallback<List<QChatMemberRole>> ) { CoroutineScope(Dispatchers.Main).launch { QChatRoleProvider.fetchChannelMemberRole( serverId, channelId, timeTag, limit ).toInform(callback) { it?.roleList } } } /** * 为某个人定制某频道的权限 */ @JvmStatic fun addMemberRole( serverId: Long, channelId: Long, accId: String, callback: FetchCallback<QChatMemberRole>? ) { CoroutineScope(Dispatchers.Main).launch { QChatRoleProvider.addMemberRole(serverId, channelId, accId) .toInform(callback) { it?.role } } } /** * 删除频道下某人的定制权限 */ @JvmStatic fun removeMemberRole( serverId: Long, channelId: Long, accId: String, callback: FetchCallback<Void>? ) { CoroutineScope(Dispatchers.Main).launch { QChatRoleProvider.removeMemberRole(serverId, channelId, accId) .toInform(callback) { it } } } /** * 修改某人的定制权限 */ @JvmStatic fun updateMemberRole( serverId: Long, channelId: Long, accId: String, auths: Map<QChatRoleResource, QChatRoleOption>, callback: FetchCallback<QChatMemberRole>? ) { CoroutineScope(Dispatchers.Main).launch { QChatRoleProvider.updateMemberRole(serverId, channelId, accId, auths) .toInform(callback) { it?.role } } } /** * 更新公告频道订阅者的权限 */ @JvmStatic fun updateEveryonePermissionForAnnounce(serverId: Long, authMap: Map<QChatRoleResource, QChatRoleOption>, callback: FetchCallback<Void>?) { CoroutineScope(Dispatchers.Main).launch { val everyoneResult = QChatRoleProvider.fetchServerRoles(serverId, 0, 2).value?.roleList?.find { it.type == QChatRoleType.EVERYONE } val roleId = everyoneResult?.roleId if (everyoneResult == null || roleId == null) { callback?.onFailed(-1) return@launch } QChatRoleProvider.updateServerRole( serverId, roleId, auths = authMap ).toInform(callback) { null } } } }
0
Java
0
0
9058d04b2d04d8d2ffad9fdda4d0d377ab90e50b
17,453
qchat-uikit-android
MIT License
tools4a-fragment/src/androidTest/java/androidx/fragment/app/test/FragmentInsiderTest.kt
panpf
288,975,150
false
{"Java": 1488750, "Kotlin": 1432456}
package androidx.fragment.app.test import android.os.Bundle import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentInsider import androidx.lifecycle.Lifecycle import androidx.test.ext.junit.runners.AndroidJUnit4 import com.github.panpf.tools4a.test.ktx.getFragmentSync import com.github.panpf.tools4a.test.ktx.launchFragment import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class FragmentInsiderTest { @Test fun testGetMaxStateWithParent() { val parentFragmentScenario = ParentFragment::class.launchFragment() val parentFragment = parentFragmentScenario.getFragmentSync() val childFragment = parentFragment.childFragmentManager.fragments.single() val grandsonFragment = childFragment.childFragmentManager.fragments.single() Assert.assertEquals(Lifecycle.State.RESUMED, FragmentInsider.getMaxState(parentFragment)) Assert.assertEquals(Lifecycle.State.RESUMED, FragmentInsider.getMaxStateWithParent(parentFragment)) Assert.assertEquals(Lifecycle.State.RESUMED, FragmentInsider.getMaxState(childFragment)) Assert.assertEquals(Lifecycle.State.RESUMED, FragmentInsider.getMaxStateWithParent(childFragment)) Assert.assertEquals(Lifecycle.State.RESUMED, FragmentInsider.getMaxState(grandsonFragment)) Assert.assertEquals(Lifecycle.State.RESUMED, FragmentInsider.getMaxStateWithParent(grandsonFragment)) parentFragmentScenario.onFragment { it.requireActivity().supportFragmentManager.beginTransaction() .setMaxLifecycle(it, Lifecycle.State.CREATED) .commit() } Thread.sleep(200) Assert.assertEquals(Lifecycle.State.CREATED, FragmentInsider.getMaxState(parentFragment)) Assert.assertEquals(Lifecycle.State.CREATED, FragmentInsider.getMaxStateWithParent(parentFragment)) Assert.assertEquals(Lifecycle.State.RESUMED, FragmentInsider.getMaxState(childFragment)) Assert.assertEquals(Lifecycle.State.CREATED, FragmentInsider.getMaxStateWithParent(childFragment)) Assert.assertEquals(Lifecycle.State.RESUMED, FragmentInsider.getMaxState(grandsonFragment)) Assert.assertEquals(Lifecycle.State.CREATED, FragmentInsider.getMaxStateWithParent(grandsonFragment)) } class ParentFragment : Fragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) childFragmentManager.beginTransaction() .add(ChildFragment(), "ChildFragment") .commit() } } class ChildFragment : Fragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) childFragmentManager.beginTransaction() .add(GrandsonFragment(), "GrandsonFragment") .commit() } } class GrandsonFragment : Fragment() }
1
Java
1
3
4fa4a1d305d939544c6a2dcb814c80b98d8ddf26
3,006
tools4a
Apache License 2.0
tmp/arrays/youTrackTests/8710.kt
DaniilStepanov
228,623,440
false
{"Git Config": 1, "Gradle": 6, "Text": 3, "INI": 5, "Shell": 2, "Ignore List": 3, "Batchfile": 2, "Markdown": 2, "Kotlin": 15942, "JavaScript": 4, "ANTLR": 2, "XML": 12, "Java": 4}
// Original bug: KT-19435 abstract class Base(val params: Array<Any> = emptyArray()) class Derived() : Base(arrayOf(1)) fun main(args: Array<String>) { println(Derived().params.contentToString()) // prints "[]" }
1
null
11
1
602285ec60b01eee473dcb0b08ce497b1c254983
220
bbfgradle
Apache License 2.0
payments-core/src/main/java/com/stripe/android/ApiVersion.kt
stripe
6,926,049
false
null
package com.stripe.android /** * A class that represents a Stripe API version. * * See [https://stripe.com/docs/api/versioning](https://stripe.com/docs/api/versioning) * for documentation on API versioning. * * See [https://stripe.com/docs/upgrades](https://stripe.com/docs/upgrades) for latest * API changes. */ internal data class ApiVersion internal constructor( internal val version: String, internal val betas: Set<StripeApiBeta> = emptySet() ) { constructor( betas: Set<StripeApiBeta> ) : this(API_VERSION_CODE, betas) val code: String get() = listOf(this.version) .plus( betas.map { it.code } ) .joinToString(";") internal companion object { const val API_VERSION_CODE: String = "2020-03-02" private val INSTANCE = ApiVersion(API_VERSION_CODE) @JvmSynthetic internal fun get(): ApiVersion { return INSTANCE } } }
57
null
516
914
64b3e9fc2862698150f4abe1617e6ba5f6f21df1
1,009
stripe-android
MIT License
demoa-kotlin/src/main/java/sviolet/demoakotlin/TempActivity.kt
shepherdviolet
37,111,683
false
null
/* * Copyright (C) 2015-2017 S.Violet * * 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. * * Project GitHub: https://github.com/shepherdviolet/turquoise * Email: <EMAIL> */ package sviolet.demoakotlin import android.os.Bundle import sviolet.demoakotlin.common.DemoDescription import sviolet.turquoise.enhance.app.TActivity import sviolet.turquoise.enhance.app.annotation.inject.ResourceId import sviolet.turquoise.enhance.app.annotation.setting.ActivitySettings /** * 临时调试用Activity */ @DemoDescription( title = "Temp", type = "Temp", info = "The activity for test" ) @ResourceId(R.layout.temp_main) @ActivitySettings( statusBarColor = 0xFF30C0C0.toInt(), navigationBarColor = 0xFF30C0C0.toInt() ) class TempActivity : TActivity() { override fun onInitViews(savedInstanceState: Bundle?) { } override fun afterDestroy() { } override fun onResume() { super.onResume() } }
1
null
2
7
281803ed4450b97fbc7c21e7dab0f85718ea9891
1,465
turquoise
Apache License 2.0
live-battery/src/main/java/com/raqun/live_battery/BatteryPlug.kt
iammert
122,179,964
false
null
package com.raqun.live_battery /** * Created by tyln on 2.05.2018. */ enum class BatteryPlug { NOT_RECOGNISED, USB, AC, WIRELESS }
0
null
1
3
ba9950a03ba0d43002bf05ecb9d4bec48efb2237
137
sensitive-activity
Apache License 2.0
native/commonizer/src/org/jetbrains/kotlin/commonizer/core/AbstractFunctionOrPropertyCommonizer.kt
krzema12
312,049,057
false
null
/* * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.commonizer.core import org.jetbrains.kotlin.commonizer.cir.CirFunctionOrProperty import org.jetbrains.kotlin.commonizer.cir.CirName import org.jetbrains.kotlin.commonizer.cir.CirProperty import org.jetbrains.kotlin.commonizer.cir.CirType import org.jetbrains.kotlin.commonizer.core.TypeCommonizer.Options.Companion.default import org.jetbrains.kotlin.commonizer.mergedtree.CirKnownClassifiers import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.DELEGATION import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.SYNTHESIZED abstract class AbstractFunctionOrPropertyCommonizer<T : CirFunctionOrProperty>( classifiers: CirKnownClassifiers ) : AbstractStandardCommonizer<T, T?>() { protected lateinit var name: CirName protected val modality = ModalityCommonizer() protected val visibility = VisibilityCommonizer.lowering() protected val extensionReceiver = ExtensionReceiverCommonizer(classifiers) protected val returnType = ReturnTypeCommonizer(classifiers).asCommonizer() protected lateinit var kind: CallableMemberDescriptor.Kind protected val typeParameters = TypeParameterListCommonizer(classifiers) override fun initialize(first: T) { name = first.name kind = first.kind } override fun doCommonizeWith(next: T): Boolean = next.kind != DELEGATION // delegated members should not be commonized && (next.kind != SYNTHESIZED || next.containingClass?.isData != true) // synthesized members of data classes should not be commonized && kind == next.kind && modality.commonizeWith(next.modality) && visibility.commonizeWith(next) && extensionReceiver.commonizeWith(next.extensionReceiver) && returnType.commonizeWith(next) && typeParameters.commonizeWith(next.typeParameters) } private class ReturnTypeCommonizer( private val classifiers: CirKnownClassifiers, ) : NullableContextualSingleInvocationCommonizer<CirFunctionOrProperty, CirType> { override fun invoke(values: List<CirFunctionOrProperty>): CirType? { if (values.isEmpty()) return null val isTopLevel = values.all { it.containingClass == null } val isCovariant = values.none { it is CirProperty && it.isVar } return TypeCommonizer(classifiers, default.withCovariantNullabilityCommonizationEnabled(isTopLevel && isCovariant)) .asCommonizer().commonize(values.map { it.returnType }) } }
34
null
2
24
af0c7cfbacc9fa1cc9bec5c8e68847b3946dc33a
2,818
kotlin-python
Apache License 2.0
plugins/gradle/src/org/jetbrains/plugins/gradle/issue/quickfix/GradleWrapperSettingsOpenQuickFix.kt
SplotyCode
185,860,757
false
null
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.issue.quickfix import com.intellij.codeInsight.highlighting.HighlightManager import com.intellij.codeInsight.highlighting.HighlightUsagesHandler import com.intellij.find.FindManager import com.intellij.find.FindModel import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VfsUtil import org.jetbrains.annotations.ApiStatus import com.intellij.build.issue.BuildIssueQuickFix import org.jetbrains.plugins.gradle.util.GradleUtil import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletableFuture.completedFuture /** * @author Vladislav.Soroka */ @ApiStatus.Experimental class GradleWrapperSettingsOpenQuickFix(private val myProjectPath: String, private val mySearch: String?) : BuildIssueQuickFix { override val id: String = "open_gradle_wrapper_settings" override fun runQuickFix(project: Project): CompletableFuture<*> { showWrapperPropertiesFile(project, myProjectPath, mySearch) return completedFuture<Any>(null) } companion object { fun showWrapperPropertiesFile(project: Project, projectPath: String, search: String?) { val wrapperPropertiesFile = GradleUtil.findDefaultWrapperPropertiesFile(projectPath) ?: return ApplicationManager.getApplication().invokeLater { val file = VfsUtil.findFileByIoFile(wrapperPropertiesFile, false) ?: return@invokeLater val editor = FileEditorManager.getInstance(project).openTextEditor(OpenFileDescriptor(project, file), false) if (search == null || editor == null) return@invokeLater val attributes = EditorColorsManager.getInstance().globalScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES) val findModel = FindModel().apply { FindModel.initStringToFind(this, search) } val findResult = FindManager.getInstance(project).findString(editor.document.charsSequence, 0, findModel, file) val highlightManager = HighlightManager.getInstance(project) HighlightUsagesHandler.highlightRanges(highlightManager, editor, attributes, false, listOf(findResult)) } } } }
1
null
1
1
b70dd12f242187f7319da65e53232c47e429280b
2,536
intellij-community
Apache License 2.0
plugins/gradle/src/org/jetbrains/plugins/gradle/issue/quickfix/GradleWrapperSettingsOpenQuickFix.kt
SplotyCode
185,860,757
false
null
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.issue.quickfix import com.intellij.codeInsight.highlighting.HighlightManager import com.intellij.codeInsight.highlighting.HighlightUsagesHandler import com.intellij.find.FindManager import com.intellij.find.FindModel import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VfsUtil import org.jetbrains.annotations.ApiStatus import com.intellij.build.issue.BuildIssueQuickFix import org.jetbrains.plugins.gradle.util.GradleUtil import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletableFuture.completedFuture /** * @author Vladislav.Soroka */ @ApiStatus.Experimental class GradleWrapperSettingsOpenQuickFix(private val myProjectPath: String, private val mySearch: String?) : BuildIssueQuickFix { override val id: String = "open_gradle_wrapper_settings" override fun runQuickFix(project: Project): CompletableFuture<*> { showWrapperPropertiesFile(project, myProjectPath, mySearch) return completedFuture<Any>(null) } companion object { fun showWrapperPropertiesFile(project: Project, projectPath: String, search: String?) { val wrapperPropertiesFile = GradleUtil.findDefaultWrapperPropertiesFile(projectPath) ?: return ApplicationManager.getApplication().invokeLater { val file = VfsUtil.findFileByIoFile(wrapperPropertiesFile, false) ?: return@invokeLater val editor = FileEditorManager.getInstance(project).openTextEditor(OpenFileDescriptor(project, file), false) if (search == null || editor == null) return@invokeLater val attributes = EditorColorsManager.getInstance().globalScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES) val findModel = FindModel().apply { FindModel.initStringToFind(this, search) } val findResult = FindManager.getInstance(project).findString(editor.document.charsSequence, 0, findModel, file) val highlightManager = HighlightManager.getInstance(project) HighlightUsagesHandler.highlightRanges(highlightManager, editor, attributes, false, listOf(findResult)) } } } }
1
null
1
1
b70dd12f242187f7319da65e53232c47e429280b
2,536
intellij-community
Apache License 2.0
src/listnode/LeetCode23.kt
Alex-Linrk
180,918,573
false
{"Text": 1, "Ignore List": 1, "Kotlin": 49, "Java": 3}
package leecode import listnode.ListNode import listnode.createListNodeByArray /* 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 示例: 输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6*/ /** * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ class Solution23 { fun mergeKLists(lists: Array<ListNode?>): ListNode? { if (lists == null || lists.isEmpty()) return null if (lists.size == 1) return lists[0] if (lists.size == 2) return mergeTwoLists(lists[0], lists[1]) val mid = lists.size / 2 val list_start = lists.copyOfRange(0, mid) val list_end = lists.copyOfRange(mid, lists.size) return mergeTwoLists(mergeKLists(list_start), mergeKLists(list_end)) } fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? { if (l1 == null) return l2 if (l2 == null) return l1 var head: ListNode? = null if (l1.`val` <= l2.`val`) { head = l1 head.next = mergeTwoLists(l1.next, l2) } else { head = l2 head.next = mergeTwoLists(l1, l2.next) } return head } } fun main() { val l1 = createListNodeByArray(1, 4, 5) val l2 = createListNodeByArray(1, 3, 4) val l3 = createListNodeByArray(2, 6) val head = Solution23().mergeKLists(arrayOf(l1, l2, l3)) println(head) }
0
Kotlin
0
0
59f4ab02819b7782a6af19bc73307b93fdc5bf37
1,467
LeetCode
Apache License 2.0
packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/ProjectUtils.kt
ThTiny
675,881,814
true
{"Java Properties": 6, "Ignore List": 18, "Gradle Kotlin DSL": 6, "Markdown": 43, "YAML": 47, "Shell": 52, "JSON with Comments": 10, "EditorConfig": 1, "JavaScript": 1308, "Batchfile": 3, "Text": 3, "Ruby": 106, "Gemfile.lock": 1, "JSON": 37, "Jest Snapshot": 82, "Dotenv": 3, "Gradle": 9, "XML": 225, "CMake": 87, "C++": 883, "Java": 776, "Objective-C": 527, "Objective-C++": 237, "OpenStep Property List": 7, "HTML": 2, "Kotlin": 129, "INI": 6, "TSX": 9, "C": 20, "Graphviz (DOT)": 1, "Unix Assembly": 13, "Proguard": 5, "Motorola 68K Assembly": 3}
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.utils import com.facebook.react.model.ModelPackageJson import com.facebook.react.utils.KotlinStdlibCompatUtils.lowercaseCompat import com.facebook.react.utils.KotlinStdlibCompatUtils.toBooleanStrictOrNullCompat import org.gradle.api.Project import org.gradle.api.file.DirectoryProperty internal object ProjectUtils { internal val Project.isNewArchEnabled: Boolean get() = project.hasProperty("newArchEnabled") && project.property("newArchEnabled").toString().toBoolean() const val HERMES_FALLBACK = true internal val Project.isHermesEnabled: Boolean get() = if (project.hasProperty("hermesEnabled")) { project .property("hermesEnabled") .toString() .lowercaseCompat() .toBooleanStrictOrNullCompat() ?: true } else if (project.extensions.extraProperties.has("react")) { @Suppress("UNCHECKED_CAST") val reactMap = project.extensions.extraProperties.get("react") as? Map<String, Any?> when (val enableHermesKey = reactMap?.get("enableHermes")) { is Boolean -> enableHermesKey is String -> enableHermesKey.lowercaseCompat().toBooleanStrictOrNullCompat() ?: true else -> HERMES_FALLBACK } } else { HERMES_FALLBACK } internal fun Project.needsCodegenFromPackageJson(rootProperty: DirectoryProperty): Boolean { val parsedPackageJson = readPackageJsonFile(this, rootProperty) return needsCodegenFromPackageJson(parsedPackageJson) } internal fun Project.needsCodegenFromPackageJson(model: ModelPackageJson?): Boolean { return model?.codegenConfig != null } internal fun Project.getReactNativeArchitectures(): List<String> { val architectures = mutableListOf<String>() if (project.hasProperty("reactNativeArchitectures")) { val architecturesString = project.property("reactNativeArchitectures").toString() architectures.addAll(architecturesString.split(",").filter { it.isNotBlank() }) } return architectures } }
0
null
0
2
2bf59c764a31afe7cdaa3f985ecdb04d200d95d0
2,312
react-native
MIT License
app/src/main/java/com/arasvitkus/chicagobearsquizzler/MainActivity.kt
arasmv
188,471,204
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 2, "XML": 16, "Kotlin": 2}
package com.arasvitkus.chicagobearsquizzler import android.app.AlertDialog import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.Button import android.widget.ProgressBar import android.widget.TextView import android.widget.Toast class MainActivity : AppCompatActivity() { //Member variables for app var mTrueButton: Button? = null var mFalseButton: Button? = null var mQuestionTextView: TextView? = null var mScoreTextView: TextView? = null var mIndex = 0 var mQuestion = 0 var mScore = 0 var mProgressBar: ProgressBar? = null //Use an array to create the question bank private val mQuestionBank = arrayOf( TrueFalse(R.string.question_1, true), TrueFalse(R.string.question_2, true), TrueFalse(R.string.question_3, true), TrueFalse(R.string.question_4, true), TrueFalse(R.string.question_5, false), TrueFalse(R.string.question_6, false), TrueFalse(R.string.question_7, true), TrueFalse(R.string.question_8, true), TrueFalse(R.string.question_9, false), TrueFalse(R.string.question_10, false), TrueFalse(R.string.question_11, false), TrueFalse(R.string.question_12, false), TrueFalse(R.string.question_13, true), TrueFalse(R.string.question_14, false), TrueFalse(R.string.question_15, false), TrueFalse(R.string.question_16, true), TrueFalse(R.string.question_17, false), TrueFalse(R.string.question_18, false), TrueFalse(R.string.question_19, false), TrueFalse(R.string.question_20, true), TrueFalse(R.string.question_21, false), TrueFalse(R.string.question_22, false), TrueFalse(R.string.question_23, false), TrueFalse(R.string.question_24, true), TrueFalse(R.string.question_25, true), TrueFalse(R.string.question_26, false), TrueFalse(R.string.question_27, false), TrueFalse(R.string.question_28, true), TrueFalse(R.string.question_29, false), TrueFalse(R.string.question_30, true), TrueFalse(R.string.question_31, false), TrueFalse(R.string.question_32, false), TrueFalse(R.string.question_33, true), TrueFalse(R.string.question_34, false), TrueFalse(R.string.question_35, true), TrueFalse(R.string.question_36, false), TrueFalse(R.string.question_37, true), TrueFalse(R.string.question_38, true), TrueFalse(R.string.question_39, false), TrueFalse(R.string.question_40, false), TrueFalse(R.string.question_41, false), TrueFalse(R.string.question_42, true), TrueFalse(R.string.question_43, false), TrueFalse(R.string.question_44, false), TrueFalse(R.string.question_45, true), TrueFalse(R.string.question_46, false), TrueFalse(R.string.question_47, false), TrueFalse(R.string.question_48, false), TrueFalse(R.string.question_49, false), TrueFalse(R.string.question_50, false) ) //Progress bar constant, had to move here for the code to work properly, due to use of mQuestionBank. //final int PROGRESS_BAR_INCREMENT = (int) Math.ceil(100.0 / mQuestionBank.length); val NUMBER_OF_QUESTIONS = 50 //New way to update progress bar, override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if (savedInstanceState != null) { mScore = savedInstanceState.getInt("ScoreKey") mIndex = savedInstanceState.getInt("IndexKey") } else { mScore = 0 mIndex = 0 } mTrueButton = findViewById(R.id.true_button) mFalseButton = findViewById(R.id.false_button) mQuestionTextView = findViewById(R.id.question_text_view) mScoreTextView = findViewById(R.id.score) mProgressBar = findViewById(R.id.progress_bar) mProgressBar?.max = NUMBER_OF_QUESTIONS //Number of questions, maximum size, previously setMax in Java mQuestion = mQuestionBank[mIndex].questionID mQuestionTextView?.setText(mQuestion) mScoreTextView?.text = "Score " + mScore + "/" + mQuestionBank.size // Need to update strings.xml //True and False button listeners with methods to run on each click mTrueButton?.setOnClickListener(View.OnClickListener { checkAnswer(true) updateQuestion() }) mFalseButton?.setOnClickListener(View.OnClickListener { checkAnswer(false) updateQuestion() }) } //Method to update next question or show final message of score and close application private fun updateQuestion() { mIndex = (mIndex + 1) % mQuestionBank.size if (mIndex == 0) { val alert = AlertDialog.Builder(this) alert.setTitle("Game Over") alert.setCancelable(false) alert.setMessage("You scored $mScore points!") alert.setPositiveButton("Close Application") { dialog, which -> finish() } alert.show() } mQuestion = mQuestionBank[mIndex].questionID mQuestionTextView!!.setText(mQuestion) //mProgressBar.incrementProgressBy(PROGRESS_BAR_INCREMENT); mProgressBar!!.progress = mIndex + 1 //New way for progress bar to update by question mScoreTextView!!.text = "Score " + mScore + "/" + mQuestionBank.size } //Method that checks the answer and display a toast message of the result private fun checkAnswer(userSelection: Boolean) { val correctAnswer = mQuestionBank[mIndex].isAnswer if (userSelection == correctAnswer) { Toast.makeText(applicationContext, R.string.correct_toast, Toast.LENGTH_SHORT).show() mScore = mScore + 1 } else { Toast.makeText(applicationContext, R.string.incorrect_toast, Toast.LENGTH_SHORT).show() } } //Save instance to store the score and question index, invoked when the activity may be temporarily destroyed, save the instance state here public override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putInt("ScoreKey", mScore) outState.putInt("IndexKey", mIndex) } }
0
Kotlin
0
0
00644e4e49c6a6d0b3c412e1e8ba1669784b5471
6,594
chicago-bears-quizzler
Apache License 2.0
network/src/main/kotlin/ru/inforion/lab403/common/network/types.kt
inforion
175,944,783
false
null
package ru.inforion.lab403.common.network import java.net.InetAddress import java.net.Socket typealias OnStartCallback = (address: InetAddress) -> Unit typealias OnConnectCallback = Socket.() -> Boolean typealias OnDisconnectCallback = Socket.() -> Unit typealias OnReceiveCallback = Socket.(buffer: ByteArray) -> Boolean
1
Kotlin
1
1
e42ce78aa5d230025f197b044db4a698736d1630
323
kotlin-extensions
MIT License
implementation/src/main/kotlin/com/aoc/intcode/amplifier/Amplifier.kt
TomPlum
227,887,094
false
null
package com.aoc.intcode.amplifier interface Amplifier { fun inputSignal(inputSignal: Long) fun outputsTo(amplifier: Amplifier) fun loadAmplifierControllerSoftware(software: String) }
7
Kotlin
1
2
12d47cc9c50aeb9e20bcf110f53d097d8dc3762f
195
advent-of-code-2019
Apache License 2.0
app/src/main/java/com/aoshenfengyu/androidexercise/GithubRepository.kt
AoShenFengYu
251,556,378
false
null
package com.aoshenfengyu.androidexercise import android.util.Log import androidx.annotation.WorkerThread import com.aoshenfengyu.androidexercise.request.RequestManager class GithubRepository { companion object { const val TAG = "GithubRepository" const val LIMIT_OF_PAGE = 50 /** * Wait for search result * **/ const val STATUS_LOADING = 2 const val STATUS_LOADED_SUCCESSFULLY = 3 const val STATUS_ON_NO_RESULT = 4 val instance = GithubRepository() } @WorkerThread fun loadSGithubUsers(offset: Int): List<GithubUser>? { val retrofit = RequestManager.getInstance().retrofit val call = retrofit .create(GithubApi::class.java) .fetchGithubUsers(offset) try { val response = call.execute() if (response.isSuccessful) { val data = response.body() if (data != null) { return data } else { return ArrayList<GithubUser>() } } else { return null } } catch (e: Exception) { Log.e(TAG, e.toString()) } return null } }
1
null
1
1
a23dfc8dfff502dbc8d36dfa2715c762492ec9a3
1,266
GithubUser
Apache License 2.0
app/src/main/java/com/work/lazxy/writeaway/db/NoteDataHandler.kt
Lazxy
134,526,825
false
null
package com.work.lazxy.writeaway.db import android.content.ContentValues import android.database.Cursor import android.database.sqlite.SQLiteDatabase import com.work.lazxy.writeaway.WriteAway import com.work.lazxy.writeaway.entity.NoteEntity import java.util.* /** * Created by lenovo on 2017/2/1. */ class NoteDataHandler private constructor() { private val mDatabase: SQLiteDatabase /** * 存储笔记文件的记录进入数据库 * * @param title 日记的标题 * @param filePath 文件存储路径,在应用私有目录下。 * @param preview 日记内容预览,用于编辑前的目录显示。 * @param editTime 日记的最后编辑时间,以格林威治时间表示 */ fun saveData(title: String?, filePath: String, preview: String?, editTime: Long): Boolean { mDatabase.beginTransaction() try { //当该条数据已存在时,删除该条数据 mDatabase.delete(DataOpenHelper.NOTE_TABLE_NAME, "path=?", arrayOf(filePath)) //然后将数据添加到表的末端 val values = ContentValues() values.put("title", title) values.put("path", filePath) values.put("preview", preview) values.put("edit_time", editTime) mDatabase.insert(DataOpenHelper.NOTE_TABLE_NAME, null, values) mDatabase.setTransactionSuccessful() } finally { mDatabase.endTransaction() } return true } /** * 获取全部日记信息。 */ fun getAllData(): List<NoteEntity> { val notes: MutableList<NoteEntity> = ArrayList() val cursor: Cursor = mDatabase.query(DataOpenHelper.NOTE_TABLE_NAME, null, null, null, null, null, "edit_time") if (cursor.moveToLast()) { do { val title = cursor.getString(cursor.getColumnIndex("title")) val path = cursor.getString(cursor.getColumnIndex("path")) val preview = cursor.getString(cursor.getColumnIndex("preview")) val editTime = cursor.getLong(cursor.getColumnIndex("edit_time")) val note = NoteEntity(title, preview, path, editTime) notes.add(note) } while (cursor.moveToPrevious()) } cursor.close() return notes } /** * 从数据库中获取一定数量的数据记录 * @param limitIndex 数据查找的起始坐标,查找时从该坐标的下一个数据开始查找 * @param num 查询的总数据量 * @return 需要的Note记录 */ fun getData(limitIndex: Int, num: Int): List<NoteEntity> { var num = num val cursor: Cursor val notes: MutableList<NoteEntity> = ArrayList() //获得数据库的总条数 val count = getNotesCount() if (limitIndex >= count) { return notes } var start = count - limitIndex - num //反向取数据,根据待取数据量计算起始点 //如果数据余量满足num的值,则取出num条数据,否则将剩下的数据全部取出 if (start < 0) { num = num + start start = 0 } cursor = mDatabase.rawQuery("select * from " + DataOpenHelper.NOTE_TABLE_NAME + " order by " + "edit_time" + " limit " + num + " offset " + start + ";", null) if (cursor.moveToLast()) { do { val title = cursor.getString(cursor.getColumnIndex("title")) val path = cursor.getString(cursor.getColumnIndex("path")) val preview = cursor.getString(cursor.getColumnIndex("preview")) val editTime = cursor.getLong(cursor.getColumnIndex("edit_time")) val note = NoteEntity(title, preview, path, editTime) notes.add(note) } while (cursor.moveToPrevious()) } cursor.close() return notes } fun deleteData(path: String): Boolean { var result = 0 mDatabase.beginTransaction() try { result = mDatabase.delete(DataOpenHelper.NOTE_TABLE_NAME, "path=?", arrayOf(path)) mDatabase.setTransactionSuccessful() } finally { mDatabase.endTransaction() } return result != 0 } fun getNotesCount(): Int { val countMeasure = mDatabase.rawQuery("select count(*) from " + DataOpenHelper.NOTE_TABLE_NAME, null) countMeasure.moveToFirst() val count = countMeasure.getLong(0) countMeasure.close() return count.toInt() } init { val helper = DataOpenHelper(WriteAway.appContext, null, DataOpenHelper.DATABASE_VERSION) mDatabase = helper.writableDatabase } companion object { val instance: NoteDataHandler by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { NoteDataHandler() } } }
1
null
1
1
7796459aedd5ad4407a5ec3567ccae7f9f48930d
4,479
WriteAway
MIT License
tmp/arrays/youTrackTests/10818.kt
DaniilStepanov
228,623,440
false
null
// Original bug: KT-842 fun foo(s: String) { s.trim() //not marked unresolved, works correctly, but doesn't refer to implementation, because it is declared in library.jet s.toUpperCase() //it isn't declared in library.jet, so it has a reference to String.kt }
1
null
1
1
602285ec60b01eee473dcb0b08ce497b1c254983
270
bbfgradle
Apache License 2.0
junit5-gradle-kotlin/src/test/kotlin/com/arhohuttunen/junit5/kotlin/RegisterStaticExtensionTest.kt
arhohuttunen
111,000,081
false
{"Java": 75737, "Kotlin": 7641}
package com.arhohuttunen.junit5.kotlin import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ParameterResolver import org.junit.jupiter.api.extension.RegisterExtension import java.net.HttpURLConnection class RegisterStaticExtensionTest { companion object { /** * A better way to provide parameters for the test method would be to make the extension implement the * [ParameterResolver] interface. However, this example is here to demonstrate the usage of [JvmField]. */ @JvmField @RegisterExtension val jettyExtension: JettyExtension = JettyExtension() } @Test fun `use randomized port from extension`() { val url = jettyExtension.serverUri.resolve("/status").toURL() val connection = url.openConnection() as HttpURLConnection val response = connection.responseCode Assertions.assertEquals(200, response) } }
0
Java
15
24
a0d6783d76b8dfa8f475941304f173a2a580cc3d
981
junit5-examples
Apache License 2.0
core/src/main/kotlin/net/dummydigit/qbranch/UnsignedShort.kt
fuzhouch
99,569,266
false
null
// Licensed under the MIT license. See LICENSE file in the project root // for full license information. package net.dummydigit.qbranch /** * Represent an unsigned short value. * * @param value Given byte value. */ class UnsignedShort(val value : Int = 0) { init { if (value < 0 || value > 0xFFFF) { throw IllegalArgumentException("NegativeArgToUnsignedShort") } } }
0
Kotlin
1
2
e126f99a6c8db6c1f998d1ddb0dc6c85b2ecb896
408
qbranch
MIT License
year2017/src/main/kotlin/net/olegg/aoc/year2017/day15/Day15.kt
0legg
110,665,187
false
null
package net.olegg.aoc.year2017.day15 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.year2017.DayOf2017 /** * See [Year 2017, Day 15](https://adventofcode.com/2017/day/15) */ object Day15 : DayOf2017(15) { override fun first(): Any? { val generators = lines .map { it.substringAfterLast(" ").toLong() } val genA = generateSequence(generators[0]) { (it * 16807L) % Int.MAX_VALUE.toLong() } val genB = generateSequence(generators[1]) { (it * 48271L) % Int.MAX_VALUE.toLong() } return genA.zip(genB) .take(40_000_000) .count { (it.first and 65535) == (it.second and 65535) } } override fun second(): Any? { val generators = lines .map { it.substringAfterLast(" ").toLong() } val genA = generateSequence(generators[0]) { (it * 16807L) % Int.MAX_VALUE.toLong() } .filter { it % 4 == 0L } val genB = generateSequence(generators[1]) { (it * 48271L) % Int.MAX_VALUE.toLong() } .filter { it % 8 == 0L } return genA.zip(genB) .take(5_000_000) .count { (it.first and 65535) == (it.second and 65535) } } } fun main() = SomeDay.mainify(Day15)
0
null
1
8
3006775fc2d1da3b12303029b9f35d2793c912df
1,138
adventofcode
MIT License
app/src/main/java/com/cren90/blessed/long_read/ble/BTPermissions.kt
cren90
626,055,286
false
null
package com.cren90.blessed.long_read.ble import android.Manifest import android.os.Build import androidx.annotation.RequiresApi /** * Strategy interface for retrieving relavent BT permissions for the device */ sealed interface BTPermissions { val permissions: List<String> /** * Used for Pre-Android 5.1 since all permissions were install time */ object Version22AndLower : BTPermissions { override val permissions: List<String> = listOf() } /** * Used for Android 6 - 10 */ object Version23Through29 : BTPermissions { override val permissions: List<String> = listOf( Manifest.permission.BLUETOOTH, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION ) } /** * Used for Android 11 */ object Version30 : BTPermissions { override val permissions: List<String> = listOf( Manifest.permission.BLUETOOTH, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION ) } /** * Used for Android 12+ */ @RequiresApi(Build.VERSION_CODES.S) object Version31AndHigher : BTPermissions { override val permissions: List<String> = listOf( Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_ADVERTISE ) } } fun getBTPermissions(): BTPermissions { return when (Build.VERSION.SDK_INT) { in 0..Build.VERSION_CODES.LOLLIPOP_MR1 -> BTPermissions.Version22AndLower in Build.VERSION_CODES.M..Build.VERSION_CODES.Q -> BTPermissions.Version23Through29 Build.VERSION_CODES.R -> BTPermissions.Version30 else -> BTPermissions.Version31AndHigher } }
0
Kotlin
0
0
255e9927ed1dc1425d9765916c20115da609c66e
1,852
blessed-long-scan
MIT License
app/src/main/java/com/thryan/secondclass/AppDataStore.kt
thriic
649,615,369
false
{"JavaScript": 622040, "Kotlin": 161309}
package com.thryan.secondclass import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import com.thryan.secondclass.model.Constant import com.thryan.secondclass.model.Constant.KEY_ACCOUNT import com.thryan.secondclass.model.Constant.KEY_DYNAMIC import com.thryan.secondclass.model.Constant.KEY_LAST_TIME import com.thryan.secondclass.model.Constant.KEY_PASSWORD import com.thryan.secondclass.model.Constant.KEY_RESIGN import com.thryan.secondclass.model.Constant.KEY_SC_PASSWORD import com.thryan.secondclass.model.Constant.KEY_TWFID import com.thryan.secondclass.model.Constant.KEY_WEB_VIEW import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.android.components.ActivityComponent import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.runBlocking import javax.inject.Inject @Module @InstallIn(ActivityComponent::class) class AppDataStore @Inject constructor(private val dataStore: DataStore<Preferences>) { suspend fun putAccount(value: String) { putString(KEY_ACCOUNT, value) } suspend fun putPassword(value: String) { putString(KEY_PASSWORD, value) } suspend fun putScPassword(value: String) { putString(KEY_SC_PASSWORD, value) } suspend fun putTwfid(value: String) { putString(KEY_TWFID, value) } suspend fun putLastTime(value: String) { putString(KEY_LAST_TIME, value) } suspend fun putDynamic(value: Boolean) { dataStore.edit { it[KEY_DYNAMIC] = value } } suspend fun putWebView(value: Boolean) { dataStore.edit { it[KEY_WEB_VIEW] = value } } suspend fun putResign(value: Boolean) { dataStore.edit { it[KEY_RESIGN] = value } } fun getAccount(default: String): String = runBlocking { val string = getString(KEY_ACCOUNT) return@runBlocking string ?: default } fun getPassword(default: String): String = runBlocking { val string = getString(KEY_PASSWORD) return@runBlocking string ?: default } fun getScPassword(default: String): String = runBlocking { val string = getString(KEY_SC_PASSWORD) return@runBlocking string ?: default } fun getTwfid(default: String): String = runBlocking { val string = getString(KEY_TWFID) return@runBlocking string ?: default } fun getLastTime(default: String): String = runBlocking { val string = getString(KEY_LAST_TIME) return@runBlocking string ?: default } fun getDynamic(default: Boolean): Boolean = runBlocking { val bool = dataStore.data.map { it[KEY_DYNAMIC] }.first() return@runBlocking bool ?: default } fun getWebView(default: Boolean): Boolean = runBlocking { val bool = dataStore.data.map { it[KEY_WEB_VIEW] }.first() return@runBlocking bool ?: default } fun getResign(default: Boolean): Boolean = runBlocking { val bool = dataStore.data.map { it[KEY_RESIGN] }.first() return@runBlocking bool ?: default } suspend fun putKeyword(value: String) { putString(Constant.KEY_KEYWORD, value) } suspend fun putStatus(value: String) { putString(Constant.KEY_STATUS, value) } suspend fun putType(value: String) { putString(Constant.KEY_TYPE, value) } suspend fun putOnlySign(value: Boolean) { dataStore.edit { it[Constant.KEY_ONLY_SIGN] = value } } suspend fun putExcludeClasses(value: Boolean) { dataStore.edit { it[Constant.KEY_EXCLUDE_CLASSES] = value } } fun getKeyword(default: String): String = runBlocking { val string = getString(Constant.KEY_KEYWORD) return@runBlocking string ?: default } fun getStatus(default: String): String = runBlocking { val string = getString(Constant.KEY_STATUS) return@runBlocking string ?: default } fun getType(default: String): String = runBlocking { val string = getString(Constant.KEY_TYPE) return@runBlocking string ?: default } fun getOnlySign(default: Boolean): Boolean = runBlocking { val bool = dataStore.data.map { it[Constant.KEY_ONLY_SIGN] }.first() return@runBlocking bool ?: default } fun getExcludeClasses(default: Boolean): Boolean = runBlocking { val bool = dataStore.data.map { it[Constant.KEY_EXCLUDE_CLASSES] }.first() return@runBlocking bool ?: default } private suspend fun putString(key: Preferences.Key<String>, value: String) = dataStore.edit { it[key] = value } private fun getString(key: Preferences.Key<String>): String? = runBlocking { return@runBlocking dataStore.data.map { it[key] }.first() } }
0
JavaScript
7
36
2ba4a75a385ebd0bcfb2dd3858969c16beeae94f
5,058
SecondClass
MIT License
src/main/kotlin/org/jglrxavpok/hephaistos/nbt/NBTLong.kt
GhastMan01012
342,115,084
true
{"INI": 1, "Gradle": 2, "Shell": 1, "Markdown": 3, "Batchfile": 1, "Ignore List": 1, "Java": 27, "Kotlin": 36, "ANTLR": 1, "YAML": 2, "Java Properties": 1}
package org.jglrxavpok.hephaistos.nbt import java.io.DataInputStream import java.io.DataOutputStream import java.util.* class NBTLong(value: Long) : NBTNumber<Long>(value) { override val ID = NBTTypes.TAG_Long constructor(): this(0) // help Java compiler to find the correct type (boxed vs primitive types) fun getValue(): Long = value override fun readContents(source: DataInputStream) { value = source.readLong() } override fun writeContents(destination: DataOutputStream) { destination.writeLong(value) } override fun toSNBT(): String { return "${value}L" } override fun deepClone() = NBTLong(value) }
0
Java
0
0
6fa6235cbe71caceb33aeb9b7d57857cc2279103
681
Hephaistos
MIT License
src/main/kotlin/dev/shtanko/concurrency/coroutines/FlowAsynchronousStreams.kt
ashtanko
203,993,092
false
{"Kotlin": 7520849, "Shell": 1168, "Makefile": 1144}
/* * Copyright 2024 Oleksii Shtanko * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.concurrency.coroutines import kotlinx.coroutines.delay import kotlinx.coroutines.flow.flow import kotlinx.coroutines.runBlocking fun main() = runBlocking { // Example of a simple flow emitting values val flow = flow { for (i in 1..3) { delay(100) // Simulating asynchronous behavior emit(i) // Emitting values asynchronously } } // Collecting values emitted by the flow flow.collect { value -> println(value) // Prints: 1, 2, 3 } }
6
Kotlin
0
19
b8d05d3b10a8b16d156234775c655038cbbfac3c
1,128
Kotlin-Lab
Apache License 2.0
app/src/main/java/com/smrahmadi/materialnote/view/main/adapter/NoteListAdapter.kt
mrzahmadi
199,874,561
false
null
package com.smrahmadi.materialnote.view.main.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.smrahmadi.materialnote.R import com.smrahmadi.materialnote.data.model.Note import com.smrahmadi.materialnote.view.main.call.NoteListCallback import com.smrahmadi.materialnote.view.main.viewholder.NoteItemViewHolder class NoteListAdapter(private var callback: NoteListCallback) : RecyclerView.Adapter<NoteItemViewHolder>() { private var list: List<Note> = arrayListOf() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoteItemViewHolder { val inflater: LayoutInflater = LayoutInflater.from(parent.context) val itemView = inflater.inflate(R.layout.item_note, parent, false) return NoteItemViewHolder(itemView, callback) } override fun onBindViewHolder(holder: NoteItemViewHolder, position: Int) { holder.bind(list[position]) } override fun getItemCount(): Int { return list.size } fun setList(list: List<Note>) { this.list = list notifyDataSetChanged() } }
0
Kotlin
0
0
8aa05a6a4dc0ae8b8bc045310e655d780f76d196
1,151
MaterialNote
Apache License 2.0
app/src/main/java/com/example/mcard/domain/factories/viewModels/features/AdditionallyViewModelFactory.kt
Ilyandr
548,715,167
false
null
@file:Suppress("UNCHECKED_CAST") package com.example.mcard.domain.factories.viewModels.features import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.mcard.domain.viewModels.features.AdditionallyViewModel import com.example.mcard.repository.di.AppComponent import dagger.assisted.Assisted import dagger.assisted.AssistedInject internal class AdditionallyViewModelFactory @AssistedInject constructor( @Assisted(value = "component") val appComponent: AppComponent, ) : ViewModelProvider.NewInstanceFactory() { override fun <T : ViewModel> create(modelClass: Class<T>) = if (modelClass.isAssignableFrom( AdditionallyViewModel::class.java ) ) AdditionallyViewModel(this.appComponent) as T else throw IllegalArgumentException() }
0
Kotlin
0
1
a5287fc7b7488994f9cfd840cd8c92f11607ef8d
849
MCard-indicative
MIT License
app/src/main/kotlin/com/litekite/systemui/app/SystemUIApp.kt
LiteKite
235,597,886
false
null
/* * Copyright 2021 LiteKite Startup. All rights reserved. * * 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.litekite.systemui.app import android.app.Application import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.content.res.Configuration import android.os.Process import android.os.UserHandle import com.litekite.systemui.R import com.litekite.systemui.base.SystemUI import com.litekite.systemui.base.SystemUIServiceProvider import com.litekite.systemui.config.ConfigController import dagger.hilt.android.HiltAndroidApp import javax.inject.Inject /** * Application class. * * @author <NAME> * @version 1.0, 22/01/2020 * @since 1.0 */ @HiltAndroidApp class SystemUIApp : Application(), SystemUIServiceProvider { companion object { val TAG = SystemUIApp::class.java.simpleName } @Inject lateinit var configController: ConfigController private var bootCompleted: Boolean = false private var serviceStarted: Boolean = false /** * Hold a reference on the stuff we start. */ internal var services: ArrayList<SystemUI> = ArrayList() private val components: MutableMap<Class<*>, Any> = HashMap() override fun onCreate() { super.onCreate() SystemUI.printLog(TAG, "onCreate: SystemUIApp started successfully") // Set the application theme that is inherited by all services. Note that setting the // application theme in the manifest does only work for activities. Keep this in sync with // the theme set there. setTheme(R.style.Theme_SystemUI) registerBootReceiver() if (Process.myUserHandle() == UserHandle.SYSTEM) { startSystemUIServices() } else { startSystemUISecondaryUserServices() } } private fun registerBootReceiver() { val filter = IntentFilter(Intent.ACTION_BOOT_COMPLETED) filter.priority = IntentFilter.SYSTEM_HIGH_PRIORITY registerReceiver( object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { SystemUI.printLog(TAG, "onReceive: BOOT_COMPLETED received") bootCompleted = true if (serviceStarted) { services.forEach { it.onBootCompleted() } } } }, filter ) } /** * Makes sure that all the SystemUI services are running. If they are already running, this is a * no-op. This is needed to conditinally start all the services, as we only need to have it in * the main process. * <p>This method must only be called from the main thread.</p> */ @Synchronized internal fun startSystemUIServices() { if (serviceStarted) { SystemUI.printLog( TAG, "startServicesIfNeeded: already started. Skipping..." ) return } val serviceComponents = resources.getStringArray(R.array.config_systemUIServiceComponents) startServices(serviceComponents) } /** * Ensures that all the Secondary user SystemUI services are running. If they are already * running, this is a no-op. This is needed to conditinally start all the services, as we only * need to have it in the main process. * <p>This method must only be called from the main thread.</p> */ @Synchronized fun startSystemUISecondaryUserServices() { if (serviceStarted) { SystemUI.printLog( TAG, "startSystemUISecondaryUserServices: already started. Skipping..." ) return } val serviceComponents = resources.getStringArray(R.array.config_systemUIServiceComponentsPerUser) startServices(serviceComponents) } private fun startServices(serviceComponents: Array<String>) { serviceComponents.forEach { val systemUIService = Class.forName(it).newInstance() as SystemUI systemUIService.context = this systemUIService.components = components systemUIService.start() services.add(systemUIService) } serviceStarted = true // If boot complete event already been received, let SystemUI components aware of boot // complete event... if (bootCompleted) { services.forEach { it.onBootCompleted() } } } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) if (serviceStarted) { configController.configChanged(newConfig) } } @Suppress("UNCHECKED_CAST") override fun <T> getComponent(interfaceType: Class<T>): T = components[interfaceType] as T }
0
Kotlin
11
29
0a389139d1a32514413373047fb8c30d4df40f45
5,464
Android-SystemUI
Apache License 2.0
app/src/main/java/com/mathroda/dashcoin/presentation/coin_detail/viewmodel/CoinViewModel.kt
MathRoda
507,060,394
false
null
package com.mathroda.dashcoin.presentation.coin_detail.viewmodel import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.mathroda.dashcoin.core.util.Constants import com.mathroda.dashcoin.core.util.Resource import com.mathroda.dashcoin.domain.use_case.DashCoinUseCases import com.mathroda.dashcoin.presentation.coin_detail.state.ChartState import com.mathroda.dashcoin.presentation.coin_detail.state.CoinState import com.mathroda.dashcoin.presentation.watchlist_screen.state.MarketState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import javax.inject.Inject @HiltViewModel class CoinViewModel @Inject constructor( private val dashCoinUseCases: DashCoinUseCases, savedStateHandle: SavedStateHandle ): ViewModel() { private val _coinState = mutableStateOf(CoinState()) val coinState: State<CoinState> = _coinState private val _chartState = mutableStateOf(ChartState()) val chartState: State<ChartState> = _chartState private val _marketStatus = mutableStateOf(MarketState()) val marketStatus: State<MarketState> = _marketStatus init { savedStateHandle.get<String>(Constants.PARAM_COIN_ID)?.let { coinId -> getChart(coinId) getCoin(coinId) } getMarketStatus() } private fun getCoin(coinId: String) { dashCoinUseCases.getCoin(coinId).onEach { result -> when(result) { is Resource.Success ->{ _coinState.value = CoinState(coin = result.data) } is Resource.Error ->{ _coinState.value = CoinState( error = result.message?: "Unexpected Error") } is Resource.Loading ->{ _coinState.value = CoinState(isLoading = true) } } }.launchIn(viewModelScope) } private fun getChart(coinId: String) { dashCoinUseCases.getChart(coinId).onEach { result -> when(result) { is Resource.Success ->{ _chartState.value = ChartState(chart = result.data) } is Resource.Error ->{ _chartState.value = ChartState( error = result.message?: "Unexpected Error") } is Resource.Loading ->{ _chartState.value = ChartState( isLoading = true) } } }.launchIn(viewModelScope) } private fun getMarketStatus() { dashCoinUseCases.getCoin("bitcoin").onEach { result -> when(result) { is Resource.Success ->{ _marketStatus.value = MarketState(coin = result.data) } is Resource.Error ->{ _marketStatus.value = MarketState( error = result.message?: "Unexpected Error") } is Resource.Loading ->{ _marketStatus.value = MarketState(isLoading = true) } } }.launchIn(viewModelScope) } }
1
Kotlin
16
111
e32b7caa921303c754cc67320bd23d1d6aab18b0
3,362
DashCoin
Apache License 2.0
backend/src/main/kotlin/com/utopia/backend/posts/model/post/PostRepository.kt
PlebPool
432,468,273
false
{"Kotlin": 28881, "JavaScript": 8710, "CSS": 4011, "HTML": 2188}
package com.utopia.backend.posts.model.post import com.utopia.backend.posts.model.pathtopost.PathToPost import org.springframework.data.r2dbc.repository.Query import org.springframework.data.repository.query.Param import org.springframework.data.repository.reactive.ReactiveCrudRepository import org.springframework.stereotype.Repository import reactor.core.publisher.Flux import reactor.core.publisher.Mono /* This interface is initialized by the Spring Framework. */ /* This establishes a connection to the mysql server with info from backend/src/main/resources/application.properties */ @Repository interface PostRepository : ReactiveCrudRepository<Post, Long> { /* Spring creates the methods, all we have to do is declare the query and the method name/parameters/return type. */ // Trying to create Like-ip log. If we get a key duplicate (composite keys on ip, and post_id) then we // Simply update(toggle) the existing one. // Then we @Query("INSERT INTO who_liked_what VALUES(inet_aton(:ip), :post_id, true) ON DUPLICATE KEY UPDATE liked = NOT liked;" + "UPDATE post SET likes = if((post_id, (SELECT liked FROM who_liked_what WHERE (ip, post_id) = (inet_aton(:ip), :post_id))) = (:post_id, true), likes+1, likes-1) WHERE post_id = :post_id; " + "SELECT * FROM post WHERE post_id = :post_id;") fun toggleLike( @Param("post_id") post_id: Long, @Param("ip") ip: String): Mono<Post> @Query("SELECT liked FROM who_liked_what WHERE ip = inet_aton(:ip) AND post_id = :post_id;") fun checkIfLiked(@Param("ip") ip: String, @Param("post_id") post_id: Long): Mono<Boolean> @Query("SELECT EXISTS(SELECT * FROM who_liked_what WHERE (ip, post_id) = (inet_aton(:ip), :post_id));") fun checkIfLogged(@Param("ip") ip: String, @Param("post_id") post_id: Long): Mono<Boolean> @Query("SELECT relative_path FROM path_to_post ORDER BY post_id DESC LIMIT :amount;") fun getAmountOfPostPaths(@Param("amount") amount: Long): Flux<PathToPost> }
0
Kotlin
0
0
3f7541db7d16697565b5489c8c1bfe4052793ed1
2,038
wesweb-term-exam
MIT License
character-favorite/src/main/java/com/vkondrav/ram/character/favorite/usecase/FetchFavoriteCharactersUseCase.kt
vkondrav
481,052,423
false
null
package com.vkondrav.ram.character.favorite.usecase import com.vkondrav.ram.character.common.composable.CharacterViewItem import com.vkondrav.ram.character.common.domain.RamCharacter import com.vkondrav.ram.character.common.usecase.HandleCharacterFavoritesUseCase import com.vkondrav.ram.character.common.usecase.NavigateToCharacterDetailsUseCase import com.vkondrav.ram.common.ui.view.ComposableItem import com.vkondrav.ram.room.FavoriteCharacter import com.vkondrav.ram.room.FavoriteCharactersDao import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map class FetchFavoriteCharactersUseCase( private val favoriteCharactersDao: FavoriteCharactersDao, private val factory: RamCharacter.Factory, private val navigateToCharacterDetailsUseCase: NavigateToCharacterDetailsUseCase, private val handleCharacterFavoritesUseCase: HandleCharacterFavoritesUseCase, ) { operator fun invoke(): Result<Flow<List<ComposableItem>>> = runCatching { favoriteCharactersDao.getAll().map { favoriteCharacters -> favoriteCharacters.map { it.viewItem } } } private val FavoriteCharacter.viewItem get() = with(factory(this, flowOf(setOf(id)))) { CharacterViewItem( character = this, onClickAction = { navigateToCharacterDetailsUseCase( id, name, ) }, onFavoriteAction = { isFavorite -> handleCharacterFavoritesUseCase(this, isFavorite) }, ) } }
0
Kotlin
1
0
78c466563652800d8001a58504a533b764507461
1,662
rick_and_morty_compose
MIT License
src/main/kotlin/com/github/sparkmuse/entity/Utility.kt
sparkmuse
304,141,216
false
null
package com.github.sparkmuse.entity data class RetrieveDomain( val metadata: Map<String, String> = mapOf(), val results: Map<String, Map<String, String>> = mapOf() ) data class RetrieveField( val metadata: Map<String, String> = mapOf(), val results: Results = Results() ) { data class Results( val entries: List<String> = listOf(), val lemmas: List<String> = listOf(), val sentences: List<String> = listOf(), val thesaurus: List<String> = listOf(), val translations: List<String> = listOf() ) } data class RetrieveFilter( val metadata: Map<String, String> = mapOf(), val results: Results = Results() ) { data class Results( val entries: List<String> = listOf(), val lemmas: List<String> = listOf(), val sentences: List<String> = listOf(), val thesaurus: List<String> = listOf(), val translations: List<String> = listOf() ) } data class RetrieveGrammaticalFeature( val metadata: Map<String, String> = mapOf(), val results: Map<String, Map<String, Map<String, String>>> = mapOf() ) data class RetrieveLanguage( val metadata: Map<String, String> = mapOf(), val results: List<Result> = listOf() ) { data class Result( val source: String = "", val sourceLanguage: Map<String, String> = mapOf(), val targetLanguage: Map<String, String> = mapOf(), val type: String = "", val region: String = "" ) } data class RetrieveLexicalCategory( val metadata: Map<String, String> = mapOf(), val results: Map<String, Map<String, String>> = mapOf() ) data class RetrieveRegister( val metadata: Map<String, String> = mapOf(), val results: Map<String, Map<String, String>> = mapOf() )
0
Kotlin
0
1
94bae310bf45c4da59f2f54bc4af103080fc8c09
1,770
kotlin-oxford-dictionaries
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/AverageOfLevelsInBinaryTree.kt
ashtanko
203,993,092
false
{"Kotlin": 7493809, "Shell": 1168, "Makefile": 1144}
/* * Copyright 2020 Oleksii Shtanko * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.annotations.BFS import dev.shtanko.algorithms.annotations.DFS import dev.shtanko.algorithms.annotations.level.Easy import java.util.LinkedList import java.util.Queue /** * 637. Average of Levels in Binary Tree * @see <a href="https://leetcode.com/problems/average-of-levels-in-binary-tree/">Source</a> */ @Easy("https://leetcode.com/problems/average-of-levels-in-binary-tree") fun interface AverageOfLevelsInBinaryTreeStrategy { operator fun invoke(root: TreeNode?): DoubleArray } // Using Depth First Search @DFS class AverageOfLevelsInBinaryTreeDFS : AverageOfLevelsInBinaryTreeStrategy { override operator fun invoke(root: TreeNode?): DoubleArray { val count: MutableList<Int> = ArrayList() val res: MutableList<Double> = ArrayList() average(root, 0, res, count) for (i in res.indices) { res[i] = res[i] / count[i] } return res.toDoubleArray() } fun average(tree: TreeNode?, index: Int, sum: MutableList<Double>, count: MutableList<Int>) { if (tree == null) return if (index < sum.size) { sum[index] = sum[index] + tree.value count[index] = count[index] + 1 } else { sum.add(1.0 * tree.value) count.add(1) } average(tree.left, index + 1, sum, count) average(tree.right, index + 1, sum, count) } } // Using Breadth First Search @BFS class AverageOfLevelsInBinaryTreeBFS : AverageOfLevelsInBinaryTreeStrategy { override operator fun invoke(root: TreeNode?): DoubleArray { val res: MutableList<Double> = ArrayList() var queue: Queue<TreeNode?> = LinkedList() queue.add(root) while (queue.isNotEmpty()) { var sum: Long = 0 var count: Long = 0 val temp: Queue<TreeNode?> = LinkedList() while (queue.isNotEmpty()) { val node: TreeNode? = queue.remove() if (node != null) { sum += node.value count++ if (node.left != null) temp.add(node.left) if (node.right != null) temp.add(node.right) } } queue = temp res.add(sum * 1.0 / count) } return res.toDoubleArray() } }
6
Kotlin
0
19
3b06c91cce03eae3aa0e282d426257c9572ee429
2,984
kotlab
Apache License 2.0
app/src/main/java/com/cvillaseca/spotifykt/app/base/data/store/cache/Cache.kt
godiLabs
197,490,008
true
{"Kotlin": 124402, "Java": 1684}
package com.cvillaseca.spotifykt.app.base.data.store.cache import com.cvillaseca.spotifykt.app.base.data.store.EntityStore interface Cache: EntityStore { }
0
Kotlin
0
0
38c8fbba666c04f28147a244f26af9f1ed2eead9
157
SpotifyKt
Apache License 2.0
core/presentation/src/main/java/es/marcrdz/presentation/domain/Domain.kt
marcRDZ
556,833,664
false
null
package es.marcrdz.presentation.domain data class CharactersVO( val copyright: String, val content: List<CharacterVO> ) data class CharacterVO( val name: String, val description: String, val thumbnail: String )
0
Kotlin
0
0
d85a758d9798b33affc3a70be14f246283017361
232
MarvelArchives
Apache License 2.0
pacific-architecture/guava-jvm/src/main/java/com/pacific/guava/jvm/domain/Source.kt
thepacific
53,495,623
false
null
package com.pacific.guava.jvm.domain sealed class Source<out T> { data class Success<T>(val data: T) : Source<T>() data class Error<T>(val throwable: Throwable) : Source<T>() /** * Returns the available data or throws [NullPointerException] if there is no data. */ fun requireData(): T { return when (this) { is Success -> data is Error -> throw throwable } } fun requireError(): Throwable { return when (this) { is Success -> throw IllegalStateException("no throwable for Success.Data") is Error -> throwable } } /** * If this [Source] is of type [Source.Error], throws the exception * Otherwise, does nothing. */ fun throwIfError() { if (this is Error) { throw throwable } } /** * If this [Source] is of type [Source.Error], returns the available error * from it. Otherwise, returns `null`. */ fun errorOrNull(): Throwable? = when (this) { is Error -> throwable else -> null } /** * If there is data available, returns it; otherwise returns null. */ fun dataOrNull(): T? = when (this) { is Success -> data else -> null } fun <R> swapType(): Source<R> = when (this) { is Error -> Error(throwable) is Success -> throw IllegalStateException("cannot swap type for Success.Data") } }
0
Kotlin
12
33
1543d1fab90ea33755a8373efaebae21b9caa7f7
1,467
architecture
Apache License 2.0
protocol/chat/src/main/kotlin/com/walletconnect/chat/engine/sync/use_case/requests/SetInviteKeyToChatInviteKeyStoreUseCase.kt
WalletConnect
435,951,419
false
null
package com.walletconnect.chat.engine.sync.use_case.requests import com.squareup.moshi.Moshi import com.walletconnect.android.internal.common.model.AccountId import com.walletconnect.android.sync.client.Sync import com.walletconnect.android.sync.client.SyncInterface import com.walletconnect.android.sync.common.model.Store import com.walletconnect.chat.engine.sync.ChatSyncStores import com.walletconnect.chat.engine.sync.model.SyncedInviteKeys import com.walletconnect.chat.engine.sync.model.toSync import com.walletconnect.foundation.common.model.PrivateKey import com.walletconnect.foundation.common.model.PublicKey import com.walletconnect.foundation.util.Logger internal class SetInviteKeyToChatInviteKeyStoreUseCase( private val logger: Logger, private val syncClient: SyncInterface, _moshi: Moshi.Builder, ) { private val moshi = _moshi.build() operator fun invoke(account: AccountId, invitePublicKey: PublicKey, invitePrivateKey: PrivateKey, onSuccess: (Boolean) -> Unit, onError: (Throwable) -> Unit) { val syncedInviteKeys = (invitePublicKey to invitePrivateKey).toSync(account) val payload = moshi.adapter(SyncedInviteKeys::class.java).toJson(syncedInviteKeys) syncClient.set( Sync.Params.Set(account, Store(ChatSyncStores.CHAT_INVITE_KEYS.value), account.value, payload), onSuccess = { didUpdate -> onSuccess(didUpdate) }, onError = { error -> onError(error.throwable).also { logger.error(error.throwable) } } ) } }
147
Kotlin
59
157
e34c0e716ca68021602463773403d8d7fd558b34
1,526
WalletConnectKotlinV2
Apache License 2.0
data_binding_app/src/main/java/com/booknara/android/apps/patterns/databinding/data/WeatherViewModel.kt
booknara
164,749,143
false
null
package com.booknara.android.apps.patterns.databinding.data import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class WeatherViewModel : ViewModel() { // This data is hard-coded but you can imagine it comes from a weather service somewhere private val _currentTemp = MutableLiveData(30) private val _currentConditions = MutableLiveData("Cloudy") private val _currentWindChill = MutableLiveData(2) // create public properties that we can bind to val currentTemp: MutableLiveData<Int> = _currentTemp val currentConditions: LiveData<String> = _currentConditions val currentWindChill: LiveData<Int> = _currentWindChill // implement methods to change the temperature fun onIncreaseTemp() { _currentTemp.value = _currentTemp.value?.plus(1) } fun onDecreaseTemp() { _currentTemp.value = _currentTemp.value?.minus(1) } }
1
null
1
1
86c1cb7ee80cef093b181b88203c9fecf7336a1c
914
android-implementation-patterns
The Unlicense
src/main/kotlin/net/codinux/jackson/InstantIso8601Serializer.kt
codinux-gmbh
843,504,397
false
{"Kotlin": 12358}
package net.codinux.jackson import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.databind.JsonSerializer import com.fasterxml.jackson.databind.SerializerProvider import kotlinx.datetime.Instant class InstantIso8601Serializer: JsonSerializer<Instant>() { override fun serialize(value: Instant, generator: JsonGenerator, serializers: SerializerProvider) { generator.writeString(value.toString()) } }
0
Kotlin
0
0
465d4e3433c5b8e745a21441ecdba0bae3998319
441
KotlinxDateTimeJacksonModule
Apache License 2.0
classic/src/main/kotlin/io/kanro/compose/jetbrains/control/DropdownMenu.kt
ButterCam
414,869,239
false
{"Kotlin": 411098}
package io.kanro.compose.jetbrains.control import androidx.compose.foundation.Indication import androidx.compose.foundation.IndicationInstance import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.hoverable import androidx.compose.foundation.interaction.InteractionSource import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsHoveredAsState import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.width import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.drawscope.ContentDrawScope import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.key import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntRect import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Popup import androidx.compose.ui.window.PopupPositionProvider import io.kanro.compose.jetbrains.JBTheme import io.kanro.compose.jetbrains.color.LocalPanelColors @OptIn(ExperimentalComposeUiApi::class) @Composable fun DropdownMenu( expanded: Boolean, onDismissRequest: () -> Unit, focusable: Boolean = true, modifier: Modifier = Modifier, offset: DpOffset = DpOffset(0.dp, 0.dp), content: @Composable ColumnScope.() -> Unit, ) { if (expanded) { val density = LocalDensity.current val popupPositionProvider = DropdownMenuPositionProvider( offset, density ) Popup( focusable = focusable, onDismissRequest = onDismissRequest, popupPositionProvider = popupPositionProvider, onKeyEvent = { if (it.key == Key.Escape) { onDismissRequest() true } else { false } }, ) { val panelColor = LocalPanelColors.current Column(modifier.background(panelColor.bgContent).border(1.dp, panelColor.border).width(IntrinsicSize.Max)) { content() } } } } @Composable fun DropdownMenuItem( modifier: Modifier = Modifier, onClick: () -> Unit, enabled: Boolean = true, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable () -> Unit, ) { Box( modifier .clickable( interactionSource = interactionSource, indication = DropdownMenuItemHoverIndication, enabled = enabled, onClick = onClick ) .fillMaxWidth() .hoverable(interactionSource, enabled), contentAlignment = Alignment.CenterStart ) { val isHovered = interactionSource.collectIsHoveredAsState() SelectionScope(isHovered.value) { content() } } } object DropdownMenuItemHoverIndication : Indication { private class HoverIndicationInstance( private val isHover: State<Boolean>, private val hoverColor: Color, ) : IndicationInstance { override fun ContentDrawScope.drawIndication() { when { isHover.value -> { drawRect(hoverColor, size = size) } } drawContent() } } @Composable override fun rememberUpdatedInstance(interactionSource: InteractionSource): IndicationInstance { val isHover = interactionSource.collectIsHoveredAsState() val hoverColor = JBTheme.selectionColors.active return remember(JBTheme.selectionColors, interactionSource) { HoverIndicationInstance( isHover, hoverColor, ) } } } data class DropdownMenuPositionProvider( val contentOffset: DpOffset, val density: Density, val onPositionCalculated: (IntRect, IntRect) -> Unit = { _, _ -> }, ) : PopupPositionProvider { override fun calculatePosition( anchorBounds: IntRect, windowSize: IntSize, layoutDirection: LayoutDirection, popupContentSize: IntSize, ): IntOffset { // The min margin above and below the menu, relative to the screen. val verticalMargin = with(density) { 0 } // The content offset specified using the dropdown offset parameter. val contentOffsetX = with(density) { contentOffset.x.roundToPx() } val contentOffsetY = with(density) { contentOffset.y.roundToPx() } // Compute horizontal position. val toRight = anchorBounds.left + contentOffsetX val toLeft = anchorBounds.right - contentOffsetX - popupContentSize.width val toDisplayRight = windowSize.width - popupContentSize.width val toDisplayLeft = 0 val x = if (layoutDirection == LayoutDirection.Ltr) { sequenceOf(toRight, toLeft, toDisplayRight) } else { sequenceOf(toLeft, toRight, toDisplayLeft) }.firstOrNull { it >= 0 && it + popupContentSize.width <= windowSize.width } ?: toLeft // Compute vertical position. val toBottom = maxOf(anchorBounds.bottom + contentOffsetY, verticalMargin) val toTop = anchorBounds.top - contentOffsetY - popupContentSize.height val toCenter = anchorBounds.top - popupContentSize.height / 2 val toDisplayBottom = windowSize.height - popupContentSize.height - verticalMargin var y = sequenceOf(toBottom, toTop, toCenter, toDisplayBottom).firstOrNull { it >= verticalMargin && it + popupContentSize.height <= windowSize.height - verticalMargin } ?: toTop // Desktop specific vertical position checking val aboveAnchor = anchorBounds.top + contentOffsetY val belowAnchor = windowSize.height - anchorBounds.bottom - contentOffsetY if (belowAnchor >= aboveAnchor) { y = anchorBounds.bottom + contentOffsetY } if (y + popupContentSize.height > windowSize.height) { y = windowSize.height - popupContentSize.height } if (y < 0) { y = 0 } onPositionCalculated( anchorBounds, IntRect(x, y, x + popupContentSize.width, y + popupContentSize.height) ) return IntOffset(x, y) } }
1
Kotlin
8
186
8f237fd0c144ee8cc425aff5430f48ae634e914e
7,170
compose-jetbrains-theme
MIT License
src/main/kotlin/org/spilth/dash/DashService.kt
spilth
75,685,008
false
null
package org.spilth.dash import org.apache.maven.model.Dependency import org.apache.maven.model.io.xpp3.MavenXpp3Reader import org.codehaus.plexus.util.xml.pull.XmlPullParserException import java.io.File import java.io.FileReader import java.io.IOException import java.lang.String.format class DashService(private val dashCommand: DashCommand) { fun installDocs() { val pomFilename = dashCommand.pomFile val pomFile = File(pomFilename) val mavenXpp3Reader = MavenXpp3Reader() try { val model = mavenXpp3Reader.read(FileReader(pomFile)) installDocsForDependencies(model.dependencies) } catch (e: IOException) { e.printStackTrace() } catch (e: XmlPullParserException) { println("Not a valid POM file.") } } private fun installDocsForDependencies(dependencies: List<Dependency>) { for (dependency in dependencies) { installDocsForDependency(dependency) } } private fun installDocsForDependency(dependency: Dependency) { val groupId = dependency.groupId val artifactId = dependency.artifactId val version = dependency.version println(format("Requesting docs for %s:%s:%s", groupId, artifactId, version)) val url = format( "dash-install://repo_name=Java Docsets&entry_name=%s:%s&version=%s", groupId, artifactId, version ) val command = arrayOf("open", url) try { val runtime = Runtime.getRuntime() runtime.exec(command) } catch (e: IOException) { e.printStackTrace() } try { Thread.sleep(2000) } catch (e: InterruptedException) { e.printStackTrace() } } }
4
Kotlin
0
7
fb6ecec34f69d930f3205a558130a17a17827c25
1,850
savant
MIT License
src/main/kotlin/com/frontleaves/fantasticeditor/exceptions/library/MailTemplateNotFoundException.kt
fantastic-editor
799,812,830
false
{"Kotlin": 185593, "Java": 71102, "HTML": 911}
/* * ******************************************************************************* * Copyright (C) 2024-NOW(至今) 妙笔智编 * Author: 锋楪技术团队 * * 本文件包含 妙笔智编「FantasticEditor」 的源代码,该项目的所有源代码均遵循MIT开源许可证协议。 * 本代码仅允许在十三届软件杯比赛授权比赛方可直接使用 * ******************************************************************************* * 免责声明: * 使用本软件的风险由用户自担。作者或版权持有人在法律允许的最大范围内, * 对因使用本软件内容而导致的任何直接或间接的损失不承担任何责任。 * ******************************************************************************* */ package com.frontleaves.fantasticeditor.exceptions.library /** * # 邮件模板未找到异常 * 用于定义邮件模板未找到异常; * * @since v1.0.0 * @see RuntimeException * @property message 异常信息 * @constructor 创建一个邮件模板未找到异常 * @author xiao_lfeng */ class MailTemplateNotFoundException(override val message: String) : RuntimeException(message)
7
Kotlin
1
3
2e2ad6e27986c03075bc274cec3c533b56fe07bd
802
FantasticEditorApi
MIT License
graph/graph-adapter-output-spring-data-neo4j-sdn6/src/main/kotlin/org/orkg/graph/adapter/output/neo4j/internal/Neo4jClassRepository.kt
TIBHannover
197,416,205
false
{"Kotlin": 6059023, "Cypher": 220506, "Python": 4881, "Shell": 2904, "Groovy": 1936, "HTML": 240, "Batchfile": 82}
package org.orkg.graph.adapter.output.neo4j.internal import java.util.* import org.orkg.common.ThingId import org.springframework.data.domain.Page import org.springframework.data.domain.Pageable import org.springframework.data.neo4j.repository.Neo4jRepository import org.springframework.data.neo4j.repository.query.Query private const val ids = "${'$'}ids" interface Neo4jClassRepository : Neo4jRepository<Neo4jClass, ThingId> { // Set operations are a bit tricky in Cypher. It only knows lists, and order matters there. APOC to the rescue! @Query("""MATCH (c:`Class`) WHERE c.id IN $ids RETURN apoc.coll.containsAll(collect(c.id), $ids) AS result""") fun existsAllById(ids: Iterable<ThingId>): Boolean @Deprecated("For removal") fun findAllByIdIn(ids: Iterable<ThingId>, pageable: Pageable): Page<Neo4jClass> fun findByUri(uri: String): Optional<Neo4jClass> @Query("""MATCH (c:Class) DETACH DELETE c""") override fun deleteAll() }
0
Kotlin
0
4
d43d0e51df579a91273618d6f34fadbbb9542c18
970
orkg-backend
MIT License
app/src/main/java/com/piardilabs/bmicalculator/ui/BottomNavigationBar.kt
fpiardi
653,576,231
false
{"Kotlin": 107625}
package com.piardilabs.bmicalculator.ui import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Create import androidx.compose.material.icons.rounded.Home import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.NavigationBar import androidx.compose.material3.NavigationBarItem import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.vectorResource import androidx.compose.ui.text.font.FontWeight import androidx.navigation.NavHostController import androidx.navigation.compose.currentBackStackEntryAsState import com.piardilabs.bmicalculator.BMICalculatorScreen import com.piardilabs.bmicalculator.R data class BottomNavItem( val name: String, val route: String, val icon: ImageVector, ) /** * Composable that displays the bottom bar with navigation controller */ @Composable fun BMICalculatorBottomBar( navController: NavHostController, modifier: Modifier = Modifier ) { val backStackEntry by navController.currentBackStackEntryAsState() NavigationBar( containerColor = MaterialTheme.colorScheme.primaryContainer, ) { val bottomNavItems = listOf( BottomNavItem( name = stringResource(R.string.bottom_nav_add), route = BMICalculatorScreen.ChooseWeight.name, icon = Icons.Rounded.Create, ), BottomNavItem( name = stringResource(R.string.bottom_nav_historical_list), route = BMICalculatorScreen.HistoricalList.name, icon = Icons.Rounded.Home, ), BottomNavItem( name = stringResource(R.string.bottom_nav_historical_graph), route = BMICalculatorScreen.HistoricalGraph.name, icon = ImageVector.vectorResource(R.drawable.baseline_stacked_bar_chart_24), ) ) bottomNavItems.forEach { item -> val selected = item.route == backStackEntry?.destination?.route NavigationBarItem( selected = selected, onClick = { handleBottomNavItemClicked(item, navController) }, label = { Text( text = item.name, fontWeight = FontWeight.SemiBold, ) }, icon = { Icon( imageVector = item.icon, contentDescription = "${item.name} Icon", ) } ) } } } private fun handleBottomNavItemClicked(item: BottomNavItem, navController: NavHostController) { if (item.route == BMICalculatorScreen.ChooseWeight.name) { navController.navigate(BMICalculatorScreen.ChooseGender.name) navController.navigate(BMICalculatorScreen.ChooseHeight.name) } navController.navigate(item.route) }
0
Kotlin
0
0
049be737756eaedf666e197c416815378674d10c
3,207
bmicalculator
Apache License 2.0
adaptive-ui/src/commonMain/kotlin/fun/adaptive/ui/namespace.kt
spxbhuhb
788,711,010
false
{"Kotlin": 2231374, "Java": 23999, "HTML": 7707, "JavaScript": 3880, "Shell": 687}
/* * Copyright © 2020-2024, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license. */ package `fun`.adaptive.ui internal const val aui = "aui"
28
Kotlin
0
3
c0fd95c9654bee332c20f8f9373f1dae9132cf6b
192
adaptive
Apache License 2.0
library/src/main/java/io/easyprefs/contract/provider/ReadPrefProvider.kt
kishandonga
277,233,141
false
null
package io.easyprefs.contract.provider import android.content.Context import io.easyprefs.contract.Read interface ReadPrefProvider { fun read(): Read fun read(fileName: String): Read fun read(context: Context): Read fun read(context: Context, fileName: String): Read }
2
Kotlin
3
10
1147c54ea6628f27678d15a206d8500a9caa3dd4
286
EasyPrefs
MIT License
app/src/main/java/pk/sufiishq/app/feature/gallery/model/Section.kt
sufiishq
427,931,739
false
{"Kotlin": 950135}
/* * Copyright 2022-2023 SufiIshq * * 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 pk.sufiishq.app.feature.gallery.model import androidx.annotation.DrawableRes data class Section( val title: String, @DrawableRes val leadingIcon: Int, val detail: String, val route: String, )
3
Kotlin
0
2
254eeb6c2b1cad21d2f971d8b49ba3327d446bb5
818
sufiishq-mobile
Apache License 2.0
src/main/kotlin/com/daymxn/dchat/datamodel/User.kt
daymxn
485,926,802
false
{"Kotlin": 118029}
/* * Copyright 2022 Daymon Littrell * * 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.daymxn.dchat.datamodel import com.daymxn.dchat.datamodel.UserTable.id import com.daymxn.dchat.datamodel.UserTable.isAdmin import com.daymxn.dchat.datamodel.UserTable.password import com.daymxn.dchat.datamodel.UserTable.primaryKey import com.daymxn.dchat.datamodel.UserTable.username import io.ktor.server.auth.* import kotlinx.serialization.Serializable import org.jetbrains.exposed.sql.Table /** * Database table schema for [User] * * @property id unique [Long] column index, automatically created and incremented for each entry * @property username unique **indexed* [String] column provided for each entry * @property password secret [String] column provided for each entry * @property isAdmin [Boolean] column that defaults to false * @property primaryKey primary key constraint pointing to the id property */ object UserTable : Table() { val id = long("id").autoIncrement() val username = varchar("username", length = 50).uniqueIndex() val password = varchar("password", length = 50) val isAdmin = bool("is_admin").default(false) override val primaryKey = PrimaryKey(id, name = "pk_user_id") } /** * An authenticated end-user for the application * * This differs from what the client may consume when fetching other users outside of * authentication. For such scenarios, take a look at [UserHead], * * @property id unique [Long] assigned to each [Chat] from the database * @property username unique [String] created by each end-user * @property password hashed [String] representing the secret chosen by the end-user * @property isAdmin [Boolean] that signifies if a [User] is and administrator of the application. * Utilized for higher privilege actions. */ @Serializable data class User( val id: Long, val username: String, val password: String, val isAdmin: Boolean = false, ) : Datamodel, Principal /** * [User] object retrieved from the database, with sensitive data removed * * Especially useful in scenarios where end-users need [User] information, but should not have * access to sensitive data stored for each entry. * * @property id unique [Long] assigned to each [Chat] from the database * @property username unique [String] created by each end-user * @property isAdmin [Boolean] that signifies if a [User] is and administrator of the application. * Utilized for higher privilege actions. */ @Serializable data class UserHead( val id: Long, val username: String, val isAdmin: Boolean, ) : Datamodel
0
Kotlin
1
7
a27a91840e7026be2cf18d1d061b20d2e88e28c3
3,085
dChat
Apache License 2.0
geocoder-googlemaps/src/main/java/com/prolificinteractive/geocoder/api/googlemaps/GoogleMaps.kt
prolificinteractive
131,605,855
false
{"Gradle": 7, "Markdown": 2, "INI": 1, "Shell": 1, "Ignore List": 6, "Batchfile": 1, "YAML": 1, "Java Properties": 1, "Proguard": 5, "XML": 13, "Kotlin": 19, "Java": 2}
package com.prolificinteractive.geocoder.api.googlemaps import android.net.Uri import com.prolificinteractive.geocoder.Downloader import com.prolificinteractive.geocoder.GeocodingApi import com.prolificinteractive.geocoder.RetriableException import com.prolificinteractive.geocoder.model.Address class GoogleMaps private constructor(private val mApiKey: String?) : GeocodingApi { override fun convert(addresses: List<*>): List<Address> { return addresses as List<Address> } override fun name() = API_NAME @Throws(Exception::class) override fun coordinateCall( downloader: Downloader, latitude: Double, longitude: Double, maxResults: Int): List<Address> { val uriBuilder = buildBaseRequestUri() .appendQueryParameter("latlng", latitude.toString() + "," + longitude) val data = downloader.request(uriBuilder.toString()) try { return Parser.parseJson(data, MAX_RESULTS, true) } catch (e: GoogleMapsException) { if (e.status == Status.OVER_QUERY_LIMIT) { // OVER_QUERY_LIMIT is is an error that is eligible for retrying. throw RetriableException(e.toString()) } else { throw e } } } override fun locationCallWithBounds( downloader: Downloader, locationName: String, maxResults: Int, lowerLeftLatitude: Double, lowerLeftLongitude: Double, upperRightLatitude: Double, upperRightLongitude: Double): List<*> { val uriBuilder = buildBaseRequestUri() .appendQueryParameter("address", locationName) .appendQueryParameter("bounds" , String.format( "%s,%s|%s,%s", lowerLeftLatitude, lowerLeftLongitude, upperRightLatitude, upperRightLongitude) ) val url = uriBuilder.toString() val data = downloader.request(url) try { return Parser.parseJson(data, MAX_RESULTS, true) } catch (e: GoogleMapsException) { if (e.status == Status.OVER_QUERY_LIMIT) { throw RetriableException(e.toString()) } else { throw e } } } @Throws(Exception::class) override fun locationCall( downloader: Downloader, locationName: String, maxResults: Int): List<Address> { val uriBuilder = buildBaseRequestUri() .appendQueryParameter("address", locationName) val url = uriBuilder.toString() val data = downloader.request(url) try { return Parser.parseJson(data, MAX_RESULTS, true) } catch (e: GoogleMapsException) { if (e.status == Status.OVER_QUERY_LIMIT) { throw RetriableException(e.toString()) } else { throw e } } } private fun buildBaseRequestUri(): Uri.Builder { val uriBuilder = Uri.parse(ENDPOINT_URL).buildUpon() if (mApiKey != null && !mApiKey.isEmpty()) { uriBuilder.appendQueryParameter("key", mApiKey) } return uriBuilder } companion object { private val API_NAME = "Google Maps Api" private val ENDPOINT_URL = "https://maps.googleapis.com/maps/api/geocode/json" private val MAX_RESULTS = -1 @JvmStatic fun create(): GoogleMaps { return GoogleMaps("") } @JvmStatic fun create(mApiKey: String): GoogleMaps { return GoogleMaps(mApiKey) } } }
4
Kotlin
1
6
f91ab60a9f2e2addf2f7de21ccd6c30e0e6c2c7f
3,294
geocoder
MIT License
src/main/kotlin/com/broeskamp/postident/dto/result/ident/IdentificationDocumentResult.kt
broestech
536,935,075
false
{"Kotlin": 99789}
package com.broeskamp.postident.dto.result.ident import com.thinkinglogic.builder.annotation.Builder @Builder data class IdentificationDocumentResult( val records: List<RecordResult>?, /** * Type of document */ val type: ResultValue, /** * Number of document */ val number: ResultValue?, /** * All given names as printed on the identification document */ val firstName: ResultValue, /** * Exact last name as printed on identification document; may include title like "Dr." */ val lastName: ResultValue, /** * Only if differing from last name * * Do not include prefixes like „geb.“ or „Geborene“ */ val birthName: ResultValue?, /** * Birth date of customer as ISO 8601 format */ val birthDate: ResultValue, /** * Place of birth. */ val birthPlace: ResultValue?, /** * Nationality according to ISO 3166 alpha 3 plus */ val nationality: ResultValue?, /** * Contains the postal address which is printed on the document. If the document has no address, this field will be empty. */ val address: AddressResult, /** * Date of issuance as ISO 8601 format. */ val dateIssued: ResultValue?, /** * Date of expiry as ISO 8601 format. */ val dateOfExpiry: ResultValue, /** * Authority issuing the document. */ val authority: ResultValue?, /** * Place of authority. Field in German passport only. */ val placeOfIssue: ResultValue?, /** * Country code as ISO-3166 ALPHA-3 plus RKS for Kosovo. */ val countryOfDocument: ResultValue, )
6
Kotlin
0
2
1258b9e1eb32f5b8afa3e201b1f5fd830ec66a4b
1,702
postident_sdk
MIT License
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/simspaceweaver/_BuildableLastArgumentExtensions.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 70198112}
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.simspaceweaver import kotlin.Unit import software.amazon.awscdk.services.simspaceweaver.CfnSimulation /** The location of the simulation schema in Amazon Simple Storage Service ( Amazon S3 ). */ public inline fun CfnSimulation.setSchemaS3Location( block: CfnSimulationS3LocationPropertyDsl.() -> Unit = {} ) { val builder = CfnSimulationS3LocationPropertyDsl() builder.apply(block) return setSchemaS3Location(builder.build()) } /** The location of the snapshot in Amazon Simple Storage Service ( Amazon S3 ). */ public inline fun CfnSimulation.setSnapshotS3Location( block: CfnSimulationS3LocationPropertyDsl.() -> Unit = {} ) { val builder = CfnSimulationS3LocationPropertyDsl() builder.apply(block) return setSnapshotS3Location(builder.build()) }
3
Kotlin
0
3
256ad92aebe2bcf9a4160089a02c76809dbbedba
1,046
awscdk-dsl-kotlin
Apache License 2.0
app/src/main/java/no/sintef/fiskinfo/util/DDMLocation.kt
SINTEF-SE
173,832,863
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Markdown": 2, "Proguard": 1, "Java": 3, "XML": 90, "Kotlin": 91, "HTML": 2, "SVG": 3, "CSS": 5, "JavaScript": 21}
/** * Copyright (C) 2020 SINTEF * * * 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 no.sintef.fiskinfo.util import android.location.Location import kotlin.math.abs import kotlin.math.floor data class DDMLocation(var latitudeSouth : Boolean = false, var latitudeDegrees : Int = 0, var latitudeDecimalMinutes : Double = 0.0, var longitudeWest : Boolean = false, var longitudeDegrees : Int = 0, var longitudeDecimalMinutes : Double = 0.0) { companion object { fun fromLocation(location: Location): DDMLocation { var ddm = DDMLocation() with(ddm) { latitudeSouth = location.latitude < 0 var absCoord = abs(location.latitude) latitudeDegrees = floor(absCoord).toInt() absCoord -= latitudeDegrees latitudeDecimalMinutes = absCoord * 60.0 longitudeWest = location.longitude < 0 absCoord = abs(location.longitude) longitudeDegrees = floor(absCoord).toInt() absCoord -= longitudeDegrees absCoord *= 60.0 longitudeDecimalMinutes = absCoord * 60.0 } return ddm; } } fun toLocation(): Location? { var loc = Location("") loc.latitude = latitudeDegrees + (latitudeDecimalMinutes/60.0) if (latitudeSouth) loc.latitude = -loc.latitude loc.longitude = longitudeDegrees + (longitudeDecimalMinutes/60.0) if (longitudeWest) loc.longitude = -loc.longitude return loc } }
1
null
1
1
6045b1551166ce87852434e670b45241e4c4b0d2
2,200
FiskInfo3
Apache License 2.0
src/main/kotlin/cz/nejakejtomas/bluemapbanners/markers/banners/BannerImage.kt
NejakejTomas
658,070,734
false
null
package cz.nejakejtomas.bluemapbanners.markers.banners import cz.nejakejtomas.bluemapbanners.markers.MarkerImage import cz.nejakejtomas.bluemapbanners.utils.MinecraftColor import cz.nejakejtomas.bluemapbanners.utils.asStream import cz.nejakejtomas.bluemapbanners.utils.scaled import java.awt.image.BufferedImage import java.io.InputStream import java.nio.file.Path import java.nio.file.Paths enum class BannerImage(private val color: MinecraftColor) : MarkerImage { White(MinecraftColor.White), Orange(MinecraftColor.Orange), Magenta(MinecraftColor.Magenta), LightBlue(MinecraftColor.LightBlue), Yellow(MinecraftColor.Yellow), Lime(MinecraftColor.Lime), Pink(MinecraftColor.Pink), Gray(MinecraftColor.Gray), LightGray(MinecraftColor.LightGray), Cyan(MinecraftColor.Cyan), Purple(MinecraftColor.Purple), Blue(MinecraftColor.Blue), Brown(MinecraftColor.Brown), Green(MinecraftColor.Green), Red(MinecraftColor.Red), Black(MinecraftColor.Black), ; override val location: Path get() = Paths.get("Banners").resolve("Far") override val anchorX get() = (sizeX / 2) * scaleFactor override val anchorY get() = sizeY * scaleFactor private val image: BufferedImage get() { val bufferedImage = BufferedImage(sizeX, sizeY, BufferedImage.TYPE_INT_ARGB) bufferedImage.paint(color) return bufferedImage.scaled(scaleFactor, scaleFactor) } override val stream: InputStream get() = image.asStream() override val fileName get() = "$name.png" companion object { private const val scaleFactor = 3 private const val sizeX = 6 private const val sizeY = 8 val values by lazy { listOf(*BannerImage.values()) } val byColor by lazy { values.map { it.color to it }.toMap() } } } private fun BufferedImage.paint(color: MinecraftColor) { val black = 0xFF000000u.toInt() val transparent = 0x00000000u.toInt() for (x in 0 until 6) setRGB(x, 0, black) for (y in 1 until 6) { setRGB(0, y, transparent) setRGB(1, y, black) setRGB(2, y, color.color) setRGB(3, y, color.color) setRGB(4, y, black) setRGB(0, y, transparent) } for (y in 6 until 8) { setRGB(0, y, transparent) setRGB(1, y, transparent) setRGB(2, y, black) setRGB(3, y, black) setRGB(4, y, transparent) setRGB(0, y, transparent) } }
0
Kotlin
0
0
b926e3022319187e5cb708814bef9ee396c4d50b
2,528
bluemap-banners
MIT License
app/src/main/java/com/example/news/NewsApp.kt
arsh-kum04
847,768,188
false
{"Kotlin": 22740}
package com.example.news import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class NewsApp:Application() { }
0
Kotlin
0
0
5a906e1d932b519cb717fe1af99b49efc656523f
147
NewsAPP
MIT License
kmqtt-common/src/commonMain/kotlin/mqtt/packets/mqttv4/MQTT4Connack.kt
davidepianca98
235,132,697
false
{"Kotlin": 524141, "Dockerfile": 3673}
package mqtt.packets.mqttv4 import mqtt.MQTTException import mqtt.packets.ConnectAcknowledgeFlags import mqtt.packets.MQTTControlPacketType import mqtt.packets.MQTTDeserializer import mqtt.packets.mqtt.MQTTConnack import mqtt.packets.mqttv5.ReasonCode import socket.streams.ByteArrayInputStream import socket.streams.ByteArrayOutputStream public class MQTT4Connack( connectAcknowledgeFlags: ConnectAcknowledgeFlags, public val connectReturnCode: ConnectReturnCode ) : MQTTConnack(connectAcknowledgeFlags), MQTT4Packet { public companion object : MQTTDeserializer { override fun fromByteArray(flags: Int, data: UByteArray): MQTT4Connack { checkFlags(flags) val inStream = ByteArrayInputStream(data) val connectAcknowledgeFlags = when (inStream.readByte()) { 0u -> ConnectAcknowledgeFlags(false) 1u -> ConnectAcknowledgeFlags(true) else -> throw MQTTException(ReasonCode.MALFORMED_PACKET) } val connectReturnCode = ConnectReturnCode.valueOf(inStream.readByte().toInt()) ?: throw MQTTException( ReasonCode.PROTOCOL_ERROR ) return MQTT4Connack( connectAcknowledgeFlags, connectReturnCode ) } } override fun toByteArray(): UByteArray { val outStream = ByteArrayOutputStream() val connectFlags = if (connectAcknowledgeFlags.sessionPresentFlag && connectReturnCode == ConnectReturnCode.CONNECTION_ACCEPTED) 1u else 0u outStream.write(connectFlags.toUByte()) outStream.write(connectReturnCode.value.toUByte()) return outStream.wrapWithFixedHeader(MQTTControlPacketType.CONNACK, 0) } }
2
Kotlin
8
92
eff347bc03c4093a974731d0974e5592bde5bb49
1,795
KMQTT
MIT License
src/main/kotlin/com/simon/kotlin/standard/LetFunction.kt
SimonRHW
159,170,398
false
{"Gradle": 2, "INI": 1, "Shell": 1, "Text": 3, "Ignore List": 1, "Batchfile": 1, "Markdown": 2, "Java Properties": 1, "Go": 2, "Go Checksums": 1, "Go Module": 1, "Java": 87, "Kotlin": 75, "CMake": 1, "C": 1, "JSON": 2}
package com.simon.kotlin.standard import com.simon.kotlin.bean.Users /** * let函数:返回值 = 最后一行 / return的表达式 */ fun main() { val user = Users() user.name = "simon" user.surname = "ren" user.email = "<EMAIL>" val result = user.let { println(it) println(it.name) println("${it.email}one") it.isEmail = true it.email = "<EMAIL>" println("${it.email}two") test() } println(result) } fun test(): Boolean { return true }
0
Java
1
0
2c71a0842207d4446b4cdb59d73229b150190bc5
508
BasicKnowledge
Apache License 2.0
kover-maven-plugin/src/functionalTest/kotlin/kotlinx/kover/maven/plugin/tests/functional/framework/CheckerContextImpl.kt
Kotlin
394,574,917
false
{"Kotlin": 730643, "Java": 23398}
/* * Copyright 2017-2024 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.kover.maven.plugin.tests.functional.framework import kotlinx.kover.maven.plugin.tests.functional.framework.BuildConstants.BUILD_DIRECTORY import org.w3c.dom.Element import java.io.File import javax.xml.parsers.DocumentBuilderFactory fun createContext(log: String, projectDirectory: File): CheckerContext { // logs: goal name -> (module id -> log) val goalsLog = mutableMapOf<String, MutableMap<String, String>>() var prevMessage = "" var content = "" var goalName = "" var isGoalOutput = false var moduleId: String? = null fun addLog(log: String) { val id = moduleId ?: throw IllegalStateException("Module id missed") goalsLog.computeIfAbsent(goalName) { mutableMapOf() }[id] = log } log.lineSequence().forEach { line -> val message = line.removePrefix("[INFO] ").removePrefix("[WARNING] ").removePrefix("[ERROR] ") when { /* ---------------------< org.example:merged-report >---------------------- */ message.matches("-*< .+:.+ >-*".toRegex()) -> { moduleId = message.substringAfterLast(":").substringBefore(" >") if (isGoalOutput) { addLog(content) } isGoalOutput = false } message.startsWith("------------------------------------------------------------------------") -> { if (isGoalOutput) { addLog(content) } isGoalOutput = false } /* --- kover:0.8.4-SNAPSHOT:report-xml (kover-xml) @ maven-test --- */ message.matches("-* .+:.+:.+ \\(.*\\) @ .+ -*".toRegex()) && prevMessage.isEmpty() -> { if (isGoalOutput) { // new goal name always starts with empty line content.removeSuffix("\n") addLog(content) } isGoalOutput = true goalName = message.substringAfter("- ").substringBeforeLast(" (") content = "" } else -> { content += (if (content.isNotEmpty()) "\n" else "") + message } } prevMessage = message } return CheckerContextImpl(log, goalsLog, projectDirectory) } fun parseXmlReport(file: File): XmlReportContent { return XmlReportContentImpl(file) } private class CheckerContextImpl( override val log: String, val goals: Map<String, Map<String, String>>, val projectDirectory: File ) : CheckerContext { override val isSuccessful: Boolean = log.contains("BUILD SUCCESS\n") override fun koverGoalLog(goalName: String, moduleId: String?): String { val filtered = goals.filterKeys { string -> string.startsWith("kover:") && string.endsWith(":$goalName") }.map { it.value } if (filtered.isEmpty()) throw MavenAssertionException("The '$goalName' goal was not found among the completed ones") if (filtered.size > 1) throw IllegalStateException("Several goals were found that were completed with the name '$goalName'") val logsByModules = filtered.first() return if (moduleId == null) { if (logsByModules.size == 1) { logsByModules.values.first() } else { throw IllegalStateException("Goal $goalName was executed in several projects: ${logsByModules.keys}") } } else { val logs = logsByModules.filterKeys { id -> moduleId == id } if (logs.size != 1) throw IllegalStateException("Goal $goalName was not executed in module $moduleId") logs.values.first() } } override fun findFile(relativePath: String, module: String?): File { val moduleDir = if (module == null) projectDirectory else projectDirectory.resolve(module) return moduleDir.resolve(BUILD_DIRECTORY).resolve(relativePath) } } private class XmlReportContentImpl(file: File) : XmlReportContent { private val document = DocumentBuilderFactory.newInstance() // This option disables checking the dtd file for JaCoCo XML file .also { it.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false) } .newDocumentBuilder().parse(file) override fun classCounter(className: String, type: CounterType): Counter { val correctedClassName = className.replace('.', '/') val packageName = correctedClassName.substringBeforeLast('/') val reportElement = ((document.getElementsByTagName("report").item(0)) as Element) val values = reportElement .filter("package", "name", packageName) ?.filter("class", "name", correctedClassName) ?.filter("counter", "type", type.name) ?.let { CounterValues( it.getAttribute("missed").toInt(), it.getAttribute("covered").toInt() ) } return Counter(className, type, values) } override fun methodCounter(className: String, methodName: String, type: CounterType): Counter { val correctedClassName = className.replace('.', '/') val packageName = correctedClassName.substringBeforeLast('/') val reportElement = ((document.getElementsByTagName("report").item(0)) as Element) val values = reportElement .filter("package", "name", packageName) ?.filter("class", "name", correctedClassName) ?.filter("method", "name", methodName) ?.filter("counter", "type", type.name) ?.let { CounterValues( it.getAttribute("missed").toInt(), it.getAttribute("covered").toInt() ) } return Counter("$className#$methodName", type, values) } } private fun Element.filter(tag: String, attributeName: String, attributeValue: String): Element? { val elements = getElementsByTagName(tag) for (i in 0 until elements.length) { val element = elements.item(i) as Element if (element.parentNode == this) { if (element.getAttribute(attributeName) == attributeValue) { return element } } } return null }
60
Kotlin
53
1,346
1acc0548ad33b0aeeccd4e95078490997abf2d54
6,488
kotlinx-kover
Apache License 2.0
app/src/main/java/com/example/whisper/ui/contacts/ContactsFragment.kt
alexandermalinov
537,907,360
false
{"Kotlin": 123950}
package com.example.whisper.ui.contacts import android.os.Bundle import android.view.View import androidx.fragment.app.viewModels import androidx.recyclerview.widget.LinearLayoutManager import com.example.whisper.R import com.example.whisper.databinding.FragmentContactsBinding import com.example.whisper.ui.base.BaseFragment import com.example.whisper.utils.common.collectState import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class ContactsFragment : BaseFragment<FragmentContactsBinding>() { /* -------------------------------------------------------------------------------------------- * Properties ---------------------------------------------------------------------------------------------*/ private val viewModel: ContactsViewModel by viewModels() /* -------------------------------------------------------------------------------------------- * Override ---------------------------------------------------------------------------------------------*/ override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initUiData() collectUiStates() observeNavigation(viewModel.navigationLiveData) } override fun getLayoutId(): Int = R.layout.fragment_contacts /* -------------------------------------------------------------------------------------------- * Private ---------------------------------------------------------------------------------------------*/ private fun initUiData() { dataBinding.presenter = viewModel initConnectionsRecyclerView() } private fun initConnectionsRecyclerView() { dataBinding.recyclerContacts.apply { adapter = ContactsAdapter(viewModel) layoutManager = LinearLayoutManager(context) } } private fun collectUiStates() { collectState { viewModel.contacts.collect { contacts -> (dataBinding.recyclerContacts.adapter as ContactsAdapter).submitList(contacts) } } } }
0
Kotlin
0
0
d020aa0f2d977d2ac05840ca658072b0f722cd44
2,100
whisper
MIT License
app/src/main/java/com/madonnaapps/wodnotify/di/modules/NotificationModule.kt
tjmadonna
217,728,308
false
null
package com.madonnaapps.wodnotify.di.modules import com.madonnaapps.wodnotify.notification.WodNotificationManager import com.madonnaapps.wodnotify.notification.WodNotificationManagerImpl import dagger.Binds import dagger.Module @Module interface NotificationModule { @Binds fun bindWodNotificationManager( wodNotificationManager: WodNotificationManagerImpl ): WodNotificationManager }
0
Kotlin
0
0
4163c1176c02415e8d8f38c6ee15ae5f812df97a
408
wod-notify
Apache License 2.0
app/src/main/java/com/example/tbilisi_parking_final_exm/data/model/parking/finish_parking/ParkingIsFinishedDto.kt
Lasha-Ilashvili
749,926,592
false
{"Kotlin": 373909}
package com.example.tbilisi_parking_final_exm.data.model.parking.finish_parking import com.example.tbilisi_parking_final_exm.domain.model.parking.finish_parking.GetParkingIsFinished data class ParkingIsFinishedDto ( val id: Int, val carId: Int, val stationExternalId: String, val startDate: String, val endDate:String, val status: String, val totalCost: Double, val parkingTypeResponse: GetParkingIsFinished.ParkingTypeResponse ) { data class ParkingTypeResponse( val id: Int, val name: String, val pricePerHour: Int ) }
0
Kotlin
1
0
20653c5077a4fa61e2c9616ddd986a82faf040dd
586
Tbilisi_Parking_FINAL_EXM
Apache License 2.0
features/home/src/main/java/com/lefarmico/home/HomeEvent.kt
LeFarmico
382,809,671
false
null
package com.lefarmico.home import com.lefarmico.core.base.BaseState import java.lang.Exception sealed class HomeEvent : BaseState.Event { object ShowEditState : HomeEvent() object HideEditState : HomeEvent() object SelectAllWorkouts : HomeEvent() object DeselectAllWorkouts : HomeEvent() object DeleteSelectedWorkouts : HomeEvent() data class ExceptionResult(val exception: Exception) : HomeEvent() }
0
Kotlin
0
3
e1fa8a81aefcb6131b704f787b1fa9b5518a6735
429
GymSupporter
Apache License 2.0
app/src/main/java/com/example/android/marsphotos/overview/OverviewViewModel.kt
matheus-miranda
368,599,747
false
null
package com.example.android.marsphotos.overview import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.android.marsphotos.network.MarsApi import com.example.android.marsphotos.network.MarsPhoto import kotlinx.coroutines.launch /** * Status of the web request. */ enum class MarsApiStatus { LOADING, ERROR, DONE } /** * The [ViewModel] that is attached to the [OverviewFragment]. */ class OverviewViewModel : ViewModel() { // The internal MutableLiveData that stores the status of the most recent request private val _status = MutableLiveData<MarsApiStatus>() // The external immutable LiveData for the request status val status: LiveData<MarsApiStatus> = _status private val _photos = MutableLiveData<List<MarsPhoto>>() val photos: LiveData<List<MarsPhoto>> = _photos /** * Call getMarsPhotos() on init so we can display status immediately. */ init { getMarsPhotos() } /** * Gets Mars photos information from the Mars API Retrofit service and updates the * [MarsPhoto] [List] [LiveData]. */ private fun getMarsPhotos() { // ViewModelScope is the built-in coroutine scope defined for each ViewModel in the app. // Any coroutine launched in this scope is automatically canceled if the ViewModel // is cleared. viewModelScope.launch { _status.value = MarsApiStatus.LOADING try { // Singleton object MarsApi _photos.value = MarsApi.retrofitService.getPhotos() _status.value = MarsApiStatus.DONE } catch (e: Exception) { _status.value = MarsApiStatus.ERROR _photos.value = listOf() // Clear the recycle view. } } } }
0
Kotlin
0
0
a8cb1d54b71ab7a477d3a3197e58c935bfdc2e8f
1,894
Mars-Photos
Apache License 2.0