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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/com/github/codingchili/process/impl/JetFactory.kt | codingchili | 217,731,038 | false | null | package com.github.codingchili.process.impl
import com.hazelcast.config.Config
import com.hazelcast.core.HazelcastInstance
import com.hazelcast.jet.Jet
import com.hazelcast.jet.JetInstance
import com.hazelcast.jet.config.JetConfig
import java.util.*
/**
* @author Robin Duda
*
* Factory for creating instances of the Jet distributed stream processing engine.
*/
object JetFactory {
@Transient
private var jet: JetInstance? = null
@Transient
private val id = UUID.randomUUID().toString().substring(0,7)
/**
* @return the Jet instance if one exists, otherwise one is created.
*/
fun jetInstance(): JetInstance {
if (jet == null) {
synchronized(javaClass) {
if (jet == null) {
jet = Jet.newJetInstance(JetConfig().setHazelcastConfig(Config().setInstanceName("jet_instance_$id")))
}
}
}
return jet!!
}
/**
* @return the hazelcast instance associated with the current Jet instance.
*/
fun hazelInstance(): HazelcastInstance {
return jetInstance().hazelcastInstance
}
}
| 0 | Kotlin | 0 | 0 | e81dabaabc3f74f960c361cb86e43591fac4668f | 1,140 | jet-pluginifer | MIT License |
app/src/main/java/ru/parcel/app/di/prefs/ATMModel.kt | gdlbo | 839,512,469 | false | {"Kotlin": 322281} | package ru.parcel.app.di.prefs
import org.koin.dsl.module
object ATMModel {
val atmModule = module {
single {
AccessTokenManager(get())
}
}
} | 0 | Kotlin | 0 | 7 | bffdef535d8056455568fc4ad3f2fb763509d89f | 179 | packageradar | MIT License |
src/main/kotlin/top/maplex/rayskillsystem/skill/tools/attribute/AttributeManager.kt | RaySkillSystem | 670,112,740 | false | null | package top.maplex.rayskillsystem.skill.tools.attribute
import org.bukkit.entity.LivingEntity
import org.bukkit.entity.Player
import top.maplex.rayskillsystem.api.script.auto.InputEngine
@InputEngine("AttributeManager")
object AttributeManager {
var attributes = object : AbstractAttribute {
override val name: String = "默认属性"
override fun getCooldown(livingEntity: LivingEntity): Double {
return 1.0
}
}
fun getCooldown(livingEntity: LivingEntity): Double {
return attributes.getCooldown(livingEntity)
}
fun getAttribute(livingEntity: LivingEntity, attribute: String, default: Double = 0.0): Double {
return attributes.getAttribute(livingEntity, attribute, default)
}
fun addAttribute(livingEntity: LivingEntity, attribute: String, value: Double, source: String) {
attributes.addAttribute(livingEntity, attribute, value, source)
}
fun tempAttribute(
livingEntity: LivingEntity,
attribute: String,
value: Double,
source: String,
tick: Long,
force: Boolean = false,
) {
attributes.tempAttribute(livingEntity, attribute, value, source, tick, force)
}
fun removeAttribute(livingEntity: LivingEntity, source: String) {
attributes.removeAttribute(livingEntity, source)
}
}
| 0 | Kotlin | 0 | 4 | 4092a6a78f9fa7494ae5552bc79f1b8c45add449 | 1,355 | RaySkillSystem | Creative Commons Zero v1.0 Universal |
ldialog/src/main/java/top/limuyang2/ldialog/base/OnDialogDismissListener.kt | limuyang2 | 139,615,653 | false | null | package top.limuyang2.ldialog.base
import android.content.DialogInterface
import android.os.Parcel
import android.os.Parcelable
/**
*
* Date 2018/7/3
* @author limuyang
*/
abstract class OnDialogDismissListener : DialogInterface.OnDismissListener, Parcelable {
override fun describeContents(): Int = 0
override fun writeToParcel(dest: Parcel, flags: Int) {}
constructor()
protected constructor(source: Parcel)
companion object {
@JvmField
val CREATOR: Parcelable.Creator<OnDialogDismissListener> = object : Parcelable.Creator<OnDialogDismissListener> {
override fun createFromParcel(source: Parcel): OnDialogDismissListener {
return object : OnDialogDismissListener(source) {
override fun onDismiss(dialog: DialogInterface) {
}
}
}
override fun newArray(size: Int): Array<OnDialogDismissListener?> {
return arrayOfNulls(size)
}
}
}
} | 8 | Kotlin | 30 | 249 | b5655b5c09c0adc2e2014d3ab5b16cb9507eb8bd | 1,030 | LDialog | Apache License 2.0 |
src/test/aoc2019/Day13Test.kt | nibarius | 154,152,607 | false | null | package test.aoc2019
import aoc2019.Day13
import org.junit.Assert.assertEquals
import org.junit.Test
import resourceAsList
class Day13Test {
@Test
fun partOneRealInput() {
assertEquals(258, Day13(resourceAsList("2019/day13.txt", ",")).solvePart1())
}
@Test
fun partTwoRealInput() {
assertEquals(12765, Day13(resourceAsList("2019/day13.txt", ",")).solvePart2())
}
} | 0 | Kotlin | 0 | 6 | c1e50b341bbbc5292560aefa45569630d2249251 | 409 | aoc | MIT License |
automotive/src/main/java/com/ixam97/carStatsViewer/ui/views/SnackbarWidget.kt | Ixam97 | 583,674,516 | false | {"Kotlin": 469242} | package com.ixam97.carStatsViewer.ui.views
import android.animation.ValueAnimator
import android.app.Activity
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.Animation.AnimationListener
import android.view.animation.AnimationUtils
import android.view.animation.LinearInterpolator
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.DrawableRes
import androidx.core.view.isVisible
import com.ixam97.carStatsViewer.R
import kotlin.math.roundToInt
class SnackbarWidget private constructor(
private val snackbarParameters: SnackbarParameters,
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
): LinearLayout(context, attrs, defStyleAttr) {
private data class SnackbarParameters(
var message: String,
val buttonText: String? = null,
val drawableId: Int? = null,
val startHidden: Boolean = false,
val duration: Long = 0,
val listener: SnackbarInterface? = null,
val isError: Boolean = false
)
fun interface SnackbarInterface {
fun onClick()
}
class Builder(val context: Context, val message: String) {
private var snackbarParameters = SnackbarParameters(message)
fun setButton(buttonText: String, listener: SnackbarInterface? = null): Builder {
snackbarParameters = snackbarParameters.copy(
buttonText = buttonText,
listener = listener
)
return this
}
fun setIsError(isError: Boolean): Builder {
snackbarParameters = snackbarParameters.copy(
isError = isError
)
return this
}
fun setDuration(duration: Long): Builder {
snackbarParameters = snackbarParameters.copy(
duration = duration
)
return this
}
fun setStartDrawable(@DrawableRes resId: Int): Builder {
snackbarParameters = snackbarParameters.copy(
drawableId = resId
)
return this
}
fun show() {
if (context is Activity) {
snackbarParameters = snackbarParameters.copy(startHidden = true)
context.window.findViewById<FrameLayout>(android.R.id.content).addView(build())
}
}
fun build(): SnackbarWidget {
return SnackbarWidget(snackbarParameters, context)
}
fun setButtonEvent() {}
}
private val confirmButton: TextView
private val messageText: TextView
private val startIcon: ImageView
private val progressBar: View
fun updateMessage(message: String) {
snackbarParameters.message = message
messageText.text = snackbarParameters.message
}
fun setProgressBarPercent(percent: Int) {
val maxWidth = [email protected]
val onePercent = maxWidth.toFloat() / 100
val newWidth = onePercent * percent
val layoutParams = findViewById<View>(R.id.progress_bar).layoutParams
layoutParams.width = newWidth.roundToInt()
progressBar.layoutParams = layoutParams
}
private fun removeSelf() {
val anim = AnimationUtils.loadAnimation(context, R.anim.snackbar_down)
anim.setAnimationListener(object: AnimationListener{
override fun onAnimationStart(animation: Animation?) = Unit
override fun onAnimationEnd(animation: Animation?) {
Handler(Looper.getMainLooper()).post {
[email protected]<FrameLayout>(android.R.id.content).removeView(this@SnackbarWidget)
}
}
override fun onAnimationRepeat(animation: Animation?) = Unit
})
this.startAnimation(anim)
}
init {
val root = inflate(context, R.layout.widget_snackbar, this)
confirmButton = findViewById(R.id.confirm_button)
messageText = findViewById(R.id.message_text)
startIcon = findViewById(R.id.start_icon)
progressBar = findViewById(R.id.progress_bar)
messageText.text = snackbarParameters.message
confirmButton.isVisible = false
snackbarParameters.buttonText?.let {
confirmButton.text = it
confirmButton.isVisible = true
}
confirmButton.setOnClickListener {
snackbarParameters.listener?.onClick()
removeSelf()
}
if (snackbarParameters.isError) {
(progressBar.parent as ViewGroup).setBackgroundColor(context.getColor(R.color.bad_red_dark))
messageText.setTextColor(context.getColor(android.R.color.white))
progressBar.setBackgroundColor(context.getColor(R.color.bad_red))
startIcon.setImageResource(R.drawable.ic_error)
startIcon.setColorFilter(context.getColor(android.R.color.white))
}
snackbarParameters.drawableId?.let {
startIcon.setImageResource(snackbarParameters.drawableId)
}
val anim = AnimationUtils.loadAnimation(context, R.anim.snackbar_up)
if (snackbarParameters.duration > 0) {
anim.setAnimationListener(object : AnimationListener {
override fun onAnimationStart(animation: Animation?) {}
override fun onAnimationEnd(animation: Animation?) {
if (snackbarParameters.duration > 0) {
Handler(Looper.getMainLooper()).postDelayed({
removeSelf()
}, snackbarParameters.duration)
}
val widthAnimator = ValueAnimator.ofInt(1, [email protected])
widthAnimator.duration = snackbarParameters.duration
widthAnimator.interpolator = LinearInterpolator()
widthAnimator.addUpdateListener { barAnimation ->
val layoutParams = findViewById<View>(R.id.progress_bar).layoutParams
layoutParams.width = barAnimation.animatedValue as Int
progressBar.layoutParams = layoutParams
}
widthAnimator.start()
}
override fun onAnimationRepeat(animation: Animation?) {}
})
this.startAnimation(anim)
}
}
} | 29 | Kotlin | 54 | 96 | fe203efcb8681ad3ea29b7b5218dfd1aac1a1397 | 6,694 | CarStatsViewer | MIT License |
src/test/kotlin/tutorial/basic/BranchFunctions1_ja.kt | ldi-github | 646,043,710 | false | {"Kotlin": 214994} | package tutorial.basic
import org.junit.jupiter.api.Order
import org.junit.jupiter.api.Test
import shirates.core.configuration.Testrun
import shirates.core.driver.branchextension.*
import shirates.core.driver.commandextension.describe
import shirates.core.driver.commandextension.screenIs
import shirates.core.testcode.UITest
@Testrun("testConfig/android/設定/testrun.properties", profile = "Android")
class BranchFunctions1_ja : UITest() {
@Test
@Order(10)
fun branch_platform_device() {
scenario {
case(1) {
action {
android {
virtualDevice {
describe("これはAndroidエミュレーターの場合に呼ばれます。")
}
realDevice {
describe("これはAndroid実機の場合に呼ばれます。")
}
}
ios {
virtualDevice {
describe("これはiOSシミュレーターの場合に呼ばれます。")
}
realDevice {
describe("これはiOS実機の場合に呼ばれます。")
}
}
}.expectation {
it.screenIs("[Android設定トップ画面]")
}
}
case(2) {
action {
emulator {
describe("これはAndroidエミュレーターの場合に呼ばれます。")
}
simulator {
describe("これはiOSシミュレーターの場合に呼ばれます。")
}
realDevice {
describe("これは実機の場合に呼ばれます。")
}
}.expectation {
it.screenIs("[Android設定トップ画面]")
}
}
}
}
} | 0 | Kotlin | 0 | 1 | 2cd598f01df2424bb1a299b89d9c887aa7c7c9c3 | 1,816 | shirates-core-samples-ja | MIT License |
library-mvvm/src/main/java/com/pp/mvvm/ActivityWindowInsetsDispatcher.kt | PPQingZhao | 651,920,234 | false | {"Kotlin": 391209, "Java": 23883} | package com.pp.mvvm
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.WindowInsets
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
/**
* 自定义 activity windowInsets分发
* 分发windowInsets给每一个fragment
*/
class ActivityWindowInsetsDispatcher : DefaultLifecycleObserver {
private var supportManager: FragmentManager? = null
private var contentView: View? = null
private val mDispatchInsets = MutableLiveData<WindowInsets>()
val dispatchInsets: LiveData<WindowInsets> = mDispatchInsets
private var fragmentLifecycleCallbacks: FragmentManager.FragmentLifecycleCallbacks? = null
private fun dispatch(a: FragmentActivity) {
supportManager = a.supportFragmentManager
contentView = a.window.decorView.findViewById(android.R.id.content)
a.lifecycle.addObserver(this)
}
companion object {
fun dispatch(a: FragmentActivity): ActivityWindowInsetsDispatcher {
return ActivityWindowInsetsDispatcher().apply {
dispatch(a)
}
}
}
override fun onCreate(owner: LifecycleOwner) {
super.onCreate(owner)
contentView?.setOnApplyWindowInsetsListener { _, windowInsets ->
// 记录windowInsets
mDispatchInsets.value = WindowInsets(windowInsets)
contentView?.apply {
// 分发windowInsets给 activity布局
(this as ViewGroup).getChildAt(0)
?.dispatchApplyWindowInsets(WindowInsets(windowInsets))
}
// 返回一个已消费的 windowInsets,结束分发流程
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
WindowInsets.CONSUMED
} else {
windowInsets.consumeSystemWindowInsets()
}
}
fragmentLifecycleCallbacks = object : FragmentManager.FragmentLifecycleCallbacks() {
override fun onFragmentViewCreated(
fm: FragmentManager,
f: Fragment,
v: View,
savedInstanceState: Bundle?,
) {
Log.e("WindowInsetsDispatcher", "onFragmentViewCreated==>> ${f}")
// 分发windowInsets 给fragment
mDispatchInsets.observe(f) {
it?.apply {
f.view?.let { view ->
ViewCompat.dispatchApplyWindowInsets(
view,
WindowInsetsCompat.toWindowInsetsCompat(WindowInsets(it))
)
}
}
}
}
}
supportManager?.registerFragmentLifecycleCallbacks(fragmentLifecycleCallbacks!!, true)
}
override fun onDestroy(owner: LifecycleOwner) {
super.onDestroy(owner)
contentView = null
mDispatchInsets.value = null
supportManager?.unregisterFragmentLifecycleCallbacks(fragmentLifecycleCallbacks!!)
fragmentLifecycleCallbacks = null
supportManager = null
}
} | 0 | Kotlin | 0 | 1 | fa136caa315c4eab80e0d86ce9ee2a210cda6fec | 3,458 | WanAndroid-kotlin | Apache License 2.0 |
src/main/kotlin/kr/co/finda/androidtemplate/model/Template.kt | FindaDeveloper | 337,247,380 | false | null | package kr.co.finda.androidtemplate.model
enum class Template(
val templateFileName: String
) {
ACTIVITY("ActivityTemplate.txt"),
BOTTOM_SHEET("BottomSheetTemplate.txt"),
FRAGMENT("FragmentTemplate.txt"),
LAYOUT("LayoutTemplate.txt"),
VIEW_MODEL("ViewModelTemplate.txt"),
VIEW_MODEL_TEST("ViewModelTestTemplate.txt")
} | 5 | Kotlin | 1 | 5 | f75cbf9e89c8b2233a5a30d06f1ffa26e770010c | 347 | FindaTemplatePlugin-Android | MIT License |
app/src/main/java/cz/ikem/dci/zscanner/persistence/Repositories.kt | ikem-cz | 183,602,578 | false | null | package cz.ikem.dci.zscanner.persistence
import android.content.Context
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
class Repositories(val app: Context) {
private val initializationScope: Lazy<CoroutineScope>
get() = lazy {
CoroutineScope(Job() + Dispatchers.IO)
}
val typeRepository: TypeRepository
val jobsRepository: SendJobRepository
val mruRepository: MruRepository
init {
val documentTypeDao = TypeDatabase.getDatabase(app, initializationScope).documentTypeDao()
typeRepository = TypeRepository(documentTypeDao)
val jobsDao = SendJobDatabase.getDatabase(app).sendJobDao()
jobsRepository = SendJobRepository(jobsDao)
val mruDao = MruDatabase.getDatabase(app, initializationScope).mruDao()
mruRepository = MruRepository(mruDao)
}
} | 1 | Kotlin | 0 | 2 | c1a5d7a449f3fed3da429bda154428ecdb4a8d42 | 910 | zscanner-android | MIT License |
android/beagle/src/main/java/br/com/zup/beagle/action/ActionExecutor.kt | thosantunes | 269,216,984 | true | {"Kotlin": 1067509, "Swift": 638142, "C++": 262909, "Objective-C": 58562, "Java": 26545, "Ruby": 17188, "Shell": 1780, "C": 1109} | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* 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 br.com.zup.beagle.action
import android.content.Context
import br.com.zup.beagle.setup.BeagleEnvironment
import br.com.zup.beagle.view.BeagleActivity
import br.com.zup.beagle.view.ServerDrivenState
internal class ActionExecutor(
private val customActionHandler: CustomActionHandler? =
BeagleEnvironment.beagleSdk.customActionHandler,
private val navigationActionHandler: NavigationActionHandler =
NavigationActionHandler(),
private val showNativeDialogActionHandler: ShowNativeDialogActionHandler =
ShowNativeDialogActionHandler(),
private val formValidationActionHandler: DefaultActionHandler<FormValidation>? = null
) {
fun doAction(context: Context, action: Action?) {
when (action) {
is Navigate -> navigationActionHandler.handle(context, action)
is ShowNativeDialog -> showNativeDialogActionHandler.handle(context, action)
is FormValidation -> formValidationActionHandler?.handle(context, action)
is CustomAction -> customActionHandler?.handle(context, action, object : ActionListener {
override fun onSuccess(action: Action) {
changeActivityState(context, ServerDrivenState.Loading(false))
doAction(context, action)
}
override fun onError(e: Throwable) {
changeActivityState(context, ServerDrivenState.Loading(false))
changeActivityState(context, ServerDrivenState.Error(e))
}
override fun onStart() {
changeActivityState(context, ServerDrivenState.Loading(true))
}
})
}
}
private fun changeActivityState(context: Context, state: ServerDrivenState) {
(context as? BeagleActivity)?.onServerDrivenContainerStateChanged(state)
}
}
| 1 | null | 1 | 1 | 046531e96d0384ae2917b0fd790f09d1a8142912 | 2,515 | beagle | Apache License 2.0 |
src/main/kotlin/jsitter/impl/TSTree.kt | JetBrains | 190,049,014 | false | {"Git Config": 1, "Maven POM": 1, "Text": 1, "Ignore List": 3, "Markdown": 1, "Shell": 1, "Kotlin": 10, "Java": 2, "edn": 1, "Clojure": 1, "CMake": 1, "C": 2} | @file:Suppress("UNCHECKED_CAST")
package jsitter.impl
import jsitter.api.*
import jsitter.interop.*
class TSTreeResource(val treePtr: Ptr) : Resource {
init {
Cleaner.register(this)
}
override fun disposer(): Disposer {
val treePtr = this.treePtr
return {
JSitter.releaseTree(treePtr)
}
}
}
class TSSubtreeResource(val subtreePtr: Ptr) : Resource {
init {
Cleaner.register(this)
}
override fun disposer(): Disposer {
val subtreePtr = this.subtreePtr
return {
JSitter.releaseSubtree(subtreePtr)
}
}
}
data class TSSubtree<out T : NodeType>(override val language: TSLanguage<*>,
val subtreePtr: Ptr,
val lifetime: Resource?) : Node<T> {
override fun equals(other: Any?): Boolean =
other is TSSubtree<*> && other.subtreePtr == this.subtreePtr
override fun hashCode(): Int =
subtreePtr.toInt() + 1
override val type: T by lazy {
this.language.getNodeType(SubtreeAccess.subtreeNodeType(this.subtreePtr)) as T
}
override val byteSize: Int
get() = SubtreeAccess.subtreeBytesSize(this.subtreePtr)
override val padding: Int
get() = SubtreeAccess.subtreeBytesPadding(this.subtreePtr)
override fun zipper(): Zipper<T> =
TSZipper(
node = this,
parent = null,
structuralChildIndex = 0,
parentAliasSequence = 0L,
byteOffset = SubtreeAccess.subtreeBytesPadding(this.subtreePtr),
childIndex = 0)
}
data class TSTree<T : NodeType>(val treePtr: Ptr,
override val root: TSSubtree<T>,
override val actual: Boolean) : Tree<T> {
override fun adjust(edits: List<Edit>): Tree<T> {
if (edits.isEmpty()) {
return this
}
else {
val treeCopy = JSitter.copyTree(this.treePtr)
for (e in edits) {
JSitter.editTree(treeCopy, e.startByte, e.oldEndByte, e.newEndByte)
}
return TSTree(
treePtr = treeCopy,
root = root.copy(
subtreePtr = SubtreeAccess.root(treeCopy),
lifetime = TSTreeResource(treeCopy)),
actual = false)
}
}
}
| 7 | Kotlin | 10 | 60 | 6c896a59ad7a03ee7fb89e10b4d721d9d3189146 | 2,185 | jsitter | Apache License 2.0 |
src/main/kotlin/org/magmaoffenburg/roboviz/util/DataTypes.kt | magmaOffenburg | 34,959,602 | false | {"Java": 647607, "Kotlin": 105860, "GLSL": 19615, "HTML": 8010, "Shell": 460, "Batchfile": 184} | package org.magmaoffenburg.roboviz.util
import java.lang.IllegalStateException
enum class Mode {
LOG,
LIVE
}
enum class ConfirmResult {
YES, NO, CANCEL;
companion object {
fun fromInt(result: Int) =
when (result) {
0 -> YES
1 -> NO
2 -> CANCEL
else -> throw IllegalStateException()
}
}
}
| 21 | Java | 17 | 52 | e660a072b3163014050a1253f8fe33c60519ffb9 | 408 | RoboViz | Apache License 2.0 |
Chapter13/kotlin-basic-example/src/Examples.kt | PacktPublishing | 94,758,234 | false | null | class Examples(val name: String) {
fun greet() {
println("Hello, ${name}");
}
}
fun main(args: Array<String>) {
//Mutability
var variable = 5
variable = 6 //You can change value
val immutable = 6
//immutable = 7//Val cannot be reassigned
//List<Integer> integers = new ArrayList<Integer>();
var string: String = "abc"
//string = null //Compilation Error
var nullableString: String? = "abc"
nullableString = null
//print(nullableString.length)//Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?
if (nullableString != null) {
print(nullableString.length)
}
println(nullableString?.length)
var char = 'c'
//if(char==1) print (char);//Operator '==' cannot be applied to 'Char' and 'Int'
//Arrays
val intArray = intArrayOf(1, 2, 10)
println(intArray[0])//1
println(intArray.get(0))//1
println(intArray.all { it > 5 }) //false
println(intArray.any { it > 5 }) //true
println(intArray.asList())//[1, 2, 10]
println(intArray.max())//10
println(intArray.min())//1
//Type Inference
var intVariable = 10
//intVariable = "String" //Type mismatch: inferred type is String but Int was expected
//String Templates
var exampleStringVariable = "SomeString"
//SomeString has 10 characters
println("$exampleStringVariable has ${exampleStringVariable.length} characters")
//Functions
println(helloBasic("foo")) // => Hello, foo!
// Named Parameters
println(helloBasic(name = "bar"))
//println(helloBasic()) //Compiler Error
println(helloWithDefaultValue())//Hello, World
//Data Class
data class Address(val line1: String,
val line2: String,
val zipCode: Int,
val state: String,
val country: String)
val myAddress = Address("234, Some Apartments", "River Valley Street", 54123, "NJ", "USA")
println(myAddress)//Address(line1=234, Some Apartments, line2=River Valley Street, zipCode=54123, state=NJ, country=USA)
val myFriendsAddress = myAddress.copy(line1 = "245, Some Apartments")
println(myFriendsAddress)//Address(line1=245, Some Apartments, line2=River Valley Street, zipCode=54123, state=NJ, country=USA)
//Destructure
val (line1, line2, zipCode, state, country) = myAddress;
println("$line1 $line2 $zipCode $state $country"); //234, Some Apartments River Valley Street 54123 NJ USA
//Collections
val countries = listOf("India", "China", "USA")
println(countries.size)//3
println(countries.first())//India
println(countries.last())//USA
println(countries[2])//USA
//countries.add("China") //Not allowed
val mutableContries = mutableListOf("India", "China", "USA")
mutableContries.add("China")
val characterOccurances = mapOf("a" to 1, "h" to 1, "p" to 2, "y" to 1)//happy
println(characterOccurances)//{a=1, h=1, p=2, y=1}
println(characterOccurances["p"])//2
//Destructuring a Map
for ((key, value) in characterOccurances) {
println("$key -> $value")
}
}
/*
Functions can be declared using the "fun" keyword.
Function arguments are specified in brackets after the function name.
Function arguments can optionally have a default value.
The function return type, if required, is specified after the arguments.
*/
fun helloBasic(name: String): String {
return "Hello, $name!"
}
fun helloWithDefaultValue(name: String = "World"): String {
return "Hello, $name!"
}
fun helloWithOneExpression(name: String = "world") = "Hello, $name!"
fun printHello(name: String = "world") = println("Hello, $name!")
| 0 | Java | 67 | 99 | 7277ec05d3bc4038f029b981a282619376373d3c | 3,470 | Mastering-Spring-5.0 | MIT License |
android/src/main/java/com/ycbjie/android/presenter/AndroidSearchPresenter.kt | kouhengsheng | 203,290,784 | false | null | package com.ycbjie.android.presenter
import com.ycbjie.android.contract.AndroidSearchContract
import com.ycbjie.android.model.helper.AndroidHelper
import com.ycbjie.android.network.BaseSchedulerProvider
import com.ycbjie.android.network.ResponseTransformer
import com.ycbjie.android.network.SchedulerProvider
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
class AndroidSearchPresenter : AndroidSearchContract.Presenter {
private var mView: AndroidSearchContract.View
private var scheduler: BaseSchedulerProvider? = null
private var page: Int = 0
constructor (androidView: AndroidSearchContract.View, scheduler: SchedulerProvider){
this.mView = androidView
this.scheduler = scheduler
}
private val compositeDisposable: CompositeDisposable by lazy {
CompositeDisposable()
}
override fun subscribe() {
}
override fun unSubscribe() {
compositeDisposable.clear()
}
override fun getSearchTag() {
val instance = AndroidHelper.instance()
var disposable: Disposable = instance.getRecommendSearchTag()
.compose(ResponseTransformer.handleResult())
.compose(scheduler?.applySchedulers())
.subscribe(
{ t -> mView.setSearchTagSuccess(t) },
{ t -> mView.setSearchTagFail(t.message!!) }
)
compositeDisposable.add(disposable)
}
override fun search(str: String, isRefresh: Boolean) {
if (isRefresh) {
page = 0
}
val instance = AndroidHelper.instance()
var disposable = instance.search(page, str)
.compose(ResponseTransformer.handleResult())
.compose(scheduler?.applySchedulers())
.subscribe(
{ t ->
if (t.size * (page + 1) >= t.total) {
mView.setAllData(t, isRefresh)
} else {
mView.setSearchResultSuccess(t, isRefresh)
page++
}
},
{ t: Throwable -> mView.setSearchResultFail(t.message!!) }
)
compositeDisposable.add(disposable)
}
}
| 14 | null | 7 | 3 | c85a3d6320b832148cdee9e1ca97432cd5e112e1 | 2,374 | LifeHelper | Apache License 2.0 |
src/main/kotlin/com/demonwav/mcdev/i18n/lang/I18nRenameInputValidator.kt | Earthcomputer | 240,984,777 | true | {"Kotlin": 1282177, "Lex": 12961, "HTML": 10151, "Groovy": 4500, "Java": 948, "Shell": 798} | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.i18n.lang
import com.demonwav.mcdev.i18n.lang.gen.psi.I18nEntry
import com.intellij.openapi.project.Project
import com.intellij.patterns.ElementPattern
import com.intellij.patterns.PlatformPatterns
import com.intellij.psi.PsiElement
import com.intellij.refactoring.rename.RenameInputValidatorEx
import com.intellij.util.ProcessingContext
class I18nRenameInputValidator : RenameInputValidatorEx {
override fun isInputValid(newName: String, element: PsiElement, context: ProcessingContext) = !newName.contains('=')
override fun getPattern(): ElementPattern<out PsiElement> = PlatformPatterns.psiElement(I18nEntry::class.java)
override fun getErrorMessage(newName: String, project: Project) =
if (newName.contains('=')) "Key must not contain separator character ('=')" else null
}
| 1 | Kotlin | 2 | 23 | ab8aaeb8804c7a8b2e439e063a73cb12d0a9d4b5 | 955 | MinecraftDev | MIT License |
bbfgradle/tmp/results/BACKUP_JVM-Xuse-ir/BACKEND_cbhuwtp_FILE.kt | DaniilStepanov | 346,008,310 | false | null | // Bug happens on JVM -Xuse-ir
// !LANGUAGE: +ProperIeee754Comparisons
// FILE: tmp0.kt
fun <A: Double, B: A> eq_double_any( a: Double,b: B) = a == b
| 1 | null | 1 | 1 | e772ef1f8f951873ebe7d8f6d73cf19aead480fa | 153 | kotlinWithFuzzer | Apache License 2.0 |
bbfgradle/tmp/results/BACKUP_JVM-Xuse-ir/BACKEND_cbhuwtp_FILE.kt | DaniilStepanov | 346,008,310 | false | null | // Bug happens on JVM -Xuse-ir
// !LANGUAGE: +ProperIeee754Comparisons
// FILE: tmp0.kt
fun <A: Double, B: A> eq_double_any( a: Double,b: B) = a == b
| 1 | null | 1 | 1 | e772ef1f8f951873ebe7d8f6d73cf19aead480fa | 153 | kotlinWithFuzzer | Apache License 2.0 |
app/src/main/java/com/ivantrogrlic/leaguestats/main/summoner/games/GamesView.kt | ivanTrogrlic | 96,999,301 | false | {"Gradle": 6, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "YAML": 2, "Markdown": 1, "XML": 40, "JSON": 1, "Proguard": 1, "Java": 4, "Kotlin": 41} | package com.ivantrogrlic.leaguestats.main.summoner.games
import com.hannesdorfmann.mosby3.mvp.MvpView
import com.ivantrogrlic.leaguestats.model.Match
import java.util.*
/**
* Created by ivan on 8/9/2017.
*/
interface GamesView : MvpView {
fun setMatches(matches: List<Match>)
}
| 1 | null | 1 | 1 | 94fa2a8aa93acf0d9746819c20540cf3e2929d93 | 286 | LeagueStats | Apache License 2.0 |
plugins/kotlin/idea/tests/testData/inspectionsLocal/equalsOrHashCode/hashCode.kt | ingokegel | 72,937,917 | true | null | class With<caret>Constructor(x: Int, s: String) {
val x: Int = 0
val s: String = ""
override fun equals(other: Any?): Boolean = false
} | 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 148 | intellij-community | Apache License 2.0 |
app/src/main/java/com/udeshcoffee/android/data/local/LocalDatabase.kt | m760622 | 163,887,222 | false | null | /*
* Copyright 2017, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.udeshcoffee.android.data.local
import android.arch.persistence.db.SupportSQLiteDatabase
import android.arch.persistence.room.Database
import android.arch.persistence.room.RoomDatabase
import android.arch.persistence.room.migration.Migration
import com.udeshcoffee.android.data.model.*
/**
* The Room Database that contains the Task table.
*/
@Database(entities = [(SongStat::class), (AlbumStat::class), (ArtistStat::class), (Bio::class), (
EQPreset::class), (Favorite::class), (Lyric::class)], version = 6, exportSchema = false)
abstract class LocalDatabase : RoomDatabase() {
abstract fun dataDao(): DataDao
companion object {
val Migration_5_6 = object: Migration(5, 6) {
override fun migrate(database: SupportSQLiteDatabase) {
// Create the new table
database.execSQL(
"CREATE TABLE song_stats (songid INTEGER, playcount INTEGER, playtime INTEGER, PRIMARY KEY(songid))")
// Copy the data
database.execSQL(
"INSERT INTO song_stats (songid, playcount, playtime) SELECT songid, rplayedid, rplayed FROM playcount")
// Remove the old table
database.execSQL("DROP TABLE playcount");
}
}
}
} | 0 | null | 1 | 1 | 928bd65fd6064a26cbb758a0604ed5718a1ea55f | 1,928 | CoffeeMusicPlayer | Apache License 2.0 |
api/src/test/java/com/github/pulsebeat02/minecraftmedialibrary/test/extraction/GifToMpegTest.kt | Conclure | 369,261,158 | false | {"Gradle Kotlin DSL": 21, "C++": 1, "Markdown": 5, "YAML": 8, "Batchfile": 2, "Shell": 2, "Text": 1, "Ignore List": 1, "Java": 211, "INI": 1, "HTML": 545, "CSS": 2, "JavaScript": 2, "Kotlin": 34, "JSON": 1} | /*............................................................................................
. Copyright © 2021 <NAME> .
. .
. Permission is hereby granted, free of charge, to any person obtaining a copy of this .
. software and associated documentation files (the “Software”), to deal in the Software .
. without restriction, including without limitation the rights to use, copy, modify, merge, .
. publish, distribute, sublicense, and/or sell copies of the Software, and to permit .
. persons to whom the Software is furnished to do so, subject to the following conditions: .
. .
. The above copyright notice and this permission notice shall be included in all copies .
. or substantial portions of the Software. .
. .
. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, .
. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF .
. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND .
. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS .
. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN .
. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN .
. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE .
. SOFTWARE. .
............................................................................................*/
package com.github.pulsebeat02.minecraftmedialibrary.test.extraction
import org.apache.commons.io.FilenameUtils
import ws.schild.jave.Encoder
import ws.schild.jave.EncoderException
import ws.schild.jave.MultimediaObject
import ws.schild.jave.encode.AudioAttributes
import ws.schild.jave.encode.EncodingAttributes
import java.io.File
fun main() {
val image = File("/Users/bli24/Desktop/test.gif")
val name: String = image.name
val encoder = Encoder()
val audio = AudioAttributes()
audio.setVolume(0)
val attrs = EncodingAttributes()
attrs.setInputFormat(FilenameUtils.getExtension(name))
attrs.setOutputFormat("mp4")
attrs.setAudioAttributes(audio)
val output = File("/Users/bli24/Desktop/", FilenameUtils.getBaseName(name) + ".mp4")
try {
encoder.encode(MultimediaObject(image), output, attrs)
} catch (e: EncoderException) {
e.printStackTrace()
}
} | 1 | null | 1 | 1 | 8d5e4a3599a54674aa1f89cc8103c1b30ddcec6b | 2,912 | MinecraftMediaLibrary | MIT License |
compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/TowerResolver.kt | rpanak | 47,044,310 | true | {"Java": 15932450, "Kotlin": 11684500, "JavaScript": 176060, "Protocol Buffer": 43063, "HTML": 26595, "Lex": 16515, "ANTLR": 9689, "CSS": 9358, "Groovy": 5204, "Shell": 4638, "Batchfile": 3703, "IDL": 3441} | /*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.resolve.calls.tower
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.calls.tasks.ExplicitReceiverKind
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.utils.addToStdlib.check
interface TowerContext<C> {
val name: Name
val scopeTower: ScopeTower
fun createCandidate(
towerCandidate: CandidateWithBoundDispatchReceiver<*>,
explicitReceiverKind: ExplicitReceiverKind,
extensionReceiver: ReceiverValue?
): C
fun getStatus(candidate: C): ResolutionCandidateStatus
fun transformCandidate(variable: C, invoke: C): C
fun contextForVariable(stripExplicitReceiver: Boolean): TowerContext<C>
// foo() -> ReceiverValue(foo), context for invoke
fun contextForInvoke(variable: C, useExplicitReceiver: Boolean): Pair<ReceiverValue, TowerContext<C>>
}
internal interface ScopeTowerProcessor<C> {
fun processTowerLevel(level: ScopeTowerLevel)
fun processImplicitReceiver(implicitReceiver: ReceiverValue)
// Candidates with matched receivers (dispatch receiver was already matched in ScopeTowerLevel)
// Candidates in one groups have same priority, first group has highest priority.
fun getCandidatesGroups(): List<Collection<C>>
}
class TowerResolver {
internal fun <C> runResolve(
context: TowerContext<C>,
processor: ScopeTowerProcessor<C>,
useOrder: Boolean = true
): Collection<C> {
val resultCollector = ResultCollector<C> { context.getStatus(it) }
fun collectCandidates(action: ScopeTowerProcessor<C>.() -> Unit): Collection<C>? {
processor.action()
val candidatesGroups = if (useOrder) {
processor.getCandidatesGroups()
}
else {
listOf(processor.getCandidatesGroups().flatMap { it })
}
for (candidatesGroup in candidatesGroups) {
resultCollector.pushCandidates(candidatesGroup)
resultCollector.getResolved()?.let { return it }
}
return null
}
// possible there is explicit member
collectCandidates { /* do nothing */ }?.let { return it }
for (level in context.scopeTower.levels) {
collectCandidates { processTowerLevel(level) }?.let { return it }
for (implicitReceiver in context.scopeTower.implicitReceivers) {
collectCandidates { processImplicitReceiver(implicitReceiver) }?.let { return it }
}
}
return resultCollector.getFinalCandidates()
}
//todo collect all candidates
internal class ResultCollector<C>(private val getStatus: (C) -> ResolutionCandidateStatus) {
private var currentCandidates: Collection<C> = emptyList()
private var currentLevel: ResolutionCandidateApplicability? = null
fun getResolved() = currentCandidates.check { currentLevel == ResolutionCandidateApplicability.RESOLVED }
fun getSyntheticResolved() = currentCandidates.check { currentLevel == ResolutionCandidateApplicability.RESOLVED_SYNTHESIZED }
fun getErrors() = currentCandidates.check {
currentLevel == null || currentLevel!! > ResolutionCandidateApplicability.RESOLVED_SYNTHESIZED
}
fun getFinalCandidates() = getResolved() ?: getSyntheticResolved() ?: getErrors() ?: emptyList()
fun pushCandidates(candidates: Collection<C>) {
if (candidates.isEmpty()) return
val minimalLevel = candidates.map { getStatus(it).resultingApplicability }.min()!!
if (currentLevel == null || currentLevel!! > minimalLevel) {
currentLevel = minimalLevel
currentCandidates = candidates.filter { getStatus(it).resultingApplicability == minimalLevel }
}
}
}
}
| 0 | Java | 0 | 0 | 9e0e3aaebb87c48da3da9fff47e79c4185d1fc1e | 4,550 | kotlin | Apache License 2.0 |
app/src/main/java/com/devlogs/client_android/Config.kt | tiendvlp | 393,977,757 | false | null | package com.devlogs.client_android
const val HOST = "http://10.0.2.2:4000"
const val PAYMENT_REQUEST_URL = "$HOST/payment" | 0 | Kotlin | 0 | 0 | 620503dfeec93608cbce8192bc2ceef0df9b5b40 | 124 | client_android | MIT License |
src/main/kotlin/org/pkl/intellij/stubs/PklStubElementTypes.kt | apple | 745,600,847 | false | {"Kotlin": 844683, "Lex": 12354, "HTML": 486} | /**
* Copyright © 2024 Apple Inc. and the Pkl project authors. 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pkl.intellij.stubs
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.*
import org.pkl.intellij.PklLanguage
import org.pkl.intellij.psi.PklModuleUri
import org.pkl.intellij.psi.escapedText
import org.pkl.intellij.psi.impl.PklModuleUriImpl
object PklStubElementTypes {
val MODULE_URI = PklModuleUriStubElementType()
}
class PklModuleUriStubElementType :
PklStubElementType<PklModuleUriStub, PklModuleUri>("MODULE_URI") {
override fun serialize(stub: PklModuleUriStub, dataStream: StubOutputStream) {
dataStream.writeName(stub.moduleUri)
}
override fun deserialize(
dataStream: StubInputStream,
parentStub: StubElement<*>
): PklModuleUriStub {
return PklModuleUriStubImpl(parentStub, dataStream.readNameString()!!)
}
override fun createStub(
psi: PklModuleUri,
parentStub: StubElement<out PsiElement>
): PklModuleUriStub {
return PklModuleUriStubImpl(parentStub, psi.stringConstant.content.escapedText())
}
override fun createPsi(stub: PklModuleUriStub): PklModuleUri {
return PklModuleUriImpl(stub, this)
}
override fun indexStub(stub: PklModuleUriStub, sink: IndexSink) {
stub.moduleUri?.let { uri ->
// we only care to index `package:` URIs so that we can build the external libraries list.
if (uri.startsWith("package:")) {
sink.occurrence(PklModuleUriIndex.Util.KEY, uri)
}
}
}
}
abstract class PklStubElementType<StubT : StubElement<*>, PsiT : PsiElement>(debugName: String) :
IStubElementType<StubT, PsiT>(debugName, PklLanguage) {
override fun getExternalId(): String = "pkl.${super.toString()}"
}
| 0 | Kotlin | 1 | 5 | 26f3ec19e2514ca79c999d5ce2f39acea150ee1c | 2,284 | pkl-intellij | Apache License 2.0 |
save-frontend-common/src/main/kotlin/com/saveourtool/save/frontend/common/externals/fontawesome/FaSetup.kt | saveourtool | 300,279,336 | false | {"Kotlin": 3391753, "SCSS": 86430, "JavaScript": 8966, "HTML": 8852, "Shell": 2770, "Smarty": 2608, "Dockerfile": 1366} | /**
* External declarations from fontawesome-svg-core
*/
@file:JsModule("@fortawesome/fontawesome-svg-core")
@file:JsNonModule
package com.saveourtool.frontend.common.externals.fontawesome
external val library: dynamic
| 202 | Kotlin | 3 | 38 | 7e126d4fb23f8527c47ca9fa27282379759d154e | 224 | save-cloud | MIT License |
domain/src/main/java/com/miguelbrmfreitas/domain/util/extensions/StringExtensions.kt | MiguelbrmFreitas | 548,562,167 | false | {"Kotlin": 31180} | package com.miguelbrmfreitas.domain.util.extensions
import java.text.SimpleDateFormat
import java.time.LocalDateTime
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
import java.util.*
const val FORMATTED_DATE_PATTERN = "MMM dd, uuuu"
const val API_DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'"
fun String.replaceSpaces(): String {
return replace(' ', '+')
}
fun String.toDate(): LocalDateTime {
val formatter = DateTimeFormatter.ofPattern(API_DATE_PATTERN)
return LocalDateTime.parse(this, formatter)
}
fun String.toFormattedDate(): String {
val offsetDateTime = OffsetDateTime.parse(this)
val formatter = DateTimeFormatter.ofPattern(FORMATTED_DATE_PATTERN, Locale.ENGLISH)
return formatter.format(offsetDateTime)
} | 0 | Kotlin | 0 | 4 | 330dec36427618e74ae5bf132889d5fba3b0e87f | 766 | iTunes-searcher | MIT License |
app/src/main/java/com/consistence/pinyin/app/list/PinyinListModel.kt | nemanjanedic | 139,743,535 | true | {"Kotlin": 96949} | package com.consistence.pinyin.app.list
import android.app.Application
import com.consistence.pinyin.Model
import com.consistence.pinyin.api.PinyinEntity
import io.reactivex.Observable
import io.reactivex.Single
abstract class PinyinListModel(application: Application)
: Model<PinyinListIntent, PinyinListState>(application) {
abstract fun search(terms: String = defaultSearch): Single<List<PinyinEntity>>
abstract val defaultSearch: String
private fun searchQuery(terms: String = defaultSearch): Observable<PinyinListState> {
return search(if (terms.isEmpty()) defaultSearch else terms)
.map<PinyinListState> { PinyinListState.Populate(it) }
.onErrorReturnItem(PinyinListState.OnError)
.toObservable()
}
override fun reducer(intent: PinyinListIntent): Observable<PinyinListState> = when(intent) {
is PinyinListIntent.Search -> searchQuery(intent.terms)
is PinyinListIntent.SelectItem -> observable(PinyinListState.NavigateToDetails(intent.pinyin))
is PinyinListIntent.PlayAudio -> observable(PinyinListState.PlayAudio(intent.audioSrc))
}
} | 0 | Kotlin | 0 | 0 | 45062d9ef1f69ca838c8f157a9f6ec6c0f4a5c5e | 1,154 | android-mvi | Apache License 2.0 |
client/app/src/main/java/com/example/client/io/AppNetwork.kt | fiord | 436,187,261 | false | null | package com.example.client.io
import android.util.Log
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import java.lang.Exception
class AppNetwork {
companion object {
fun greetPost(encryptedName: String): String {
try {
Log.d("Network", "send name: ${encryptedName}")
val client = OkHttpClient()
val req = Request.Builder().apply {
url("https://encrypted-connection-sample.herokuapp.com/greet")
post(FormBody.Builder()
.add("name", encryptedName)
.build())
}.build()
client.newCall(req).execute().use {
val str = it.body?.string()
Log.d("Network", "response: ${str}")
return str!!
}
} catch (e: Exception) {
Log.e("AppNetwork", e.toString())
throw e
}
}
}
} | 0 | Kotlin | 0 | 0 | 7e5de4de36a97f82372d3d832d505a4dd3dd5370 | 1,045 | Encrypted-Connection-Sample | MIT License |
benchmarks/ecs/src/jmh/kotlin/fledware/ecs/jmh/FledEcsBenchmark.kt | fledware | 484,792,398 | false | null | package fledware.ecs.jmh
import fledware.ecs.Engine
import fledware.ecs.benchmark.Constants
import fledware.ecs.benchmark.FledCollisionSystem
import fledware.ecs.benchmark.FledMovementSystem
import fledware.ecs.benchmark.FledRandomAdder
import fledware.ecs.benchmark.FledRandomDeleter
import fledware.ecs.benchmark.FledRemovalSystem
import fledware.ecs.benchmark.FledStateSystem
import fledware.ecs.benchmark.stdWorldEntity
import fledware.ecs.createWorldAndFlush
import fledware.ecs.impl.DefaultEngine
import fledware.ecs.impl.mainThreadUpdateStrategy
import org.openjdk.jmh.annotations.Benchmark
import org.openjdk.jmh.annotations.Scope
import org.openjdk.jmh.annotations.Setup
import org.openjdk.jmh.annotations.State
import org.openjdk.jmh.annotations.TearDown
@State(Scope.Benchmark)
open class FledEcsBenchmark : AbstractBenchmark() {
private lateinit var engine: Engine
@Setup
open fun init() {
engine = DefaultEngine(mainThreadUpdateStrategy())
engine.start()
val world = engine.createWorldAndFlush("main") {
addSystem(FledMovementSystem())
addSystem(FledStateSystem())
addSystem(FledCollisionSystem())
addSystem(FledRemovalSystem())
addSystem(FledRandomDeleter())
addSystem(FledRandomAdder())
}
for (entityIndex in 0 until entityCount) {
world.data.createEntity {
stdWorldEntity(entityIndex)
}
}
}
@TearDown
fun shutdown() {
engine.shutdown()
}
@Benchmark
open fun baseline() {
engine.update(Constants.DELTA_TIME)
}
}
| 0 | Kotlin | 0 | 0 | 18fb2540768b621f216ea82400a06edf3979830f | 1,540 | FledECS | Apache License 2.0 |
app/src/main/java/org/ddosolitary/okcagent/Utils.kt | AmesianX | 235,913,044 | true | {"Kotlin": 39226} | package org.ddosolitary.okcagent
import android.content.Context
import android.content.Intent
import java.io.OutputStream
fun showError(context: Context, msg: String) {
context.startActivity(Intent(context, ErrorDialogActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK
putExtra(EXTRA_ERROR_MESSAGE, msg)
})
}
fun showError(context: Context, resId: Int) = showError(context, context.getString(resId))
fun writeString(output: OutputStream, str: String) {
val strBuf = str.toByteArray(Charsets.UTF_8)
val lenBuf = byteArrayOf(
(strBuf.size shr 8).toByte(),
(strBuf.size and Byte.MAX_VALUE.toInt()).toByte()
)
output.write(lenBuf)
output.write(strBuf)
output.flush()
}
| 0 | null | 0 | 0 | ef0890cf401f1bb76921fb6fbe57dcd7f5bbc1c6 | 702 | OkcAgent | MIT License |
app/src/main/java/com/thakurnitin2684/codeforces/data/api/ApiServiceImpl.kt | thakurnitin2684 | 262,277,771 | false | null | package com.thakurnitin2684.codeforces.data.api
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object RetrofitBuilder {
private const val BASE_URL = "https://codeforces.com/api/"
private fun getInstance(): Retrofit {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
@Singleton
@Provides
fun provideApiService(): ApiService {
return getInstance().create(ApiService::class.java)
}
} | 0 | Kotlin | 0 | 1 | 1ad02cfdc2b441753e63ebd34d8f4a8e965537a3 | 756 | Codeforces.info | MIT License |
feature/webview-api/src/main/kotlin/org/bmsk/lifemash/feature/topic/api/WebViewNavController.kt | AndroidStudy-bmsk | 632,254,827 | false | {"Kotlin": 119717} | package org.bmsk.lifemash.feature.topic.api
import org.bmsk.lifemash.feature.nav.LifeMashNavController
interface WebViewNavController : LifeMashNavController<WebViewNavControllerInfo>
data class WebViewNavControllerInfo(
val url: String,
)
| 1 | Kotlin | 1 | 0 | 3e0d37ea57a8cb8877bd65130e249ceeea897d51 | 247 | LifeMash-NewsApp | MIT License |
core/repository/src/main/java/jp/kaleidot725/easycalc/core/repository/ThemeRepository.kt | kaleidot725 | 727,725,457 | false | {"Kotlin": 331996, "Ruby": 106} | package jp.kaleidot725.easycalc.core.repository
import jp.kaleidot725.easycalc.core.domain.model.theme.Theme
import kotlinx.coroutines.flow.Flow
interface ThemeRepository {
fun get(): Flow<Theme>
suspend fun update(theme: Theme)
}
| 2 | Kotlin | 0 | 0 | d507dd11a73cd67b1b253db0156d3f00cdcf994a | 241 | EasyCalc | MIT License |
src/main/kotlin/com/edd/memestream/modules/api/RepositoryAware.kt | Edvinas01 | 101,769,017 | false | null | package com.edd.memestream.modules.api
import com.edd.memestream.storage.RepositoryManager
interface RepositoryAware {
/**
* Inject repository manager.
*/
fun initRepositories(repositoryManager: RepositoryManager)
} | 3 | Kotlin | 0 | 1 | c728292e8fb077221adb50efb469d10a1ce961a1 | 236 | meme-stream | MIT License |
app/src/main/java/com/edmundweather/android/EdmundWeatherApplication.kt | edmund03 | 442,791,768 | false | {"Kotlin": 25223} | package com.edmundweather.android
import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import java.security.AccessControlContext
class EdmundWeatherApplication : Application(){
companion object{
const val TOKEN = "auv03EiB3Zt9RZcn"
@SuppressLint("StaticFieldLeak")
lateinit var context: Context
}
override fun onCreate(){
super.onCreate()
context = applicationContext
}
} | 0 | Kotlin | 0 | 0 | 10075c82865f4bfacec7a5ebcd88452f3acb20b0 | 478 | EdmundWeather | Apache License 2.0 |
src/main/kotlin/jamule/AmuleConnection.kt | vexdev | 704,976,422 | false | null | package jamule
import jamule.auth.PasswordHasher
import jamule.ec.packet.PacketParser
import jamule.ec.packet.PacketWriter
import jamule.ec.tag.TagEncoder
import jamule.ec.tag.TagParser
import jamule.exception.CommunicationException
import jamule.exception.ServerException
import jamule.request.AuthRequest
import jamule.request.Request
import jamule.request.SaltRequest
import jamule.response.*
import org.slf4j.Logger
import java.io.IOException
import java.net.Socket
internal class AmuleConnection(
private val host: String,
private val port: Int,
private val timeout: Int,
private val password: String,
private val logger: Logger
) {
private var socket = Socket(host, port).apply { soTimeout = timeout }
private var connected = false
@OptIn(ExperimentalUnsignedTypes::class)
private val tagParser = TagParser(logger)
@OptIn(ExperimentalUnsignedTypes::class)
private val packetParser = PacketParser(tagParser, logger)
@OptIn(ExperimentalUnsignedTypes::class)
private val tagEncoder = TagEncoder(logger)
@OptIn(ExperimentalUnsignedTypes::class)
private val packetWriter = PacketWriter(tagEncoder, logger)
fun reconnect() {
synchronized(socket) {
logger.info("Reconnecting...")
connected = false
runCatching { socket.close() }
socket = Socket(host, port).apply { soTimeout = timeout }
authenticate()
}
}
fun sendRequest(request: Request): Response {
if (!connected) reconnect()
try {
return sendRequestNoAuth(request)
} catch (e: IOException) {
connected = false
throw e
}
}
@OptIn(ExperimentalUnsignedTypes::class)
fun sendRequestNoAuth(request: Request): Response {
val outputStream = socket.getOutputStream()
val inputStream = socket.getInputStream().buffered()
val packet = request.packet()
packetWriter.write(packet, outputStream)
val responsePacket = packetParser.parse(inputStream)
return ResponseParser.parse(responsePacket).also {
if (it is ErrorResponse) {
throw ServerException(it.serverMessage)
}
}
}
@OptIn(ExperimentalUnsignedTypes::class)
private fun authenticate() {
logger.info("Authenticating...")
val saltResponse = sendRequestNoAuth(SaltRequest())
if (saltResponse is AuthFailedResponse)
throw ServerException("Authentication failed", saltResponse)
else if (saltResponse !is AuthSaltResponse)
throw CommunicationException("Unable to get auth salt")
val saltedPassword = PasswordHasher.hash(password, saltResponse.salt)
val response = sendRequestNoAuth(AuthRequest(saltedPassword))
if (response is AuthFailedResponse)
throw ServerException("Authentication failed", response)
else if (response !is AuthOkResponse)
throw CommunicationException("Unable to authenticate")
logger.info("Authenticated with server version ${response.version}")
connected = true
}
} | 3 | null | 0 | 1 | d19293db9fe49b9720f407130b04a878222b329c | 3,155 | jamule | MIT License |
core/converter/api/src/main/kotlin/odoo/miem/android/core/jsonrpc/converter/api/di/IConverterApi.kt | 19111OdooApp | 546,191,502 | false | {"Kotlin": 889625} | package odoo.miem.android.core.jsonrpc.converter.api.di
import odoo.miem.android.core.di.api.Api
import odoo.miem.android.core.jsonrpc.converter.api.IDeserializer
import odoo.miem.android.core.jsonrpc.converter.api.ISerializer
/**
* [IConverterApi] needed for wrapping over [ISerializer], [IDeserializer] and
* providing in common **DI graph**
*
* @see Api
*
* @author <NAME>
*/
interface IConverterApi : Api {
val serializer: ISerializer
val deserializer: IDeserializer
}
| 0 | Kotlin | 1 | 5 | e107fcbb8db2d179d40b5c1747051d2cb75e58c6 | 492 | OdooApp-Android | Apache License 2.0 |
2022/kotlin/app/src/main/kotlin/day07/Day07.kt | jghoman | 726,228,039 | false | {"Kotlin": 15309, "Rust": 14555, "Scala": 1804, "Shell": 737} | package day07
import java.lang.Exception
import java.util.Stack
val testInput = "\$ cd /\n" +
"\$ ls\n" +
"dir a\n" +
"14848514 b.txt\n" +
"8504156 c.dat\n" +
"dir d\n" +
"\$ cd a\n" +
"\$ ls\n" +
"dir e\n" +
"29116 f\n" +
"2557 g\n" +
"62596 h.lst\n" +
"\$ cd e\n" +
"\$ ls\n" +
"584 i\n" +
"\$ cd ..\n" +
"\$ cd ..\n" +
"\$ cd d\n" +
"\$ ls\n" +
"4060174 j\n" +
"8033020 d.log\n" +
"5626152 d.ext\n" +
"7214296 k"
sealed class Node() {
data class Directory(val name: String):Node() {
val nodes = ArrayList<Node>()
override fun size() = nodes.sumOf { it.size() }
fun addNode(node: Node) = nodes.add(node)
override fun toString(): String {
return "File(name='$name', totalSize=${size()})"
}
}
data class File(val name: String, val size: Long): Node() {
override fun size() = size
override fun toString(): String {
return "File(name='$name', size=$size)"
}
}
abstract fun size():Long
}
fun printNode(node: Node, offset:Int = 0) {
val sb = StringBuilder("")
for(i in 0..offset) sb.append(" ")
when(node) {
is Node.Directory -> {
println("${sb}${node.name}")
node.nodes.forEach { printNode(it, offset + 1)}
}
is Node.File -> println("${sb}${node.name} ${node.size}")
}
}
fun allDirs(node: Node): List<Node.Directory> {
when(node) {
is Node.Directory -> return (node.nodes.map{ allDirs(it) }.flatten()) + node
is Node.File -> return ArrayList()
}
}
fun part1(input: String): Pair<Long, Node.Directory> {
val lines = input
.split("\n")
val root = Node.Directory("/")
val dirStack = Stack<Node.Directory>()
dirStack.add(root)
var currentDir = root;
for(line in lines) {
if(line.equals("$ ls")) {
continue
//println("LS-ing")
} else if (line.startsWith("dir")) {
val dirName = line.split(" ")[1];
currentDir.addNode(Node.Directory(dirName))
} else if (line[0].isDigit()) {
val split = line.split(" ")
val fileName = split[1]
val size = split[0].toLong()
currentDir.addNode(Node.File(fileName, size))
} else if (line.equals("$ cd ..")) {
if (dirStack.size == 1) {
currentDir = root
} else {
currentDir = dirStack.pop();
}
} else if (line.equals("$ cd /")) {
dirStack.clear()
dirStack.add(root)
} else if (line.startsWith("$ cd ")) {
val targetDir = line.split(" ")[2]
val targetNode = currentDir.nodes.find {it is Node.Directory && it.name.equals(targetDir)} as Node.Directory
if(targetNode == null) {
throw Exception("No such dir.")
}
if(!(dirStack.size == 1 && currentDir == root)) {
dirStack.push(currentDir)
}
currentDir = targetNode
} else {
println("Huh? $line")
}
}
return Pair(allDirs(root)
.filter { it.size() <= 100000 }
.sumOf { it.size() }, root)
}
fun part2(root:Node): Long {
val totalSize = 70000000
val needed = 30000000
val freeSpace = totalSize - root.size()
val needToFree = needed - freeSpace
return allDirs(root)
.map { it.size() }
.filter { it >= needToFree }
.minBy { it }
}
fun main() {
val realInput = util.readFileUsingGetResource("day-7-input.txt")
val input = realInput
val (partOneSize, root) = part1(input)
println("Part 1 result: $partOneSize")
println("Part 2 result: ${part2(root)}")
} | 0 | Kotlin | 0 | 0 | 2eb856af5d696505742f7c77e6292bb83a6c126c | 3,910 | aoc | Apache License 2.0 |
src/main/java/wiles/checker/inferrers/InferFromCodeBlock.kt | Alex-Costea | 527,241,623 | false | null | package wiles.checker.inferrers
import wiles.checker.CheckerConstants.NOTHING_TYPE
import wiles.checker.Inferrer
import wiles.checker.InferrerDetails
import wiles.checker.InferrerUtils.isFormerSuperTypeOfLatter
import wiles.checker.exceptions.UnusedExpressionException
import wiles.shared.AbstractCompilationException
import wiles.shared.SyntaxType
class InferFromCodeBlock(details: InferrerDetails) : InferFromStatement(details) {
override fun infer()
{
for(part in statement.components)
{
try
{
val inferrer = Inferrer(InferrerDetails(part,variables, exceptions))
inferrer.infer()
if(part.type== SyntaxType.EXPRESSION && !isFormerSuperTypeOfLatter(NOTHING_TYPE, inferrer.getType()))
throw UnusedExpressionException(part.getFirstLocation())
}
catch (ex : AbstractCompilationException)
{
exceptions.add(ex)
}
}
}
} | 0 | Kotlin | 0 | 0 | 28972b9483af5afe5eace28627ac17194f2b68b1 | 1,008 | Wiles | MIT License |
apps/etterlatte-beregning-kafka/src/main/kotlin/no/nav/etterlatte/beregningkafka/MigreringHendelser.kt | navikt | 417,041,535 | false | null | package no.nav.etterlatte.beregningkafka
import io.ktor.client.call.body
import kotlinx.coroutines.runBlocking
import no.nav.etterlatte.beregning.grunnlag.BarnepensjonBeregningsGrunnlag
import no.nav.etterlatte.beregning.grunnlag.GrunnlagMedPeriode
import no.nav.etterlatte.libs.common.beregning.BeregningDTO
import no.nav.etterlatte.libs.common.grunnlag.opplysningstyper.SoeskenMedIBeregning
import no.nav.etterlatte.libs.common.logging.withLogContext
import no.nav.etterlatte.libs.common.person.Folkeregisteridentifikator
import no.nav.etterlatte.libs.common.rapidsandrivers.correlationId
import no.nav.etterlatte.libs.common.rapidsandrivers.eventName
import no.nav.etterlatte.rapidsandrivers.migrering.MigreringRequest
import no.nav.etterlatte.rapidsandrivers.migrering.Migreringshendelser
import no.nav.etterlatte.rapidsandrivers.migrering.hendelseData
import no.nav.helse.rapids_rivers.JsonMessage
import no.nav.helse.rapids_rivers.MessageContext
import no.nav.helse.rapids_rivers.RapidsConnection
import no.nav.helse.rapids_rivers.River
import org.slf4j.LoggerFactory
import rapidsandrivers.BEHANDLING_ID_KEY
import rapidsandrivers.BEREGNING_KEY
import rapidsandrivers.HENDELSE_DATA_KEY
import rapidsandrivers.behandlingId
import rapidsandrivers.withFeilhaandtering
internal class MigreringHendelser(rapidsConnection: RapidsConnection, private val beregningService: BeregningService) :
River.PacketListener {
private val logger = LoggerFactory.getLogger(this::class.java)
init {
River(rapidsConnection).apply {
eventName(Migreringshendelser.BEREGN)
validate { it.requireKey(BEHANDLING_ID_KEY) }
validate { it.requireKey(HENDELSE_DATA_KEY) }
correlationId()
}.register(this)
}
override fun onPacket(packet: JsonMessage, context: MessageContext) {
withLogContext(packet.correlationId) {
withFeilhaandtering(packet, context, Migreringshendelser.BEREGN) {
val behandlingId = packet.behandlingId
logger.info("Mottatt beregnings-migreringshendelse for $BEHANDLING_ID_KEY $behandlingId")
beregningService.opprettBeregningsgrunnlag(behandlingId, tilGrunnlagDTO(packet.hendelseData))
runBlocking {
val beregning = beregningService.beregn(behandlingId).body<BeregningDTO>()
packet[BEREGNING_KEY] = beregning
}
packet.eventName = Migreringshendelser.VEDTAK
context.publish(packet.toJson())
logger.info("Publiserte oppdatert migreringshendelse fra beregning for behandling $behandlingId")
}
}
}
private fun tilGrunnlagDTO(request: MigreringRequest): BarnepensjonBeregningsGrunnlag =
BarnepensjonBeregningsGrunnlag(
soeskenMedIBeregning = listOf(
GrunnlagMedPeriode(
fom = request.trygdetidsgrunnlag.fom,
tom = null,
data = request.persongalleri.soesken.map {
SoeskenMedIBeregning(foedselsnummer = Folkeregisteridentifikator.of(it), skalBrukes = true)
}
)
),
institusjonsopphold = emptyList()
)
} | 16 | Kotlin | 0 | 3 | 3f003be38db3c064b9a9d7b2af44f9668582bd4a | 3,285 | pensjon-etterlatte-saksbehandling | MIT License |
code/android/src/main/java/no/bakkenbaeck/porchpirateprotector/fragment/DeviceListFragment.kt | bakkenbaeck | 172,894,385 | false | null | package no.bakkenbaeck.porchpirateprotector.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.snackbar.Snackbar.LENGTH_LONG
import kotlinx.android.synthetic.main.fragment_device_list.*
import no.bakkenbaeck.pppshared.model.PairedDevice
import no.bakkenbaeck.porchpirateprotector.R
import no.bakkenbaeck.porchpirateprotector.adapter.DeviceListAdapter
import no.bakkenbaeck.porchpirateprotector.adapter.DeviceSelectionListener
import no.bakkenbaeck.porchpirateprotector.extension.updateAnimating
import no.bakkenbaeck.porchpirateprotector.fragment.DeviceDetailFragment.Companion.ARG_DEVICE
import no.bakkenbaeck.porchpirateprotector.manager.SharedPreferencesManager
import no.bakkenbaeck.pppshared.presenter.DeviceListPresenter
class DeviceListFragment: Fragment(), DeviceSelectionListener {
private val adapter by lazy { DeviceListAdapter(this) }
private val insecureStorage: SharedPreferencesManager
get() = SharedPreferencesManager(this.context!!)
private val presenter = DeviceListPresenter()
// FRAGMENT LIFECYCLE
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_device_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerview_device_list.layoutManager = LinearLayoutManager(context)
recyclerview_device_list.adapter = this.adapter
fab_add_device.setOnClickListener { showAddDevice() }
}
override fun onResume() {
super.onResume()
val viewState = presenter.updateViewState(insecureStorage)
configureForViewState(viewState)
}
override fun onDestroy() {
presenter.onDestroy()
super.onDestroy()
}
// DEVICE SELECTION LISTENER
override fun deviceSelected(device: PairedDevice) {
showDetailForDevice(device)
}
// VIEW STATE CONFIGURATION
private fun configureForViewState(viewState: DeviceListPresenter.DeviceListViewState) {
adapter.list = viewState.pairedDeviceList
progress_bar_device_list.updateAnimating(viewState.indicatorAnimating)
fab_add_device.isEnabled = viewState.addButtonEnabled
viewState.apiError?.let {
Snackbar.make(coordinator_device_list, it, LENGTH_LONG).show()
}
}
private fun showAddDevice() {
findNavController().navigate(R.id.action_deviceListFragment_to_addDeviceFragment)
}
private fun showDetailForDevice(device: PairedDevice) {
val bundle = Bundle().apply {
putString(ARG_DEVICE, device.toJSONString())
}
findNavController().navigate(R.id.action_deviceListFragment_to_deviceDetailFragment, bundle)
}
} | 0 | Kotlin | 6 | 26 | c99e5900d8fe4b5fbafd2607d118760e6e2793ff | 3,143 | PorchPirateProtector | MIT License |
app/src/main/java/com/aliasadi/clean/presentation/feed/FeedActivity.kt | AliAsadi | 264,456,753 | false | null | package com.aliasadi.clean.presentation.feed
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.get
import com.aliasadi.clean.R
import com.aliasadi.clean.presentation.base.BaseActivity
import com.aliasadi.clean.presentation.details.MovieDetailsActivity
import kotlinx.android.synthetic.main.activity_feed.*
import javax.inject.Inject
/**
* Created by <NAME> on 13/05/2020
*/
class FeedActivity : BaseActivity<FeedViewModel>(R.layout.activity_feed) {
@Inject
lateinit var factory: FeedViewModel.Factory
private var movieAdapter = MovieAdapter()
override fun createViewModel(): FeedViewModel {
return ViewModelProvider(this, factory).get()
}
override fun onCreate(savedInstanceState: Bundle?) {
daggerInjector.createFeedComponent().inject(this)
super.onCreate(savedInstanceState)
init()
observeViewModel()
setupViewListeners()
}
private fun init() {
recyclerView.adapter = movieAdapter
}
private fun setupViewListeners() {
loadButton.setOnClickListener {
viewModel.onLoadButtonClicked()
}
movieAdapter.setMovieClickListener { movie ->
viewModel.onMovieClicked(movie)
}
}
private fun observeViewModel() {
viewModel.getHideLoadingLiveData().observe {
progressBar.visibility = View.GONE
}
viewModel.getShowLoadingLiveData().observe {
progressBar.visibility = View.VISIBLE
}
viewModel.getMoviesLiveData().observe { movies ->
movieAdapter.setItems(movies)
}
viewModel.getNavigateToMovieDetails().observe { movie ->
MovieDetailsActivity.start(this, movie)
}
viewModel.getShowErrorLiveData().observe { error ->
Toast.makeText(this, error, Toast.LENGTH_LONG).show()
}
}
} | 0 | Kotlin | 9 | 39 | f3b9dbb30e443ec65a2ec4c3d77f34b01559e284 | 1,981 | Android-Clean-Architecture | Apache License 2.0 |
app/src/main/java/com/azamovhudstc/taskapp/data/remote/response/LessonsResponse.kt | professorDeveloper | 677,510,765 | false | null | package com.azamovhudstc.taskapp.data.remote.response
data class LessonsResponse(
val lessons: List<Lesson>
) | 0 | Kotlin | 0 | 1 | 6e32649e7145a91ee93c12057ed2a44149bac112 | 114 | Task-App | MIT License |
library/src/main/java/renetik/android/core/extensions/content/Context+Toast.kt | renetik | 506,035,450 | false | {"Kotlin": 180888} | package renetik.android.core.extensions.content
//import renetik.android.core.lang.CSEnvironment.app
import android.content.Context
import android.widget.Toast.LENGTH_LONG
import android.widget.Toast.LENGTH_SHORT
import android.widget.Toast.makeText
import renetik.android.core.extensions.content.CSToastLength.LongTime
import renetik.android.core.extensions.content.CSToastLength.ShortTime
import renetik.android.core.lang.CSEnvironment.app
object CSToast {
fun toast(text: String) = app.toast(text)
fun toast(text: String, time: CSToastLength = ShortTime) = app.toast(text, time)
}
fun Context.toast(text: String) = toast(text, LongTime)
fun Context.toast(text: String, time: CSToastLength = ShortTime) =
makeText(this, text, time.value).show()
enum class CSToastLength(val value: Int) {
LongTime(LENGTH_LONG), ShortTime(LENGTH_SHORT)
} | 0 | Kotlin | 1 | 1 | 5aaa579c3dacec9308a5007ff3f31c1bb370b38c | 859 | renetik-android-core | MIT License |
sample/src/main/java/com/arttttt/simplemvi/sample/timer/store/TimerMiddleware.kt | arttttt | 854,289,980 | false | {"Kotlin": 24209} | package com.arttttt.simplemvi.sample.timer.store
import android.util.Log
import com.arttttt.simplemvi.middleware.Middleware
class TimerMiddleware : Middleware<TimerStore.Intent, TimerStore.State, TimerStore.SideEffect> {
private val tag = "TimerMiddleware"
override fun onIntent(intent: TimerStore.Intent, state: TimerStore.State) {
logV(
"""
TimerStore received intent: $intent,
current state: $state,
""".trimIndent()
)
}
override fun onStateChanged(oldState: TimerStore.State, newState: TimerStore.State) {
logV(
"""
TimerStore changed state
old state: $oldState
new state: $newState
""".trimIndent()
)
}
override fun onSideEffect(sideEffect: TimerStore.SideEffect, state: TimerStore.State) {
logV(
"""
TimerStore emitted side effect: $sideEffect
current state: $state
""".trimIndent()
)
}
private fun logV(message: String) {
Log.v(tag, message)
}
} | 6 | Kotlin | 0 | 1 | 80315db2940fb09e6e0830e84a988e77b253aa8b | 1,135 | SimpleMVI | MIT License |
src/main/kotlin/no/nav/syfo/Bootstrap.kt | navikt | 172,480,575 | false | null | package no.nav.syfo
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import io.ktor.application.Application
import io.ktor.routing.routing
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import net.logstash.logback.argument.StructuredArguments.keyValue
import no.nav.syfo.api.registerNaisApi
import no.nav.syfo.util.connectionFactory
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.w3c.dom.Document
import org.xml.sax.InputSource
import java.io.StringReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import javax.jms.MessageConsumer
import javax.jms.Session
import javax.jms.TextMessage
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.xpath.XPathFactory
data class ApplicationState(var running: Boolean = true, var initialized: Boolean = false)
val objectMapper: ObjectMapper = ObjectMapper().apply {
registerKotlinModule()
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
}
val log: Logger = LoggerFactory.getLogger("no.nav.syfo.syfosmarenamock")
fun main() = runBlocking(Executors.newFixedThreadPool(2).asCoroutineDispatcher()) {
val config = ApplicationConfig()
val credentials: VaultCredentials = objectMapper.readValue(vaultApplicationPropertiesPath.toFile())
val applicationState = ApplicationState()
val applicationServer = embeddedServer(Netty, config.applicationPort) {
initRouting(applicationState)
}.start(wait = false)
connectionFactory(config).createConnection(credentials.mqUsername, credentials.mqPassword).use { connection ->
connection.start()
try {
val listeners = (1..config.applicationThreads).map {
launch {
val session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)
val inputQueue = session.createQueue(config.inputQueue)
val inputConsumer = session.createConsumer(inputQueue)
blockingApplicationLogic(config, applicationState, inputConsumer)
}
}.toList()
runBlocking {
Runtime.getRuntime().addShutdownHook(Thread {
applicationServer.stop(10, 10, TimeUnit.SECONDS)
})
applicationState.initialized = true
listeners.forEach { it.join() }
}
} finally {
applicationState.running = false
}
}
}
suspend fun blockingApplicationLogic(config: ApplicationConfig, applicationState: ApplicationState, inputConsumer: MessageConsumer) {
while (applicationState.running) {
val message = inputConsumer.receiveNoWait()
if (message == null) {
delay(100)
continue
}
try {
val inputMessageText = when (message) {
is TextMessage -> message.text
else -> throw RuntimeException("Incoming message needs to be a byte message or text message")
}
val smId = inputMessageText.extractXPath(config.smIdXpath)
if (config.notifyRestMock) {
val connection = URL("http://syfosmrestmock/api/v1/status").openConnection() as HttpURLConnection
try {
connection.requestMethod = "POST"
connection.doInput = true
connection.doOutput = true
// connection.addRequestProperty("Accept", "application/json")
connection.addRequestProperty("Content-Type", "application/json")
objectMapper.writeValue(connection.outputStream, mapOf(
"smId" to smId,
"step" to config.stepName
))
val response = connection.inputStream.readAllBytes()
if (connection.responseCode >= 200 || connection.responseCode <= 400) {
log.info("Received response with {} ${response.toString(Charsets.UTF_8)} from syfosmrestmock",
keyValue("responseCode", connection.responseCode))
} else {
log.error("Received response with {} ${response.toString(Charsets.UTF_8)} from syfosmrestmock",
keyValue("responseCode", connection.responseCode))
}
} finally {
connection.disconnect()
}
}
log.info("Message is read with {} with {}", keyValue("smId", smId), keyValue("step", config.stepName))
} catch (e: Exception) {
log.error("Exception caught while handling message", e)
}
delay(100)
}
}
fun String.extractXPath(xPath: String): String? = XPathFactory.newInstance().newXPath().evaluate(xPath, toXMLDocument())
fun String.toXMLDocument(): Document =
DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(InputSource(StringReader(this)))
fun Application.initRouting(applicationState: ApplicationState) {
routing {
registerNaisApi(
readynessCheck = { applicationState.initialized },
livenessCheck = { applicationState.running }
)
}
}
| 0 | Kotlin | 0 | 0 | ed9214a9dc3087a3eb5feff6db4a9f3f58567b76 | 5,683 | syfosmarenamock | MIT License |
src/main/kotlin/model/KbotProperties.kt | marius-brauterfallet | 818,308,765 | false | {"Kotlin": 28459, "HTML": 6953, "Dockerfile": 983} | package model
import java.util.*
class KbotProperties(properties: Properties) {
val appVersion = properties.getProperty("version")
?: throw IllegalStateException("Something went wrong when retrieving app properties")
} | 2 | Kotlin | 0 | 0 | 482ae5e3a46b6afa040c2c4119155c4fc84afee0 | 232 | kbot | MIT License |
educational-core/src/com/jetbrains/edu/learning/stepik/hyperskill/HyperskillService.kt | dstibbe | 155,983,569 | false | {"Text": 40, "Gradle": 2, "Java Properties": 7, "Python": 2, "HTML": 11, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "YAML": 1, "Markdown": 4, "XML": 63, "Java": 257, "Kotlin": 341, "SVG": 25, "JSON": 105, "JavaScript": 10, "CSS": 17, "INI": 2, "Diff": 5} | package com.jetbrains.edu.learning.stepik.hyperskill
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.jetbrains.edu.learning.authUtils.TokenInfo
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Path
import retrofit2.http.Query
@Suppress("unused")
interface HyperskillService {
@POST("oauth2/token/")
fun getTokens(
@Query("client_id") clientId: String,
@Query("redirect_uri") redirectUri: String,
@Query("code") code: String,
@Query("grant_type") grantType: String
): Call<TokenInfo>
@POST("oauth2/token/")
fun refreshTokens(
@Query("grant_type") grantType: String,
@Query("client_id") clientId: String,
@Query("refresh_token") refreshToken: String
): Call<TokenInfo>
@GET("api/users/{id}")
fun getUserInfo(@Path("id") userId: Int): Call<UsersData>
@GET("api/stages")
fun stages(@Query("project") projectId: Int): Call<StagesData>
@GET("api/topics")
fun topics(@Query("stage") stageId: Int): Call<TopicsData>
}
@JsonIgnoreProperties(ignoreUnknown = true)
class UsersData {
lateinit var meta: Any
lateinit var users: List<HyperskillUserInfo>
}
@JsonIgnoreProperties(ignoreUnknown = true)
class StagesData {
lateinit var meta: Any
lateinit var stages: List<HyperskillStage>
}
@JsonIgnoreProperties(ignoreUnknown = true)
class TopicsData {
lateinit var topics: List<HyperskillTopic>
}
@JsonIgnoreProperties(ignoreUnknown = true)
class HyperskillTopic {
var id: Int = -1
var title: String = ""
lateinit var children: List<String>
}
| 1 | null | 1 | 1 | 9cac107535925f52f858448eea7bf4f04bbda978 | 1,579 | educational-plugin | Apache License 2.0 |
androidApp/src/main/java/com/mbta/tid/mbta_app/android/util/managePinnedRoutes.kt | mbta | 718,216,969 | false | {"Kotlin": 1254365, "Swift": 613197, "Shell": 4593, "Ruby": 4129} | package com.mbta.tid.mbta_app.android.util
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import com.mbta.tid.mbta_app.repositories.IPinnedRoutesRepository
import com.mbta.tid.mbta_app.usecases.TogglePinnedRouteUsecase
import kotlinx.coroutines.launch
import org.koin.compose.koinInject
data class ManagedPinnedRoutes(
val pinnedRoutes: Set<String>?,
val togglePinnedRoute: (String) -> Unit
)
@Composable
fun managePinnedRoutes(
pinnedRoutesRepository: IPinnedRoutesRepository = koinInject(),
togglePinnedRouteUsecase: TogglePinnedRouteUsecase = koinInject()
): ManagedPinnedRoutes {
var pinnedRoutes: Set<String>? by remember { mutableStateOf(null) }
LaunchedEffect(null) { pinnedRoutes = pinnedRoutesRepository.getPinnedRoutes() }
val coroutineScope = rememberCoroutineScope()
val togglePinnedRoute: (String) -> Unit = { routeId ->
coroutineScope.launch {
togglePinnedRouteUsecase.execute(routeId)
pinnedRoutes = pinnedRoutesRepository.getPinnedRoutes()
}
}
return ManagedPinnedRoutes(pinnedRoutes, togglePinnedRoute)
}
| 10 | Kotlin | 0 | 2 | ddd64e58d541054904f5a9f03a2b67b51987a830 | 1,377 | mobile_app | MIT License |
Postgrest/src/commonMain/kotlin/io/github/jan/supabase/postgrest/request/DeleteRequest.kt | supabase-community | 495,084,592 | false | {"Kotlin": 601024} | package io.github.jan.supabase.postgrest.request
import io.github.jan.supabase.postgrest.query.Count
import io.github.jan.supabase.postgrest.query.Returning
import io.ktor.http.HttpMethod
@PublishedApi
internal class DeleteRequest(
private val returning: Returning = Returning.REPRESENTATION,
private val count: Count? = null,
override val filter: Map<String, List<String>>,
override val schema: String
) : PostgrestRequest {
override val method = HttpMethod.Delete
override val prefer = buildList {
add("return=${returning.identifier}")
if (count != null) add("count=${count.identifier}")
}
} | 9 | Kotlin | 24 | 211 | 81c10873ca169a506535cf43a2c633d9e85b0ba7 | 641 | supabase-kt | MIT License |
libs/networkInterface/src/main/java/com/solanamobile/mintyfresh/networkinterface/rpcconfig/IRpcConfig.kt | solana-mobile | 586,997,383 | false | {"Kotlin": 207429, "Shell": 1506} | package com.solanamobile.mintyfresh.networkinterface.rpcconfig
import com.solana.mobilewalletadapter.clientlib.Blockchain
import com.solana.mobilewalletadapter.clientlib.Solana
import com.solana.mobilewalletadapter.common.ProtocolContract
/**
* RPC config interface
*/
interface IRpcConfig {
/**
* A Solana RPC url.
* @see [https://docs.solana.com/api/http] for API docs
*/
val solanaRpcUrl: String
/**
* blockchain where requests/transactions are submit.
*/
val blockchain: Blockchain
}
val IRpcConfig.clusterName: String get() = when (blockchain) {
Solana.Devnet -> ProtocolContract.CLUSTER_DEVNET
Solana.Testnet -> ProtocolContract.CLUSTER_TESTNET
Solana.Mainnet -> ProtocolContract.CLUSTER_MAINNET_BETA
else -> blockchain.cluster
} | 13 | Kotlin | 17 | 42 | e06d6d3c4b45c5ed736e422ed622cac9cd330ce1 | 799 | Minty-fresh | Apache License 2.0 |
core/domain/src/main/java/com/uragiristereo/mikansei/core/domain/DomainModule.kt | uragiristereo | 583,834,091 | false | null | package com.uragiristereo.mikansei.core.domain
import com.uragiristereo.mikansei.core.domain.usecase.ConvertFileSizeUseCase
import com.uragiristereo.mikansei.core.domain.usecase.DownloadPostUseCase
import com.uragiristereo.mikansei.core.domain.usecase.DownloadPostWithNotificationUseCase
import com.uragiristereo.mikansei.core.domain.usecase.GetFavoriteGroupsUseCase
import com.uragiristereo.mikansei.core.domain.usecase.GetFavoritesAndFavoriteGroupsUseCase
import com.uragiristereo.mikansei.core.domain.usecase.GetFavoritesUseCase
import com.uragiristereo.mikansei.core.domain.usecase.GetPostsUseCase
import com.uragiristereo.mikansei.core.domain.usecase.GetTagsAutoCompleteUseCase
import com.uragiristereo.mikansei.core.domain.usecase.GetTagsUseCase
import com.uragiristereo.mikansei.core.domain.usecase.PerformLoginUseCase
import com.uragiristereo.mikansei.core.domain.usecase.SyncUserSettingsUseCase
import com.uragiristereo.mikansei.core.domain.usecase.UpdateUserSettingsUseCase
import org.koin.core.module.Module
import org.koin.core.module.dsl.factoryOf
import org.koin.dsl.module
object DomainModule {
operator fun invoke(): Module = module {
factoryOf(::GetPostsUseCase)
factoryOf(::GetTagsAutoCompleteUseCase)
factoryOf(::GetTagsUseCase)
factoryOf(::DownloadPostUseCase)
factoryOf(::DownloadPostWithNotificationUseCase)
factoryOf(::ConvertFileSizeUseCase)
factoryOf(::PerformLoginUseCase)
factoryOf(::SyncUserSettingsUseCase)
factoryOf(::UpdateUserSettingsUseCase)
factoryOf(::GetFavoritesUseCase)
factoryOf(::GetFavoriteGroupsUseCase)
factoryOf(::GetFavoritesAndFavoriteGroupsUseCase)
}
}
| 0 | null | 2 | 6 | d38021420f4015677378fa879b0db6e52299b14a | 1,706 | Mikansei | Apache License 2.0 |
feature/onboarding/src/main/kotlin/net/thunderbird/feature/onboarding/navigation/OnboardingNavigation.kt | airathalca | 629,495,779 | false | null | package net.thunderbird.feature.onboarding.navigation
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavOptions
import androidx.navigation.compose.composable
import net.thunderbird.feature.onboarding.OnboardingScreen
const val NAVIGATION_ROUTE_ONBOARDING = "onboarding"
fun NavController.navigateToOnboarding(
navOptions: NavOptions? = null,
) {
navigate(NAVIGATION_ROUTE_ONBOARDING, navOptions)
}
fun NavGraphBuilder.onboardingScreen(
onStartClick: () -> Unit,
onImportClick: () -> Unit,
) {
composable(route = NAVIGATION_ROUTE_ONBOARDING) {
OnboardingScreen(
onStartClick = onStartClick,
onImportClick = onImportClick,
)
}
}
| 0 | Kotlin | 1 | 0 | 2eeecbb4c57b561efe50d5f35fccd2ce20a78633 | 759 | Email-Client-With-Signature | Apache License 2.0 |
sample/src/androidTest/java/com/kaspersky/kaspressample/measure_tests/KautomatorMeasureTest.kt | crim3hound | 238,460,769 | true | {"Kotlin": 466447, "Java": 10748} | package com.kaspersky.kaspressample.measure_tests
import android.Manifest
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.rule.ActivityTestRule
import androidx.test.rule.GrantPermissionRule
import com.kaspersky.kaspressample.MainActivity
import com.kaspersky.kaspressample.R
import com.kaspersky.kaspressample.external_screens.UiCommonFlakyScreen
import com.kaspersky.kaspressample.external_screens.UiMainScreen
import com.kaspersky.kaspressample.external_screens.UiSimpleScreen
import com.kaspersky.kaspressample.external_screens.UiWaitForIdleScreen
import com.kaspersky.kaspresso.idlewaiting.KautomatorWaitForIdleSettings
import com.kaspersky.kaspresso.kaspresso.Kaspresso
import com.kaspersky.kaspresso.testcases.api.testcase.TestCase
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class KautomatorMeasureTest : TestCase(
kaspressoBuilder = Kaspresso.Builder.advanced {
kautomatorWaitForIdleSettings = KautomatorWaitForIdleSettings.boost()
}
) {
companion object {
private val RANGE = 0..20
}
@get:Rule
val runtimePermissionRule: GrantPermissionRule = GrantPermissionRule.grant(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE
)
@get:Rule
val activityTestRule = ActivityTestRule(MainActivity::class.java, true, false)
@Test
fun test() =
before {
activityTestRule.launchActivity(null)
}.after {}.run {
step("MainScreen. Check `simple fragment` button existence and click") {
UiMainScreen {
simpleButton {
isDisplayed()
hasText(device.targetContext.getString(R.string.main_screen_simple_fragment_button).toUpperCase())
click()
}
}
}
step("Simple fragment. Work with buttons") {
UiSimpleScreen {
button1 {
isDisplayed()
hasText(device.targetContext.getString(R.string.simple_fragment_text_button_1).toUpperCase())
click()
}
button2 {
isDisplayed()
hasText(device.targetContext.getString(R.string.simple_fragment_text_button_2).toUpperCase())
click()
}
}
}
step("Simple fragment. Work with EditText in the cycle") {
UiSimpleScreen {
edit {
isDisplayed()
hasText(device.targetContext.getString(R.string.simple_fragment_text_edittext))
(RANGE).forEach { _ ->
clearText()
typeText("bla-bla-bla")
hasText("bla-bla-bla")
clearText()
typeText("mo-mo-mo")
hasText("mo-mo-mo")
clearText()
}
}
}
}
step("Return to MainScreen") {
UiSimpleScreen {
pressBack()
}
}
step("MainScreen. Check `flaky sample` button existence and click") {
UiMainScreen {
flakyButton {
isDisplayed()
hasText(device.targetContext.getString(R.string.main_screen_scroll_view_sample_button).toUpperCase())
click()
}
}
}
step("FlakyScreen. Check btn5") {
UiCommonFlakyScreen {
btn5 {
isDisplayed()
hasText("5")
}
}
}
step("Return to MainScreen") {
UiCommonFlakyScreen {
pressBack()
}
}
step("MainScreen. Check `waiting for idle sample` button existence and click") {
UiMainScreen {
idleWaitingButton {
isDisplayed()
hasText(device.targetContext.getString(R.string.main_screen_idlewaiting_sample_button).toUpperCase())
click()
}
}
}
step("UiWaitForIdleScreen. Check text in EditText") {
UiWaitForIdleScreen {
edit {
isDisplayed()
containsText(device.targetContext.getString(R.string.idlewaiting_fragment_text_edittext))
}
}
}
}
} | 0 | null | 0 | 0 | 449472fe7be57fa7f1688907e89b89d08126debb | 4,950 | Kaspresso | Apache License 2.0 |
prime-router/src/test/kotlin/MapperTests.kt | whytheplatypus | 428,428,846 | true | {"Kotlin": 1059439, "HCL": 96860, "HTML": 95370, "Shell": 73658, "CSS": 40381, "JavaScript": 30028, "TypeScript": 24137, "Liquid": 22909, "PLpgSQL": 12858, "Python": 5842, "Makefile": 5603, "Dockerfile": 3100} | package gov.cdc.prime.router
import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.isNull
import java.io.ByteArrayInputStream
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
import kotlin.test.fail
class MapperTests {
private val livdPath = "./metadata/tables/LIVD-SARS-CoV-2-2021-01-20.csv"
@Test
fun `test MiddleInitialMapper`() {
val mapper = MiddleInitialMapper()
val args = listOf("test_element")
val element = Element("test")
assertThat(mapper.apply(element, args, listOf(ElementAndValue(element, "Rick")))).isEqualTo("R")
assertThat(mapper.apply(element, args, listOf(ElementAndValue(element, "rick")))).isEqualTo("R")
}
@Test
fun `test LookupMapper`() {
val csv = """
a,b,c
1,2,x
3,4,y
5,6,z
""".trimIndent()
val table = LookupTable.read(ByteArrayInputStream(csv.toByteArray()))
val schema = Schema(
"test", topic = "test",
elements = listOf(
Element("a", type = Element.Type.TABLE, table = "test", tableColumn = "a"),
Element("c", type = Element.Type.TABLE, table = "test", tableColumn = "c")
)
)
val metadata = Metadata(schema = schema, table = table, tableName = "test")
val indexElement = metadata.findSchema("test")?.findElement("a") ?: fail("")
val lookupElement = metadata.findSchema("test")?.findElement("c") ?: fail("")
val mapper = LookupMapper()
val args = listOf("a")
assertThat(mapper.valueNames(lookupElement, args)).isEqualTo(listOf("a"))
assertThat(mapper.apply(lookupElement, args, listOf(ElementAndValue(indexElement, "3")))).isEqualTo("y")
}
@Test
fun `test LookupMapper with two`() {
val csv = """
a,b,c
1,2,x
3,4,y
5,6,z
""".trimIndent()
val table = LookupTable.read(ByteArrayInputStream(csv.toByteArray()))
val schema = Schema(
"test", topic = "test",
elements = listOf(
Element("a", type = Element.Type.TABLE, table = "test", tableColumn = "a"),
Element("b", type = Element.Type.TABLE, table = "test", tableColumn = "b"),
Element("c", type = Element.Type.TABLE, table = "test", tableColumn = "c")
)
)
val metadata = Metadata(schema = schema, table = table, tableName = "test")
val lookupElement = metadata.findSchema("test")?.findElement("c") ?: fail("")
val indexElement = metadata.findSchema("test")?.findElement("a") ?: fail("")
val index2Element = metadata.findSchema("test")?.findElement("b") ?: fail("")
val mapper = LookupMapper()
val args = listOf("a", "b")
val elementAndValues = listOf(ElementAndValue(indexElement, "3"), ElementAndValue(index2Element, "4"))
assertThat(mapper.valueNames(lookupElement, args)).isEqualTo(listOf("a", "b"))
assertThat(mapper.apply(lookupElement, args, elementAndValues)).isEqualTo("y")
}
@Test
fun `test livdLookup with DeviceId`() {
val lookupTable = LookupTable.read(livdPath)
val codeElement = Element(
"ordered_test_code",
tableRef = lookupTable,
tableColumn = "Test Ordered LOINC Code"
)
val deviceElement = Element("device_id")
val mapper = LIVDLookupMapper()
// Test with a EUA
val ev1 = ElementAndValue(
deviceElement,
"BinaxNOW COVID-19 Ag Card Home Test_Abbott Diagnostics Scarborough, Inc._EUA"
)
assertEquals("94558-4", mapper.apply(codeElement, emptyList(), listOf(ev1)))
// Test with a truncated device ID
val ev1a = ElementAndValue(deviceElement, "BinaxNOW COVID-19 Ag Card Home Test_Abb#")
assertEquals("94558-4", mapper.apply(codeElement, emptyList(), listOf(ev1a)))
// Test with a ID NOW device id which is has a FDA number
val ev2 = ElementAndValue(deviceElement, "10811877011269_DII")
assertEquals("94534-5", mapper.apply(codeElement, emptyList(), listOf(ev2)))
// With GUDID DI
val ev3 = ElementAndValue(deviceElement, "10811877011269")
assertEquals("94534-5", mapper.apply(codeElement, emptyList(), listOf(ev3)))
}
@Test
fun `test livdLookup with Equipment Model Name`() {
val lookupTable = LookupTable.read(livdPath)
val codeElement = Element(
"ordered_test_code",
tableRef = lookupTable,
tableColumn = "Test Ordered LOINC Code"
)
val modelElement = Element("equipment_model_name")
val mapper = LIVDLookupMapper()
// Test with a EUA
val ev1 = ElementAndValue(modelElement, "BinaxNOW COVID-19 Ag Card")
assertEquals("94558-4", mapper.apply(codeElement, emptyList(), listOf(ev1)))
// Test with a ID NOW device id
val ev2 = ElementAndValue(modelElement, "ID NOW")
assertEquals("94534-5", mapper.apply(codeElement, emptyList(), listOf(ev2)))
}
@Test
fun `test livdLookup for Sofia 2`() {
val lookupTable = LookupTable.read("./metadata/tables/LIVD-SARS-CoV-2-2021-04-28.csv")
val codeElement = Element(
"ordered_test_code",
tableRef = lookupTable,
tableColumn = "Test Performed LOINC Long Name"
)
val modelElement = Element("equipment_model_name")
val testPerformedElement = Element("test_performed_code")
val mapper = LIVDLookupMapper()
mapper.apply(
codeElement,
emptyList(),
listOf(
ElementAndValue(modelElement, "Sofia 2 Flu + SARS Antigen FIA*"),
ElementAndValue(testPerformedElement, "95209-3")
)
).let {
assertThat(it)
.equals("SARS-CoV+SARS-CoV-2 (COVID-19) Ag [Presence] in Respiratory specimen by Rapid immunoassay")
}
}
@Test
fun `test livdLookup supplemental table by device_id`() {
val lookupTable = LookupTable.read("./metadata/tables/LIVD-Supplemental-2021-06-07.csv")
val codeElement = Element(
"test_authorized_for_otc",
tableRef = lookupTable,
tableColumn = "is_otc"
)
val deviceElement = Element("device_id")
val mapper = LIVDLookupMapper()
// Test with an FDA device id
val ev1 = ElementAndValue(deviceElement, "10811877011337")
assertEquals("N", mapper.apply(codeElement, emptyList(), listOf(ev1)))
// Test with a truncated device ID
val ev1a = ElementAndValue(deviceElement, "BinaxNOW COVID-19 Ag Card 2 Home#")
assertEquals("Y", mapper.apply(codeElement, emptyList(), listOf(ev1a)))
}
@Test
fun `test livdLookup supplemental table by model`() {
val lookupTable = LookupTable.read("./metadata/tables/LIVD-Supplemental-2021-06-07.csv")
val codeElement = Element(
"test_authorized_for_otc",
tableRef = lookupTable,
tableColumn = "is_otc"
)
val deviceElement = Element("equipment_model_name")
val mapper = LIVDLookupMapper()
// Test with an FDA device id
val ev1 = ElementAndValue(deviceElement, "BinaxNOW COVID-19 Ag Card Home Test")
assertEquals("N", mapper.apply(codeElement, emptyList(), listOf(ev1)))
// Test with another
val ev1a = ElementAndValue(deviceElement, "BinaxNOW COVID-19 Ag Card 2 Home Test")
assertEquals("Y", mapper.apply(codeElement, emptyList(), listOf(ev1a)))
}
@Test
fun `test ifPresent`() {
val element = Element("a")
val mapper = IfPresentMapper()
val args = listOf("a", "const")
assertThat(mapper.valueNames(element, args)).isEqualTo(listOf("a"))
assertThat(mapper.apply(element, args, listOf(ElementAndValue(element, "3")))).isEqualTo("const")
assertThat(mapper.apply(element, args, emptyList())).isNull()
}
@Test
fun `test use`() {
val elementA = Element("a")
val elementB = Element("b")
val elementC = Element("c")
val mapper = UseMapper()
val args = listOf("b", "c")
assertThat(mapper.valueNames(elementA, args)).isEqualTo(listOf("b", "c"))
assertThat(
mapper.apply(elementA, args, listOf(ElementAndValue(elementB, "B"), ElementAndValue(elementC, "C")))
).isEqualTo("B")
assertThat(mapper.apply(elementA, args, listOf(ElementAndValue(elementC, "C")))).isEqualTo("C")
assertThat(mapper.apply(elementA, args, emptyList())).isNull()
}
@Test
fun `test ConcatenateMapper`() {
val mapper = ConcatenateMapper()
val args = listOf("a", "b", "c")
val elementA = Element("a")
val elementB = Element("b")
val elementC = Element("c")
val values = listOf(
ElementAndValue(elementA, "string1"),
ElementAndValue(elementB, "string2"),
ElementAndValue(elementC, "string3")
)
assertThat(mapper.apply(elementA, args, values)).isEqualTo("string1, string2, string3")
}
@Test
fun `test concatenate mapper with custom delimiter`() {
// arrange
val mapper = ConcatenateMapper()
val args = listOf("a", "b", "c")
val elementA = Element("a", delimiter = "^")
val elementB = Element("b")
val elementC = Element("c")
val values = listOf(
ElementAndValue(elementA, "string1"),
ElementAndValue(elementB, "string2"),
ElementAndValue(elementC, "string3")
)
// act
val expected = "string1^string2^string3"
val actual = mapper.apply(elementA, args, values)
// assert
assertThat(actual).isEqualTo(expected)
}
@Test
fun `test date time offset mapper with seconds`() {
// arrange
val mapper = DateTimeOffsetMapper()
val args = listOf(
"a",
"seconds",
"6"
)
val element = Element("a")
val values = listOf(
ElementAndValue(element, "202103020000-0600")
)
// act
val expected = "20210302000006.0000-0600"
val actual = mapper.apply(element, args, values)
// assert
assertThat(actual).isEqualTo(expected)
}
@Test
fun `test date time offset mapper with negative seconds`() {
// arrange
val mapper = DateTimeOffsetMapper()
val args = listOf(
"a",
"seconds",
"-6"
)
val element = Element("a")
val values = listOf(
ElementAndValue(element, "20210302000006.0000-0600")
)
// act
val expected = "20210302000000.0000-0600"
val actual = mapper.apply(element, args, values)
// assert
assertThat(actual).isEqualTo(expected)
}
@Test
fun `test date time offset mapper with minutes`() {
// arrange
val mapper = DateTimeOffsetMapper()
val args = listOf(
"a",
"minutes",
"1"
)
val element = Element("a")
val values = listOf(
ElementAndValue(element, "202103020000-0600")
)
// act
val expected = "20210302000100.0000-0600"
val actual = mapper.apply(element, args, values)
// assert
assertThat(actual).isEqualTo(expected)
}
@Test
fun `test date time offset mapper with negative minutes`() {
// arrange
val mapper = DateTimeOffsetMapper()
val args = listOf(
"a",
"minutes",
"-1"
)
val element = Element("a")
val values = listOf(
ElementAndValue(element, "20210302000100.0000-0600")
)
// act
val expected = "20210302000000.0000-0600"
val actual = mapper.apply(element, args, values)
// assert
assertEquals(expected, actual, "Expected $expected. Actual: $actual")
assertThat(actual).isEqualTo(expected)
}
@Test
fun `test coalesce mapper`() {
// arrange
val mapper = CoalesceMapper()
val args = listOf("a", "b", "c")
val element = Element("target")
var values = listOf(
ElementAndValue(Element("a"), ""),
ElementAndValue(Element("b"), ""),
ElementAndValue(Element("c"), "c")
)
// act
var expected = "c"
var actual = mapper.apply(element, args, values)
// assert
assertEquals(expected, actual, "Expected $expected. Actual $actual")
values = listOf(
ElementAndValue(Element("a"), ""),
ElementAndValue(Element("b"), "b"),
ElementAndValue(Element("c"), "c")
)
expected = "b"
actual = mapper.apply(element, args, values)
assertThat(actual).isEqualTo(expected)
}
@Test
fun `test strip formatting mapper`() {
val mapper = StripPhoneFormattingMapper()
val args = listOf("patient_phone_number_raw")
val element = Element("patient_phone_number")
val values = listOf(
ElementAndValue(Element("patient_phone_number_raw"), "(850) 999-9999xHOME")
)
val expected = "8509999999:1:"
val actual = mapper.apply(element, args, values)
assertThat(actual).isEqualTo(expected)
}
@Test
fun `test strip numeric mapper`() {
val mapper = StripNumericDataMapper()
val args = listOf("patient_age_and_units")
val element = Element("patient_age")
val values = listOf(
ElementAndValue(Element("patient_age_and_units"), "99 years")
)
val expected = "years"
val actual = mapper.apply(element, args, values)
assertThat(actual).isEqualTo(expected)
}
@Test
fun `test strip non numeric mapper`() {
val mapper = StripNonNumericDataMapper()
val args = listOf("patient_age_and_units")
val element = Element("patient_age")
val values = listOf(
ElementAndValue(Element("patient_age_and_units"), "99 years")
)
val expected = "99"
val actual = mapper.apply(element, args, values)
assertThat(actual).isEqualTo(expected)
}
@Test
fun `test split mapper`() {
val mapper = SplitMapper()
val args = listOf("patient_name", "0")
val element = Element("patient_first_name")
val values = listOf(
ElementAndValue(Element("patient_name"), "John Doe")
)
val expected = "John"
val actual = mapper.apply(element, args, values)
assertThat(actual).isEqualTo(expected)
}
@Test
fun `test split mapper with error condition`() {
val mapper = SplitMapper()
val args = listOf("patient_name", "1")
val element = Element("patient_first_name")
val values = listOf(
ElementAndValue(Element("patient_name"), "ThereAreNoSpacesHere")
)
val actual = mapper.apply(element, args, values)
assertThat(actual).isNull()
}
@Test
fun `test split by comma mapper`() {
val mapper = SplitByCommaMapper()
val args = listOf("patient_name", "2")
val element = Element("patient_first_name")
val values = listOf(
ElementAndValue(Element("patient_name"), "Antley, ARNP, Mona")
)
val expected = "Mona"
val actual = mapper.apply(element, args, values)
assertThat(actual).isEqualTo(expected)
}
@Test
fun `test split by comma mapper error condition`() {
val mapper = SplitByCommaMapper()
val args = listOf("patient_name", "2")
val element = Element("patient_first_name")
val values = listOf(
ElementAndValue(Element("patient_name"), "I have no commas")
)
val actual = mapper.apply(element, args, values)
assertThat(actual).isNull()
}
@Test
fun `test zip code to county mapper`() {
val mapper = ZipCodeToCountyMapper()
val csv = """
zipcode,county
32303,Leon
""".trimIndent()
val table = LookupTable.read(ByteArrayInputStream(csv.toByteArray()))
val schema = Schema(
"test", topic = "test",
elements = listOf(
Element("a", type = Element.Type.TABLE, table = "test", tableColumn = "a"),
)
)
val metadata = Metadata(schema = schema, table = table, tableName = "test")
val lookupElement = metadata.findSchema("test")?.findElement("a") ?: fail("Schema element missing")
val values = listOf(
ElementAndValue(Element("patient_zip_code"), "32303-4509")
)
val expected = "Leon"
val actual = mapper.apply(lookupElement, listOf("patient_zip_code"), values)
assertThat(actual).isEqualTo(expected)
}
@Test
fun `test HashMapper`() {
val mapper = HashMapper()
val elementA = Element("a")
val elementB = Element("b")
val elementC = Element("c")
// Single value conversion
val arg = listOf("a")
val value = listOf(ElementAndValue(elementA, "6086edf8e412650032408e96"))
assertThat(mapper.apply(elementA, arg, value))
.isEqualTo("47496cafa04e9c489444b60575399f51e9abc061f4fdda40c31d814325bfc223")
// Multiple values concatenated
val args = listOf("a", "b", "c")
val values = listOf(
ElementAndValue(elementA, "string1"),
ElementAndValue(elementB, "string2"),
ElementAndValue(elementC, "string3")
)
assertThat(mapper.apply(elementA, args, values))
.isEqualTo("c8fa773cd54e7a7eb7ca08577d0bd23e6ce3a73e61df176213d9ec90f06cb45f")
// Unhappy path cases
assertFails { mapper.apply(elementA, listOf(), listOf()) } // must pass a field name
assertThat(mapper.apply(elementA, arg, listOf())).isNull() // column not found in the data.
// column has empty data
assertThat(mapper.apply(elementA, arg, listOf(ElementAndValue(elementA, "")))).isNull()
}
} | 26 | Kotlin | 0 | 0 | e35be69be726b1ecfc15bac324af3b7cd628500d | 18,492 | prime-reportstream | Creative Commons Zero v1.0 Universal |
app/src/main/java/com/cameronvwilliams/raise/di/PerFragment.kt | RaiseSoftware | 119,627,507 | false | null | package com.cameronvwilliams.raise.di
import javax.inject.Scope
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class PerFragment
| 1 | null | 1 | 4 | 3cd0786dba77645efa5508a662478e5893037919 | 142 | Raise-Android | MIT License |
widgetssdk/src/main/java/com/glia/widgets/view/unifiedui/theme/SnackBarTheme.kt | salemove | 312,288,713 | false | {"Kotlin": 1962263, "Java": 448482, "Shell": 1802} | package com.glia.widgets.view.unifiedui.theme
import com.glia.widgets.view.unifiedui.Mergeable
import com.glia.widgets.view.unifiedui.merge
import com.glia.widgets.view.unifiedui.theme.base.ColorTheme
internal data class SnackBarTheme(
val backgroundColorTheme: ColorTheme?,
val textColorTheme: ColorTheme?
) : Mergeable<SnackBarTheme> {
override fun merge(other: SnackBarTheme): SnackBarTheme = SnackBarTheme(
backgroundColorTheme = backgroundColorTheme merge other.backgroundColorTheme,
textColorTheme = textColorTheme merge other.textColorTheme
)
}
| 3 | Kotlin | 1 | 7 | 0a8101cc7e6d8347eafd5ee88334157e9eb6936d | 586 | android-sdk-widgets | MIT License |
app/src/main/java/ru/tech/cookhelper/presentation/pick_products/viewModel/PickProductsViewModel.kt | T8RIN | 483,296,940 | false | null | package ru.tech.cookhelper.presentation.pick_products.viewModel
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ErrorOutline
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import ru.tech.cookhelper.core.onEmpty
import ru.tech.cookhelper.core.onError
import ru.tech.cookhelper.core.onSuccess
import ru.tech.cookhelper.core.utils.kotlin.cptlize
import ru.tech.cookhelper.domain.model.Product
import ru.tech.cookhelper.domain.use_case.get_available_products.GetAvailableProductsUseCase
import ru.tech.cookhelper.domain.use_case.get_user.GetUserUseCase
import ru.tech.cookhelper.presentation.app.components.UserState
import ru.tech.cookhelper.presentation.ui.utils.compose.StateUtils.update
import ru.tech.cookhelper.presentation.ui.utils.compose.UIText
import ru.tech.cookhelper.presentation.ui.utils.event.Event
import ru.tech.cookhelper.presentation.ui.utils.event.ViewModelEvents
import ru.tech.cookhelper.presentation.ui.utils.event.ViewModelEventsImpl
import ru.tech.cookhelper.presentation.ui.utils.getUIText
import javax.inject.Inject
@HiltViewModel
class PickProductsViewModel @Inject constructor(
getUserUseCase: GetUserUseCase,
getAvailableProductsUseCase: GetAvailableProductsUseCase
) : ViewModel(), ViewModelEvents<Event> by ViewModelEventsImpl() {
private val _selectedProducts: SnapshotStateList<Product> = mutableStateListOf()
val selectedProducts: List<Product> = _selectedProducts
private val _allProducts: SnapshotStateList<Product> = mutableStateListOf()
val allProducts: List<Product> = _allProducts
private val _user: MutableState<UserState> = mutableStateOf(UserState())
val userState: UserState by _user
private val _loadingProducts: MutableState<Boolean> = mutableStateOf(false)
val loadingProducts: Boolean by _loadingProducts
init {
getUserUseCase().onEach {
_user.update { UserState(it) }
}.launchIn(viewModelScope)
viewModelScope.launch {
_loadingProducts.update { true }
getAvailableProductsUseCase()
.onSuccess {
_allProducts.clear()
_allProducts.addAll(this.map { it.copy(title = it.title.cptlize()) })
}.onEmpty {
sendEvent(
Event.ShowToast(
getUIText(),
Icons.Rounded.ErrorOutline
)
)
}.onError {
sendEvent(
Event.ShowToast(
UIText.UIText(this),
Icons.Rounded.ErrorOutline
)
)
}.also { _loadingProducts.update { false } }
}
}
fun addProductToSelection(product: Product) {
_selectedProducts.add(product)
}
fun removeProductFromSelection(product: Product) {
_selectedProducts.remove(product)
}
} | 1 | Kotlin | 10 | 91 | cee8f8d8cd6bfc53e88c461edc1c9aaf43ce18c7 | 3,455 | CookHelper | Apache License 2.0 |
app/viewmodeldemo/src/main/java/com/example/viewmodeldemo/ui/activity/vm/DemoAndroidViewModel.kt | False-Mask | 387,738,713 | false | null | package com.example.viewmodeldemo.ui.activity.vm
import android.app.Application
import androidx.lifecycle.AndroidViewModel
/**
*@author <NAME>
*@time 2021/7/19 21:06
*@signature 我们不明前路,却已在路上
*/
class DemoAndroidViewModel(application: Application) : AndroidViewModel(application) {
val mApplication = getApplication<Application>()
} | 0 | Kotlin | 2 | 4 | d0d84724a73f8ec48ca76cd11a80023b214ddb60 | 344 | JetpackDemos | Apache License 2.0 |
src/test/kotlin/com/github/florianholzapfel/gtin/GtinTest.kt | florianholzapfel | 368,671,482 | false | null | package com.github.florianholzapfel.gtin
import strikt.api.expectThat
import strikt.assertions.isEqualTo
import strikt.assertions.isFalse
import strikt.assertions.isTrue
import kotlin.test.Test
class GtinTest {
@Test
fun testIsGtin() {
val list = arrayOf(
Pair("abcdabcdabcd", false),
Pair("1234", false),
Pair("123412341", false),
Pair("12341234123412341", false),
Pair("12341234", true),
Pair("123412341234", true),
Pair("1234123412343", true),
Pair("12341234123434", true)
)
for (it in list) {
val gtin = isGtin(it.first)
expectThat(gtin).isEqualTo(it.second)
}
}
@Test
fun testIsValid() {
val list = arrayOf(
"12341238",
"012000007897",
"1234123412344",
"12341234123413"
)
for (it in list) {
expectThat(isGtinValid(it)).isTrue()
}
}
@Test
fun testPartialBarcodeIsValid() {
val list = arrayOf(
Pair("1234123", 8),
Pair("01200000789", 7),
Pair("123412341234", 4),
Pair("1234123412341", 3)
)
for (it in list) {
for (i in 0..9) {
if (i == it.second) continue
expectThat(isGtinValid("${it.first}${i}")).isFalse()
}
expectThat(isGtinValid("${it.first}${it.second}")).isTrue()
}
}
} | 0 | Kotlin | 0 | 0 | 5cb64064a2f396c0edbcc5200c8919e3c59e30d2 | 1,515 | gtin | MIT License |
app/src/main/java/top/yogiczy/mytv/ui/utils/ModifierUtils.kt | yaoxieyoulei | 784,724,425 | false | {"Kotlin": 141358, "HTML": 14393} | package top.yogiczy.mytv.ui.utils
import android.os.Build
import android.view.KeyEvent
import androidx.compose.foundation.gestures.detectVerticalDragGestures
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.util.VelocityTracker
import androidx.compose.ui.unit.dp
/**
* 监听短按、长按按键事件
*/
fun Modifier.handleKeyEvents(
onKeyTap: Map<Int, () -> Unit> = emptyMap(),
onKeyLongTap: Map<Int, () -> Unit> = emptyMap(),
): Modifier {
val keyDownMap = mutableMapOf<Int, Boolean>()
return onKeyEvent {
when (it.nativeKeyEvent.action) {
KeyEvent.ACTION_DOWN -> {
if (it.nativeKeyEvent.repeatCount == 0) {
keyDownMap[it.nativeKeyEvent.keyCode] = true
} else if (it.nativeKeyEvent.repeatCount == 1) {
onKeyLongTap[it.nativeKeyEvent.keyCode]?.invoke()
keyDownMap.remove(it.nativeKeyEvent.keyCode)
}
}
KeyEvent.ACTION_UP -> {
if (keyDownMap[it.nativeKeyEvent.keyCode] != true) return@onKeyEvent true
keyDownMap.remove(it.nativeKeyEvent.keyCode)
onKeyTap[it.nativeKeyEvent.keyCode]?.invoke()
}
}
true
}
}
/**
* 监听全方位的DPad按键事件
*/
fun Modifier.handleDPadKeyEvents(
onLeft: (() -> Unit) = {},
onRight: (() -> Unit) = {},
onUp: (() -> Unit) = {},
onDown: (() -> Unit) = {},
onEnter: (() -> Unit) = {},
onLongEnter: (() -> Unit) = {},
onSettings: (() -> Unit) = {},
onNumber: ((Int) -> Unit) = {},
) = handleKeyEvents(
onKeyTap = mapOf(
KeyEvent.KEYCODE_DPAD_LEFT to onLeft,
KeyEvent.KEYCODE_DPAD_RIGHT to onRight,
KeyEvent.KEYCODE_DPAD_UP to onUp,
KeyEvent.KEYCODE_CHANNEL_UP to onUp,
KeyEvent.KEYCODE_DPAD_DOWN to onDown,
KeyEvent.KEYCODE_CHANNEL_DOWN to onDown,
KeyEvent.KEYCODE_DPAD_CENTER to onEnter,
KeyEvent.KEYCODE_ENTER to onEnter,
KeyEvent.KEYCODE_NUMPAD_ENTER to onEnter,
KeyEvent.KEYCODE_MENU to onSettings,
KeyEvent.KEYCODE_SETTINGS to onSettings,
KeyEvent.KEYCODE_HELP to onSettings,
KeyEvent.KEYCODE_H to onSettings,
KeyEvent.KEYCODE_UNKNOWN to onSettings,
KeyEvent.KEYCODE_0 to { onNumber(0) },
KeyEvent.KEYCODE_1 to { onNumber(1) },
KeyEvent.KEYCODE_2 to { onNumber(2) },
KeyEvent.KEYCODE_3 to { onNumber(3) },
KeyEvent.KEYCODE_4 to { onNumber(4) },
KeyEvent.KEYCODE_5 to { onNumber(5) },
KeyEvent.KEYCODE_6 to { onNumber(6) },
KeyEvent.KEYCODE_7 to { onNumber(7) },
KeyEvent.KEYCODE_8 to { onNumber(8) },
KeyEvent.KEYCODE_9 to { onNumber(9) },
).apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
KeyEvent.KEYCODE_SYSTEM_NAVIGATION_LEFT to onLeft
KeyEvent.KEYCODE_SYSTEM_NAVIGATION_RIGHT to onRight
KeyEvent.KEYCODE_SYSTEM_NAVIGATION_UP to onUp
KeyEvent.KEYCODE_SYSTEM_NAVIGATION_DOWN to onDown
}
},
onKeyLongTap = mapOf(
KeyEvent.KEYCODE_ENTER to onLongEnter,
KeyEvent.KEYCODE_NUMPAD_ENTER to onLongEnter,
KeyEvent.KEYCODE_DPAD_CENTER to onLongEnter,
),
)
/**
* 监听手势上下滑动事件
*/
@Composable
fun Modifier.handleVerticalDragGestures(
onSwipeUp: () -> Unit = {},
onSwipeDown: () -> Unit = {},
): Modifier {
val verticalTracker = remember { VelocityTracker() }
val swipeThreshold = 100.dp
return this then pointerInput(Unit) {
detectVerticalDragGestures(
onDragEnd = {
if (verticalTracker.calculateVelocity().y > swipeThreshold.toPx()) {
onSwipeDown()
} else if (verticalTracker.calculateVelocity().y < -swipeThreshold.toPx()) {
onSwipeUp()
}
},
) { change, _ ->
verticalTracker.addPosition(change.uptimeMillis, change.position)
}
}
} | 2 | Kotlin | 2 | 5 | ccb342c61394ca1d129041219c1317197c773d04 | 4,220 | mytv-android | MIT License |
src/main/kotlin/com/kneelawk/packvulcan/util/CacheExt.kt | Kneelawk | 464,289,102 | false | {"Kotlin": 540809} | package com.kneelawk.packvulcan.util
import com.github.benmanes.caffeine.cache.AsyncCache
import com.github.benmanes.caffeine.cache.AsyncLoadingCache
import com.github.benmanes.caffeine.cache.Caffeine
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.future.await
import kotlinx.coroutines.future.future
import kotlinx.coroutines.supervisorScope
suspend fun <K, V> AsyncCache<K, V>.suspendGet(key: K, mappingFunction: suspend (K) -> V): V = supervisorScope {
get(key) { keyInternal, _ ->
future {
mappingFunction(keyInternal)
}
}.await()
}
@OptIn(DelicateCoroutinesApi::class)
fun <K, V> Caffeine<K, V>.buildSuspend(
scope: CoroutineScope = GlobalScope, mappingFunction: suspend (K) -> V
): AsyncLoadingCache<K, V> {
return buildAsync { key, _ ->
scope.future {
mappingFunction(key)
}
}
}
| 0 | Kotlin | 0 | 4 | 7e296751d8bb2a939b4d2aa51a44884b4a62233d | 971 | PackVulcan | MIT License |
src/main/kotlin/app/trian/validator/ValidationResult.kt | triandamai | 396,588,758 | false | null | package app.trian.validator
typealias PropertyPath = String
typealias ValidationError = String
sealed class ValidationResult {
object NotValidated : ValidationResult()
object Valid : ValidationResult()
class Invalid(val errors: Map<PropertyPath, List<ValidationError>>) : ValidationResult()
} | 0 | Kotlin | 0 | 0 | 4c109230464971f6225c2f05a1af1613b37c0b7a | 306 | backend_ktor | Apache License 2.0 |
app/src/main/java/com/zone/chatterz/connection/RequestCallback.kt | Bluesachinkr | 212,034,673 | false | {"Kotlin": 279133} | package com.zone.chatterz.connection
import com.google.firebase.database.DataSnapshot
open class RequestCallback{
open fun onDataChanged(dataSnapshot: DataSnapshot){
println("DOne")
}
} | 0 | Kotlin | 3 | 4 | 2da249eee6bdc89b6172a43beae3a50c81733476 | 203 | chatterz-android | MIT License |
src/lang-xdm/main/uk/co/reecedunn/intellij/plugin/xdm/types/impl/psi/XsQName.kt | rhdunn | 62,201,764 | false | {"Kotlin": 8262637, "XQuery": 996770, "HTML": 39377, "XSLT": 6853} | /*
* Copyright (C) 2018-2020 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xdm.types.impl.psi
import com.intellij.psi.PsiElement
import uk.co.reecedunn.intellij.plugin.xdm.types.XdmElementRef
import uk.co.reecedunn.intellij.plugin.xdm.types.XsAnyUriValue
import uk.co.reecedunn.intellij.plugin.xdm.types.XsNCNameValue
import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue
import java.lang.ref.WeakReference
data class XsQName(
override val namespace: XsAnyUriValue?,
override val prefix: XsNCNameValue?,
override val localName: XsNCNameValue?,
override val isLexicalQName: Boolean,
private val reference: WeakReference<PsiElement>?
) : XsQNameValue, XdmElementRef {
constructor(
namespace: XsAnyUriValue?,
prefix: XsNCNameValue?,
localName: XsNCNameValue?,
isLexicalQName: Boolean,
element: PsiElement?
) : this(namespace, prefix, localName, isLexicalQName, element?.let { WeakReference(it) })
override val element: PsiElement?
get() = reference?.get()
}
| 49 | Kotlin | 9 | 25 | d8d460d31334e8b2376a22f3832a20b2845bacab | 1,614 | xquery-intellij-plugin | Apache License 2.0 |
j2k/src/org/jetbrains/jet/j2k/Utils.kt | chashnikov | 14,658,474 | true | {"Java": 14526655, "Kotlin": 6831811, "JavaScript": 897073, "Groovy": 43935, "CSS": 14421, "Shell": 9248} | /*
* Copyright 2010-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.jet.j2k
import org.jetbrains.jet.lang.types.expressions.OperatorConventions
import com.intellij.psi.*
import com.intellij.psi.util.PsiUtil
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.jet.j2k.ast.*
import com.intellij.psi.util.PsiMethodUtil
fun quoteKeywords(packageName: String): String = packageName.split("\\.").map { Identifier.toKotlin(it) }.joinToString(".")
fun findVariableUsages(variable: PsiVariable, scope: PsiElement): Collection<PsiReferenceExpression> {
return ReferencesSearch.search(variable, LocalSearchScope(scope)).findAll().filterIsInstance(javaClass<PsiReferenceExpression>())
}
fun findMethodCalls(method: PsiMethod, scope: PsiElement): Collection<PsiMethodCallExpression> {
return ReferencesSearch.search(method, LocalSearchScope(scope)).findAll().map {
if (it is PsiReferenceExpression) {
val methodCall = it.getParent() as? PsiMethodCallExpression
if (methodCall?.getMethodExpression() == it) methodCall else null
}
else {
null
}
}.filterNotNull()
}
fun PsiVariable.countWriteAccesses(scope: PsiElement?): Int
= if (scope != null) findVariableUsages(this, scope).count { PsiUtil.isAccessedForWriting(it) } else 0
fun PsiVariable.hasWriteAccesses(scope: PsiElement?): Boolean
= if (scope != null) findVariableUsages(this, scope).any { PsiUtil.isAccessedForWriting(it) } else false
fun getDefaultInitializer(field: Field): Expression? {
val t = field.`type`
val result = if (t.isNullable) {
LiteralExpression("null")
}
else if (t is PrimitiveType) {
when (t.name.name) {
"Boolean" -> LiteralExpression("false")
"Char" -> LiteralExpression("' '")
"Double" -> MethodCallExpression.buildNotNull(LiteralExpression("0").assignNoPrototype(), OperatorConventions.DOUBLE.toString())
"Float" -> MethodCallExpression.buildNotNull(LiteralExpression("0").assignNoPrototype(), OperatorConventions.FLOAT.toString())
else -> LiteralExpression("0")
}
}
else {
null
}
return result?.assignNoPrototype()
}
fun isVal(field: PsiField): Boolean {
if (field.hasModifierProperty(PsiModifier.FINAL)) return true
if (!field.hasModifierProperty(PsiModifier.PRIVATE)) return false
val containingClass = field.getContainingClass() ?: return false
val writes = findVariableUsages(field, containingClass).filter { PsiUtil.isAccessedForWriting(it) }
if (writes.size == 0) return true
if (writes.size > 1) return false
val write = writes.single()
val parent = write.getParent()
if (parent is PsiAssignmentExpression &&
parent.getOperationSign().getTokenType() == JavaTokenType.EQ &&
isQualifierEmptyOrThis(write)) {
val constructor = write.getContainingConstructor()
return constructor != null &&
constructor.getContainingClass() == containingClass &&
parent.getParent() is PsiExpressionStatement &&
parent.getParent()?.getParent() == constructor.getBody()
}
return false
}
fun shouldGenerateDefaultInitializer(field: PsiField)
= field.getInitializer() == null && !(isVal(field) && field.hasWriteAccesses(field.getContainingClass()))
fun isQualifierEmptyOrThis(ref: PsiReferenceExpression): Boolean {
val qualifier = ref.getQualifierExpression()
return qualifier == null || (qualifier is PsiThisExpression && qualifier.getQualifier() == null)
}
fun PsiElement.isInSingleLine(): Boolean {
if (this is PsiWhiteSpace) {
val text = getText()!!
return text.indexOf('\n') < 0 && text.indexOf('\r') < 0
}
var child = getFirstChild()
while (child != null) {
if (!child!!.isInSingleLine()) return false
child = child!!.getNextSibling()
}
return true
}
fun PsiElement.getContainingMethod(): PsiMethod? {
var context = getContext()
while (context != null) {
val _context = context!!
if (_context is PsiMethod) return _context
context = _context.getContext()
}
return null
}
fun PsiElement.getContainingConstructor(): PsiMethod? {
val method = getContainingMethod()
return if (method?.isConstructor() == true) method else null
}
fun PsiElement.isConstructor(): Boolean = this is PsiMethod && this.isConstructor()
fun PsiModifierListOwner.accessModifier(): String = when {
hasModifierProperty(PsiModifier.PUBLIC) -> PsiModifier.PUBLIC
hasModifierProperty(PsiModifier.PRIVATE) -> PsiModifier.PRIVATE
hasModifierProperty(PsiModifier.PROTECTED) -> PsiModifier.PROTECTED
else -> PsiModifier.PACKAGE_LOCAL
}
fun PsiMethod.isMainMethod(): Boolean = PsiMethodUtil.isMainMethod(this)
fun <T: Any> List<T>.singleOrNull2(): T? = if (size == 1) this[0] else null
fun <T: Any> Array<T>.singleOrNull2(): T? = if (size == 1) this[0] else null
fun PsiMember.isImported(file: PsiJavaFile): Boolean {
if (this is PsiClass) {
val fqName = getQualifiedName()
val index = fqName?.lastIndexOf('.') ?: -1
val parentName = if (index >= 0) fqName!!.substring(0, index) else null
return file.getImportList()?.getAllImportStatements()?.any {
it.getImportReference()?.getQualifiedName() == (if (it.isOnDemand()) parentName else fqName)
} ?: false
}
else {
return getContainingClass() != null && file.getImportList()?.getImportStaticStatements()?.any {
it.resolveTargetClass() == getContainingClass() && (it.isOnDemand() || it.getReferenceName() == getName())
} ?: false
}
}
| 1 | Java | 1 | 1 | 88a261234860ff0014e3c2dd8e64072c685d442d | 6,334 | kotlin | Apache License 2.0 |
domain/src/main/kotlin/domain/login/sms/SmsLogin.kt | stoyicker | 291,049,724 | false | null | package domain.login.sms
import domain.login.DomainAuthenticatedUser
import io.reactivex.Single
interface SmsLogin {
fun requestOtp(parameters: DomainRequestOneTimePasswordRequestParameters): Single<DomainSmsOneTimePassword>
fun verifyOtp(parameters: DomainVerifyOneTimePasswordRequestParameters): Single<DomainSmsVerifiedOneTimePasswordRefreshToken>
fun login(parameters: DomainSmsAuthRequestParameters): Single<DomainAuthenticatedUser>
}
| 1 | null | 1 | 1 | fecfefd7a64dc8c9397343850b9de4d52117b5c3 | 448 | dinger-unpublished | MIT License |
src/main/kotlin/net/pdutta/sandbox/Main.kt | pdvcs | 91,922,358 | false | null | package net.pdutta.sandbox
fun main () {
println(piglatin("please bring my aardvark some almond milk"))
}
| 0 | Kotlin | 0 | 0 | 4663835ffcee40651c0672d6f461c9dd7e7c30d1 | 111 | PiglatinKt | Apache License 2.0 |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/GalaxyPlanet.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Outline.GalaxyPlanet: ImageVector
get() {
if (_galaxyPlanet != null) {
return _galaxyPlanet!!
}
_galaxyPlanet = Builder(name = "GalaxyPlanet", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(3.0f, 2.5f)
curveToRelative(0.0f, -0.828f, 0.672f, -1.5f, 1.5f, -1.5f)
reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f)
reflectiveCurveToRelative(-0.672f, 1.5f, -1.5f, 1.5f)
reflectiveCurveToRelative(-1.5f, -0.672f, -1.5f, -1.5f)
close()
moveTo(0.0f, 13.5f)
curveToRelative(0.0f, -1.93f, 1.57f, -3.5f, 3.5f, -3.5f)
reflectiveCurveToRelative(3.5f, 1.57f, 3.5f, 3.5f)
reflectiveCurveToRelative(-1.57f, 3.5f, -3.5f, 3.5f)
reflectiveCurveToRelative(-3.5f, -1.57f, -3.5f, -3.5f)
close()
moveTo(2.0f, 13.5f)
curveToRelative(0.0f, 0.827f, 0.673f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.673f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.673f, -1.5f, -1.5f, -1.5f)
reflectiveCurveToRelative(-1.5f, 0.673f, -1.5f, 1.5f)
close()
moveTo(17.5f, 21.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, 0.672f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f)
close()
moveTo(22.5f, 18.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, 0.672f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f)
close()
moveTo(24.0f, 12.189f)
curveToRelative(0.0f, 0.352f, -0.185f, 0.691f, -0.486f, 0.871f)
curveToRelative(-0.057f, 0.035f, -0.687f, 0.407f, -1.688f, 0.817f)
curveToRelative(-0.613f, 2.368f, -2.768f, 4.123f, -5.325f, 4.123f)
reflectiveCurveToRelative(-4.712f, -1.755f, -5.325f, -4.123f)
curveToRelative(-1.001f, -0.409f, -1.631f, -0.782f, -1.688f, -0.817f)
curveToRelative(-0.302f, -0.18f, -0.486f, -0.506f, -0.486f, -0.857f)
curveToRelative(0.0f, -0.367f, 0.202f, -0.719f, 0.525f, -0.894f)
curveToRelative(0.081f, -0.044f, 0.741f, -0.39f, 1.793f, -0.651f)
curveToRelative(0.759f, -2.13f, 2.795f, -3.659f, 5.182f, -3.659f)
reflectiveCurveToRelative(4.423f, 1.529f, 5.182f, 3.659f)
curveToRelative(1.055f, 0.262f, 1.716f, 0.61f, 1.792f, 0.651f)
curveToRelative(0.324f, 0.175f, 0.525f, 0.513f, 0.525f, 0.88f)
close()
moveTo(13.001f, 12.411f)
curveToRelative(1.0f, 0.32f, 2.219f, 0.588f, 3.499f, 0.588f)
reflectiveCurveToRelative(2.499f, -0.268f, 3.499f, -0.588f)
curveToRelative(-0.047f, -1.889f, -1.599f, -3.412f, -3.499f, -3.412f)
reflectiveCurveToRelative(-3.452f, 1.523f, -3.499f, 3.412f)
close()
moveTo(19.226f, 14.691f)
curveToRelative(-0.842f, 0.185f, -1.765f, 0.308f, -2.726f, 0.308f)
reflectiveCurveToRelative(-1.884f, -0.123f, -2.726f, -0.308f)
curveToRelative(0.642f, 0.797f, 1.626f, 1.308f, 2.726f, 1.308f)
reflectiveCurveToRelative(2.084f, -0.511f, 2.726f, -1.308f)
close()
moveTo(11.429f, 19.086f)
curveToRelative(-3.883f, 2.698f, -7.52f, 3.657f, -8.846f, 2.33f)
curveToRelative(-0.408f, -0.408f, -0.603f, -1.044f, -0.582f, -1.892f)
curveToRelative(0.015f, -0.552f, -0.421f, -1.011f, -0.974f, -1.025f)
curveToRelative(-0.578f, -0.024f, -1.012f, 0.422f, -1.025f, 0.975f)
curveToRelative(-0.036f, 1.396f, 0.367f, 2.558f, 1.167f, 3.356f)
curveToRelative(0.783f, 0.783f, 1.873f, 1.167f, 3.185f, 1.167f)
curveToRelative(2.237f, 0.0f, 5.119f, -1.116f, 8.217f, -3.269f)
curveToRelative(0.453f, -0.315f, 0.565f, -0.938f, 0.25f, -1.392f)
curveToRelative(-0.314f, -0.454f, -0.938f, -0.566f, -1.392f, -0.251f)
close()
moveTo(6.315f, 9.161f)
curveToRelative(0.193f, 0.182f, 0.439f, 0.271f, 0.685f, 0.271f)
curveToRelative(0.266f, 0.0f, 0.532f, -0.105f, 0.729f, -0.315f)
curveToRelative(0.223f, -0.236f, 0.452f, -0.472f, 0.685f, -0.705f)
curveToRelative(2.612f, -2.611f, 5.482f, -4.63f, 8.084f, -5.682f)
curveToRelative(2.259f, -0.913f, 4.099f, -0.969f, 4.919f, -0.148f)
curveToRelative(0.662f, 0.661f, 0.765f, 1.957f, 0.29f, 3.646f)
curveToRelative(-0.149f, 0.532f, 0.161f, 1.084f, 0.693f, 1.233f)
curveToRelative(0.531f, 0.149f, 1.083f, -0.161f, 1.233f, -0.692f)
curveToRelative(0.869f, -3.098f, 0.044f, -4.756f, -0.802f, -5.602f)
curveToRelative(-1.448f, -1.449f, -3.964f, -1.553f, -7.083f, -0.291f)
curveToRelative(-2.845f, 1.15f, -5.952f, 3.324f, -8.75f, 6.122f)
curveToRelative(-0.248f, 0.248f, -0.49f, 0.497f, -0.727f, 0.749f)
curveToRelative(-0.378f, 0.402f, -0.359f, 1.035f, 0.043f, 1.413f)
close()
}
}
.build()
return _galaxyPlanet!!
}
private var _galaxyPlanet: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 6,699 | icons | MIT License |
examples/kotlin/src/main/kotlin/com/xebia/functional/xef/auto/Colors.kt | xebia-functional | 629,411,216 | false | null | package com.xebia.functional.xef.auto
import kotlinx.serialization.Serializable
@Serializable
data class Colors(val colors: List<String>)
suspend fun main() {
ai {
val colors: Colors = prompt("a selection of 10 beautiful colors that go well together")
println(colors)
}.getOrElse { println(it) }
}
| 7 | Kotlin | 4 | 74 | c0af078c0293d3f4e8d233571bdd026142cad0a4 | 325 | xef | Apache License 2.0 |
core/data/src/main/kotlin/com/naveenapps/expensemanager/core/data/repository/SettingsRepositoryImpl.kt | nkuppan | 536,435,007 | false | {"Kotlin": 773385} | package com.naveenapps.expensemanager.core.data.repository
import com.naveenapps.expensemanager.core.common.utils.AppCoroutineDispatchers
import com.naveenapps.expensemanager.core.datastore.SettingsDataStore
import com.naveenapps.expensemanager.core.model.Resource
import com.naveenapps.expensemanager.core.model.TransactionType
import com.naveenapps.expensemanager.core.repository.SettingsRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext
import javax.inject.Inject
class SettingsRepositoryImpl @Inject constructor(
private val dataStore: SettingsDataStore,
private val dispatcher: AppCoroutineDispatchers
) : SettingsRepository {
override fun getTransactionTypes(): Flow<List<TransactionType>?> {
return dataStore.getTransactionType()
}
override suspend fun setTransactionTypes(transactionTypes: List<TransactionType>?): Resource<Boolean> =
withContext(dispatcher.io) {
dataStore.setTransactionType(transactionTypes)
return@withContext Resource.Success(true)
}
override fun getAccounts(): Flow<List<String>?> {
return dataStore.getAccounts()
}
override suspend fun setAccounts(accounts: List<String>?): Resource<Boolean> =
withContext(dispatcher.io) {
dataStore.setAccounts(accounts)
return@withContext Resource.Success(true)
}
override fun getCategories(): Flow<List<String>?> {
return dataStore.getCategories()
}
override suspend fun setCategories(categories: List<String>?): Resource<Boolean> =
withContext(dispatcher.io) {
dataStore.setCategories(categories)
return@withContext Resource.Success(true)
}
override fun isPreloaded(): Flow<Boolean> {
return dataStore.isPreloaded()
}
override suspend fun setPreloaded(preloaded: Boolean): Resource<Boolean> =
withContext(dispatcher.io) {
dataStore.setPreloaded(preloaded)
return@withContext Resource.Success(true)
}
override fun isOnboardingCompleted(): Flow<Boolean> {
return dataStore.isOnboardingCompleted()
}
override suspend fun setOnboardingCompleted(isOnboardingCompleted: Boolean): Resource<Boolean> =
withContext(dispatcher.io) {
dataStore.setOnboardingCompleted(isOnboardingCompleted)
return@withContext Resource.Success(true)
}
}
| 1 | Kotlin | 2 | 0 | 302d4ede25ca730f8ba5e062bd669d67c4a80be2 | 2,447 | expensemanager | Apache License 2.0 |
src/main/kotlin/no/nav/syfo/fastlege/ws/fastlege/model/Fastlegekontor.kt | navikt | 402,451,651 | false | null | package no.nav.syfo.fastlege.ws.fastlege.model
data class Fastlegekontor(
val navn: String,
val besoeksadresse: Adresse?,
val postadresse: Adresse?,
val telefon: String,
val epost: String,
val orgnummer: String?,
)
| 0 | Kotlin | 0 | 0 | e2df8d4edad949b9647e48837e541aa4ed0c2b59 | 240 | isproxy | MIT License |
src/main/kotlin/com/thelastpickle/tlpstress/StressContext.kt | daniilmelkunov | 436,243,410 | true | {"Kotlin": 128524, "Shell": 863} | package com.thelastpickle.tlpstress
import com.google.common.util.concurrent.RateLimiter
import com.thelastpickle.tlpstress.commands.Run
import com.thelastpickle.tlpstress.generators.Registry
import shaded.com.scylladb.cdc.driver3.driver.core.Session
import java.util.concurrent.Semaphore
data class StressContext(val session: Session,
val mainArguments: Run,
val thread: Int,
val metrics: Metrics,
val permits: Int,
val registry: Registry,
val rateLimiter: RateLimiter?)
| 0 | Kotlin | 0 | 0 | 0957f5e39fb2fb4b874cbb259a1f50c83ad379c7 | 626 | tlp-stress | Apache License 2.0 |
src/auth/ktor/Principal.kt | DiSSCo | 517,633,705 | false | null | package org.synthesis.auth.ktor
import java.time.LocalDate
import java.time.LocalDateTime
import java.util.*
import kotlin.collections.LinkedHashMap
import org.synthesis.account.*
import org.synthesis.institution.InstitutionId
import org.synthesis.keycloak.KeycloakApiClient
import org.synthesis.keycloak.KeycloakRealm
import org.synthesis.keycloak.admin.KeycloakAttribute
import org.synthesis.keycloak.admin.KeycloakUserGroup
/**
* Parsing a token and creating an internal user representation based on it.
*/
internal fun JWTCredential.principal(realm: KeycloakRealm, client: KeycloakApiClient): UserAccount = UserAccount(
id = id(),
email = "",
groups = groups(),
roles = roles(client),
fullName = UserFullName(
firstName = "",
lastName = ""
),
realmId = realm.value,
attributes = attributes(),
synchronizedAt = LocalDateTime.now(),
status = UserAccountStatus.Active()
)
/**
* Parsing a token and retrieving all roles that are assigned to a user
*/
@Suppress("UNCHECKED_CAST")
private fun JWTCredential.roles(client: KeycloakApiClient): List<String> {
@Suppress("UnsafeCast")
val permissionsMap = payload
.getClaim("resource_access")
.asMap()[client.id] as LinkedHashMap<String, List<String>>
return permissionsMap["roles"]?.toList() ?: listOf()
}
/**
* Parsing a token and retrieving all groups the user is a member of.
*/
private fun JWTCredential.groups(): List<String> {
val groups = payload
.getClaim("groups")
.asList(KeycloakUserGroup::class.java)
return groups?.map { it.toApplicationRepresentation() } ?: listOf()
}
/**
* Parsing a token and retrieving all user attributes
*/
private fun JWTCredential.attributes(): UserAccountAttributes = UserAccountAttributes(
orcId = orcIdAttribute(),
institutionId = institutionIdAttribute(),
relatedInstitutionId = relatedInstitutionIdAttribute(),
gender = genderAttribute(),
birthDate = birthDateAttribute(),
nationality = nationalityAttribute(),
countryOtherInstitution = countryOtherInstitutionAttribute()
)
/**
* Parsing the token and extracting the user ID
*/
private fun JWTCredential.id(): UserAccountId = UserAccountId(UUID.fromString(payload.getClaim("sub").asString()))
/**
* Parsing the token and extracting the OrcId
*/
private fun JWTCredential.orcIdAttribute(): OrcId? = payload
.getClaim(KeycloakAttribute.orcIdAttributeName)
?.asString()
?.let { OrcId(it) }
/**
* Parsing the token and extracting the birthdate
*/
private fun JWTCredential.birthDateAttribute(): LocalDate? = payload
.getClaim(KeycloakAttribute.birthDateAttributeName)
?.asString()
?.let { LocalDate.parse(it) }
/**
* Parsing the token and extracting the OrcId
*/
private fun JWTCredential.genderAttribute(): Gender = payload
.getClaim(KeycloakAttribute.genderAttributeName)
?.asString()
?.let { Gender.valueOf(it.uppercase()) }
?: Gender.OTHER
/**
* Parsing the token and extracting the identifier of the institution to which the user is bound.
*/
private fun JWTCredential.institutionIdAttribute(): InstitutionId? =
payload
.getClaim(KeycloakAttribute.institutionAttributeName)
?.asString()
?.let { InstitutionId.fromString(it) }
/**
* Parsing the token and extracting the related institution id.
*/
private fun JWTCredential.relatedInstitutionIdAttribute(): InstitutionId? =
payload
.getClaim(KeycloakAttribute.relatedInstitutionAttributeName)
?.asString()
?.let { InstitutionId.fromString(it) }
/**
* Parsing the token and extracting the identifier of the institution to which the user is bound.
*/
private fun JWTCredential.nationalityAttribute(): String? =
payload
.getClaim(KeycloakAttribute.nationalityAttributeName)
?.asString()
/**
* Parsing the token and extracting the identifier of the institution to which the user is bound.
*/
private fun JWTCredential.countryOtherInstitutionAttribute(): String? =
payload
.getClaim(KeycloakAttribute.countryOtherInstitutionAttributeName)
?.asString()
| 0 | Kotlin | 0 | 0 | 4b6387f85e9b8f006021e3de09e1246fbf13a8b2 | 4,144 | elvis-backend | Apache License 2.0 |
demo/muon-monitor/src/commonMain/kotlin/ru/mipt/npm/muon/monitor/Model.kt | SciProgCentre | 174,502,624 | false | {"Kotlin": 856546, "CSS": 913} | package ru.mipt.npm.muon.monitor
import ru.mipt.npm.muon.monitor.Monitor.CENTRAL_LAYER_Z
import ru.mipt.npm.muon.monitor.Monitor.LOWER_LAYER_Z
import ru.mipt.npm.muon.monitor.Monitor.UPPER_LAYER_Z
import space.kscience.visionforge.VisionManager
import space.kscience.visionforge.removeAll
import space.kscience.visionforge.root
import space.kscience.visionforge.solid.*
import kotlin.math.PI
class Model(val manager: VisionManager) {
private val map = HashMap<String, SolidGroup>()
private val events = HashSet<Event>()
private fun SolidGroup.pixel(pixel: SC1) {
val group = group(pixel.name) {
position = Point3D(pixel.center.x, pixel.center.y, pixel.center.z)
box(pixel.xSize, pixel.ySize, pixel.zSize)
label(pixel.name) {
z = -Monitor.PIXEL_Z_SIZE / 2 - 5
rotationY = PI
}
}
map[pixel.name] = group
}
private fun SolidGroup.detector(detector: SC16) {
group(detector.name) {
detector.pixels.forEach {
pixel(it)
}
}
}
var tracks: SolidGroup
val root: SolidGroup = SolidGroup().apply {
root([email protected])
rotationX = PI / 2
group("bottom") {
Monitor.detectors.filter { it.center.z == LOWER_LAYER_Z }.forEach {
detector(it)
}
}
group("middle") {
Monitor.detectors.filter { it.center.z == CENTRAL_LAYER_Z }.forEach {
detector(it)
}
}
group("top") {
Monitor.detectors.filter { it.center.z == UPPER_LAYER_Z }.forEach {
detector(it)
}
}
tracks = group("tracks")
}
private fun highlight(pixel: String) {
map[pixel]?.color?.invoke("blue")
}
fun reset() {
map.values.forEach {
it.setProperty(SolidMaterial.MATERIAL_COLOR_KEY, null)
}
tracks.removeAll()
}
fun displayEvent(event: Event) {
events.add(event)
event.hits.forEach {
highlight(it)
}
event.track?.let {
tracks.polyline(*it.toTypedArray(), name = "track[${event.id}]") {
thickness = 4
}
}
}
fun encodeToString(): String = manager.encodeToString(this.root)
} | 15 | Kotlin | 6 | 34 | fb12ca8902509914910e8a39c4e525bee5e3fd46 | 2,377 | visionforge | Apache License 2.0 |
HKBusETA/app/src/main/java/com/loohp/hkbuseta/compose/AdvanceScroll.kt | LOOHP | 686,756,915 | false | {"Kotlin": 312062, "Java": 145675} | package com.loohp.hkbuseta.compose
import android.content.res.Configuration
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.TweenSpec
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.gestures.FlingBehavior
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.calculateEndPadding
import androidx.compose.foundation.layout.calculateStartPadding
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
fun Modifier.fullPageVerticalScrollbar(
state: ScrollState,
indicatorThickness: Dp = 8.dp,
indicatorColor: Color = Color.LightGray,
alpha: Float = 0.8f
): Modifier = composed {
val configuration = LocalConfiguration.current
var scrollOffsetViewPort by remember { mutableStateOf(0F) }
val animatedScrollOffsetViewPort by animateFloatAsState(
targetValue = scrollOffsetViewPort,
animationSpec = TweenSpec(durationMillis = 100, easing = LinearEasing),
label = ""
)
drawWithContent {
drawContent()
val contentOffset = state.value
val viewPortLength = size.height
val contentLength = (viewPortLength + state.maxValue).coerceAtLeast(0.001f)
if (viewPortLength < contentLength) {
val indicatorLength = viewPortLength / contentLength
val indicatorThicknessPx = indicatorThickness.toPx()
val halfIndicatorThicknessPx = (indicatorThickness.value / 2F).dp.toPx()
scrollOffsetViewPort = contentOffset / contentLength
if (configuration.screenLayout and Configuration.SCREENLAYOUT_ROUND_MASK == Configuration.SCREENLAYOUT_ROUND_YES) {
val topLeft = Offset(halfIndicatorThicknessPx, halfIndicatorThicknessPx)
val size = Size(configuration.screenWidthDp.dp.toPx() - indicatorThicknessPx, configuration.screenHeightDp.dp.toPx() - indicatorThicknessPx)
val style = Stroke(width = indicatorThicknessPx, cap = StrokeCap.Round)
drawArc(
startAngle = -30F,
sweepAngle = 60F,
useCenter = false,
color = Color.DarkGray,
topLeft = topLeft,
size = size,
alpha = alpha,
style = style
)
drawArc(
startAngle = -30F + animatedScrollOffsetViewPort * 60F,
sweepAngle = indicatorLength * 60F,
useCenter = false,
color = indicatorColor,
topLeft = topLeft,
size = size,
alpha = alpha,
style = style
)
} else {
val cornerRadius = CornerRadius(indicatorThicknessPx / 2F)
val topLeft = Offset(configuration.screenWidthDp.dp.toPx() - indicatorThicknessPx, viewPortLength * 0.125F)
val size = Size(indicatorThicknessPx, viewPortLength * 0.75F)
drawRoundRect(
color = Color.DarkGray,
topLeft = topLeft,
size = size,
cornerRadius = cornerRadius
)
drawRoundRect(
color = indicatorColor,
topLeft = Offset(topLeft.x, topLeft.y + animatedScrollOffsetViewPort * size.height),
size = Size(size.width, size.height * indicatorLength),
cornerRadius = cornerRadius
)
}
}
}
}
fun Modifier.fullPageVerticalScrollbar(
state: LazyListState,
indicatorThickness: Dp = 8.dp,
indicatorColor: Color = Color.LightGray,
alpha: Float = 0.8f
): Modifier = composed {
val configuration = LocalConfiguration.current
val actualItemLength: MutableMap<Int, Int> = remember { mutableMapOf() }
var totalItemCount by remember { mutableStateOf(0) }
var indicatorLength by remember { mutableStateOf(0F) }
var scrollOffsetViewPort by remember { mutableStateOf(0F) }
val animatedIndicatorLength by animateFloatAsState(
targetValue = indicatorLength,
animationSpec = TweenSpec(durationMillis = 300, easing = LinearEasing),
label = ""
)
val animatedScrollOffsetViewPort by animateFloatAsState(
targetValue = scrollOffsetViewPort,
animationSpec = TweenSpec(durationMillis = 100, easing = LinearEasing),
label = ""
)
drawWithContent {
drawContent()
val viewPortLength = size.height
val itemsVisible = state.layoutInfo.visibleItemsInfo
if (totalItemCount != state.layoutInfo.totalItemsCount) {
actualItemLength.clear()
totalItemCount = state.layoutInfo.totalItemsCount
}
itemsVisible.forEach { actualItemLength[it.index] = it.size }
val visibleItemsLength = itemsVisible.sumOf { it.size }.toFloat() - state.firstVisibleItemScrollOffset
val knownLength = actualItemLength.entries.sumOf { it.value }
val knownAmount = actualItemLength.values.count()
val knownAverageItemLength = knownLength / knownAmount
val contentOffset = (0 until state.firstVisibleItemIndex).sumOf { actualItemLength.getOrDefault(it, knownAverageItemLength) }.toFloat() + state.firstVisibleItemScrollOffset
val contentLength = knownLength + (state.layoutInfo.totalItemsCount - knownAmount) * (knownLength / knownAmount)
if (viewPortLength < contentLength) {
indicatorLength = (if (itemsVisible.last { it.offset < viewPortLength }.index >= state.layoutInfo.totalItemsCount) 1F - (contentOffset / contentLength) else visibleItemsLength / contentLength).coerceAtLeast(0.05F)
val indicatorThicknessPx = indicatorThickness.toPx()
val halfIndicatorThicknessPx = (indicatorThickness.value / 2F).dp.toPx()
scrollOffsetViewPort = contentOffset / contentLength
if (configuration.screenLayout and Configuration.SCREENLAYOUT_ROUND_MASK == Configuration.SCREENLAYOUT_ROUND_YES) {
val topLeft = Offset(halfIndicatorThicknessPx, halfIndicatorThicknessPx)
val size = Size(configuration.screenWidthDp.dp.toPx() - indicatorThicknessPx, configuration.screenHeightDp.dp.toPx() - indicatorThicknessPx)
val style = Stroke(width = indicatorThicknessPx, cap = StrokeCap.Round)
val startAngle = (-30F + animatedScrollOffsetViewPort * 60F).coerceIn(-30F, 30F)
drawArc(
startAngle = -30F,
sweepAngle = 60F,
useCenter = false,
color = Color.DarkGray,
topLeft = topLeft,
size = size,
alpha = alpha,
style = style
)
drawArc(
startAngle = startAngle,
sweepAngle = (animatedIndicatorLength * 60F).coerceAtMost(60F - (startAngle + 30F)),
useCenter = false,
color = indicatorColor,
topLeft = topLeft,
size = size,
alpha = alpha,
style = style
)
} else {
val cornerRadius = CornerRadius(indicatorThicknessPx / 2F)
val topLeft = Offset(configuration.screenWidthDp.dp.toPx() - indicatorThicknessPx, viewPortLength * 0.125F)
val size = Size(indicatorThicknessPx, viewPortLength * 0.75F)
val startHeight = (topLeft.y + animatedScrollOffsetViewPort * size.height).coerceIn(topLeft.y, topLeft.y + size.height)
drawRoundRect(
color = Color.DarkGray,
topLeft = topLeft,
size = size,
cornerRadius = cornerRadius
)
drawRoundRect(
color = indicatorColor,
topLeft = Offset(topLeft.x, startHeight),
size = Size(size.width, (size.height * animatedIndicatorLength).coerceAtMost(size.height - (startHeight - topLeft.y))),
cornerRadius = cornerRadius
)
}
}
}
}
data class FullPageScrollBarConfig(
val indicatorThickness: Dp = 8.dp,
val indicatorColor: Color = Color.LightGray,
val alpha: Float? = null,
val alphaAnimationSpec: AnimationSpec<Float>? = null
)
fun Modifier.fullPageVerticalLazyScrollbar(
state: LazyListState,
scrollbarConfigFullPage: FullPageScrollBarConfig = FullPageScrollBarConfig()
) = this
.fullPageVerticalScrollbar(
state,
indicatorThickness = scrollbarConfigFullPage.indicatorThickness,
indicatorColor = scrollbarConfigFullPage.indicatorColor,
alpha = scrollbarConfigFullPage.alpha ?: 0.8f
)
fun Modifier.fullPageVerticalScrollWithScrollbar(
state: ScrollState,
enabled: Boolean = true,
flingBehavior: FlingBehavior? = null,
reverseScrolling: Boolean = false,
scrollbarConfigFullPage: FullPageScrollBarConfig = FullPageScrollBarConfig()
) = this
.fullPageVerticalScrollbar(
state,
indicatorThickness = scrollbarConfigFullPage.indicatorThickness,
indicatorColor = scrollbarConfigFullPage.indicatorColor,
alpha = scrollbarConfigFullPage.alpha ?: 0.8f
)
.verticalScroll(state, enabled, flingBehavior, reverseScrolling)
fun Modifier.scrollbar(
state: ScrollState,
direction: Orientation,
indicatorThickness: Dp = 8.dp,
indicatorColor: Color = Color.LightGray,
alpha: Float = if (state.isScrollInProgress) 0.8f else 0f,
alphaAnimationSpec: AnimationSpec<Float> = tween(
delayMillis = if (state.isScrollInProgress) 0 else 1500,
durationMillis = if (state.isScrollInProgress) 150 else 500
),
padding: PaddingValues = PaddingValues(all = 0.dp)
): Modifier = composed {
val scrollbarAlpha by animateFloatAsState(
targetValue = alpha,
animationSpec = alphaAnimationSpec,
label = ""
)
drawWithContent {
drawContent()
val showScrollBar = (state.isScrollInProgress || scrollbarAlpha > 0.0f) && (state.canScrollForward || state.canScrollBackward)
// Draw scrollbar only if currently scrolling or if scroll animation is ongoing.
if (showScrollBar) {
val (topPadding, bottomPadding, startPadding, endPadding) = listOf(
padding.calculateTopPadding().toPx(), padding.calculateBottomPadding().toPx(),
padding.calculateStartPadding(layoutDirection).toPx(),
padding.calculateEndPadding(layoutDirection).toPx()
)
val contentOffset = state.value
val viewPortLength = if (direction == Orientation.Vertical)
size.height else size.width
val viewPortCrossAxisLength = if (direction == Orientation.Vertical)
size.width else size.height
val contentLength = (viewPortLength + state.maxValue).coerceAtLeast(0.001f) // To prevent divide by zero error
val indicatorLength = ((viewPortLength / contentLength) * viewPortLength) - (
if (direction == Orientation.Vertical) topPadding + bottomPadding
else startPadding + endPadding
)
val indicatorThicknessPx = indicatorThickness.toPx()
val scrollOffsetViewPort = viewPortLength * contentOffset / contentLength
val scrollbarSizeWithoutInsets = if (direction == Orientation.Vertical)
Size(indicatorThicknessPx, indicatorLength)
else Size(indicatorLength, indicatorThicknessPx)
val scrollbarPositionWithoutInsets = if (direction == Orientation.Vertical)
Offset(
x = if (layoutDirection == LayoutDirection.Ltr)
viewPortCrossAxisLength - indicatorThicknessPx - endPadding
else startPadding,
y = scrollOffsetViewPort + topPadding
)
else
Offset(
x = if (layoutDirection == LayoutDirection.Ltr)
scrollOffsetViewPort + startPadding
else viewPortLength - scrollOffsetViewPort - indicatorLength - endPadding,
y = viewPortCrossAxisLength - indicatorThicknessPx - bottomPadding
)
drawRoundRect(
color = indicatorColor,
cornerRadius = CornerRadius(
x = indicatorThicknessPx / 2, y = indicatorThicknessPx / 2
),
topLeft = scrollbarPositionWithoutInsets,
size = scrollbarSizeWithoutInsets,
alpha = scrollbarAlpha
)
}
}
}
data class ScrollBarConfig(
val indicatorThickness: Dp = 8.dp,
val indicatorColor: Color = Color.LightGray,
val alpha: Float? = null,
val alphaAnimationSpec: AnimationSpec<Float>? = null,
val padding: PaddingValues = PaddingValues(all = 0.dp)
)
fun Modifier.verticalScrollWithScrollbar(
state: ScrollState,
enabled: Boolean = true,
flingBehavior: FlingBehavior? = null,
reverseScrolling: Boolean = false,
scrollbarConfig: ScrollBarConfig = ScrollBarConfig()
) = this
.scrollbar(
state, Orientation.Vertical,
indicatorThickness = scrollbarConfig.indicatorThickness,
indicatorColor = scrollbarConfig.indicatorColor,
alpha = scrollbarConfig.alpha ?: if (state.isScrollInProgress) 0.8f else 0f,
alphaAnimationSpec = scrollbarConfig.alphaAnimationSpec ?: tween(
delayMillis = if (state.isScrollInProgress) 0 else 1500,
durationMillis = if (state.isScrollInProgress) 150 else 500
),
padding = scrollbarConfig.padding
)
.verticalScroll(state, enabled, flingBehavior, reverseScrolling)
fun Modifier.horizontalScrollWithScrollbar(
state: ScrollState,
enabled: Boolean = true,
flingBehavior: FlingBehavior? = null,
reverseScrolling: Boolean = false,
scrollbarConfig: ScrollBarConfig = ScrollBarConfig()
) = this
.scrollbar(
state, Orientation.Horizontal,
indicatorThickness = scrollbarConfig.indicatorThickness,
indicatorColor = scrollbarConfig.indicatorColor,
alpha = scrollbarConfig.alpha ?: if (state.isScrollInProgress) 0.8f else 0f,
alphaAnimationSpec = scrollbarConfig.alphaAnimationSpec ?: tween(
delayMillis = if (state.isScrollInProgress) 0 else 1500,
durationMillis = if (state.isScrollInProgress) 150 else 500
),
padding = scrollbarConfig.padding
)
.horizontalScroll(state, enabled, flingBehavior, reverseScrolling) | 0 | Kotlin | 0 | 0 | 0fea9dc60746fca6ff376dfefb7cf9cf8280647e | 16,041 | HK-Bus-ETA-WearOS | MIT License |
app/src/main/java/com/danisbana/danisbanaapp/presentation/screen/response/SuccessScreen.kt | burhancabiroglu | 598,760,819 | false | null | package com.danisbana.danisbanaapp.presentation.screen.response
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.MaterialTheme
import androidx.compose.material.OutlinedButton
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.danisbana.danisbanaapp.R
import com.danisbana.danisbanaapp.presentation.components.LottieView
import com.danisbana.danisbanaapp.presentation.theme.DanisBanaAppTheme
import com.danisbana.danisbanaapp.presentation.theme.QueenBlue
@Composable
fun SuccessScreen(
action: () -> Unit = {}
) {
Surface(modifier = Modifier.fillMaxSize()) {
Box(
modifier = Modifier
.fillMaxSize()
.navigationBarsPadding()
.statusBarsPadding(),
) {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(14.dp,Alignment.CenterVertically)
) {
LottieView(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1.4f),
res = R.raw.lottie_anim_email_send,
replay = true,
speed = 0.8f
)
Text(
text = "Doğrulama E-Postası Gönderildi",
style = MaterialTheme.typography.h2,
)
Text(
text = "Hesabınızı kullanabilmek için lütfen e-postanıza gönderilen doğrulama postasını onaylayın.",
style = MaterialTheme.typography.body2,
textAlign = TextAlign.Center,
)
Spacer(modifier = Modifier.height(6.dp))
OutlinedButton(
onClick = action,
shape = RoundedCornerShape(18.dp),
border = BorderStroke(1.dp,QueenBlue),
contentPadding = PaddingValues(horizontal = 24.dp, vertical = 12.dp)
) {
Text(
text = stringResource(id = R.string.login),
style = MaterialTheme.typography.h3
)
}
}
}
}
}
@Preview
@Composable
fun SuccessPagePreview() {
DanisBanaAppTheme {
SuccessScreen()
}
} | 0 | Kotlin | 0 | 0 | 50cb4466f3dfcdb42d430b8cb6afc63526d53d43 | 2,862 | PsychologistCounselorApp | Creative Commons Zero v1.0 Universal |
sample/src/main/java/com/github/aachartmodel/aainfographics/demo/chartcomposer/SpecialChartComposer.kt | cromod | 309,104,247 | true | {"Kotlin": 130408, "JavaScript": 6324, "HTML": 1162} | /**
* ◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉ ...... SOURCE CODE ......◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉
* ◉◉◉................................................... ◉◉◉
* ◉◉◉ https://github.com/AAChartModel/AAChartCore ◉◉◉
* ◉◉◉ https://github.com/AAChartModel/AAChartCore-Kotlin ◉◉◉
* ◉◉◉................................................... ◉◉◉
* ◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉ ...... SOURCE CODE ......◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉◉
*/
/**
* -------------------------------------------------------------------------------
*
* 🌕 🌖 🌗 🌘 ❀❀❀ WARM TIPS!!! ❀❀❀ 🌑 🌒 🌓 🌔
*
* Please contact me on GitHub,if there are any problems encountered in use.
* GitHub Issues : https://github.com/AAChartModel/AAChartCore-Kotlin/issues
* -------------------------------------------------------------------------------
* And if you want to contribute for this project, please contact me as well
* GitHub : https://github.com/AAChartModel
* StackOverflow : https://stackoverflow.com/users/7842508/codeforu
* JianShu : http://www.jianshu.com/u/f1e6753d4254
* SegmentFault : https://segmentfault.com/u/huanghunbieguan
*
* -------------------------------------------------------------------------------
*/
package com.github.aachartmodel.aainfographics.demo.chartcomposer
import com.github.aachartmodel.aainfographics.aachartcreator.*
import com.github.aachartmodel.aainfographics.aaoptionsmodel.AADataLabels
import com.github.aachartmodel.aainfographics.aaoptionsmodel.AAStyle
import com.github.aachartmodel.aainfographics.aaoptionsmodel.AATooltip
import com.github.aachartmodel.aainfographics.aaoptionsmodel.AAWaterfall
import com.github.aachartmodel.aainfographics.aatools.AAColor
import com.github.aachartmodel.aainfographics.aatools.AAGradientColor
import java.util.*
object SpecialChartComposer {
fun configurePolarColumnChart(): AAChartModel {
return AAChartModel()
.chartType(AAChartType.Column)
.polar(true)
.dataLabelsEnabled(false)
.categories(
arrayOf(
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
)
)
.series(
arrayOf(
AASeriesElement()
.name("2018")
.data(
arrayOf(
7.0,
6.9,
9.5,
14.5,
18.2,
21.5,
25.2,
26.5,
23.3,
18.3,
13.9,
9.6
)
)
)
)
}
fun configurePieChart(): AAChartModel {
return AAChartModel()
.chartType(AAChartType.Pie)
.backgroundColor("#ffffff")
.title("LANGUAGE MARKET SHARES JANUARY,2020 TO MAY")
.subtitle("virtual data")
.dataLabelsEnabled(true)//是否直接显示扇形图数据
.yAxisTitle("℃")
.series(
arrayOf(
AASeriesElement()
.name("Language market shares")
.data(
arrayOf(
arrayOf("Java", 67),
arrayOf("Swift", 999),
arrayOf("Python", 83),
arrayOf("OC", 11),
arrayOf("Go", 30)
)
)
)
)
}
fun configureBubbleChart(): AAChartModel {
return AAChartModel()
.chartType(AAChartType.Bubble)
.title("AACHARTKIT BUBBLES")
.subtitle("JUST FOR FUN")
.yAxisTitle("℃")
.gradientColorEnable(true)
.colorsTheme(arrayOf("#0c9674", "#7dffc0", "#d11b5f", "#facd32", "#ffffa0", "#EA007B"))
.series(
arrayOf(
AASeriesElement()
.name("BubbleOne")
.data(
arrayOf(
arrayOf(97, 36, 79),
arrayOf(94, 74, 60),
arrayOf(68, 76, 58),
arrayOf(64, 87, 56),
arrayOf(68, 27, 73),
arrayOf(74, 99, 42),
arrayOf(7, 93, 99),
arrayOf(51, 69, 40),
arrayOf(38, 23, 33),
arrayOf(57, 86, 31),
arrayOf(33, 24, 22)
)
),
AASeriesElement()
.name("BubbleTwo")
.data(
arrayOf(
arrayOf(25, 60, 87),
arrayOf(2, 75, 59),
arrayOf(11, 54, 8),
arrayOf(86, 55, 93),
arrayOf(5, 33, 88),
arrayOf(90, 63, 44),
arrayOf(91, 43, 17),
arrayOf(97, 56, 56),
arrayOf(15, 67, 48),
arrayOf(54, 25, 81),
arrayOf(55, 66, 11)
)
),
AASeriesElement()
.name("BubbleThree")
.data(
arrayOf(
arrayOf(47, 47, 21),
arrayOf(20, 12, 66),
arrayOf(6, 76, 91),
arrayOf(38, 30, 60),
arrayOf(57, 98, 64),
arrayOf(61, 47, 80),
arrayOf(83, 60, 13),
arrayOf(67, 78, 75),
arrayOf(64, 12, 55),
arrayOf(30, 77, 82),
arrayOf(88, 66, 13)
)
)
)
)
}
fun configureScatterChart(): AAChartModel {
val elementOne = AASeriesElement()
.name("Female")
.color("#ff0000")
.data(
arrayOf(
arrayOf(161.2, 51.6),
arrayOf(167.5, 59.0),
arrayOf(159.5, 49.2),
arrayOf(157.0, 63.0),
arrayOf(155.8, 53.6),
arrayOf(170.0, 59.0),
arrayOf(159.1, 47.6),
arrayOf(166.0, 69.8),
arrayOf(176.2, 66.8),
arrayOf(160.2, 75.2),
arrayOf(172.5, 55.2),
arrayOf(170.9, 54.2),
arrayOf(172.9, 62.5),
arrayOf(153.4, 42.0),
arrayOf(160.0, 50.0),
arrayOf(147.2, 49.8),
arrayOf(168.2, 49.2),
arrayOf(175.0, 73.2),
arrayOf(157.0, 47.8),
arrayOf(167.6, 68.8),
arrayOf(159.5, 50.6),
arrayOf(175.0, 82.5),
arrayOf(166.8, 57.2),
arrayOf(176.5, 87.8),
arrayOf(170.2, 72.8),
arrayOf(174.0, 54.5),
arrayOf(173.0, 59.8),
arrayOf(179.9, 67.3),
arrayOf(170.5, 67.8),
arrayOf(160.0, 47.0),
arrayOf(154.4, 46.2),
arrayOf(162.0, 55.0),
arrayOf(176.5, 83.0),
arrayOf(160.0, 54.4),
arrayOf(152.0, 45.8),
arrayOf(162.1, 53.6),
arrayOf(170.0, 73.2),
arrayOf(160.2, 52.1),
arrayOf(161.3, 67.9),
arrayOf(166.4, 56.6),
arrayOf(168.9, 62.3),
arrayOf(163.8, 58.5),
arrayOf(167.6, 54.5),
arrayOf(160.0, 50.2),
arrayOf(161.3, 60.3),
arrayOf(167.6, 58.3),
arrayOf(165.1, 56.2),
arrayOf(160.0, 50.2),
arrayOf(170.0, 72.9),
arrayOf(157.5, 59.8),
arrayOf(167.6, 61.0),
arrayOf(160.7, 69.1),
arrayOf(163.2, 55.9),
arrayOf(152.4, 46.5),
arrayOf(157.5, 54.3),
arrayOf(168.3, 54.8),
arrayOf(180.3, 60.7),
arrayOf(165.5, 60.0),
arrayOf(165.0, 62.0),
arrayOf(164.5, 60.3),
arrayOf(156.0, 52.7),
arrayOf(160.0, 74.3),
arrayOf(163.0, 62.0),
arrayOf(165.7, 73.1),
arrayOf(161.0, 80.0),
arrayOf(162.0, 54.7),
arrayOf(166.0, 53.2),
arrayOf(174.0, 75.7),
arrayOf(172.7, 61.1),
arrayOf(167.6, 55.7),
arrayOf(151.1, 48.7),
arrayOf(164.5, 52.3),
arrayOf(163.5, 50.0),
arrayOf(152.0, 59.3),
arrayOf(169.0, 62.5),
arrayOf(164.0, 55.7),
arrayOf(161.2, 54.8),
arrayOf(155.0, 45.9),
arrayOf(170.0, 70.6),
arrayOf(176.2, 67.2),
arrayOf(170.0, 69.4),
arrayOf(162.5, 58.2),
arrayOf(170.3, 64.8),
arrayOf(164.1, 71.6),
arrayOf(169.5, 52.8),
arrayOf(163.2, 59.8),
arrayOf(154.5, 49.0),
arrayOf(159.8, 50.0),
arrayOf(173.2, 69.2),
arrayOf(170.0, 55.9),
arrayOf(161.4, 63.4),
arrayOf(169.0, 58.2),
arrayOf(166.2, 58.6),
arrayOf(159.4, 45.7),
arrayOf(162.5, 52.2),
arrayOf(159.0, 48.6),
arrayOf(162.8, 57.8),
arrayOf(159.0, 55.6),
arrayOf(179.8, 66.8),
arrayOf(162.9, 59.4),
arrayOf(161.0, 53.6),
arrayOf(151.1, 73.2),
arrayOf(168.2, 53.4),
arrayOf(168.9, 69.0),
arrayOf(173.2, 58.4),
arrayOf(171.8, 56.2),
arrayOf(178.0, 70.6),
arrayOf(164.3, 59.8),
arrayOf(163.0, 72.0),
arrayOf(168.5, 65.2),
arrayOf(166.8, 56.6),
arrayOf(172.7, 88.8),
arrayOf(163.5, 51.8),
arrayOf(169.4, 63.4),
arrayOf(167.8, 59.0),
arrayOf(159.5, 47.6),
arrayOf(167.6, 63.0),
arrayOf(161.2, 55.2),
arrayOf(160.0, 45.0),
arrayOf(163.2, 54.0),
arrayOf(162.2, 50.2),
arrayOf(161.3, 60.2),
arrayOf(149.5, 44.8),
arrayOf(157.5, 58.8),
arrayOf(163.2, 56.4),
arrayOf(172.7, 62.0),
arrayOf(155.0, 49.2),
arrayOf(156.5, 67.2),
arrayOf(164.0, 53.8),
arrayOf(160.9, 54.4),
arrayOf(162.8, 58.0),
arrayOf(167.0, 59.8),
arrayOf(160.0, 54.8),
arrayOf(160.0, 43.2),
arrayOf(168.9, 60.5),
arrayOf(158.2, 46.4),
arrayOf(156.0, 64.4),
arrayOf(160.0, 48.8),
arrayOf(167.1, 62.2),
arrayOf(158.0, 55.5),
arrayOf(167.6, 57.8),
arrayOf(156.0, 54.6),
arrayOf(162.1, 59.2),
arrayOf(173.4, 52.7),
arrayOf(159.8, 53.2),
arrayOf(170.5, 64.5),
arrayOf(159.2, 51.8),
arrayOf(157.5, 56.0),
arrayOf(161.3, 63.6),
arrayOf(162.6, 63.2),
arrayOf(160.0, 59.5),
arrayOf(168.9, 56.8),
arrayOf(165.1, 64.1),
arrayOf(162.6, 50.0),
arrayOf(165.1, 72.3),
arrayOf(166.4, 55.0),
arrayOf(160.0, 55.9),
arrayOf(152.4, 60.4),
arrayOf(170.2, 69.1),
arrayOf(162.6, 84.5),
arrayOf(170.2, 55.9),
arrayOf(158.8, 55.5),
arrayOf(172.7, 69.5),
arrayOf(167.6, 76.4),
arrayOf(162.6, 61.4),
arrayOf(167.6, 65.9),
arrayOf(156.2, 58.6),
arrayOf(175.2, 66.8),
arrayOf(172.1, 56.6),
arrayOf(162.6, 58.6),
arrayOf(160.0, 55.9),
arrayOf(165.1, 59.1),
arrayOf(182.9, 81.8),
arrayOf(166.4, 70.7),
arrayOf(165.1, 56.8),
arrayOf(177.8, 60.0),
arrayOf(165.1, 58.2),
arrayOf(175.3, 72.7),
arrayOf(154.9, 54.1),
arrayOf(158.8, 49.1),
arrayOf(172.7, 75.9),
arrayOf(168.9, 55.0),
arrayOf(161.3, 57.3),
arrayOf(167.6, 55.0),
arrayOf(165.1, 65.5),
arrayOf(175.3, 65.5),
arrayOf(157.5, 48.6),
arrayOf(163.8, 58.6),
arrayOf(167.6, 63.6),
arrayOf(165.1, 55.2),
arrayOf(165.1, 62.7),
arrayOf(168.9, 56.6),
arrayOf(162.6, 53.9),
arrayOf(164.5, 63.2),
arrayOf(176.5, 73.6),
arrayOf(168.9, 62.0),
arrayOf(175.3, 63.6),
arrayOf(159.4, 53.2),
arrayOf(160.0, 53.4),
arrayOf(170.2, 55.0),
arrayOf(162.6, 70.5),
arrayOf(167.6, 54.5),
arrayOf(162.6, 54.5),
arrayOf(160.7, 55.9),
arrayOf(160.0, 59.0),
arrayOf(157.5, 63.6),
arrayOf(162.6, 54.5),
arrayOf(152.4, 47.3),
arrayOf(170.2, 67.7),
arrayOf(165.1, 80.9),
arrayOf(172.7, 70.5),
arrayOf(165.1, 60.9),
arrayOf(170.2, 63.6),
arrayOf(170.2, 54.5),
arrayOf(170.2, 59.1),
arrayOf(161.3, 70.5),
arrayOf(167.6, 52.7),
arrayOf(167.6, 62.7),
arrayOf(165.1, 86.3),
arrayOf(162.6, 66.4),
arrayOf(152.4, 67.3),
arrayOf(168.9, 63.0),
arrayOf(170.2, 73.6),
arrayOf(175.2, 62.3),
arrayOf(175.2, 57.7),
arrayOf(160.0, 55.4),
arrayOf(165.1, 77.7),
arrayOf(174.0, 55.5),
arrayOf(170.2, 77.3),
arrayOf(160.0, 80.5),
arrayOf(167.6, 64.5),
arrayOf(167.6, 72.3),
arrayOf(167.6, 61.4),
arrayOf(154.9, 58.2),
arrayOf(162.6, 81.8),
arrayOf(175.3, 63.6),
arrayOf(171.4, 53.4),
arrayOf(157.5, 54.5),
arrayOf(165.1, 53.6),
arrayOf(160.0, 60.0),
arrayOf(174.0, 73.6),
arrayOf(162.6, 61.4),
arrayOf(174.0, 55.5),
arrayOf(162.6, 63.6),
arrayOf(161.3, 60.9),
arrayOf(156.2, 60.0),
arrayOf(149.9, 46.8),
arrayOf(169.5, 57.3),
arrayOf(160.0, 64.1),
arrayOf(175.3, 63.6),
arrayOf(169.5, 67.3),
arrayOf(160.0, 75.5),
arrayOf(172.7, 68.2),
arrayOf(162.6, 61.4),
arrayOf(157.5, 76.8),
arrayOf(176.5, 71.8),
arrayOf(164.4, 55.5),
arrayOf(160.7, 48.6),
arrayOf(174.0, 66.4),
arrayOf(163.8, 67.3)
)
)
val elementTwo = AASeriesElement()
.name("Male")
.color("rgba(119, 152, 191, 1)")
.data(
arrayOf(
arrayOf(174.0, 65.6),
arrayOf(175.3, 71.8),
arrayOf(193.5, 80.7),
arrayOf(186.5, 72.6),
arrayOf(187.2, 78.8),
arrayOf(181.5, 74.8),
arrayOf(184.0, 86.4),
arrayOf(184.5, 78.4),
arrayOf(175.0, 62.0),
arrayOf(184.0, 81.6),
arrayOf(180.0, 76.6),
arrayOf(177.8, 83.6),
arrayOf(192.0, 90.0),
arrayOf(176.0, 74.6),
arrayOf(174.0, 71.0),
arrayOf(184.0, 79.6),
arrayOf(192.7, 93.8),
arrayOf(171.5, 70.0),
arrayOf(173.0, 72.4),
arrayOf(176.0, 85.9),
arrayOf(176.0, 78.8),
arrayOf(180.5, 77.8),
arrayOf(172.7, 66.2),
arrayOf(176.0, 86.4),
arrayOf(173.5, 81.8),
arrayOf(178.0, 89.6),
arrayOf(180.3, 82.8),
arrayOf(180.3, 76.4),
arrayOf(164.5, 63.2),
arrayOf(173.0, 60.9),
arrayOf(183.5, 74.8),
arrayOf(175.5, 70.0),
arrayOf(188.0, 72.4),
arrayOf(189.2, 84.1),
arrayOf(172.8, 69.1),
arrayOf(170.0, 59.5),
arrayOf(182.0, 67.2),
arrayOf(170.0, 61.3),
arrayOf(177.8, 68.6),
arrayOf(184.2, 80.1),
arrayOf(186.7, 87.8),
arrayOf(171.4, 84.7),
arrayOf(172.7, 73.4),
arrayOf(175.3, 72.1),
arrayOf(180.3, 82.6),
arrayOf(182.9, 88.7),
arrayOf(188.0, 84.1),
arrayOf(177.2, 94.1),
arrayOf(172.1, 74.9),
arrayOf(167.0, 59.1),
arrayOf(169.5, 75.6),
arrayOf(174.0, 86.2),
arrayOf(172.7, 75.3),
arrayOf(182.2, 87.1),
arrayOf(164.1, 55.2),
arrayOf(163.0, 57.0),
arrayOf(171.5, 61.4),
arrayOf(184.2, 76.8),
arrayOf(174.0, 86.8),
arrayOf(174.0, 72.2),
arrayOf(177.0, 71.6),
arrayOf(186.0, 84.8),
arrayOf(167.0, 68.2),
arrayOf(171.8, 66.1),
arrayOf(182.0, 72.0),
arrayOf(167.0, 64.6),
arrayOf(177.8, 74.8),
arrayOf(164.5, 70.0),
arrayOf(192.0, 99.9),
arrayOf(175.5, 63.2),
arrayOf(171.2, 79.1),
arrayOf(181.6, 78.9),
arrayOf(167.4, 67.7),
arrayOf(181.1, 66.0),
arrayOf(177.0, 68.2),
arrayOf(174.5, 63.9),
arrayOf(177.5, 72.0),
arrayOf(170.5, 56.8),
arrayOf(182.4, 74.5),
arrayOf(197.1, 90.9),
arrayOf(180.1, 93.0),
arrayOf(175.5, 80.9),
arrayOf(180.6, 72.7),
arrayOf(184.4, 68.0),
arrayOf(175.5, 70.9),
arrayOf(180.6, 72.5),
arrayOf(177.0, 72.5),
arrayOf(177.1, 83.4),
arrayOf(181.6, 75.5),
arrayOf(176.5, 73.0),
arrayOf(175.0, 70.2),
arrayOf(174.0, 73.4),
arrayOf(165.1, 70.5),
arrayOf(177.0, 68.9),
arrayOf(192.0, 99.7),
arrayOf(176.5, 68.4),
arrayOf(169.4, 65.9),
arrayOf(182.1, 75.7),
arrayOf(179.8, 84.5),
arrayOf(175.3, 87.7),
arrayOf(184.9, 86.4),
arrayOf(177.3, 73.2),
arrayOf(167.4, 53.9),
arrayOf(178.1, 72.0),
arrayOf(168.9, 55.5),
arrayOf(157.2, 58.4),
arrayOf(180.3, 83.2),
arrayOf(170.2, 72.7),
arrayOf(177.8, 64.1),
arrayOf(172.7, 72.3),
arrayOf(165.1, 65.0),
arrayOf(186.7, 86.4),
arrayOf(165.1, 65.0),
arrayOf(174.0, 88.6),
arrayOf(175.3, 84.1),
arrayOf(185.4, 66.8),
arrayOf(177.8, 75.5),
arrayOf(180.3, 93.2),
arrayOf(180.3, 82.7),
arrayOf(177.8, 58.0),
arrayOf(177.8, 79.5),
arrayOf(177.8, 78.6),
arrayOf(177.8, 71.8),
arrayOf(177.8, 88.8),
arrayOf(163.8, 72.2),
arrayOf(188.0, 83.6),
arrayOf(198.1, 85.5),
arrayOf(175.3, 90.9),
arrayOf(166.4, 85.9),
arrayOf(190.5, 89.1),
arrayOf(166.4, 75.0),
arrayOf(177.8, 77.7),
arrayOf(179.7, 86.4),
arrayOf(172.7, 90.9),
arrayOf(190.5, 73.6),
arrayOf(185.4, 76.4),
arrayOf(168.9, 69.1),
arrayOf(167.6, 84.5),
arrayOf(175.3, 64.5),
arrayOf(170.2, 69.1),
arrayOf(190.5, 108.6),
arrayOf(177.8, 86.4),
arrayOf(190.5, 80.9),
arrayOf(177.8, 87.7),
arrayOf(184.2, 94.5),
arrayOf(176.5, 80.2),
arrayOf(177.8, 72.0),
arrayOf(180.3, 71.4),
arrayOf(171.4, 72.7),
arrayOf(172.7, 84.1),
arrayOf(172.7, 76.8),
arrayOf(177.8, 63.6),
arrayOf(177.8, 80.9),
arrayOf(182.9, 80.9),
arrayOf(170.2, 85.5),
arrayOf(167.6, 68.6),
arrayOf(175.3, 67.7),
arrayOf(165.1, 66.4),
arrayOf(185.4, 77.7),
arrayOf(181.6, 70.5),
arrayOf(172.7, 95.9),
arrayOf(190.5, 84.1),
arrayOf(179.1, 87.3),
arrayOf(175.3, 71.8),
arrayOf(170.2, 65.9),
arrayOf(193.0, 95.9),
arrayOf(171.4, 91.4),
arrayOf(177.8, 81.8),
arrayOf(177.8, 96.8),
arrayOf(167.6, 69.1),
arrayOf(167.6, 82.7),
arrayOf(180.3, 75.5),
arrayOf(182.9, 79.5),
arrayOf(176.5, 73.6),
arrayOf(186.7, 91.8),
arrayOf(188.0, 84.1),
arrayOf(188.0, 85.9),
arrayOf(177.8, 81.8),
arrayOf(174.0, 82.5),
arrayOf(177.8, 80.5),
arrayOf(171.4, 70.0),
arrayOf(185.4, 81.8),
arrayOf(185.4, 84.1),
arrayOf(188.0, 90.5),
arrayOf(188.0, 91.4),
arrayOf(182.9, 89.1),
arrayOf(176.5, 85.0),
arrayOf(175.3, 69.1),
arrayOf(175.3, 73.6),
arrayOf(188.0, 80.5),
arrayOf(188.0, 82.7),
arrayOf(175.3, 86.4),
arrayOf(170.5, 67.7),
arrayOf(179.1, 92.7),
arrayOf(177.8, 93.6),
arrayOf(175.3, 70.9),
arrayOf(182.9, 75.0),
arrayOf(170.8, 93.2),
arrayOf(188.0, 93.2),
arrayOf(180.3, 77.7),
arrayOf(177.8, 61.4),
arrayOf(185.4, 94.1),
arrayOf(168.9, 75.0),
arrayOf(185.4, 83.6),
arrayOf(180.3, 85.5),
arrayOf(174.0, 73.9),
arrayOf(167.6, 66.8),
arrayOf(182.9, 87.3),
arrayOf(160.0, 72.3),
arrayOf(180.3, 88.6),
arrayOf(167.6, 75.5),
arrayOf(186.7, 66.8),
arrayOf(175.3, 91.1),
arrayOf(175.3, 67.3),
arrayOf(175.9, 77.7),
arrayOf(175.3, 81.8),
arrayOf(179.1, 75.5),
arrayOf(181.6, 84.5),
arrayOf(177.8, 76.6),
arrayOf(182.9, 85.0),
arrayOf(177.8, 81.8),
arrayOf(184.2, 77.3),
arrayOf(179.1, 71.8),
arrayOf(176.5, 87.9),
arrayOf(188.0, 94.3),
arrayOf(174.0, 70.9),
arrayOf(167.6, 64.5),
arrayOf(170.2, 77.3),
arrayOf(167.6, 72.3),
arrayOf(188.0, 87.3),
arrayOf(174.0, 80.0),
arrayOf(176.5, 82.3),
arrayOf(180.3, 73.6),
arrayOf(167.6, 74.1),
arrayOf(188.0, 85.9),
arrayOf(180.3, 73.2),
arrayOf(167.6, 76.3),
arrayOf(183.0, 65.9),
arrayOf(183.0, 90.9),
arrayOf(179.1, 89.1),
arrayOf(170.2, 62.3),
arrayOf(177.8, 82.7),
arrayOf(179.1, 79.1),
arrayOf(190.5, 98.2),
arrayOf(177.8, 84.1),
arrayOf(180.3, 83.2),
arrayOf(180.3, 83.2)
)
);
val seriesElements = arrayOf(elementOne, elementTwo)
return AAChartModel()
.chartType(AAChartType.Scatter)
.title("Height and weight distribution by sex")
.yAxisTitle("kg")
.markerRadius(8f)
.markerSymbolStyle(AAChartSymbolStyleType.InnerBlank)
.series(seriesElements)
}
fun configureArearangeChart(): AAChartModel {
return AAChartModel()
.chartType(AAChartType.Arearange)
.title("Twilight Hall day temperature fluctuation map")
.subtitle("real-time monitoring data")
.yAxisTitle("℃")
.series(
arrayOf(
AASeriesElement()
.name("2020")
.data(
arrayOf(
/* 2014-01-01 */
arrayOf(138853800, 1.1, 4.7),
arrayOf(138862440, 1.8, 6.4),
arrayOf(138871080, 1.7, 6.9),
arrayOf(138879720, 2.6, 7.4),
arrayOf(138888360, 3.3, 9.3),
arrayOf(138897000, 3.0, 7.9),
arrayOf(138905640, 3.9, 6.0),
arrayOf(138914280, 3.9, 5.5),
arrayOf(138922920, -0.6, 4.5),
arrayOf(138931560, -0.5, 5.3),
arrayOf(138940200, -0.3, 2.4),
arrayOf(138948840, -6.5, -0.4),
arrayOf(138957480, -7.3, -3.4),
arrayOf(138966120, -7.3, -2.3),
arrayOf(138974760, -7.9, -4.2),
arrayOf(138983400, -4.7, 0.9),
arrayOf(138992040, -1.2, 0.4),
arrayOf(139000680, -2.3, -0.1),
arrayOf(139009320, -2.0, 0.3),
arrayOf(139017960, -5.1, -2.0),
arrayOf(139026600, -4.4, -0.5),
arrayOf(139035240, -6.4, -2.7),
arrayOf(139043880, -3.2, -0.5),
arrayOf(139052520, -5.5, -0.8),
arrayOf(139061160, -4.4, 2.4),
arrayOf(139069800, -4.0, 1.1),
arrayOf(139078440, -3.4, 0.8),
arrayOf(139087080, -1.7, 2.6),
arrayOf(139095720, -3.1, 3.9),
arrayOf(139104360, -8, -1.9),
arrayOf(139113000, -7, -2.8),
/* 2014-02-01 */
arrayOf(139121640, -2.7, 2.6),
arrayOf(139130280, -1.3, 8.2),
arrayOf(139138920, 1.5, 7.7),
arrayOf(139147560, -0.5, 5.3),
arrayOf(139156200, -0.2, 5.2),
arrayOf(139164840, 0.7, 4.8),
arrayOf(139173480, 0.9, 5.7),
arrayOf(139182120, 1.7, 3.9),
arrayOf(139190760, 2.2, 8.8),
arrayOf(139199400, 3.0, 6.6),
arrayOf(139208040, 1.4, 5.4),
arrayOf(139216680, 0.6, 5.1),
arrayOf(139225320, 0.1, 7.8),
arrayOf(139233960, 3.4, 7.3),
arrayOf(139242600, 2.0, 5.9),
arrayOf(139251240, 1.1, 4.7),
arrayOf(139259880, 1.1, 4.4),
arrayOf(139268520, -2.8, 2.6),
arrayOf(139277160, -5.0, 0.1),
arrayOf(139285800, -5.7, 0.2),
arrayOf(139294440, -0.7, 3.9),
arrayOf(139303080, 1.5, 7.8),
arrayOf(139311720, 5.5, 8.8),
arrayOf(139320360, 5.3, 11.7),
arrayOf(139329000, 1.7, 11.1),
arrayOf(139337640, 3.4, 9.3),
arrayOf(139346280, 3.4, 7.3),
arrayOf(139354920, 4.5, 8.0),
/* 2014-03-01 */
arrayOf(139363560, 2.1, 8.9),
arrayOf(139372200, 0.6, 6.1),
arrayOf(139380840, 1.2, 9.4),
arrayOf(139389480, 2.6, 7.3),
arrayOf(139398120, 3.9, 9.5),
arrayOf(139406760, 5.3, 9.9),
arrayOf(139415400, 2.7, 7.1),
arrayOf(139424040, 4.0, 8.6),
arrayOf(139432680, 6.1, 10.7),
arrayOf(139441320, 4.2, 7.6),
arrayOf(139449960, 2.5, 9.0),
arrayOf(139458600, 0.2, 7.0),
arrayOf(139467240, -1.2, 6.9),
arrayOf(139475880, 0.4, 6.7),
arrayOf(139484520, 0.2, 5.1),
arrayOf(139493160, -0.1, 6.0),
arrayOf(139501800, 1.0, 5.6),
arrayOf(139510440, -1.1, 6.3),
arrayOf(139519080, -1.9, 0.3),
arrayOf(139527720, 0.3, 4.5),
arrayOf(139536360, 2.4, 6.7),
arrayOf(139545000, 3.2, 9.2),
arrayOf(139553640, 1.7, 3.6),
arrayOf(139562280, -0.3, 7.9),
arrayOf(139570920, -2.4, 8.6),
arrayOf(139579560, -1.7, 10.3),
arrayOf(139588200, 4.1, 10.0),
arrayOf(139596840, 4.4, 14.0),
arrayOf(139605480, 3.3, 11.0),
arrayOf(139614120, 3.0, 12.5),
arrayOf(139622400, 1.4, 10.4),
/* 2014-04-01 */
arrayOf(139631040, -1.2, 8.8),
arrayOf(139639680, 2.2, 7.6),
arrayOf(139648320, -1.0, 10.1),
arrayOf(139656960, -1.8, 9.5),
arrayOf(139665600, 0.2, 7.7),
arrayOf(139674240, 3.7, 6.4),
arrayOf(139682880, 5.8, 11.4),
arrayOf(139691520, 5.4, 8.7),
arrayOf(139700160, 4.5, 12.2),
arrayOf(139708800, 3.9, 8.4),
arrayOf(139717440, 4.5, 8.0),
arrayOf(139726080, 6.6, 8.4),
arrayOf(139734720, 3.7, 7.3),
arrayOf(139743360, 3.6, 6.7),
arrayOf(139752000, 3.5, 8.3),
arrayOf(139760640, 1.5, 10.2),
arrayOf(139769280, 4.9, 9.4),
arrayOf(139777920, 3.5, 12.0),
arrayOf(139786560, 1.5, 13.1),
arrayOf(139795200, 1.7, 15.6),
arrayOf(139803840, 1.4, 16.0),
arrayOf(139812480, 3.0, 18.4),
arrayOf(139821120, 5.6, 18.8),
arrayOf(139829760, 5.7, 17.2),
arrayOf(139838400, 4.5, 16.4),
arrayOf(139847040, 3.1, 17.6),
arrayOf(139855680, 4.7, 18.9),
arrayOf(139864320, 4.9, 16.6),
arrayOf(139872960, 6.8, 15.6),
arrayOf(139881600, 2.8, 9.2),
/* 2014-05-01 */
arrayOf(139890240, -2.7, 10.5),
arrayOf(139898880, -1.9, 10.9),
arrayOf(139907520, 4.5, 8.5),
arrayOf(139916160, -0.6, 10.4),
arrayOf(139924800, 4.0, 9.7),
arrayOf(139933440, 5.5, 9.5),
arrayOf(139942080, 6.5, 13.2),
arrayOf(139950720, 3.2, 14.5),
arrayOf(139959360, 2.1, 13.5),
arrayOf(139968000, 6.5, 15.6),
arrayOf(139976640, 5.7, 16.2),
arrayOf(139985280, 6.3, 15.3),
arrayOf(139993920, 5.3, 15.3),
arrayOf(140002560, 6.0, 14.1),
arrayOf(140011200, 1.9, 7.7),
arrayOf(140019840, 7.2, 9.8),
arrayOf(140028480, 8.9, 15.2),
arrayOf(140037120, 9.1, 20.5),
arrayOf(140045760, 8.4, 17.9),
arrayOf(140054400, 6.8, 21.5),
arrayOf(140063040, 7.6, 14.1),
arrayOf(140071680, 11.1, 16.5),
arrayOf(140080320, 9.3, 14.3),
arrayOf(140088960, 10.4, 19.3),
arrayOf(140097600, 5.7, 19.4),
arrayOf(140106240, 7.9, 17.9),
arrayOf(140114880, 5.0, 22.5),
arrayOf(140123520, 7.6, 22.0),
arrayOf(140132160, 5.7, 21.9),
arrayOf(140140800, 4.6, 20.0),
arrayOf(140149440, 7.0, 22.0),
/* 2014-06-01 */
arrayOf(140158080, 5.1, 20.6),
arrayOf(140166720, 6.6, 24.6),
arrayOf(140175360, 9.7, 22.2),
arrayOf(140184000, 9.6, 21.6),
arrayOf(140192640, 13.0, 20.0),
arrayOf(140201280, 12.9, 18.2),
arrayOf(140209920, 8.5, 23.2),
arrayOf(140218560, 9.2, 21.4),
arrayOf(140227200, 10.5, 22.0),
arrayOf(140235840, 7.3, 23.4),
arrayOf(140244480, 12.1, 18.2),
arrayOf(140253120, 11.1, 13.3),
arrayOf(140261760, 10.0, 20.7),
arrayOf(140270400, 5.8, 23.4),
arrayOf(140279040, 7.4, 20.1),
arrayOf(140287680, 10.3, 21.9),
arrayOf(140296320, 7.8, 16.8),
arrayOf(140304960, 11.6, 19.7),
arrayOf(140313600, 9.8, 16.0),
arrayOf(140322240, 10.7, 14.4),
arrayOf(140330880, 9.0, 15.5),
arrayOf(140339520, 5.1, 13.3),
arrayOf(140348160, 10.0, 19.3),
arrayOf(140356800, 5.2, 22.1),
arrayOf(140365440, 6.3, 21.3),
arrayOf(140374080, 5.5, 21.1),
arrayOf(140382720, 8.4, 19.7),
arrayOf(140391360, 7.1, 23.3),
arrayOf(140400000, 6.1, 20.8),
arrayOf(140408640, 8.4, 22.6),
/* 2014-07-01 */
arrayOf(140417280, 7.6, 23.3),
arrayOf(140425920, 8.1, 21.5),
arrayOf(140434560, 11.2, 18.1),
arrayOf(140443200, 6.4, 14.9),
arrayOf(140451840, 12.7, 23.1),
arrayOf(140460480, 15.3, 21.7),
arrayOf(140469120, 15.1, 19.4),
arrayOf(140477760, 10.8, 22.8),
arrayOf(140486400, 15.8, 29.7),
arrayOf(140495040, 15.8, 29.0),
arrayOf(140503680, 15.2, 30.5),
arrayOf(140512320, 14.9, 28.1),
arrayOf(140520960, 13.1, 27.4),
arrayOf(140529600, 15.5, 23.5),
arrayOf(140538240, 14.7, 20.1),
arrayOf(140546880, 14.4, 16.8),
arrayOf(140555520, 12.6, 18.5),
arrayOf(140564160, 13.9, 24.4),
arrayOf(140572800, 11.3, 26.9),
arrayOf(140581440, 13.3, 27.4),
arrayOf(140590080, 13.3, 29.7),
arrayOf(140598720, 14.0, 28.8),
arrayOf(140607360, 14.1, 29.8),
arrayOf(140616000, 15.4, 31.1),
arrayOf(140624640, 17.0, 26.5),
arrayOf(140633280, 16.6, 27.1),
arrayOf(140641920, 13.3, 25.6),
arrayOf(140650560, 16.8, 21.9),
arrayOf(140659200, 16.0, 22.8),
arrayOf(140667840, 14.4, 19.0),
arrayOf(140676480, 12.8, 18.1),
/* 2014-08-01 */
arrayOf(140685120, 12.6, 18.0),
arrayOf(140693760, 11.4, 19.7),
arrayOf(140702400, 13.9, 18.9),
arrayOf(140711040, 12.5, 19.9),
arrayOf(140719680, 12.3, 23.4),
arrayOf(140728320, 12.8, 23.3),
arrayOf(140736960, 11.0, 20.4),
arrayOf(140745600, 14.7, 22.4),
arrayOf(140754240, 11.1, 23.6),
arrayOf(140762880, 13.5, 20.7),
arrayOf(140771520, 13.7, 23.1),
arrayOf(140780160, 12.8, 19.6),
arrayOf(140788800, 12.1, 18.7),
arrayOf(140797440, 8.8, 22.4),
arrayOf(140806080, 8.2, 20.1),
arrayOf(140814720, 10.9, 16.3),
arrayOf(140823360, 10.7, 16.1),
arrayOf(140832000, 11.0, 18.9),
arrayOf(140840640, 12.1, 14.7),
arrayOf(140849280, 11.2, 14.4),
arrayOf(140857920, 9.9, 16.6),
arrayOf(140866560, 6.9, 15.7),
arrayOf(140875200, 8.9, 15.3),
arrayOf(140883840, 8.2, 17.6),
arrayOf(140892480, 8.4, 19.5),
arrayOf(140901120, 6.6, 19.9),
arrayOf(140909760, 6.4, 19.7),
arrayOf(140918400, null, null),
arrayOf(140927040, null, null),
arrayOf(140935680, null, null),
arrayOf(140944320, null, null),
/* 2014-09-01 */
arrayOf(140952960, null, null),
arrayOf(140961600, null, null),
arrayOf(140970240, null, null),
arrayOf(140978880, null, null),
arrayOf(140987520, null, null),
arrayOf(140996160, 13.4, 13.4),
arrayOf(141004800, 13.2, 17.1),
arrayOf(141013440, 11.9, 18.9),
arrayOf(141022080, 9.0, 15.9),
arrayOf(141030720, 5.9, 17.5),
arrayOf(141039360, 6.8, 16.2),
arrayOf(141048000, 10.3, 19.9),
arrayOf(141056640, 8.7, 17.9),
arrayOf(141065280, 7.9, 19.1),
arrayOf(141073920, 6.0, 20.1),
arrayOf(141082560, 4.7, 19.9),
arrayOf(141091200, 4.0, 18.8),
arrayOf(141099840, 4.5, 17.9),
arrayOf(141108480, 3.1, 16.1),
arrayOf(141117120, 8.5, 12.2),
arrayOf(141125760, 7.6, 13.8),
arrayOf(141134400, 1.3, 12.6),
arrayOf(141143040, 2.0, 10.9),
arrayOf(141151680, 5.0, 10.8),
arrayOf(141160320, 6.4, 10.1),
arrayOf(141168960, 8.2, 13.3),
arrayOf(141177600, 8.9, 11.8),
arrayOf(141186240, 9.9, 15.9),
arrayOf(141194880, 5.2, 12.5),
arrayOf(141203520, 4.6, 11.7),
/* 2014-10-01 */
arrayOf(141212160, 8.8, 12.1),
arrayOf(141220800, 3.9, 12.3),
arrayOf(141229440, 2.7, 18.1),
arrayOf(141238080, 10.2, 18.2),
arrayOf(141246720, 9.6, 17.9),
arrayOf(141255360, 9.3, 17.5),
arrayOf(141264000, 8.1, 12.7),
arrayOf(141272640, 6.7, 11.2),
arrayOf(141281280, 4.0, 10.0),
arrayOf(141289920, 6.3, 10.2),
arrayOf(141298560, 6.6, 10.7),
arrayOf(141307200, 6.6, 10.3),
arrayOf(141315840, 5.9, 10.4),
arrayOf(141324480, 1.2, 10.6),
arrayOf(141333120, -0.1, 9.2),
arrayOf(141341760, -1.0, 9.4),
arrayOf(141350400, -1.7, 8.3),
arrayOf(141359040, -0.6, 7.5),
arrayOf(141367680, 6.9, 10.1),
arrayOf(141376320, 7.7, 10.5),
arrayOf(141384960, 3.8, 9.7),
arrayOf(141393600, 6.2, 8.6),
arrayOf(141402240, 6.5, 9.2),
arrayOf(141410880, 7.9, 10.7),
arrayOf(141419520, 6.1, 10.9),
arrayOf(141428160, 10.3, 13.1),
arrayOf(141437160, 7.1, 13.3),
arrayOf(141445800, 0.0, 10.1),
arrayOf(141454440, 0.0, 5.7),
arrayOf(141463080, 3.9, 4.6),
arrayOf(141471720, 4.0, 4.8),
/* 2014-11-01 */
arrayOf(141480360, 4.8, 11.2),
arrayOf(141489000, 7.0, 8.5),
arrayOf(141497640, 3.0, 9.8),
arrayOf(141506280, 2.8, 5.9),
arrayOf(141514920, 0.8, 4.8),
arrayOf(141523560, -0.2, 2.9),
arrayOf(141532200, -0.6, 5.5),
arrayOf(141540840, 6.6, 10.3),
arrayOf(141549480, 5.4, 7.3),
arrayOf(141558120, 3.0, 8.4),
arrayOf(141566760, 0.4, 3.2),
arrayOf(141575400, -0.1, 6.8),
arrayOf(141584040, 4.8, 8.8),
arrayOf(141592680, 4.6, 8.5),
arrayOf(141601320, 4.3, 7.7),
arrayOf(141609960, 3.3, 7.5),
arrayOf(141618600, -0.4, 3.2),
arrayOf(141627240, 1.9, 4.7),
arrayOf(141635880, -0.2, 3.7),
arrayOf(141644520, -1.3, 2.1),
arrayOf(141653160, -1.8, 0.9),
arrayOf(141661800, -2.7, 1.3),
arrayOf(141670440, 0.3, 2.5),
arrayOf(141679080, 3.4, 6.5),
arrayOf(141687720, 0.8, 6.1),
arrayOf(141696360, -1.0, 1.3),
arrayOf(141705000, 0.4, 3.1),
arrayOf(141713640, -1.2, 1.9),
arrayOf(141722280, -1.1, 2.8),
arrayOf(141730920, -0.7, 1.8),
/* 2014-12-01 */
arrayOf(141739560, 0.5, 2.5),
arrayOf(141748200, 1.4, 3.2),
arrayOf(141756840, 4.5, 10.2),
arrayOf(141765480, 0.4, 10.0),
arrayOf(141774120, 2.5, 3.7),
arrayOf(141782760, 1.1, 5.0),
arrayOf(141791400, 2.0, 4.4),
arrayOf(141800040, 1.4, 2.2),
arrayOf(141808680, 0.7, 4.6),
arrayOf(141817320, 1.9, 3.9),
arrayOf(141825960, -0.2, 3.7),
arrayOf(141834600, -0.1, 1.7),
arrayOf(141843240, -1.0, 3.8),
arrayOf(141851880, 0.5, 5.4),
arrayOf(141860520, -1.7, 5.6),
arrayOf(141869160, 0.3, 2.8),
arrayOf(141877800, -3.0, 0.4),
arrayOf(141886440, -1.1, 1.5),
arrayOf(141895080, 0.8, 3.4),
arrayOf(141903720, 0.9, 4.4),
arrayOf(141912360, 0.3, 3.9),
arrayOf(141921000, 0.6, 5.3),
arrayOf(141929640, 1.5, 4.4),
arrayOf(141938280, 0, 0),
arrayOf(141946920, 0, 0),
arrayOf(141955560, 10.6, 4),
arrayOf(141964200, 10.8, 5),
arrayOf(141972840, 8.4, 4),
arrayOf(141981480, 5.2, 2.4),
arrayOf(141990120, 1.3, 2.5),
arrayOf(141998760, 1.6, 4.2)
)
)
)
)
}
fun configureAreasplinerangeChart(): AAChartModel {
val gradientColorDic = "#ff0000"
return AAChartModel()
.chartType(AAChartType.Areasplinerange)
.title("Area spline range chart")
.subtitle("virtual data")
.yAxisTitle("℃")
.series(
arrayOf(
AASeriesElement()
.name("2020")
.color(gradientColorDic)//猩红色
.data(
arrayOf(
/* 2014-06-01 */
arrayOf(140158080, 5.1, 20.6),
arrayOf(140166720, 6.6, 24.6),
arrayOf(140175360, 9.7, 22.2),
arrayOf(140184000, 9.6, 21.6),
arrayOf(140192640, 13.0, 20.0),
arrayOf(140201280, 12.9, 18.2),
arrayOf(140209920, 8.5, 23.2),
arrayOf(140218560, 9.2, 21.4),
arrayOf(140227200, 10.5, 22.0),
arrayOf(140235840, 7.3, 23.4),
arrayOf(140244480, 12.1, 18.2),
arrayOf(140253120, 11.1, 13.3),
arrayOf(140261760, 10.0, 20.7),
arrayOf(140270400, 5.8, 23.4),
arrayOf(140279040, 7.4, 20.1),
arrayOf(140287680, 10.3, 21.9),
arrayOf(140296320, 7.8, 16.8),
arrayOf(140304960, 11.6, 19.7),
arrayOf(140313600, 9.8, 16.0),
arrayOf(140322240, 10.7, 14.4),
arrayOf(140330880, 9.0, 15.5),
arrayOf(140339520, 5.1, 13.3),
arrayOf(140348160, 10.0, 19.3),
arrayOf(140356800, 5.2, 22.1),
arrayOf(140365440, 6.3, 21.3),
arrayOf(140374080, 5.5, 21.1),
arrayOf(140382720, 8.4, 19.7),
arrayOf(140391360, 7.1, 23.3),
arrayOf(140400000, 6.1, 20.8),
arrayOf(140408640, 8.4, 22.6)
)
)
)
)
}
fun configureColumnrangeChart(): AAChartModel {
return AAChartModel()
.chartType(AAChartType.Columnrange)
.title("TEMPERATURE VARIATION BY MONTH")
.subtitle("observed in Gotham city")
.yAxisTitle("℃")
.categories(
arrayOf(
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
)
)
.dataLabelsEnabled(true)
.inverted(true)//x 轴是否垂直翻转
.series(
arrayOf(
AASeriesElement()
.name("temperature")
.data(
arrayOf(
arrayOf(-9.7, 9.4),
arrayOf(-8.7, 6.5),
arrayOf(-3.5, 9.4),
arrayOf(-1.4, 19.9),
arrayOf(0.0, 22.6),
arrayOf(2.9, 29.5),
arrayOf(9.2, 30.7),
arrayOf(7.3, 26.5),
arrayOf(4.4, 18.0),
arrayOf(-3.1, 11.4),
arrayOf(-5.2, 10.4),
arrayOf(-13.5, 9.8)
)
)
)
)
}
fun configureStepLineChart(): AAChartModel {
return AAChartModel()
.chartType(AAChartType.Line)//图形类型
.animationType(AAChartAnimationType.Bounce)//图形渲染动画类型为"bounce"
.title("STEP LINE CHART")//图形标题
.subtitle("2020/08/08")//图形副标题
.dataLabelsEnabled(false)//是否显示数字
.markerSymbolStyle(AAChartSymbolStyleType.BorderBlank)//折线连接点样式
.markerRadius(7f)//折线连接点半径长度,为0时相当于没有折线连接点
.series(
arrayOf(
AASeriesElement()
.name("Berlin")
.data(arrayOf(450, 432, 401, 454, 590, 530, 510))
.step("right")//设置折线样式为直方折线,折线连接点位置靠右👉
, AASeriesElement()
.name("New York")
.data(arrayOf(220, 282, 201, 234, 290, 430, 410))
.step("center")//设置折线样式为直方折线,折线连接点位置居中
, AASeriesElement()
.name("Tokyo")
.data(arrayOf(120, 132, 101, 134, 90, 230, 210))
.step("left")//设置折线样式为直方折线,折线连接点位置靠左👈
)
)
}
fun configureStepAreaChart(): AAChartModel {
return AAChartModel()
.chartType(AAChartType.Area)//图形类型
.animationType(AAChartAnimationType.Bounce)//图形渲染动画类型为"bounce"
.title("STEP AREA CHART")//图形标题
.subtitle("2049/08/08")//图形副标题
.dataLabelsEnabled(false)//是否显示数字
.markerSymbolStyle(AAChartSymbolStyleType.InnerBlank)//折线连接点样式
.markerRadius(0f)//折线连接点半径长度,为0时相当于没有折线连接点
.series(
arrayOf(
AASeriesElement()
.name("Berlin")
.data(arrayOf(450, 432, 401, 454, 590, 530, 510))
.step(true)//设置折线样式为直方折线,折线连接点位置靠左👈
, AASeriesElement()
.name("New York")
.data(arrayOf(220, 282, 201, 234, 290, 430, 410))
.step(true)//设置折线样式为直方折线,折线连接点位置靠左👈
, AASeriesElement()
.name("Tokyo")
.data(arrayOf(120, 132, 101, 134, 90, 230, 210))
.step(true)//设置折线样式为直方折线,折线连接点位置靠左👈
)
)
}
fun configureBoxplotChart(): AAChartModel {
return AAChartModel()
.chartType(AAChartType.Boxplot)
.title("BOXPLOT CHART")
.subtitle("virtual data")
.yAxisTitle("℃")
.series(
arrayOf(
AASeriesElement()
.name("Observed Data")
.color("#ef476f")
.fillColor(AAGradientColor.firebrickColor())
.data(
arrayOf(
arrayOf(760, 801, 848, 895, 965),
arrayOf(733, 853, 939, 980, 1080),
arrayOf(714, 762, 817, 870, 918),
arrayOf(724, 802, 806, 871, 950),
arrayOf(834, 836, 864, 882, 910)
)
)
)
)
}
fun configureWaterfallChart(): AAChartModel {
val dataElement1 = HashMap<String, Any>()
dataElement1["name"] = "启动资金"
dataElement1["y"] = 120000
val dataElement2 = HashMap<String, Any>()
dataElement2["name"] = "产品收入"
dataElement2["y"] = 569000
val dataElement3 = HashMap<String, Any>()
dataElement3["name"] = "服务收入"
dataElement3["y"] = 231000
val dataElement4 = HashMap<String, Any>()
dataElement4["name"] = "正平衡"
dataElement4["isIntermediateSum"] = true
dataElement4["color"] = "#ffd066"
val dataElement5 = HashMap<String, Any>()
dataElement5["name"] = "固定成本"
dataElement5["y"] = -342000
val dataElement6 = HashMap<String, Any>()
dataElement6["name"] = "可变成本"
dataElement6["y"] = -233000
val dataElement7 = HashMap<String, Any>()
dataElement7["name"] = "余额"
dataElement7["isSum"] = true
dataElement7["color"] = "#04d69f"
val seriesElement = AAWaterfall()
.upColor("#9b43b4")
.color("#ef476f")
.borderWidth(0f)
.data(
arrayOf(
dataElement1,
dataElement2,
dataElement3,
dataElement4,
dataElement5,
dataElement6,
dataElement7
)
)
return AAChartModel()
.chartType(AAChartType.Waterfall)
.title("WATERFALL CHART")
.subtitle("virtual data")
// .series(arrayOf(seriesElement))
}
fun configurePyramidChart(): AAChartModel {
return AAChartModel()
.chartType(AAChartType.Pyramid)
.title("THE HEAT OF PROGRAM LANGUAGE")
.subtitle("virtual data")
.yAxisTitle("℃")
.series(
arrayOf(
AASeriesElement()
.name("2020")
.data(
arrayOf(
arrayOf("Swift", 11850),
arrayOf("Objective-C", 12379),
arrayOf("JavaScript", 14286),
arrayOf("Go", 15552),
arrayOf("Python", 18654)
)
)
)
)
}
fun configureFunnelChart(): AAChartModel {
return AAChartModel()
.chartType(AAChartType.Funnel)
.title("THE HEAT OF PROGRAM LANGUAGE")
.subtitle("virtual data")
.yAxisTitle("℉")
.series(
arrayOf(
AASeriesElement()
.name("2020")
.dataLabels(
AADataLabels()
.enabled(true)
.inside(true)
.verticalAlign(AAChartVerticalAlignType.Middle)
.color(AAColor.blackColor())
.style(
AAStyle()
.fontSize(25f)
.textOutline("0px 0px contrast")
)
)
.data(
arrayOf(
arrayOf("Swift", 11850),
arrayOf("Objective-C", 12379),
arrayOf("JavaScript", 14286),
arrayOf("Go", 15552),
arrayOf("Python", 18654)
)
)
)
)
}
fun configureErrorbarChart(): AAChartModel {
return AAChartModel()
.yAxisTitle("")
.categories(
arrayOf(
"一月", "二月", "三月", "四月", "五月", "六月",
"七月", "八月", "九月", "十月", "十一月", "十二月"
)
)
.series(
arrayOf(
AASeriesElement()
.name("降水")
.type(AAChartType.Column)
.color("#06caf4")
.data(
arrayOf(
49.9, 71.5, 106.4, 129.2, 144.0, 176.0,
135.6, 148.5, 216.4, 194.1, 95.6, 54.4
)
),
AASeriesElement()
.name("降雨误差")
.type(AAChartType.Errorbar)
.lineWidth(2.5f)
.color(AAColor.redColor())
.data(
arrayOf(
arrayOf(48, 51),
arrayOf(68, 73),
arrayOf(92, 110),
arrayOf(128, 136),
arrayOf(140, 150),
arrayOf(171, 179),
arrayOf(135, 143),
arrayOf(142, 149),
arrayOf(204, 220),
arrayOf(189, 199),
arrayOf(95, 110),
arrayOf(52, 56)
)
)
.tooltip(
AATooltip()
.pointFormat("(误差范围: {point.low}-{point.high} mm)<br/>")
)
)
)
}
}
| 0 | null | 0 | 0 | cee1472782fc4a513fb6484b20702c5d1a8e0ec0 | 66,548 | AAChartCore-Kotlin | Apache License 2.0 |
idea/idea-analysis/src/org/jetbrains/kotlin/caches/resolve/JsResolverForModuleFactory.kt | kostasp-BC | 250,519,392 | true | {"Markdown": 63, "Gradle": 650, "Gradle Kotlin DSL": 385, "Java Properties": 14, "Shell": 10, "Ignore List": 12, "Batchfile": 9, "Git Attributes": 7, "Protocol Buffer": 11, "Java": 6435, "Kotlin": 55348, "Proguard": 12, "XML": 1576, "Text": 11132, "INI": 165, "JavaScript": 272, "JAR Manifest": 2, "Roff": 211, "Roff Manpage": 36, "AsciiDoc": 1, "SVG": 31, "HTML": 479, "Groovy": 33, "JSON": 106, "JFlex": 3, "Maven POM": 97, "CSS": 4, "JSON with Comments": 7, "Ant Build System": 50, "Graphviz (DOT)": 57, "C": 1, "YAML": 9, "Ruby": 3, "Objective-C": 4, "OpenStep Property List": 2, "Swift": 2, "Scala": 1} | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.caches.resolve
import org.jetbrains.kotlin.analyzer.*
import org.jetbrains.kotlin.builtins.DefaultBuiltIns
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.container.StorageComponentContainer
import org.jetbrains.kotlin.container.get
import org.jetbrains.kotlin.context.ModuleContext
import org.jetbrains.kotlin.descriptors.PackageFragmentProvider
import org.jetbrains.kotlin.descriptors.impl.CompositePackageFragmentProvider
import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl
import org.jetbrains.kotlin.frontend.di.createContainerForLazyResolve
import org.jetbrains.kotlin.idea.klib.createKlibPackageFragmentProvider
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.js.resolve.JsPlatformAnalyzerServices
import org.jetbrains.kotlin.konan.util.KlibMetadataFactories
import org.jetbrains.kotlin.resolve.BindingTraceContext
import org.jetbrains.kotlin.resolve.TargetEnvironment
import org.jetbrains.kotlin.resolve.lazy.ResolveSession
import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactoryService
import org.jetbrains.kotlin.serialization.js.DynamicTypeDeserializer
import org.jetbrains.kotlin.serialization.js.KotlinJavascriptSerializationUtil
import org.jetbrains.kotlin.serialization.js.createKotlinJavascriptPackageFragmentProvider
import org.jetbrains.kotlin.serialization.konan.impl.KlibMetadataModuleDescriptorFactoryImpl
import org.jetbrains.kotlin.utils.KotlinJavascriptMetadataUtils
class JsResolverForModuleFactory(
private val targetEnvironment: TargetEnvironment
) : ResolverForModuleFactory() {
override fun <M : ModuleInfo> createResolverForModule(
moduleDescriptor: ModuleDescriptorImpl,
moduleContext: ModuleContext,
moduleContent: ModuleContent<M>,
resolverForProject: ResolverForProject<M>,
languageVersionSettings: LanguageVersionSettings
): ResolverForModule {
val (moduleInfo, syntheticFiles, moduleContentScope) = moduleContent
val project = moduleContext.project
val declarationProviderFactory = DeclarationProviderFactoryService.createDeclarationProviderFactory(
project,
moduleContext.storageManager,
syntheticFiles,
moduleContentScope,
moduleInfo
)
val container = createContainerForLazyResolve(
moduleContext,
declarationProviderFactory,
BindingTraceContext(/* allowSliceRewrite = */ true),
moduleDescriptor.platform!!,
JsPlatformAnalyzerServices,
targetEnvironment,
languageVersionSettings
)
var packageFragmentProvider = container.get<ResolveSession>().packageFragmentProvider
val libraryProviders = createPackageFragmentProvider(moduleInfo, container, moduleContext, moduleDescriptor)
if (libraryProviders.isNotEmpty()) {
packageFragmentProvider = CompositePackageFragmentProvider(listOf(packageFragmentProvider) + libraryProviders)
}
return ResolverForModule(packageFragmentProvider, container)
}
}
internal fun <M : ModuleInfo> createPackageFragmentProvider(
moduleInfo: M,
container: StorageComponentContainer,
moduleContext: ModuleContext,
moduleDescriptor: ModuleDescriptorImpl
): List<PackageFragmentProvider> = when (moduleInfo) {
is JsKlibLibraryInfo -> {
if (moduleInfo.compatibilityInfo.isCompatible) {
val library = moduleInfo.resolvedKotlinLibrary
val languageVersionSettings = container.get<LanguageVersionSettings>()
val metadataFactories = KlibMetadataFactories(
{ DefaultBuiltIns.Instance },
DynamicTypeDeserializer
)
val klibMetadataModuleDescriptorFactory = KlibMetadataModuleDescriptorFactoryImpl(
metadataFactories.DefaultDescriptorFactory,
metadataFactories.DefaultPackageFragmentsFactory,
metadataFactories.flexibleTypeDeserializer,
metadataFactories.platformDependentTypeTransformer
)
val klibBasedPackageFragmentProvider = library.createKlibPackageFragmentProvider(
moduleContext.storageManager,
klibMetadataModuleDescriptorFactory,
languageVersionSettings,
moduleDescriptor
)
listOfNotNull(klibBasedPackageFragmentProvider)
} else {
emptyList()
}
}
is LibraryModuleInfo -> {
moduleInfo.getLibraryRoots()
.flatMap { KotlinJavascriptMetadataUtils.loadMetadata(it) }
.filter { it.version.isCompatible() }
.map { metadata ->
val (header, packageFragmentProtos) =
KotlinJavascriptSerializationUtil.readModuleAsProto(metadata.body, metadata.version)
createKotlinJavascriptPackageFragmentProvider(
moduleContext.storageManager, moduleDescriptor, header, packageFragmentProtos, metadata.version,
container.get(), LookupTracker.DO_NOTHING
)
}
}
else -> emptyList()
} | 0 | Kotlin | 0 | 0 | b0d96eb1403a6ad28c2dddf51ba50e565749f1c7 | 5,488 | kotlin | Apache License 2.0 |
data/slack-jackson-dto-test-extensions/src/main/kotlin/com/kreait/slack/api/contract/jackson/group/channels/ChannelsJoinExtension.kt | ramyaravi-opsmx | 317,497,071 | true | {"Kotlin": 1216622, "Shell": 935} | package com.kreait.slack.api.contract.jackson.group.channels
import com.kreait.slack.api.contract.jackson.common.types.Channel
import com.kreait.slack.api.contract.jackson.common.types.sample
fun ChannelsJoinRequest.Companion.sample(): ChannelsJoinRequest = ChannelsJoinRequest("")
fun SuccessfulChannelsJoinResponse.Companion.sample(): SuccessfulChannelsJoinResponse = SuccessfulChannelsJoinResponse(true, Channel.sample())
fun ErrorChannelsJoinResponse.Companion.sample(): ErrorChannelsJoinResponse = ErrorChannelsJoinResponse(false, "")
| 0 | null | 0 | 0 | d2eb88733f0513665b8a625351b599feba926b69 | 544 | slack-spring-boot-starter | MIT License |
sqlite-embedder-graalvm/src/jvmMain/kotlin/host/module/emscripten/function/SyscallFchmod.kt | illarionov | 769,429,996 | false | {"Kotlin": 1560774} | /*
* Copyright 2024, the wasm-sqlite-open-helper project authors and contributors. Please see the AUTHORS file
* for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
* SPDX-License-Identifier: Apache-2.0
*/
package ru.pixnews.wasm.sqlite.open.helper.graalvm.host.module.emscripten.function
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary
import com.oracle.truffle.api.frame.VirtualFrame
import org.graalvm.wasm.WasmContext
import org.graalvm.wasm.WasmInstance
import org.graalvm.wasm.WasmLanguage
import org.graalvm.wasm.WasmModule
import ru.pixnews.wasm.sqlite.open.helper.graalvm.ext.getArgAsInt
import ru.pixnews.wasm.sqlite.open.helper.graalvm.ext.getArgAsUint
import ru.pixnews.wasm.sqlite.open.helper.graalvm.host.module.BaseWasmNode
import ru.pixnews.wasm.sqlite.open.helper.host.EmbedderHost
import ru.pixnews.wasm.sqlite.open.helper.host.emscripten.function.SyscallFchmodFunctionHandle
import ru.pixnews.wasm.sqlite.open.helper.host.wasi.preview1.type.Fd
internal class SyscallFchmod(
language: WasmLanguage,
module: WasmModule,
host: EmbedderHost,
) : BaseWasmNode<SyscallFchmodFunctionHandle>(language, module, SyscallFchmodFunctionHandle(host)) {
override fun executeWithContext(frame: VirtualFrame, context: WasmContext, instance: WasmInstance): Int {
val args = frame.arguments
return syscallFchmod(
args.getArgAsInt(0),
args.getArgAsUint(1),
)
}
@TruffleBoundary
@Suppress("MemberNameEqualsClassName")
private fun syscallFchmod(
fd: Int,
mode: UInt,
): Int = handle.execute(Fd(fd), mode)
}
| 4 | Kotlin | 0 | 3 | a108f071520ab5e20fad01cb3b9a6e91549914dd | 1,691 | wasm-sqlite-open-helper | Apache License 2.0 |
examples/generateOptimized.kt | viclee888 | 78,071,748 | true | null | package generateOptimized
import generate.Generator
import kotlin.coroutines.Continuation
import kotlin.coroutines.CoroutineIntrinsics
import kotlin.coroutines.createCoroutine
fun <T> generate(block: suspend Generator<T>.() -> Unit): Sequence<T> = object : Sequence<T> {
override fun iterator(): Iterator<T> {
val iterator = GeneratorIterator<T>()
iterator.nextStep = block.createCoroutine(receiver = iterator, completion = iterator)
return iterator
}
}
class GeneratorIterator<T>: AbstractIterator<T>(), Generator<T>, Continuation<Unit> {
lateinit var nextStep: Continuation<Unit>
// AbstractIterator implementation
override fun computeNext() { nextStep.resume(Unit) }
// Completion continuation implementation
override fun resume(value: Unit) { done() }
override fun resumeWithException(exception: Throwable) { throw exception }
// Generator implementation
override suspend fun yield(value: T) {
setNext(value)
return CoroutineIntrinsics.suspendCoroutineOrReturn { c ->
nextStep = c
CoroutineIntrinsics.SUSPENDED
}
}
}
| 0 | null | 0 | 0 | 9e1774ae37ffa30483a220a247f49654b6050aa9 | 1,143 | kotlin-coroutines | Apache License 2.0 |
platform/script-debugger/protocol/protocol-model-generator/src/org/jetbrains/protocolReader/FileSet.kt | rbalazsi | 32,920,355 | true | {"Text": 1957, "XML": 4004, "Ant Build System": 22, "Shell": 27, "Markdown": 6, "Ignore List": 19, "Git Attributes": 4, "Batchfile": 20, "Java": 46615, "Java Properties": 78, "HTML": 2222, "Groovy": 2137, "INI": 171, "JavaScript": 37, "JFlex": 31, "XSLT": 109, "desktop": 2, "Python": 6157, "C#": 32, "Smalltalk": 14, "Rich Text Format": 2, "JSON": 148, "CoffeeScript": 3, "Kotlin": 82, "CSS": 39, "J": 18, "Protocol Buffer": 8, "JAR Manifest": 6, "Gradle": 21, "E-mail": 18, "Roff": 38, "Roff Manpage": 1, "Gherkin": 4, "Diff": 12, "Maven POM": 1, "Checksums": 42, "Java Server Pages": 24, "C": 34, "AspectJ": 2, "Perl": 3, "HLSL": 2, "Erlang": 1, "Scala": 1, "Ruby": 2, "AMPL": 4, "Linux Kernel Module": 1, "Makefile": 9, "Microsoft Visual Studio Solution": 8, "C++": 23, "Objective-C": 7, "OpenStep Property List": 2, "NSIS": 15, "Vim Script": 1, "Emacs Lisp": 1, "Yacc": 1, "ActionScript": 1, "TeX": 4, "reStructuredText": 39, "Gettext Catalog": 125, "Jupyter Notebook": 4, "YAML": 1, "Regular Expression": 9} | package org.jetbrains.protocolReader
/**
* Records a list of files in the root directory and deletes files that were not re-generated.
*/
class FileSet [throws(javaClass<IOException>())]
(private val rootDir: Path) {
SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
private val unusedFiles: THashSet<Path>
{
unusedFiles = THashSet<Path>()
Files.walkFileTree(rootDir, object : SimpleFileVisitor<Path>() {
throws(javaClass<IOException>())
override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult {
return if (Files.isHidden(dir)) FileVisitResult.SKIP_SUBTREE else FileVisitResult.CONTINUE
}
throws(javaClass<IOException>())
override fun visitFile(path: Path, attrs: BasicFileAttributes): FileVisitResult {
if (!Files.isHidden(path)) {
unusedFiles.add(path)
}
return FileVisitResult.CONTINUE
}
})
}
fun createFileUpdater(filePath: String): FileUpdater {
val file = rootDir.resolve(filePath)
unusedFiles.remove(file)
return FileUpdater(file)
}
fun deleteOtherFiles() {
unusedFiles.forEach(object : TObjectProcedure<Path> {
override fun execute(path: Path): Boolean {
try {
if (Files.deleteIfExists(path)) {
val parent = path.getParent()
Files.newDirectoryStream(parent).use { stream ->
if (!stream.iterator().hasNext()) {
Files.delete(parent)
}
}
}
}
catch (e: IOException) {
throw RuntimeException(e)
}
return true
}
})
}
}
| 0 | Java | 0 | 0 | 32e003e5073d316b591b317a320743dacbc2651c | 1,655 | intellij-community | Apache License 2.0 |
backend.native/tests/codegen/inline/correctOrderFunctionReference.kt | JetBrains | 58,957,623 | false | null | /*
* Copyright 2010-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.
*/
import kotlin.test.*
class Foo(val a: String) {
fun test() = a
}
inline fun test(a: String, b: () -> String, c: () -> String, d: () -> String, e: String): String {
return a + b() + c() + d() + e
}
var effects = ""
fun create(a: String): Foo {
effects += a
return Foo(a)
}
fun create2(a: String, f: () -> String): Foo {
effects += a
return Foo(a)
}
fun box(): String {
val result = test(create("A").a, create("B")::a, create("C")::test, create2("E", create("D")::test)::test, create("F").a)
if (effects != "ABCDEF") return "fail 1: $effects"
return if (result == "ABCEF") "OK" else "fail 2: $result"
}
| 181 | null | 625 | 7,100 | 9fb0a75ab17e9d8cddd2c3d1802a1cdd83774dfa | 797 | kotlin-native | Apache License 2.0 |
10-async/src/main/kotlin/coroutines/coroutines-basic_01.kt | iproduct | 277,474,020 | false | {"JavaScript": 3237497, "Kotlin": 545267, "Java": 110766, "HTML": 83688, "CSS": 44893, "SCSS": 32196, "Dockerfile": 58} | package course.kotilin.async.coroutines
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking { // this: CoroutineScope
val job = launch { // launch a new coroutine and continue
delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
println("World!") // print after delay
}
println("Hello") // main coroutine continues while a previous one is delayed
}
| 0 | JavaScript | 1 | 4 | 89884f8c29fffe6c6f0384a49ae8768c8e7ab509 | 476 | course-kotlin | Apache License 2.0 |
android/app/src/main/kotlin/com/example/anyinspect_app/MainActivity.kt | mdddj | 431,313,582 | true | {"Dart": 70581, "C++": 21513, "CMake": 15266, "HTML": 3863, "Ruby": 2684, "Swift": 2445, "C": 1425, "Kotlin": 131, "Objective-C": 38} | package com.example.anyinspect_app
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | Dart | 0 | 1 | 6e9df4af2ae679d9b6a474bae6dd6064796c65b5 | 131 | anyinspect_app | MIT License |
xmlschema/src/jvmTest/kotlin/io/github/pdvrieze/formats/xmlschema/test/AttributeViewer.kt | pdvrieze | 143,553,364 | false | {"Kotlin": 3481762} | /*
* Copyright (c) 2023.
*
* This file is part of xmlutil.
*
* This file is licenced to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You should have received a copy of the license with the source distribution.
* Alternatively, you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.github.pdvrieze.formats.xmlschema.test
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerializationStrategy
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.CompositeEncoder
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.modules.EmptySerializersModule
import kotlinx.serialization.modules.SerializersModule
import nl.adaptivity.xmlutil.serialization.OutputKind
import nl.adaptivity.xmlutil.serialization.structure.*
import javax.xml.namespace.QName
class AttributeViewer(
val serializersModule: SerializersModule = EmptySerializersModule(),
) {
private val _elementInfos = mutableMapOf<String, Array<ElementInfo>>()
fun structInfo(descriptor: XmlDescriptor): Array<ElementInfo> {
val info = _elementInfos.getOrPut(
descriptor.serialDescriptor.serialName,
{
Array(
maxOf(
descriptor.elementsCount,
descriptor.serialDescriptor.elementsCount
)
) { ElementInfo(descriptor.getElementDescriptor(it)) }
})
return info
}
fun elementInfo(descriptor: XmlDescriptor, index: Int): ElementInfo {
return structInfo(descriptor)[index]
}
fun <T> encode(serializer: KSerializer<T>, value: T, rootDescriptor: XmlRootDescriptor) {
val elementDescriptor = rootDescriptor.getElementDescriptor(0)
val encoder = AttrEncoder(elementDescriptor, ElementInfo(elementDescriptor))
encoder.encodeSerializableValue(serializer, value)
}
inner class AttrEncoder(val xmlDescriptor: XmlDescriptor, val elementInfo: ElementInfo) : Encoder {
override val serializersModule: SerializersModule
get() = [email protected]
private fun recordElementPresent() {
if (!elementInfo.seen) {
elementInfo.seen = true
}
}
@ExperimentalSerializationApi
override fun encodeNull() {
if (!elementInfo.hasBeenAbsent) {
elementInfo.hasBeenAbsent = true
}
}
override fun beginCollection(descriptor: SerialDescriptor, collectionSize: Int): CompositeEncoder {
elementInfo.hasBeenAbsent = elementInfo.hasBeenAbsent || collectionSize == 0
return super.beginCollection(descriptor, collectionSize)
}
override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder {
return when (xmlDescriptor) {
is XmlPolymorphicDescriptor -> {
recordElementPresent()
PolymorphicEncoder(xmlDescriptor)
}
is XmlListDescriptor -> ListEncoder(xmlDescriptor, elementInfo)
else -> {
recordElementPresent()
CompositeAttrEncoder(xmlDescriptor)
}
}
}
override fun encodeInline(descriptor: SerialDescriptor): Encoder {
recordElementPresent()
val childDescriptor= when {
xmlDescriptor.serialDescriptor == descriptor ->
xmlDescriptor.getElementDescriptor(0)
else -> xmlDescriptor
}
return AttrEncoder(childDescriptor, this.elementInfo)
}
override fun <T> encodeSerializableValue(serializer: SerializationStrategy<T>, value: T) {
val effectiveSerializer = serializer.getEffectiveSerializer(xmlDescriptor)
effectiveSerializer.serialize(this, value)
}
override fun encodeString(value: String) = recordElementPresent()
override fun encodeBoolean(value: Boolean) = recordElementPresent()
override fun encodeByte(value: Byte) = recordElementPresent()
override fun encodeChar(value: Char) = recordElementPresent()
override fun encodeDouble(value: Double) = recordElementPresent()
override fun encodeEnum(enumDescriptor: SerialDescriptor, index: Int) = recordElementPresent()
override fun encodeFloat(value: Float) = recordElementPresent()
override fun encodeInt(value: Int) = recordElementPresent()
override fun encodeLong(value: Long) = recordElementPresent()
override fun encodeShort(value: Short) = recordElementPresent()
}
inner abstract class AbstractCompositeEncoder : CompositeEncoder {
abstract val xmlDescriptor: XmlDescriptor
override val serializersModule: SerializersModule
get() = [email protected]
abstract fun encodePrimiteElement(descriptor: SerialDescriptor, index: Int, value: Any)
override fun encodeBooleanElement(descriptor: SerialDescriptor, index: Int, value: Boolean) {
encodePrimiteElement(descriptor, index, value)
}
override fun encodeByteElement(descriptor: SerialDescriptor, index: Int, value: Byte) {
encodePrimiteElement(descriptor, index, value)
}
override fun encodeCharElement(descriptor: SerialDescriptor, index: Int, value: Char) {
encodePrimiteElement(descriptor, index, value)
}
override fun encodeDoubleElement(descriptor: SerialDescriptor, index: Int, value: Double) {
encodePrimiteElement(descriptor, index, value)
}
override fun encodeFloatElement(descriptor: SerialDescriptor, index: Int, value: Float) {
encodePrimiteElement(descriptor, index, value)
}
override fun encodeIntElement(descriptor: SerialDescriptor, index: Int, value: Int) {
encodePrimiteElement(descriptor, index, value)
}
override fun encodeLongElement(descriptor: SerialDescriptor, index: Int, value: Long) {
encodePrimiteElement(descriptor, index, value)
}
override fun encodeShortElement(descriptor: SerialDescriptor, index: Int, value: Short) {
encodePrimiteElement(descriptor, index, value)
}
override fun encodeStringElement(descriptor: SerialDescriptor, index: Int, value: String) {
encodePrimiteElement(descriptor, index, value)
}
}
inner class PolymorphicEncoder(
override val xmlDescriptor: XmlPolymorphicDescriptor
) : AbstractCompositeEncoder() {
val structInfo = _elementInfos.getOrPut(
xmlDescriptor.serialDescriptor.serialName,
{
xmlDescriptor.polyInfo.values.map { desc -> ElementInfo(desc) }.toTypedArray()
})
var type: String? = null
fun elementInfo(childDescriptor: XmlDescriptor): ElementInfo {
return structInfo.first { it.name == childDescriptor.tagName }
}
override fun encodeInlineElement(descriptor: SerialDescriptor, index: Int): Encoder {
require(index == 1)
val childDescriptor = xmlDescriptor.getPolymorphicDescriptor(requireNotNull(type))
return AttrEncoder(childDescriptor, elementInfo(childDescriptor))
}
@ExperimentalSerializationApi
override fun <T : Any> encodeNullableSerializableElement(
descriptor: SerialDescriptor,
index: Int,
serializer: SerializationStrategy<T>,
value: T?
) {
throw UnsupportedOperationException("Not valid")
}
override fun <T> encodeSerializableElement(
descriptor: SerialDescriptor,
index: Int,
serializer: SerializationStrategy<T>,
value: T
) {
require(index == 1)
val childDescriptor = xmlDescriptor.getPolymorphicDescriptor(requireNotNull(type))
val encoder = AttrEncoder(childDescriptor, elementInfo(childDescriptor))
encoder.encodeSerializableValue(serializer, value)
}
override fun endStructure(descriptor: SerialDescriptor) {}
override fun encodeStringElement(descriptor: SerialDescriptor, index: Int, value: String) {
if (index ==0) {
type = value
}
}
override fun encodePrimiteElement(descriptor: SerialDescriptor, index: Int, value: Any) {
/** Ignore, this is just the type name */
}
}
inner class CompositeAttrEncoder(
override val xmlDescriptor: XmlDescriptor
) : AbstractCompositeEncoder() {
private val baseStructInfo = structInfo(xmlDescriptor)
val structInfo: Array<ElementInfo> = Array(baseStructInfo.size) { ElementInfo(baseStructInfo[it].name) }
private fun recordElementPresent(idx: Int) {
val elementInfo = structInfo[idx]
elementInfo.seen = true
}
override fun encodePrimiteElement(descriptor: SerialDescriptor, index: Int, value: Any) {
recordElementPresent(index)
}
override fun encodeInlineElement(descriptor: SerialDescriptor, index: Int): Encoder {
return AttrEncoder(xmlDescriptor.getElementDescriptor(index), structInfo[index])
}
@ExperimentalSerializationApi
override fun shouldEncodeElementDefault(descriptor: SerialDescriptor, index: Int): Boolean {
return false
}
@ExperimentalSerializationApi
override fun <T : Any> encodeNullableSerializableElement(
descriptor: SerialDescriptor,
index: Int,
serializer: SerializationStrategy<T>,
value: T?
) {
if (value == null) {
val elementInfo = structInfo[index]
val childDescriptor = xmlDescriptor.getElementDescriptor(index)
val encoder = AttrEncoder(childDescriptor, elementInfo)
encoder.encodeNull()
} else {
encodeSerializableElement(descriptor, index, serializer, value)
}
}
override fun <T> encodeSerializableElement(
descriptor: SerialDescriptor,
index: Int,
serializer: SerializationStrategy<T>,
value: T
) {
val encoder = when (descriptor.kind) {
StructureKind.LIST -> {
val elementInfo = structInfo[0]
val childDescriptor = xmlDescriptor.getElementDescriptor(0)
AttrEncoder(childDescriptor, elementInfo)
}
StructureKind.MAP -> {
val childDescriptor = xmlDescriptor.getElementDescriptor(index % 2)
if (childDescriptor.outputKind != OutputKind.Element) return
if (index %2 ==1) {
val elementInfo = structInfo[1]
AttrEncoder(childDescriptor, elementInfo)
} else return
}
else -> {
val elementInfo = structInfo[index]
val childDescriptor = xmlDescriptor.getElementDescriptor(index)
AttrEncoder(childDescriptor, elementInfo)
}
}
val effectiveSerializer = serializer.getEffectiveSerializer(xmlDescriptor)
encoder.encodeSerializableValue(effectiveSerializer, value)
}
override fun endStructure(descriptor: SerialDescriptor) {
for (i in 0 until xmlDescriptor.elementsCount) {
val info = structInfo[i]
if (!(structInfo[i].seen || info.hasBeenAbsent)) {
info.hasBeenAbsent = true
}
baseStructInfo[i] += info
}
}
}
inner class ListEncoder(override val xmlDescriptor: XmlListLikeDescriptor, val elementInfo: ElementInfo): AbstractCompositeEncoder() {
var seenHere = false
override fun encodePrimiteElement(descriptor: SerialDescriptor, index: Int, value: Any) {
elementInfo.seen = true
seenHere = true
}
override fun encodeInlineElement(descriptor: SerialDescriptor, index: Int): Encoder {
return AttrEncoder(xmlDescriptor.getElementDescriptor(0), elementInfo)
}
@ExperimentalSerializationApi
override fun <T : Any> encodeNullableSerializableElement(
descriptor: SerialDescriptor,
index: Int,
serializer: SerializationStrategy<T>,
value: T?
) {
if (value == null) {
elementInfo.hasBeenAbsent = true
} else {
encodeSerializableElement(descriptor, index, serializer, value)
}
}
override fun <T> encodeSerializableElement(
descriptor: SerialDescriptor,
index: Int,
serializer: SerializationStrategy<T>,
value: T
) {
val childDescriptor = xmlDescriptor.getElementDescriptor(0)
val encoder = AttrEncoder(childDescriptor, elementInfo)
val effectiveSerializer = serializer.getEffectiveSerializer(childDescriptor)
encoder.encodeSerializableValue(effectiveSerializer, value)
seenHere = true
}
override fun endStructure(descriptor: SerialDescriptor) {
if (! seenHere) elementInfo.hasBeenAbsent = true
}
}
@OptIn(ExperimentalSerializationApi::class)
private fun <T> SerializationStrategy<T>.getEffectiveSerializer(
elementDescriptor: XmlDescriptor
): SerializationStrategy<T> {
val overriddenSerializer = elementDescriptor.overriddenSerializer
@Suppress("UNCHECKED_CAST")
return when {
this.javaClass.name == "nl.adaptivity.xmlutil.serialization.impl.XmlQNameSerializer" ||
this.descriptor.serialName == "javax.xml.namespace.QName"
-> SimpleQNameSerializer
// overriddenSerializer != null
// -> overriddenSerializer
else -> this
} as SerializationStrategy<T>
}
}
object SimpleQNameSerializer : KSerializer<QName> {
override val descriptor: SerialDescriptor
get() = PrimitiveSerialDescriptor("nl.adaptivity.xmlutil.serialization.test.QName", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder): QName {
throw UnsupportedOperationException("Deserializing not supported")
}
override fun serialize(encoder: Encoder, value: QName) {
encoder.encodeString(value.localPart) // No need to do special
}
}
| 35 | Kotlin | 31 | 378 | c4053519a8b6c90af9e1683a5fe0e9e2b2c0db79 | 15,460 | xmlutil | Apache License 2.0 |
semester_2/ProgLabs/Lab05/src/main/kotlin/commands/names/RemoveDistance.kt | Mrjoulin | 404,489,566 | false | null | package commands.names
import commands.annotations.ConsoleCommand
import commands.interfaces.Command
import receiver.interfaces.ReceiverInterface
import entities.Route
import kotlin.collections.ArrayList
/**
* Class to remove any entity from collection with distance equal given distance
* Extends Command
*
* @param receiver Default command argument.
*
* @author <NAME>.
*/
@ConsoleCommand(
name = "remove_any_by_distance", args = "distance",
description = "Remove any entity from collection with distance equal given distance"
)
class RemoveDistance(private val receiver: ReceiverInterface<Route>) : Command {
override fun execute(args: ArrayList<String>) : Boolean {
if (args.isEmpty()) {
println("Please input distance of entity witch need to be removed")
return false
}
val distance: Double? = args[0].toDoubleOrNull()
if (distance == null) {
println("Distance must be in double format!")
return false
}
val route = receiver.getEntitiesSet().find { it.distance == distance }
if (route != null) {
val success = receiver.removeEntity(route)
if (success)
println("Entity ID #${route.id} with distance ${route.distance} was removed")
else
println("Entity found, but wasn't removed because of unexpected error")
return success
}
println("Entity with distance $distance not found")
return true
}
}
| 1 | Kotlin | 3 | 1 | a1e1368d8eecb11d4e684d9644b1295ab34a1705 | 1,539 | ITMOLabs | MIT License |
src/main/kotlin/io/github/riej/lsl/psi/LslStatementBlock.kt | riej | 597,798,011 | false | {"Java": 199569, "Kotlin": 197853, "ANTLR": 5887, "Lex": 3385, "HTML": 90} | package io.github.riej.lsl.psi
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.util.parentOfType
import io.github.riej.lsl.parser.LslTypes
class LslStatementBlock(node: ASTNode) : ASTWrapperPsiElement(node), LslStatement {
val statements: List<LslStatement>
get() = findChildrenByType(LslTypes.STATEMENTS)
val braceLeftEl: PsiElement?
get() = findChildByType(LslTypes.BRACE_LEFT)
val braceRightEl: PsiElement?
get() = findChildByType(LslTypes.BRACE_RIGHT)
val labels: Map<String, LslStatementLabel>
get() = (parentOfType<LslStatementBlock>()?.labels ?: emptyMap()).plus(
statements.filterIsInstance<LslStatementLabel>().associateBy { it.name ?: "" }
.filterKeys { it.isNotBlank() }
)
} | 5 | Kotlin | 2 | 4 | c341386601dd0cdb062a82ed1c06a20c3997587f | 870 | lsl | MIT License |
app/src/main/java/eu/benayoun/androidmoviedatabase/ui/theme/Color.kt | BenayounP | 525,430,424 | false | null | package eu.benayoun.androidmoviedatabase.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
// Some colors are inspired by <NAME> french movie
// https://www.colourlovers.com/palette/187404/Am%C3%A9lie_Poulain
val vertAmelie = Color(0xFF006F1A)
val vertFonceAmelie = Color(0xFF015E40)
val orangeAmelie = Color(0xFFCA7900)
val Red700= Color(0xFFD32F2F)
val Red900= Color(0xFFB71C1C)
val Blue800= Color(0xFF1565C0)
val Grey50= Color(0xFFFAFAFA)
val Grey100= Color(0xFFF5F5F5)
val Grey200= Color(0xFFEEEEEE)
val Grey300= Color(0xFFE0E0E0)
val Grey400= Color(0xFFBDBDBD)
val Grey500= Color(0xFF9E9E9E)
val Grey600= Color(0xFF757575)
val Grey700= Color(0xFF616161)
val Grey800= Color(0xFF424242)
val Grey900= Color(0xFF212121)
val Black1000= Color(0xFF000000)
data class BackgroundAndContentColor(val background:Color, val content:Color)
class ComposeColors {
companion object {
@Composable
fun updating() = BackgroundAndContentColor(getColor(light = Blue800, dark = Grey500),
getColor(light=Color.White, dark = Color.Black))
@Composable
fun success() = BackgroundAndContentColor(getColor(light = vertAmelie, dark = Grey600),
getColor(light=Color.White, dark = Color.White))
@Composable
fun problem() = BackgroundAndContentColor(getColor(light = Red700, dark = Red900),
getColor(light=Color.White, dark = Color.White))
@Composable
private fun getColor(light: Color, dark: Color) : Color {
if (isDarkTheme()){
return dark
}
else
{
return light
}
}
@Composable
fun isDarkTheme() = isSystemInDarkTheme()
}
}
| 0 | Kotlin | 0 | 21 | d45a7c7bec90f75075fa6c90b4a71e981a2caf8b | 1,838 | AndroidMovieDataBase | Apache License 2.0 |
compiler/light-classes/src/org/jetbrains/kotlin/asJava/ImpreciseResolveResult.kt | JakeWharton | 99,388,807 | false | null | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.asJava
enum class ImpreciseResolveResult {
MATCH,
NO_MATCH,
UNSURE;
inline fun ifSure(body: (Boolean) -> Unit) = when (this) {
MATCH -> body(true)
NO_MATCH -> body(false)
UNSURE -> Unit
}
}
| 0 | null | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 867 | kotlin | Apache License 2.0 |
Section8/Video8.4/Transitions1/app/src/main/java/materialdesign/packt/com/toolbar/MassageActivity.kt | PacktPublishing | 166,975,495 | false | null | package materialdesign.packt.com.toolbar
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.opengl.Visibility
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.view.ViewAnimationUtils
import android.view.animation.Animation
import kotlinx.android.synthetic.main.activity_massage.*
/**
* Created by ${Mona}
*/
class MassageActivity : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_massage)
}
var checker = 0
fun CircularTransition(view: View){
val x : Int = (view.left + view.right )/2
val y : Int = (view.bottom + view.top )/2
val radius = Math.max(cl_view.width,cl_view.height)* 0.2f
if(checker == 0){
checker = 1
cl_view.background = resources.getDrawable(R.drawable.capture)
ViewAnimationUtils.createCircularReveal(cl_view,x,y,0f,radius).start()
}else if(checker == 1) {
checker = 0
cl_view.background = resources.getDrawable(R.drawable.capture2)
ViewAnimationUtils.createCircularReveal(cl_view,x,y,0f,radius).start()
}
}
} | 0 | null | 4 | 11 | a7a8c95f571e84b0a84c1814d89fac6d6e26d16f | 1,252 | Hands-On-Android-Material-Design | MIT License |
app/src/main/java/com/dluvian/nozzle/data/room/helper/extended/PostEntityExtended.kt | dluvian | 645,936,540 | false | null | package com.dluvian.nozzle.data.room.helper.extended
import androidx.room.Embedded
import com.dluvian.nozzle.data.room.entity.PostEntity
data class PostEntityExtended(
@Embedded
val postEntity: PostEntity,
val replyToPubkey: String?,
val replyToName: String?,
val name: String?,
val numOfReplies: Int,
val isLikedByMe: Boolean,
)
| 5 | null | 3 | 35 | 30ffd7b88fdb612afd80e422a0bfe92a74733338 | 360 | Nozzle | MIT License |
EmojiPanel/src/main/java/com/binlee/emoji/model/EmojiGroup.kt | sleticalboy | 119,377,384 | false | null | package com.binlee.emoji.model
import com.alibaba.fastjson.annotation.JSONField
import java.io.Serializable
import java.util.Objects
/**
* Created on 19-7-16.
*
* @author leebin
*/
class EmojiGroup : Serializable {
//表情和表情包的关联字段(唯一)
var uuid: String? = null
var name: String? = null
var description: String? = null
var size = 0
var sha1: String? = null
var path: String? = null
var thumbnail: String? = null
var surface: String? = null
var advertisement: String? = null
@JSONField(name = "updated_at")
var updatedAt: String? = null
var count = 0
var type = 0
/**
* 切换到其他组时,当前组出于第几页
*/
var lastChildIndex = 0
/**
* 退出重进时直接进入此分组,入库时 0 或 1
*/
var isLastGroup = false
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
val that = other as EmojiGroup
return uuid == that.uuid && sha1 == that.sha1
}
override fun hashCode(): Int {
return Objects.hash(uuid, sha1)
}
companion object {
private const val serialVersionUID = 2836324578616418084L
}
} | 0 | C | 1 | 1 | 69f09a5202dda9096adba4ec9af5f92cdbb9b9da | 1,125 | Dailearn | Apache License 2.0 |
AcornUiCore/src/com/acornui/component/AttachmentHolder.kt | konsoletyper | 105,533,124 | false | null | package com.acornui.component
/**
* An AttachmentHolder can contain a map of arbitrary objects. This is used to create components through composition
* rather than inheritance.
*/
interface AttachmentHolder {
fun <T : Any> getAttachment(key: Any): T?
fun setAttachment(key: Any, value: Any)
/**
* Removes an attachment added via [setAttachment]
*/
fun <T : Any> removeAttachment(key: Any): T?
}
fun <T : Any> AttachmentHolder.createOrReuseAttachment(key: Any, factory: () -> T): T {
val existing = getAttachment<T>(key)
if (existing != null) {
return existing
} else {
val newAttachment = factory()
setAttachment(key, newAttachment)
return newAttachment
}
} | 0 | Kotlin | 3 | 0 | a84b559fe1d1cad01eb9223ad9af73b4d5fb5bc8 | 685 | Acorn | Apache License 2.0 |
core/src/main/kotlin/com/trevjonez/composer/PropertyHelpers.kt | fondesa | 177,767,862 | true | {"Kotlin": 57357} | /*
* Copyright 2018 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.trevjonez.composer
import org.gradle.api.Project
import org.gradle.api.internal.provider.DefaultPropertyState
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
/**
* This is using internal API.
* Probably shouldn't but need better optional prop support on primitives
*/
inline fun <reified T> Project.emptyProperty(): Property<T> {
return DefaultPropertyState<T>(T::class.java)
}
inline fun <reified T> Property<T>.eval(value: Any) {
@Suppress("UNCHECKED_CAST")
when (value) {
is T -> set(value)
is Provider<*> -> set(value as Provider<out T>)
else ->
throw IllegalArgumentException("Unsupported type: ${value.javaClass}, expecting ${T::class.java} or ${Provider::class.java}")
}
}
inline fun <reified T> ListProperty<T>.eval(value: Any) {
@Suppress("UNCHECKED_CAST")
when (value) {
is T -> add(value)
is Provider<*> -> add(value as Provider<out T>)
else ->
throw IllegalArgumentException("Unsupported type: ${value.javaClass}, expecting ${T::class.java} or ${Provider::class.java}")
}
}
inline fun <reified T> ListProperty<T>.evalAll(value: Any) {
@Suppress("UNCHECKED_CAST")
when (value) {
is Iterable<*> -> addAll(value as Iterable<T>)
is Provider<*> -> addAll(value as Provider<out Iterable<T>>)
else ->
throw IllegalArgumentException("Unsupported type: ${value.javaClass}, expecting ${Iterable::class.java} or ${Provider::class.java}")
}
} | 0 | Kotlin | 0 | 0 | be3c86970f9f9fb5f805bc0932423734cebedc05 | 2,133 | composer-gradle-plugin | Apache License 2.0 |
core/src/main/kotlin/com/trevjonez/composer/PropertyHelpers.kt | fondesa | 177,767,862 | true | {"Kotlin": 57357} | /*
* Copyright 2018 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.trevjonez.composer
import org.gradle.api.Project
import org.gradle.api.internal.provider.DefaultPropertyState
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
/**
* This is using internal API.
* Probably shouldn't but need better optional prop support on primitives
*/
inline fun <reified T> Project.emptyProperty(): Property<T> {
return DefaultPropertyState<T>(T::class.java)
}
inline fun <reified T> Property<T>.eval(value: Any) {
@Suppress("UNCHECKED_CAST")
when (value) {
is T -> set(value)
is Provider<*> -> set(value as Provider<out T>)
else ->
throw IllegalArgumentException("Unsupported type: ${value.javaClass}, expecting ${T::class.java} or ${Provider::class.java}")
}
}
inline fun <reified T> ListProperty<T>.eval(value: Any) {
@Suppress("UNCHECKED_CAST")
when (value) {
is T -> add(value)
is Provider<*> -> add(value as Provider<out T>)
else ->
throw IllegalArgumentException("Unsupported type: ${value.javaClass}, expecting ${T::class.java} or ${Provider::class.java}")
}
}
inline fun <reified T> ListProperty<T>.evalAll(value: Any) {
@Suppress("UNCHECKED_CAST")
when (value) {
is Iterable<*> -> addAll(value as Iterable<T>)
is Provider<*> -> addAll(value as Provider<out Iterable<T>>)
else ->
throw IllegalArgumentException("Unsupported type: ${value.javaClass}, expecting ${Iterable::class.java} or ${Provider::class.java}")
}
} | 0 | Kotlin | 0 | 0 | be3c86970f9f9fb5f805bc0932423734cebedc05 | 2,133 | composer-gradle-plugin | Apache License 2.0 |
ui-search/src/main/java/com/nikitin/ui_search/di/scope/SearchFeatureScope.kt | IstrajI | 478,113,719 | false | null | package com.nikitin.ui_search.di.scope
import javax.inject.Scope
@MustBeDocumented
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class SearchFeatureScope | 0 | Kotlin | 1 | 1 | 86d3ad1250037aa3ff6c4a95a02be8170d000b54 | 168 | android-feature-module-architecture | Apache License 2.0 |
app/src/main/java/com/example/tabbottomkit/demo2/Demo2Activity.kt | ydstar | 349,349,178 | false | null | package com.example.tabbottomkit.demo2
import android.graphics.BitmapFactory
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.widget.Toast
import com.example.tabbottomkit.R
import com.tab.bottom.kit.TabBottomInfo
import com.tab.bottom.kit.TabBottomKitLayout
import com.tab.bottom.kit.util.DisplayUtil
import java.util.ArrayList
class Demo2Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_demo2)
initTabBottom2()
}
private fun initTabBottom2() {
val hiTabBottomLayout: TabBottomKitLayout = findViewById(R.id.itablayout)
hiTabBottomLayout.setTabAlpha(0.85f)
val defaultColor: Int = getResources().getColor(R.color.tabBottomDefaultColor)
val tintColor: Int = getResources().getColor(R.color.tabBottomTintColor)
val bottomInfoList: MutableList<TabBottomInfo<*>> = ArrayList()
val bitmap = BitmapFactory.decodeResource(resources,
R.drawable.fire, null)
val bitmap2 = BitmapFactory.decodeResource(resources,
R.drawable.fire2, null)
val homeInfo = TabBottomInfo(
"首页",
"fonts/iconfont.ttf",
getString(R.string.if_home),
null,
defaultColor,
tintColor
)
val infoRecommend = TabBottomInfo(
"收藏",
"fonts/iconfont.ttf",
getString(R.string.if_favorite),
null,
defaultColor,
tintColor
)
val infoCategory = TabBottomInfo(
"分类",
bitmap,
bitmap2,
defaultColor,
tintColor
)
val infoChat = TabBottomInfo(
"推荐",
"fonts/iconfont.ttf",
getString(R.string.if_recommend),
null,
defaultColor,
tintColor
)
val infoProfile = TabBottomInfo(
"我的",
"fonts/iconfont.ttf",
getString(R.string.if_profile),
null,
defaultColor,
tintColor
)
bottomInfoList.add(homeInfo)
bottomInfoList.add(infoRecommend)
bottomInfoList.add(infoCategory)
bottomInfoList.add(infoChat)
bottomInfoList.add(infoProfile)
hiTabBottomLayout.inflateInfo(bottomInfoList)
Handler().postDelayed(Runnable {
bottomInfoList.removeAt(1)
hiTabBottomLayout.inflateInfo(bottomInfoList)
hiTabBottomLayout.defaultSelected(homeInfo)
// 改变某个tab的高度
val tabBottom = hiTabBottomLayout.findTab(bottomInfoList[1])
tabBottom?.apply { resetHeight(DisplayUtil.dp2px(100f, resources)) }
},2000)
hiTabBottomLayout.addTabSelectedChangeListener { _, _, currentSelectInfo ->
Toast.makeText(this@Demo2Activity, currentSelectInfo.mName, Toast.LENGTH_SHORT).show()
}
hiTabBottomLayout.defaultSelected(homeInfo)
// 改变某个tab的高度
val tabBottom = hiTabBottomLayout.findTab(bottomInfoList[2])
tabBottom?.apply { resetHeight(DisplayUtil.dp2px(100f, resources)) }
}
} | 1 | null | 9 | 104 | a1d3bcb06607abc54fe97846e611ae7f9c8e9398 | 3,296 | TabBottomKit | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.