path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/kotlin/com/leon/bilihub/wraps/LiveQualityWrap.kt
LeonNOV
529,860,854
false
null
package com.leon.bilihub.wraps /** * @Author Leon * @Time 2022/08/25 * @Desc */ data class LiveQualityWrap(var quality: Int, var position: Int)
5
Java
0
63
d9f843d40c31f99f625b9ec0e1d410594ada47ce
149
BiliHub
MIT License
app/src/main/java/com/hustunique/vlive/util/ThreadUtil.kt
UniqueStudioAndroid
361,579,917
false
null
package com.hustunique.vlive.util import android.os.Handler import android.os.Looper /** * author : <NAME> * e-mail : <EMAIL> * date : 2021/5/20 */ object ThreadUtil { private val handler = Handler(Looper.getMainLooper()) fun execUi(runnable: () -> Unit) { if (Thread.currentThread() == Looper.getMainLooper().thread) { runnable() } else { handler.post { runnable() } } } }
1
Kotlin
1
7
d9ecbf7d12b7771fb12adae6e4482d0999438801
480
VLive
MIT License
shared/news-list/news-list-impl/src/commonMain/kotlin/ru/slartus/forpda/news_list/NewsListComponent.kt
slartus
722,678,243
false
{"Kotlin": 7477, "Swift": 1103, "Shell": 228}
package ru.slartus.forpda.news_list import com.arkivanov.decompose.ComponentContext import com.arkivanov.decompose.value.MutableValue import com.arkivanov.decompose.value.Value import ru.slartus.forpda.news_list.api.NewsItem interface NewsListComponent { val model: Value<Model> data class Model( val items: List<NewsItem>, ) } class NewsListComponentImpl( componentContext: ComponentContext ) : NewsListComponent, ComponentContext by componentContext { override val model: Value<NewsListComponent.Model> = MutableValue(NewsListComponent.Model(items = List(100) { NewsItem("Item $it") })) }
0
Kotlin
0
0
67e777ddecd734798fc23dd5b422dc46d2f08dba
630
4pdaClient-mp
Apache License 2.0
lib-extensions/src/main/java/com/qusion/kotlin/lib/extensions/network/CachePolicy.kt
Qusion
212,573,167
false
{"Kotlin": 4058}
package com.qusion.kotlin.lib.extensions.network enum class CachePolicy { CACHE_ONLY, CACHE_AND_NETWORK, NETWORK_ONLY }
0
Kotlin
0
5
3e69f4f4cdf08993b391a9edffd77ae9077d171b
132
kotlin-q-extensions
MIT License
classfile/src/main/kotlin/org/tinygears/bat/classfile/evaluation/Frame.kt
TinyGearsOrg
562,774,371
false
{"Kotlin": 1879358, "Smali": 712514, "ANTLR": 26362, "Shell": 12090}
/* * Copyright (c) 2020-2022 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.tinygears.bat.classfile.evaluation import org.tinygears.bat.classfile.attribute.preverification.VerificationType import org.tinygears.bat.classfile.constant.editor.ConstantPoolEditor import org.tinygears.bat.classfile.evaluation.value.ReferenceValue import org.tinygears.bat.classfile.evaluation.value.TopValue import org.tinygears.bat.classfile.evaluation.value.UninitializedReferenceValue import org.tinygears.bat.classfile.evaluation.value.Value import org.tinygears.bat.util.mutableListOfCapacity import java.util.* import java.util.concurrent.atomic.AtomicBoolean class Frame private constructor(private val _variables: MutableList<Value> = mutableListOfCapacity(0), private val _stack: MutableList<Value> = mutableListOfCapacity(0), private val _alive: MutableList<AtomicBoolean> = mutableListOfCapacity(0)) { val variables: List<Value> get() = _variables val stack: List<Value> get() = _stack val stackSize: Int get() = stack.fold(0) { agg, type -> agg + type.operandSize } val variableSize: Int get() = variables.size val variableCount: Int get() { var i = 0 var count = 0 while (i < variables.size) { val type = variables[i] count++ i += type.operandSize } return count } val aliveVariableCount: Int get() { var i = 0 var count = 0 while (i < variables.size) { val type = variables[i] if (_alive[i].get()) { count++ } i += type.operandSize } return count } fun copy(): Frame { return Frame(variables.toMutableList(), stack.toMutableList(), _alive.toMutableList()) } fun pop(): Value { return _stack.removeLast() } fun peek(): Value { return _stack.last() } fun pop(count: Int) { for (i in 0 until count) { _stack.removeLast() } } fun push(value: Value) { _stack.add(value) } fun clearStack() { _stack.clear() } fun isAlive(variable: Int): Boolean { return _alive[variable].get() } fun load(variable: Int): Value { val value = variables[variable] check(value !is TopValue) { "trying to load a TopValue at variableIndex $variable" } return value } fun store(variable: Int, value: Value) { val maxVariableIndex = if (value.isCategory2) variable + 1 else variable ensureVariableCapacity(maxVariableIndex) _variables[variable] = value } internal fun variableRead(variable: Int) { _alive[variable].set(true) } internal fun resetVariableLiveness(variable: Int) { _alive[variable] = AtomicBoolean(false) } internal fun resetVariableLiveness() { for (i in _alive.indices) { _alive[i] = AtomicBoolean(_alive[i].get()) } } internal fun mergeLiveness(other: Frame) { for (i in _alive.indices) { if (i in other._alive.indices) { _alive[i].set(_alive[i].get() or other._alive[i].get()) } } } internal fun variableWritten(variable: Int) { val maxVariableIndex = if (_variables[variable].isCategory2) variable + 1 else variable ensureAliveCapacity(maxVariableIndex) resetVariableLiveness(variable) } private fun ensureVariableCapacity(capacity: Int) { while (capacity >= variables.size) { _variables.add(TopValue) } } private fun ensureAliveCapacity(capacity: Int) { while (capacity >= _alive.size) { _alive.add(AtomicBoolean(false)) } } internal fun referenceInitialized(reference: Value, initializedReference: Value) { for (i in _variables.indices) { if (_variables[i] == reference) { _variables[i] = initializedReference } } for (i in _stack.indices) { if (_stack[i] == reference) { _stack[i] = initializedReference } } } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Frame return _variables == other._variables && _stack == other._stack } override fun hashCode(): Int { return Objects.hash(_variables, _stack) } override fun toString(): String { return buildString { append(_variables.joinToString(separator = ", ", prefix = "{", postfix = "}")) append(" ") append(_stack.joinToString(separator = ", ", prefix = "{", postfix = "}")) append(" ") append(_alive.joinToString(separator = ", ", prefix = "{", postfix = "}")) } } companion object { fun empty(): Frame { return Frame() } } } fun List<Value>.toVerificationTypeList(constantPoolEditor: ConstantPoolEditor): List<VerificationType> { val result = mutableListOf<VerificationType>() var i = 0 while (i < size) { val value = this[i] result.add(value.toVerificationType(constantPoolEditor)) i += value.operandSize } return result }
0
Kotlin
0
0
50083893ad93820f9cf221598692e81dda05d150
6,143
bat
Apache License 2.0
build-logic/convention/src/main/kotlin/KotlinInjectConventionPlugin.kt
khalid64927
813,915,854
false
{"Kotlin": 1284599, "Shell": 14536, "HTML": 2098, "JavaScript": 1122, "Swift": 594, "CSS": 342}
/* * Copyright 2024 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 * * 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. */ import com.google.samples.apps.nowinandroid.libs import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.dependencies class KotlinInjectConventionPlugin: Plugin<Project> { override fun apply(target: Project) { with(target) { with(pluginManager) { apply("com.google.devtools.ksp") } dependencies { add("kspCommonMainMetadata", libs.findLibrary("kotlin.inject.compiler.ksp").get()) add("commonMainImplementation", libs.findLibrary("kotlin.inject.runtime").get()) // KSP will eventually have better multiplatform support and we'll be able to simply have // `ksp libs.kotlinInject.compiler` in the dependencies block of each source set // https://github.com/google/ksp/pull/1021 add("kspIosX64", libs.findLibrary("kotlin.inject.compiler.ksp").get()) add("kspIosArm64", libs.findLibrary("kotlin.inject.compiler.ksp").get()) add("kspIosSimulatorArm64", libs.findLibrary("kotlin.inject.compiler.ksp").get()) // add("kspWasmJs", libs.findLibrary("kotlin.inject.compiler.ksp").get()) add("kspAndroid", libs.findLibrary("kotlin.inject.compiler.ksp").get()) add("kspJvm", libs.findLibrary("kotlin.inject.compiler.ksp").get()) add("kspMacosX64", libs.findLibrary("kotlin.inject.compiler.ksp").get()) add("kspMacosArm64", libs.findLibrary("kotlin.inject.compiler.ksp").get()) } } } }
10
Kotlin
0
0
620ad9acbec33b5cdb316aafbb8376bd0718e875
2,215
nowinkmp-copy
Apache License 2.0
app/src/main/java/com/guildacode/agendakotlin/ListStudentActivity.kt
carlosFattor
92,443,722
false
null
package com.guildacode.agendakotlin import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.ContextMenu import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Toast import com.guildacode.agendakotlin.dao.StudentDAO import com.guildacode.agendakotlin.model.Student import kotlinx.android.synthetic.main.activity_list_students.* class ListStudentActivity : AppCompatActivity() { var listStudents = arrayListOf<Student>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_list_students) btn_new_user.setOnClickListener { val go2Form = Intent(this, FormActivity::class.java) startActivity(go2Form) } registerForContextMenu(lst_students) // fast click on item list of ListView lst_students.setOnItemClickListener { list, item, position, id -> val student = listStudents[position] val go2form = Intent(this, FormActivity::class.java) go2form.putExtra("student", student) startActivity(go2form) } } override fun onResume() { super.onResume() loadStudents() } override fun onCreateContextMenu(menu: ContextMenu?, v: View?, menuInfo: ContextMenu.ContextMenuInfo?) { val delete = menu?.add("Delete") delete?.setOnMenuItemClickListener { val info = menuInfo as AdapterView.AdapterContextMenuInfo val student = listStudents[info.position] StudentDAO(this).delete(student.id!!) loadStudents() Toast.makeText(this, "Student ${student.name} deleted", Toast.LENGTH_SHORT).show() false } } private fun loadStudents() { val dao = StudentDAO(this) listStudents = dao.listStudents() dao.close() val adapter = ArrayAdapter<Student>(this, android.R.layout.simple_list_item_1, listStudents) lst_students.adapter = adapter } }
0
Kotlin
1
1
ba64c50f54464ab3dfccb08414f1e5ded71710f6
2,139
AgendaKotlin
MIT License
formbuilder/src/main/java/it/ciaosonokekko/formbuilder/form/holder/FormDateTimeButtonHolder.kt
ciaosonokekko
305,103,256
false
null
package it.ciaosonokekko.formbuilder.form.holder import android.app.AlertDialog import android.app.DatePickerDialog import android.app.TimePickerDialog import android.content.Context import android.view.View import androidx.recyclerview.widget.RecyclerView import it.ciaosonokekko.formbuilder.databinding.ViewFormButtonBinding import it.ciaosonokekko.formbuilder.extension.* import it.ciaosonokekko.formbuilder.form.Form import it.ciaosonokekko.formbuilder.form.FormDateTimeButtonType import java.util.* class FormDateTimeButtonHolder(_context: Context, _view: ViewFormButtonBinding) : RecyclerView.ViewHolder(_view.root) { private var view: ViewFormButtonBinding = _view private var context: Context = _context fun bind(data: Form.DateTimeButton) { setup(data) } fun updateValue(value: String) { view.btnMain.text = value } private fun setup(data: Form.DateTimeButton) { data.subTitle?.let { view.txtSubtitle.text = it } if (view.txtSubtitle.text.isNullOrEmpty()) { view.txtSubtitle.visibility = View.GONE } view.btnMain.isEnabled = data.editable == true view.btnMain.text = data.hint data.dateValue?.let { when(data.type) { FormDateTimeButtonType.DateTime -> { view.btnMain.text = it.toHumanFullFormat() } FormDateTimeButtonType.Time -> { view.btnMain.text = it.toHumanHourFormat() } FormDateTimeButtonType.Date -> { view.btnMain.text = it.toHumanDateFormat() } } } view.btnMain.setOnClickListener { // open date time val calendar = GregorianCalendar() calendar.time = data.dateValue ?: Date() val year = calendar.get(Calendar.YEAR) val month = calendar.get(Calendar.MONTH) val day = calendar.get(Calendar.DAY_OF_MONTH) val hour: Int = calendar.get(Calendar.HOUR_OF_DAY) val minute: Int = calendar.get(Calendar.MINUTE) var datePickerDialog: AlertDialog? = null when(data.type) { FormDateTimeButtonType.DateTime -> { datePickerDialog = DatePickerDialog(context, { _, newYear, monthOfYear, dayOfMonth -> val newCalendar = GregorianCalendar() newCalendar.set(Calendar.YEAR, newYear) newCalendar.set(Calendar.MONTH, monthOfYear) newCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth) datePickerDialog = TimePickerDialog(context, { _, newHour, newMinute -> newCalendar.set(Calendar.HOUR_OF_DAY, newHour) newCalendar.set(Calendar.MINUTE, newMinute) data.dateValue = newCalendar.time data.value = newCalendar.time.toHumanFullFormat() view.btnMain.text = data.value data.onClickView(data, this) }, hour, minute, true) datePickerDialog?.show() }, year, month, day) } FormDateTimeButtonType.Date -> { datePickerDialog = DatePickerDialog(context, { _, newYear, monthOfYear, dayOfMonth -> val newCalendar = GregorianCalendar() newCalendar.set(Calendar.YEAR, newYear) newCalendar.set(Calendar.MONTH, monthOfYear) newCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth) data.dateValue = newCalendar.time data.value = newCalendar.time.toHumanFullFormat() view.btnMain.text = data.dateValue?.toHumanDateFormat() data.onClickView(data, this) }, year, month, day) } FormDateTimeButtonType.Time -> { datePickerDialog = TimePickerDialog(context, { _, newHour, newMinute -> val newCalendar = GregorianCalendar() newCalendar.set(Calendar.HOUR_OF_DAY, newHour) newCalendar.set(Calendar.MINUTE, newMinute) data.dateValue = newCalendar.time data.value = newCalendar.time.toHumanFullFormat() view.btnMain.text = data.dateValue?.toHumanHourFormat() data.onClickView(data, this) }, hour, minute, true) } } datePickerDialog?.show() } } }
0
Kotlin
0
2
030afcadef342d8bf3cbd527d2a095c0edffe293
4,825
KBuilder
MIT License
subprojects/samples/src/test/kotlin/kotools/types/collection/NotEmptySetCompanionKotlinSampleTest.kt
kotools
581,475,148
false
{"Kotlin": 425309, "Java": 19213}
package kotools.types.collection import org.kotools.types.assertPrints import kotlin.test.Test class NotEmptySetCompanionKotlinSampleTest { private val sample = NotEmptySetCompanionKotlinSample() @Test fun `create(Collection) should pass`() { val expected = "[1, 2, 3]" assertPrints(expected, this.sample::createWithCollection) } @Test fun `create(MutableCollection) should pass`() { val expected: String = listOf( "[1, 2, 3]", "[1, 2, 3]", "[]", "[1, 2, 3]" ).joinToString(separator = "\n") assertPrints(expected, this.sample::createWithMutableCollection) } @Test fun `createOrNull(Collection) should pass`() { val expected = "[1, 2, 3]" assertPrints(expected, this.sample::createOrNullWithCollection) } @Test fun `createOrNull(MutableCollection) should pass`() { val expected: String = listOf( "[1, 2, 3]", "[1, 2, 3]", "[]", "[1, 2, 3]" ).joinToString(separator = "\n") assertPrints(expected, this.sample::createOrNullWithMutableCollection) } @Test fun `of(E, vararg E) should pass`() { val expected = "[1, 2, 3]" assertPrints(expected, this.sample::of) } }
28
Kotlin
6
79
55871069932249cf9e65f867c4e3d9bbc5adfeee
1,324
types
MIT License
infrastructure/src/main/kotlin/com/jvmhater/moduticket/repository/SpringDataConcertRepository.kt
jvm-hater
587,725,795
false
null
package com.jvmhater.moduticket.repository import com.jvmhater.moduticket.model.Concert import org.springframework.stereotype.Repository @Repository class SpringDataConcertRepository : ConcertRepository { override suspend fun findConcerts(): List<Concert> { TODO("Not yet implemented") } override suspend fun find(id: String): Concert { TODO("Not yet implemented") } override suspend fun create(): Concert { TODO("Not yet implemented") } override suspend fun delete() { TODO("Not yet implemented") } } @Repository interface R2dbcConcertRepository
4
Kotlin
0
0
33dcc1ee90d8e3effeb4b6bcbec4a0c542ab8369
617
modu-ticket-backend
MIT License
app/src/main/java/io/github/luckyace/hardwareinventoryapp/ScanActivity.kt
luckyace
121,941,483
false
null
package io.github.luckyace.hardwareinventoryapp import android.os.Bundle import android.support.v7.app.AppCompatActivity class ScanActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.scan_activity) } }
0
Kotlin
0
0
399b629ad806dbd477bc0c124ded40e26da62faa
321
HardwareInventoryApp
Apache License 2.0
src/main/kotlin/flyer/easyKeyValue/physicalFile/Stream.kt
FALLANGELZOU
539,926,510
false
{"Kotlin": 66070, "Assembly": 74}
package flyer.easyKeyValue.physicalFile import flyer.easyKeyValue.KVConf /** * 流文件 * */ class Stream(private val kvName: String) { private var handler = PhysicalDataHandler("./EasyKV/${kvName}.skv", KVConf.STREAM_DEFAULT_SIZE) val pos get() = handler.pos val writtenBytes get() = handler.writtenBytes /** * 写入字节 */ fun writeBytes(len: Int, byteArray: ByteArray): Int { var nextPos = handler.pos + getBlockNum(len) * KVConf.BLOCK_SIZE handler.writeInt(len) handler.writeBytes(byteArray) handler.pos = nextPos return nextPos } /** * 读取字节 */ fun readBytes(position: Int): ByteArray { val len = handler.readInt(position) return handler.readBytes(position + Int.SIZE_BYTES, len) } /** * 传入len,计算改记录占用了多少个block */ private fun getBlockNum(len: Int): Int { val totalBytes = len + KVConf.INT_SIZE val blockNum = totalBytes / KVConf.BLOCK_SIZE return if (totalBytes % KVConf.BLOCK_SIZE != 0) blockNum + 1 else blockNum } }
0
Kotlin
0
1
479077213a7381c6f08a333e10e7bdaf7861e949
1,077
Flyer
Apache License 2.0
ERMSEmployee/src/main/java/com/kust/ermsemployee/ui/auth/LoginActivity.kt
sabghat90
591,653,827
false
null
package com.kust.ermsemployee.ui.auth import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.lifecycle.ViewModelProvider import com.kust.ermsemployee.ui.dashboard.DashboardActivity import com.kust.ermsemployee.databinding.ActivityLoginBinding import com.kust.ermsemployee.utils.UiState import com.kust.ermsemployee.utils.toast import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class LoginActivity : AppCompatActivity() { private lateinit var binding : ActivityLoginBinding private lateinit var viewModel : AuthViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityLoginBinding.inflate(layoutInflater) val view = binding.root setContentView(view) viewModel = ViewModelProvider(this)[AuthViewModel::class.java] if (viewModel.isUserLoggedIn.value == true){ val intent = Intent(this, DashboardActivity::class.java) startActivity(intent) finish() } observer() binding.btnLogin.setOnClickListener { if (validation()){ viewModel.login( email = binding.editTextEmail.text.toString(), password = binding.editTextPassword.text.toString() ) } } } private fun observer() { viewModel.login.observe(this) { state -> when(state){ is UiState.Loading -> { binding.btnLogin.text = "" binding.progressBar.show() } is UiState.Error -> { binding.btnLogin.text = "Login" binding.progressBar.hide() toast(state.error) } is UiState.Success -> { binding.btnLogin.text = "Login" binding.progressBar.hide() toast(state.data) val intent = Intent(this, DashboardActivity::class.java) startActivity(intent) finish() } } } } private fun validation () : Boolean { if (binding.editTextEmail.text.toString().isEmpty()){ binding.editTextEmail.error = "Email is required" binding.editTextEmail.requestFocus() return false } if (binding.editTextPassword.text.toString().isEmpty()){ binding.editTextPassword.error = "Password is required" binding.editTextPassword.requestFocus() return false } return true } }
2
Kotlin
1
6
17b9e9ba833a5e8b9d27210d71f7ca7463b9af4d
2,737
ERMS
MIT License
src/test/kotlin/interactor/FindCitiesWithBestValueForMoneyInteractorTest.kt
FlourlessTeam
652,238,006
false
null
package interactor import dataSource.* import kotlin.test.Test import kotlin.test.assertEquals class FindCitiesWithBestValueForMoneyInteractorTest { @Test fun `should return cities with best value for money`() { // GIVEN List High Quality Data ( listOf(cityI, cityII, cityIII) ) val dataSource = FakeHighQualityDataOfCityWithBestValueForMoney() val interactor = FindCitiesWithBestValueForMoneyInteractor(dataSource) // WHEN val result = interactor.execute(3) // THEN assertEquals(result, listOf(cityII, cityI, cityIII)) } @Test fun `should exclude cities with null values and return empty list if all data have null`() { // GIVEN list of missing data ( listOf(cityIV, cityV) ) val dataSource = FakeNullsDataOfCityWithBestValueForMoney() val interactor = FindCitiesWithBestValueForMoneyInteractor(dataSource) // WHEN val result = interactor.execute(2) // THEN assertEquals(emptyList(), result) } @Test fun `should exclude duplicate cities`() { // GIVEN List of cityIV,cityI with the same values ( listOf(cityI, cityIV) ) val dataSource = FakeDuplicateDataOfCityWithBestValueForMoney() val interactor = FindCitiesWithBestValueForMoneyInteractor(dataSource) // WHEN val result = interactor.execute(3) // THEN filter out the duplicate assertEquals(result, listOf(cityI)) } @Test fun `should exclude low quality cities`() { // GIVEN List of Two City Entities Fake Date cityI with true quality data and the false one is cityVII ( listOf(cityVII, cityI) ) val dataSource = FakeLowQualityDataOfCityWithBestValueForMoney() val interactor = FindCitiesWithBestValueForMoneyInteractor(dataSource) // WHEN val result = interactor.execute(3) // THEN cityVII filter Out assertEquals(result, listOf(cityI)) } }
0
Kotlin
0
0
8a53a82a864c25bd3ae38456bbef97ef7db484b5
1,985
cost-of-living
Apache License 2.0
app/src/main/java/com/nutrition/balanceme/presentation/features/home/fridge/ResultsPage.kt
DatTrannn
521,896,551
false
null
package com.nutrition.balanceme.presentation.features.home.fridge import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.* import androidx.compose.material.MaterialTheme.colors import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.FilterList import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import coil.annotation.ExperimentalCoilApi import com.nutrition.balanceme.domain.models.Item import com.nutrition.balanceme.presentation.components.NetImage import com.nutrition.balanceme.presentation.components.SmallSpace import com.nutrition.balanceme.presentation.components.TinySpace import com.nutrition.balanceme.presentation.theme.* @Composable @ExperimentalCoilApi fun ResultsPage(onOpen: () -> Unit, controller: NavController){ val viewmodel: FridgeViewmodel = hiltViewModel() val recipes by remember { viewmodel.recipes } val selected by remember { viewmodel.selected } val ingredients by remember { viewmodel.ingredients } Box(modifier = Modifier.fillMaxSize()){ Column { SmallSpace() Text( text = "What you can cook", style = typography.h5.copy(color = colors.primary) ) SmallSpace() LazyColumn { items(recipes){ recipe -> val missing = recipe.ingredients .filter { id -> !selected.map { it._id }.contains(id) } .map { id -> ingredients.first { it._id == id } } Card(modifier = Modifier.smallVPadding().clickable { controller.navigate("/recipe/${recipe._id}") }) { Box(modifier = Modifier.fillMaxWidth().background(colors.background)){ Column { NetImage( url = recipe.image, modifier = Modifier.fillMaxWidth().height(175.dp) ) Column(modifier = Modifier.smallPadding()){ Text( text = recipe.name, style = typography.h6.copy(fontSize = 16.sp), ) Text(text = "What you're missing:") } MissingItems(items = missing) TinySpace() } } } } } } Box(modifier = Modifier.align(Alignment.BottomEnd)) { FloatingActionButton(onClick = { onOpen() }) { Icon(Icons.Default.FilterList, contentDescription = "fab icon") } } } } @Composable @ExperimentalCoilApi fun MissingItems(items: List<Item>){ LazyRow { items(items){ Box(modifier = Modifier.tinyHPadding()) { NetImage(url = it.image, modifier = Modifier.size(65.dp).clip(CircleShape)) } } } }
0
Kotlin
0
0
f51d0276b1d34e00b27b44689aedf80e1580c542
3,796
BalanceMeApp
MIT License
jvm/jvm-analysis-java-tests/testSrc/com/intellij/codeInspection/tests/java/logging/JavaLoggingStatementNotGuardedByLogConditionInspectionTest.kt
JetBrains
2,489,216
false
null
package com.intellij.codeInspection.tests.java.logging import com.intellij.analysis.JvmAnalysisBundle import com.intellij.jvm.analysis.internal.testFramework.logging.LoggingStatementNotGuardedByLogConditionInspectionTestBase import com.intellij.jvm.analysis.testFramework.JvmLanguage class JavaLoggingStatementNotGuardedByLogConditionInspectionTest : LoggingStatementNotGuardedByLogConditionInspectionTestBase() { fun `test slf4j`() { myFixture.testHighlighting(JvmLanguage.JAVA, """ import org.slf4j.Logger; import org.slf4j.LoggerFactory; class X { private static final Logger LOG = LoggerFactory.getLogger(X.class); void n(String arg) { <warning descr="Logging call not guarded by log condition">LOG.debug("test" + arg)</warning>; } } """.trimIndent()) } fun `test inside lambda slf4j`() { myFixture.testHighlighting(JvmLanguage.JAVA, """ import org.slf4j.Logger; import org.slf4j.LoggerFactory; class X { private static final Logger LOG = LoggerFactory.getLogger(X.class); void n(String arg) { Runnable r = ()->LOG.debug("test" + arg); } } """.trimIndent()) } fun `test log4j2`() { myFixture.testHighlighting(JvmLanguage.JAVA, """ import org.apache.logging.log4j.*; class X { static final Logger LOG = LogManager.getLogger(); void n(String arg) { <warning descr="Logging call not guarded by log condition">LOG.debug("test" + arg)</warning>; } } """.trimIndent()) } fun `test custom logger`() { myFixture.testHighlighting(JvmLanguage.JAVA, """ import java.util.logging.*; class X { static final Logger LOG = Logger.getLogger(""); void n(String arg) { <warning descr="Logging call not guarded by log condition">LOG.fine("test" + arg)</warning>; } } """.trimIndent()) } fun `test skip according level for slf4j`() { myFixture.testHighlighting(JvmLanguage.JAVA, """ import org.slf4j.Logger; import org.slf4j.LoggerFactory; class X { private static final Logger LOG = LoggerFactory.getLogger(X.class); void n(String arg) { LOG.warn("test" + arg); } } """.trimIndent()) } fun `test skip according level for custom logger`() { myFixture.testHighlighting(JvmLanguage.JAVA, """ import java.util.logging.*; class X { static final Logger LOG = Logger.getLogger(""); void n(String arg) { LOG.warning("test" + arg); } } """.trimIndent()) } fun `test is surrounded by guard for slf4j`() { myFixture.testHighlighting(JvmLanguage.JAVA, """ import org.slf4j.Logger; import org.slf4j.LoggerFactory; class X { private static final Logger LOG = LoggerFactory.getLogger(X.class); void n(String arg) { if((LOG.isDebugEnabled())) { LOG.debug("test" + arg); } if(LOG.isInfoEnabled()) { <warning descr="Logging call not guarded by log condition">LOG.debug("test" + arg)</warning>; //todo! } if(true && LOG.isDebugEnabled()) { LOG.debug("test" + arg); } if(true && LOG.isDebugEnabled()) { if(true) { LOG.debug("test" + arg); } } if(true) { if(true) { <warning descr="Logging call not guarded by log condition">LOG.debug("test" + arg)</warning>; } } } } """.trimIndent()) } fun `test is surrounded by guard for custom logger`() { myFixture.testHighlighting(JvmLanguage.JAVA, """ import java.util.logging.*; class X { static final Logger LOG = Logger.getLogger(""); void n(String arg) { if(LOG.isLoggable(java.util.logging.Level.FINE)) { LOG.fine("test" + arg); } if(true && LOG.isLoggable(java.util.logging.Level.FINE)) { LOG.fine("test" + arg); } } } """.trimIndent()) } fun `test skip if only constant arguments for slf4j`() { myFixture.testHighlighting(JvmLanguage.JAVA, """ import org.slf4j.Logger; import org.slf4j.LoggerFactory; class X { private static final Logger LOG = LoggerFactory.getLogger(X.class); void n(String arg) { LOG.debug("test"); LOG.debug("test {} {}", "test" + "test", 1 + 1); } } """.trimIndent()) } fun `test don't skip if only constant arguments for slf4j flagUnguardedConstant`() { myFixture.testHighlighting(JvmLanguage.JAVA, """ import org.slf4j.Logger; import org.slf4j.LoggerFactory; class X { private static final Logger LOG = LoggerFactory.getLogger(X.class); void n1(String arg) { <warning descr="Logging call not guarded by log condition">LOG.debug("test")</warning>; } void n2(String arg) { <warning descr="Logging call not guarded by log condition">LOG.debug("test")</warning>; } } """.trimIndent()) } fun `test skip with several log calls for slf4j`() { myFixture.testHighlighting(JvmLanguage.JAVA, """ import org.slf4j.Logger; import org.slf4j.LoggerFactory; class X { private static final Logger LOG = LoggerFactory.getLogger(X.class); void n2(String arg) { <warning descr="Logging call not guarded by log condition">LOG.debug("test1" + arg)</warning>; LOG.debug("test2" + arg); } void n3(String arg) { <warning descr="Logging call not guarded by log condition">LOG.debug("test1" + arg)</warning>; LOG.debug("test2" + arg); LOG.debug("test2" + arg); } void constantCall(String arg) { LOG.debug("test1"); <warning descr="Logging call not guarded by log condition">LOG.debug("test2" + arg)</warning>; } void beforeNotLog(String arg) { constantCall(arg); <warning descr="Logging call not guarded by log condition">LOG.debug("test2" + arg)</warning>; } void differentLevels(String arg) { <warning descr="Logging call not guarded by log condition">LOG.debug("test1" + arg)</warning>; LOG.warn("test2" + arg); } } """.trimIndent()) } fun `test skip with several log calls for custom logger`() { myFixture.testHighlighting(JvmLanguage.JAVA, """ import java.util.logging.*; class X { static final Logger LOG = Logger.getLogger(""); void n(String arg) { <warning descr="Logging call not guarded by log condition">LOG.fine("test" + arg)</warning>; LOG.fine("test" + arg); } } """.trimIndent()) } fun `test lambda`() { myFixture.testHighlighting(JvmLanguage.JAVA, """ import org.apache.logging.log4j.*; class X { static final Logger LOG = LogManager.getLogger(); void n(String arg) { LOG.info("test {}", ()->"1"); } } """.trimIndent()) } fun `test fix simple slf4j`() { myFixture.testQuickFix( testPreview = true, lang = JvmLanguage.JAVA, before = """ import org.slf4j.Logger; import org.slf4j.LoggerFactory; class X { private static final Logger LOG = LoggerFactory.getLogger(X.class); void n(String arg) { LOG.<caret>debug("test" + arg); } } """.trimIndent(), after = """ import org.slf4j.Logger; import org.slf4j.LoggerFactory; class X { private static final Logger LOG = LoggerFactory.getLogger(X.class); void n(String arg) { if (LOG.isDebugEnabled()) { LOG.debug("test" + arg); } } } """.trimIndent(), hint = JvmAnalysisBundle.message("jvm.inspection.log.statement.not.guarded.log.fix.family.name") ) } fun `test fix simple nested slf4j`() { myFixture.testQuickFix( testPreview = false, lang = JvmLanguage.JAVA, before = """ import org.slf4j.Logger; import org.slf4j.LoggerFactory; class X { private static final Logger LOG = LoggerFactory.getLogger(X.class); void n(String arg) { if(true){ LOG.<caret>debug("test" + arg); } } } """.trimIndent(), after = """ import org.slf4j.Logger; import org.slf4j.LoggerFactory; class X { private static final Logger LOG = LoggerFactory.getLogger(X.class); void n(String arg) { if(true){ if (LOG.isDebugEnabled()) { LOG.debug("test" + arg); } } } } """.trimIndent(), hint = JvmAnalysisBundle.message("jvm.inspection.log.statement.not.guarded.log.fix.family.name") ) } fun `test fix simple custom`() { myFixture.testQuickFix( testPreview = true, lang = JvmLanguage.JAVA, before = """ import java.util.logging.*; class X { static final Logger LOG = Logger.getLogger(""); void n(String arg) { LOG.<caret>fine("test" + arg); } } """.trimIndent(), after = """ import java.util.logging.*; class X { static final Logger LOG = Logger.getLogger(""); void n(String arg) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("test" + arg); } } } """.trimIndent(), hint = JvmAnalysisBundle.message("jvm.inspection.log.statement.not.guarded.log.fix.family.name") ) } fun `test fix simple nested custom`() { myFixture.testQuickFix( testPreview = true, lang = JvmLanguage.JAVA, before = """ import java.util.logging.*; class X { static final Logger LOG = Logger.getLogger(""); void n(String arg) { if(true){ LOG.<caret>fine("test" + arg); } } } """.trimIndent(), after = """ import java.util.logging.*; class X { static final Logger LOG = Logger.getLogger(""); void n(String arg) { if(true){ if (LOG.isLoggable(Level.FINE)) { LOG.fine("test" + arg); } } } } """.trimIndent(), hint = JvmAnalysisBundle.message("jvm.inspection.log.statement.not.guarded.log.fix.family.name") ) } fun `test fix several similar slf4j`() { myFixture.testQuickFix( testPreview = true, lang = JvmLanguage.JAVA, before = """ import org.slf4j.Logger; import org.slf4j.LoggerFactory; class X { private static final Logger LOG = LoggerFactory.getLogger(X.class); void n(String arg) { LOG<caret>.debug("test1" + arg); LOG.debug("test2" + arg); LOG.debug("test3" + arg); } } """.trimIndent(), after = """ import org.slf4j.Logger; import org.slf4j.LoggerFactory; class X { private static final Logger LOG = LoggerFactory.getLogger(X.class); void n(String arg) { if (LOG.isDebugEnabled()) { LOG.debug("test1" + arg); LOG.debug("test2" + arg); LOG.debug("test3" + arg); } } } """.trimIndent(), hint = JvmAnalysisBundle.message("jvm.inspection.log.statement.not.guarded.log.fix.family.name") ) } fun `test fix several similar custom`() { myFixture.testQuickFix( testPreview = true, lang = JvmLanguage.JAVA, before = """ import java.util.logging.*; class X { static final Logger LOG = Logger.getLogger(""); void n(String arg) { LOG<caret>.fine("test1" + arg); LOG.fine("test2" + arg); LOG.fine("test3" + arg); } } """.trimIndent(), after = """ import java.util.logging.*; class X { static final Logger LOG = Logger.getLogger(""); void n(String arg) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("test1" + arg); LOG.fine("test2" + arg); LOG.fine("test3" + arg); } } } """.trimIndent(), hint = JvmAnalysisBundle.message("jvm.inspection.log.statement.not.guarded.log.fix.family.name") ) } fun `test fix several different slf4j`() { myFixture.testQuickFix( testPreview = true, lang = JvmLanguage.JAVA, before = """ import org.slf4j.Logger; import org.slf4j.LoggerFactory; class X { private static final Logger LOG = LoggerFactory.getLogger(X.class); void n(String arg) { LOG<caret>.debug("test1" + arg); LOG.debug("test2" + arg); LOG.trace("test3" + arg); } } """.trimIndent(), after = """ import org.slf4j.Logger; import org.slf4j.LoggerFactory; class X { private static final Logger LOG = LoggerFactory.getLogger(X.class); void n(String arg) { if (LOG.isDebugEnabled()) { LOG.debug("test1" + arg); LOG.debug("test2" + arg); } LOG.trace("test3" + arg); } } """.trimIndent(), hint = JvmAnalysisBundle.message("jvm.inspection.log.statement.not.guarded.log.fix.family.name") ) } fun `test fix several different custom`() { myFixture.testQuickFix( testPreview = true, lang = JvmLanguage.JAVA, before = """ import java.util.logging.*; class X { static final Logger LOG = Logger.getLogger(""); void n(String arg) { LOG<caret>.fine("test1" + arg); LOG.fine("test2" + arg); LOG.finer("test3" + arg); } } """.trimIndent(), after = """ import java.util.logging.*; class X { static final Logger LOG = Logger.getLogger(""); void n(String arg) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("test1" + arg); LOG.fine("test2" + arg); } LOG.finer("test3" + arg); } } """.trimIndent(), hint = JvmAnalysisBundle.message("jvm.inspection.log.statement.not.guarded.log.fix.family.name") ) } }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
14,784
intellij-community
Apache License 2.0
2022/src/main/kotlin/sh/weller/aoc/Day01.kt
Guruth
328,467,380
false
{"Kotlin": 171430, "Rust": 13289, "Elixir": 1833}
package sh.weller.aoc object Day01 : SomeDay<String, Int> { override fun partOne(input: List<String>): Int = input .caloriesPerElv() .max() override fun partTwo(input: List<String>): Int = input .caloriesPerElv() .sortedDescending() .take(3) .sum() private fun List<String>.caloriesPerElv() = fold(mutableListOf(0)) { acc, s -> if (s.isBlank()) { acc.add(0) } else { acc.add(acc.removeLast() + s.toInt()) } acc } }
0
Kotlin
0
0
e5505f796420c844a7ac939399692c5351999b43
578
AdventOfCode
MIT License
app/src/main/java/com/kylecorry/trail_sense/tools/tides/ui/tidelistitem/EstimatedTideListItemFactory.kt
kylecorry31
215,154,276
false
null
package com.kylecorry.trail_sense.tools.tides.ui.tidelistitem import android.content.Context import com.kylecorry.andromeda.alerts.Alerts import com.kylecorry.sol.science.oceanography.Tide import com.kylecorry.trail_sense.R class EstimatedTideListItemFactory(context: Context) : DefaultTideListItemFactory(context) { override fun onClick(tide: Tide) { Alerts.dialog( context, context.getString(R.string.disclaimer_estimated_tide_title), context.getString(R.string.disclaimer_estimated_tide), cancelText = null ) } override fun formatTideHeight(tide: Tide): String { return context.getString(R.string.estimated) } }
240
Kotlin
33
353
9d27ba8e10a45979859c8d4a8f2c8a7910559ec7
706
Trail-Sense
MIT License
domain/src/main/kotlin/dev/tsnanh/android/domain/Interactors.kt
coder7eeN
589,514,809
false
null
package dev.tsnanh.android.domain import androidx.paging.PagingConfig import androidx.paging.PagingData import dev.tsnanh.kotlin.base.InvokeError import dev.tsnanh.kotlin.base.InvokeStarted import dev.tsnanh.kotlin.base.InvokeStatus import dev.tsnanh.kotlin.base.InvokeSuccess import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flow import kotlinx.coroutines.withTimeout import java.util.concurrent.TimeUnit abstract class Interactor<in P> { operator fun invoke( params: P, timeoutMs: Long = defaultTimeoutMs ): Flow<InvokeStatus> = flow { try { withTimeout(timeoutMs) { emit(InvokeStarted) doWork(params) emit(InvokeSuccess) } } catch (timeOutException: TimeoutCancellationException) { emit(InvokeError(timeOutException)) } }.catch { t -> emit(InvokeError(t)) } protected abstract suspend fun doWork(params: P) suspend fun executeSync(params: P) = doWork(params) companion object { private val defaultTimeoutMs = TimeUnit.MINUTES.toMillis(5) } } abstract class ResultInteractor<in P, R> { operator fun invoke(params: P): Flow<R> = flow { emit(doWork(params)) } protected abstract suspend fun doWork(params: P): R } abstract class SubjectInteractor<P : Any, T> { private val paramState = MutableSharedFlow<P>( replay = 1, extraBufferCapacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST, ) val flow: Flow<T> = paramState .distinctUntilChanged() .flatMapLatest { createObservable(it) } .distinctUntilChanged() abstract fun createObservable(params: P): Flow<T> operator fun invoke(params: P) { paramState.tryEmit(params) } } abstract class PagingInteractor<P : PagingInteractor.Parameter<T>, T : Any> : SubjectInteractor<P, PagingData<T>>() { interface Parameter<T : Any> { val pagingConfig: PagingConfig } } abstract class SuspendingWorkInteractor<P : Any, T> : SubjectInteractor<P, T>() { abstract fun doWork(params: P): T override fun createObservable(params: P) = flow { emit(doWork(params)) } }
0
null
0
0
fadef8cd52195e256d393d9be197b9f38c3955e7
2,510
MADBaseSourceCode
MIT License
app/src/main/java/com/battlelancer/seriesguide/util/tasks/RateEpisodeTask.kt
UweTrottmann
1,990,682
false
{"Kotlin": 2280980, "Java": 880919, "PowerShell": 1268}
// SPDX-License-Identifier: Apache-2.0 // Copyright 2015-2024 <NAME> package com.battlelancer.seriesguide.util.tasks import android.content.Context import com.battlelancer.seriesguide.provider.SgRoomDatabase import com.uwetrottmann.trakt5.entities.ShowIds import com.uwetrottmann.trakt5.entities.SyncEpisode import com.uwetrottmann.trakt5.entities.SyncItems import com.uwetrottmann.trakt5.entities.SyncSeason import com.uwetrottmann.trakt5.entities.SyncShow import com.uwetrottmann.trakt5.enums.Rating /** * See [BaseRateItemTask] */ class RateEpisodeTask( context: Context, rating: Rating?, private val episodeId: Long ) : BaseRateItemTask(context, rating) { override val traktAction: String get() = "rate episode" override fun buildTraktSyncItems(): SyncItems? { val database = SgRoomDatabase.getInstance(context) val episode = database.sgEpisode2Helper().getEpisodeNumbers(episodeId) ?: return null val showTmdbId = database.sgShow2Helper().getShowTmdbId(episode.showId) if (showTmdbId == 0) return null return SyncItems() .shows( SyncShow().id(ShowIds.tmdb(showTmdbId)) .seasons( SyncSeason().number(episode.season) .episodes( SyncEpisode().number(episode.episodenumber) .rating(rating) ) ) ) } override fun doDatabaseUpdate(): Boolean { val rowsUpdated = SgRoomDatabase.getInstance(context).sgEpisode2Helper() .updateUserRating(episodeId, rating?.value ?: 0) return rowsUpdated > 0 } }
56
Kotlin
401
1,966
c7bc6445ecc58b841c1887a56146dc2d2f817007
1,738
SeriesGuide
Apache License 2.0
2019-10-02/SystemServices/app/src/main/java/br/ufpe/cin/android/systemservices/sensor/GestureDetectorActivity.kt
if710
99,732,816
false
null
package br.ufpe.cin.android.systemservices.sensor import android.app.Activity import android.os.Build import android.os.Bundle import android.text.Html import android.text.Spanned import android.view.GestureDetector import android.view.MotionEvent import br.ufpe.cin.android.systemservices.R import kotlinx.android.synthetic.main.activity_gesture_detector.* class GestureDetectorActivity : Activity(), GestureDetector.OnDoubleTapListener, GestureDetector.OnGestureListener { private var gestureDetector: GestureDetector? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_gesture_detector) //o primeiro this é pq GestureDetectorActivity é uma Activity (óbvio!) //o segundo é pq a gente precisa de um listener, no caso OnGestureListener gestureDetector = GestureDetector(this, this) //esse this é pq esta Activity implementa OnDoubleTapListener gestureDetector!!.setOnDoubleTapListener(this) //vamos monitorar longpress gestureDetector!!.setIsLongpressEnabled(true) } override fun onTouchEvent(event: MotionEvent): Boolean { gestureDetector!!.onTouchEvent(event) return super.onTouchEvent(event) } private fun formatSingleMotionEvent(event: String, me: MotionEvent): Spanned { val sb = StringBuilder() sb.append("<h2>") sb.append(event) sb.append("</h2>") sb.append("<p>") sb.append("<b>X:</b> ") sb.append(me.x) sb.append("</p>") sb.append("<p>") sb.append("<b>Y:</b> ") sb.append(me.y) sb.append("</p>") sb.append("<p>") sb.append("<b>Pressure:</b> ") sb.append(me.pressure) sb.append("</p>") //me.get... return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Html.fromHtml(sb.toString(), Html.FROM_HTML_MODE_LEGACY) } else { Html.fromHtml(sb.toString()) } } private fun formatComplexMotionEvent(event: String, me1: MotionEvent, me2: MotionEvent, attr: String, attrX: Float, attrY: Float): Spanned { val sb = StringBuilder() sb.append("<h2>") sb.append(event) sb.append("</h2>") sb.append("<p>") sb.append("<b>X:</b> ") sb.append(me1.x) sb.append(" | ") sb.append("<b>Y:</b> ") sb.append(me1.y) sb.append("</p>") sb.append("<p>") sb.append("<b>Pressure:</b> ") sb.append(me1.pressure) sb.append("</p>") sb.append("<p>") sb.append("<b>X:</b> ") sb.append(me2.x) sb.append(" | ") sb.append("<b>Y:</b> ") sb.append(me2.y) sb.append("</p>") sb.append("<p>") sb.append("<b>Pressure:</b> ") sb.append(me2.pressure) sb.append("</p>") sb.append("<h2>") sb.append(attr) sb.append("</h2>") sb.append("<p>") sb.append("<b>X:</b> ") sb.append(attrX) sb.append(" | ") sb.append("<b>Y:</b> ") sb.append(attrY) sb.append("</p>") return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Html.fromHtml(sb.toString(), Html.FROM_HTML_MODE_LEGACY) } else { Html.fromHtml(sb.toString()) } } override fun onSingleTapConfirmed(e: MotionEvent): Boolean { tvGesture.text = formatSingleMotionEvent("onSingleTapConfirmed", e) return false } override fun onDoubleTap(e: MotionEvent): Boolean { tvGesture.text = formatSingleMotionEvent("onDoubleTap", e) return false } override fun onDoubleTapEvent(e: MotionEvent): Boolean { tvGesture.text = formatSingleMotionEvent("onDoubleTapEvent", e) return false } override fun onDown(e: MotionEvent): Boolean { tvGesture.text = formatSingleMotionEvent("onDown", e) return false } override fun onShowPress(e: MotionEvent) { tvGesture.text = formatSingleMotionEvent("onShowPress", e) } override fun onSingleTapUp(e: MotionEvent): Boolean { tvGesture.text = formatSingleMotionEvent("onSingleTapUp", e) return false } override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean { tvGesture.text = formatComplexMotionEvent("onScroll", e1, e2, "Distance", distanceX, distanceY) return false } override fun onLongPress(e: MotionEvent) { tvGesture.text = formatSingleMotionEvent("onLongPress", e) } override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean { tvGesture.text = formatComplexMotionEvent("onFling", e1, e2, "Velocity", velocityX, velocityY) return false } }
1
null
29
12
ce4131eb6aca5e33fa5ed503d613ba6ed40dec4d
4,916
if710.github.io
MIT License
app-sample/src/main/java/io/noties/markwon/app/utils/ReadMeUtils.kt
noties
91,698,982
false
{"Gradle": 22, "Markdown": 104, "Java Properties": 1, "Shell": 3, "Text": 1, "Ignore List": 1, "Batchfile": 1, "INI": 18, "Java": 394, "XML": 75, "YAML": 3, "JSON": 6, "Kotlin": 59, "EditorConfig": 2, "SVG": 6, "JavaScript": 5, "Stylus": 11, "Vue": 32}
package io.noties.markwon.app.utils import android.net.Uri import android.text.TextUtils import java.util.regex.Pattern object ReadMeUtils { // username, repo, branch, lastPathSegment @Suppress("RegExpRedundantEscape") private val RE_FILE = Pattern.compile("^https:\\/\\/github\\.com\\/([\\w-.]+?)\\/([\\w-.]+?)\\/(?:blob|raw)\\/([\\w-.]+?)\\/(.+)\$") @Suppress("RegExpRedundantEscape") private val RE_REPOSITORY: Pattern = Pattern.compile("^https:\\/\\/github.com\\/([\\w-.]+?)\\/([\\w-.]+?)\\/*\$") data class GithubInfo( val username: String, val repository: String, val branch: String, val fileName: String ) fun parseRepository(url: String): Pair<String, String>? { val matcher = RE_REPOSITORY.matcher(url) val (user, repository) = if (matcher.matches()) { Pair(matcher.group(1), matcher.group(2)) } else { Pair(null, null) } return if (TextUtils.isEmpty(user) || TextUtils.isEmpty(repository)) { null } else { Pair(user!!, repository!!) } } fun parseInfo(data: Uri?): GithubInfo? { if (data == null) { return null } val matcher = RE_FILE.matcher(data.toString()) if (!matcher.matches()) { return null } return GithubInfo( username = matcher.group(1)!!, repository = matcher.group(2)!!, branch = matcher.group(3)!!, fileName = matcher.group(4)!! ) } fun buildRawGithubUrl(data: Uri): String { val info = parseInfo(data) return if (info == null) { data.toString() } else { buildRawGithubUrl(info) } } @Suppress("MemberVisibilityCanBePrivate") fun buildRawGithubUrl(info: GithubInfo): String { return "https://github.com/${info.username}/${info.repository}/raw/${info.branch}/${info.fileName}" } fun buildRepositoryReadMeUrl(username: String, repository: String): String { return buildRawGithubUrl(GithubInfo(username, repository, "master", "README.md")) } }
66
Java
295
2,662
2ea148c30a07f91ffa37c0aa36af1cf2670441af
2,214
Markwon
Apache License 2.0
Android/App_Petridish/App/src/main/java/com/zktony/android/data/dao/CalibrationDao.kt
OriginalLight
556,213,614
false
{"Kotlin": 6123849, "C#": 376657, "Vue": 164353, "Rust": 101266, "C++": 63250, "TypeScript": 62359, "Python": 28781, "CMake": 18271, "C": 16214, "Less": 2885, "Dockerfile": 1898, "HTML": 648, "JavaScript": 450}
package com.zktony.android.data.dao import androidx.room.* import com.zktony.android.data.entities.Calibration import kotlinx.coroutines.flow.Flow /** * @author: 刘贺贺 * @date: 2022-10-25 11:09 */ @Dao abstract class CalibrationDao : BaseDao<Calibration> { @Query( """ SELECT * FROM calibrations ORDER BY create_time ASC """ ) abstract fun getAll(): Flow<List<Calibration>> @Query( """ UPDATE calibrations SET active = (CASE WHEN id = :id THEN 1 ELSE 0 END) """ ) abstract suspend fun active(id: Long) @Query( """ DELETE FROM calibrations WHERE id = :id """ ) abstract suspend fun deleteById(id: Long) }
0
Kotlin
0
1
bcf0671b9e4ad199e579764f29683c1c575369d2
740
ZkTony
Apache License 2.0
src/core/src/commonMain/kotlin/community/flock/aigentic/core/dsl/AgentDsl.kt
flock-community
791,132,993
false
{"Kotlin": 111822}
package community.flock.aigentic.core.dsl @DslMarker @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) annotation class AgentDSL interface Config<T> { fun build(): T }
0
Kotlin
0
1
5f3c9af3ef6e95f7510b95d052523b3ec516116e
183
aigentic
MIT License
src/main/kotlin/eu/mctraveler/discord-activity.kt
Blazzike
860,069,656
false
{"Kotlin": 7296, "Java": 5535}
package eu.mctraveler import io.github.vyfor.kpresence.ConnectionState import io.github.vyfor.kpresence.RichClient import io.github.vyfor.kpresence.event.ActivityUpdateEvent import io.github.vyfor.kpresence.event.DisconnectEvent import io.github.vyfor.kpresence.rpc.ActivityType import io.github.vyfor.kpresence.utils.epochMillis import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents import kotlin.math.max var regionName: String = "" var playerCount = 0 var connectionTime: Long? = null var isInRegion = false; val discordRichClient = RichClient(708032641261371424) fun initializeDiscordActivity() { discordRichClient.on<ActivityUpdateEvent> { logger?.info("Updated rich presence") } discordRichClient.on<DisconnectEvent> { connect(shouldBlock = true) } ClientPlayConnectionEvents.DISCONNECT.register { _, client -> val ip = client.connection?.serverData?.ip ?: return@register if (isDevelopmentEnvironment || ip.lowercase().endsWith("mctraveler.eu")) { disconnect() } } } fun mcTravelerConnect() { connectionTime = epochMillis() updateActivity() } fun updateIsInRegion(newIsInRegion: Boolean) { isInRegion = newIsInRegion updateActivity() } fun disconnect() { connectionTime = null updateActivity() } fun updatePlayerCount(count: Int) { playerCount = max(0, count - 1) updateActivity() } fun updateRegionName(name: String) { regionName = name updateActivity() } fun updateActivity() { try { if (connectionTime == null) { discordRichClient.clear() return } if (discordRichClient.connectionState != ConnectionState.CONNECTED) { discordRichClient.connect() } discordRichClient.update { type = ActivityType.GAME details = "Playing with $playerCount other player${if (playerCount == 1) "" else "s"}" state = "In ${if (!isInRegion) "the wilderness" else regionName}" timestamps { start = connectionTime } assets { largeImage = "logo" largeText = "play.MCTraveler.eu" } button("Visit Website", "https://mctraveler.eu/") } } catch (e: Exception) { // logger.error("Failed to update discord presence", e) TODO } }
0
Kotlin
0
0
107e6b7dfac38279d0e9cad84cc9fe6be3bb81e4
2,231
mctraveler-client
Creative Commons Zero v1.0 Universal
app/src/main/java/com/example/androiddevchallenge/ui/composable/Shape.kt
chachako
349,062,434
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge.ui.composable import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.unit.Dp import com.example.androiddevchallenge.ui.theme.currentShapes @Composable fun Circle(size: Dp, color: Color, modifier: Modifier = Modifier) { Canvas(modifier = modifier.size(size)) { drawCircle(color) } } @Composable fun Shape(color: Color, modifier: Modifier = Modifier, shape: Shape = currentShapes.large) { Box(modifier = modifier.background(color, shape)) }
2
Kotlin
1
17
bb1ac181bc859e6ed831d216c6955e5a1dd402e0
1,422
compose-weather
Apache License 2.0
app/src/main/java/com/kobeissidev/jetpackcomposepokedex/ui/composable/LoadingLayout.kt
kobeissi2
454,511,440
false
{"Kotlin": 648363, "Java": 50280}
package com.kobeissidev.jetpackcomposepokedex.ui.composable import android.content.res.Configuration import androidx.compose.foundation.layout.* import androidx.compose.material.LinearProgressIndicator import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.hilt.navigation.compose.hiltViewModel import androidx.paging.ExperimentalPagingApi import coil.compose.AsyncImage import coil.request.ImageRequest import com.kobeissidev.jetpackcomposepokedex.R import com.kobeissidev.jetpackcomposepokedex.ui.screen.MainViewModel /** * Loading screen that will show an image of the app logo. * @param orientation is used to update the size of the image depending on the orientation. * @param isShowImage will show the logo if true. */ @ExperimentalPagingApi @Composable fun LoadingLayout( isShowImage: Boolean = false, viewModel: MainViewModel = hiltViewModel() ) { val orientation by viewModel.orientationFlow.collectAsState(initial = viewModel.currentOrientation) val widthPercentage = if (orientation == Configuration.ORIENTATION_LANDSCAPE) 0.5f else 0.75f Row(modifier = Modifier.fillMaxWidth()) { LinearProgressIndicator( modifier = Modifier.fillMaxWidth(), color = MaterialTheme.colors.onPrimary ) } if (isShowImage) { Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { AsyncImage( modifier = Modifier.fillMaxSize(fraction = widthPercentage), model = ImageRequest.Builder(LocalContext.current).data(R.drawable.ic_pokeball).build(), contentDescription = null ) } } }
2
Kotlin
0
0
9ee22f783f4ecab9bdc1293c519e89b90a1564f4
2,022
Compedex
Apache License 2.0
app/src/main/java/com/hongwei/android_lab/lab/compose/demo/dataflow/DataFlowDemoViewModel.kt
hongwei-bai
364,924,389
false
null
package com.hongwei.android_lab.lab.compose.demo.dataflow import androidx.lifecycle.* import dagger.hilt.android.lifecycle.HiltViewModel import io.reactivex.schedulers.Schedulers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class DataFlowDemoViewModel @Inject constructor( repository: DataFlowDemoRepository ) : ViewModel() { val accountName: LiveData<String> = liveData { delay(3000) emit("Netbank Saver") delay(3000) emit("Netbank Saver 2") delay(3000) emit("Netbank Saver 3") } val accountNameFromFlow: LiveData<String> = repository.accountNameFlow.asLiveData() val accountNameFromRx: MutableLiveData<String> = MutableLiveData() init { repository.getAccountNameFromRxJava() .subscribeOn(Schedulers.io()) .subscribe({ accountNameFromRx.postValue(it) }, { }) } }
0
Kotlin
0
0
c3fc0d4b4145f1ff537b7e4cbbceec8a831b3093
979
android-lab
MIT License
BarcodeScanner/app/src/main/java/com/poc/barcode/MainActivity.kt
Rishika-20
736,164,247
false
{"Kotlin": 9997}
package com.poc.barcode import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import com.poc.barcode.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { /** * This is an instance of the ActivityResultLauncher<String> interface, * which is used to handle the result of requesting camera permission. * **/ private var requestCamera : ActivityResultLauncher<String>? = null /** * This property is of type ActivityMainBinding, used to access UI elements * defined in the associated XML layout file (activity_main.xml). **/ private lateinit var binding: ActivityMainBinding /** * The onCreate() method is called when the activity is being created. * It sets up the layout using the ActivityMainBinding class. **/ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) /** * This method registers an ActivityResultLauncher for requesting camera permission. * It uses the ActivityResultContracts.RequestPermission() contract, * - which handles the permission request and its result. * The second parameter is a lambda function that is executed when * -the permission request result is received. **/ requestCamera = registerForActivityResult(ActivityResultContracts.RequestPermission(),) { if(it){ val intent = Intent(this, Scan:: class.java) startActivity(intent) } else{ Toast.makeText(this,"Permission Not Granted",Toast.LENGTH_SHORT).show() } } /** * This method sets a click listener on the "Scan" button (btnScanner). * When the button is clicked, the requestCamera?.launch() method * - is called to request camera permission. * This launches the camera permission request using the ActivityResultLauncher defined earlier. * It takes the permission string (android.Manifest.permission.CAMERA) as a parameter. * **/ binding.btnScanner.setOnClickListener { requestCamera?.launch(android.Manifest.permission.CAMERA) } } }
0
Kotlin
0
0
226ead5b875d7eb13a2dcfd8c2d6f28c789d8a2c
2,594
Barcode-Scanner-POC
MIT License
app/src/main/java/pl/applover/androidarchitecture/models/example/ExampleModel.kt
ApploverSoftware
118,103,725
false
null
package pl.applover.androidarchitecture.models.example import pl.applover.androidarchitecture.data.example.internet.response.ExampleResponse /** * Created by <NAME> on 2018-01-12. */ class ExampleModel(exampleResponse: ExampleResponse) { private val body: String? private val id: String? private val title: String? private val userId: String? init { body = exampleResponse.body id = exampleResponse.id title = exampleResponse.title userId = exampleResponse.userId } }
27
Kotlin
1
2
c099425be26b22728597b893ebb676dec5ee1d0c
530
android_architecture
Apache License 2.0
core/design/src/main/kotlin/br/com/mob1st/core/design/atoms/typography/FontTypeScale.kt
mob1st
526,655,668
false
{"Kotlin": 796049, "Shell": 1558}
package br.com.mob1st.core.design.atoms.typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.em import androidx.compose.ui.unit.sp import kotlin.math.pow /** * The progression of font sizes used in the app typography. * It calculates the font size based on a given [base] text unit and a ratio. * @property base the base text size unit to be used to calculate the font size. * @property fontSizeRatio the ratio to be used to calculate the font size. The default value is the Major Second. * @property lineHeightRatio the ratio to be used to calculate the line height. * @see [https://supercharge.design/blog/what-is-a-type-scale] */ class FontTypeScale( private val base: TextUnit = baseTextUnit, private val fontSizeRatio: Float = MAJOR_SECOND_FONT_SCALE, private val lineHeightRatio: Float = LINE_HEIGHT_RATIO, private val letterSpacingRatio: Double = LETTER_SPACING_RATIO, ) { /** * Creates a [TextStyle] using the given parameters and calculating the font size and line height with the scale * ratio and the base text unit. * @param fontFamily the font family to be used. * @param fontWeight the font weight to be used. * @param sizePower the power to be used to calculate the font size. It's applied to the [fontSizeRatio] before * multiplying it by the [base]. */ fun style( fontFamily: FontFamily, fontWeight: FontWeight, sizePower: Int, ): TextStyle { val fontSize = base * (fontSizeRatio.pow(sizePower)) val lineHeight = fontSize * lineHeightRatio val letterSpacing = (letterSpacingRatio / fontSize.value).em return TextStyle( fontFamily = fontFamily, fontSize = fontSize, fontWeight = fontWeight, lineHeight = lineHeight, letterSpacing = letterSpacing, ) } companion object { private val baseTextUnit = 14.sp private const val MAJOR_SECOND_FONT_SCALE = 1.125f private const val LINE_HEIGHT_RATIO = 1.2f private const val LETTER_SPACING_RATIO = 0.2 } }
11
Kotlin
0
3
48eadc8642a06cad6cbe3dc5e068655bb9c03839
2,272
bet-app-android
Apache License 2.0
src/main/kotlin/de/julasoftware/fxsmtp/server/MailStore.kt
JulaSoftware
687,031,030
false
{"Kotlin": 29830}
package de.julasoftware.fxsmtp.server import de.julasoftware.fxsmtp.core.Configuration import de.julasoftware.fxsmtp.model.Email import org.slf4j.LoggerFactory import org.subethamail.smtp.server.Session import java.io.* import java.nio.file.Path import java.text.SimpleDateFormat import java.util.* import javax.mail.internet.MimeMessage import kotlin.io.path.deleteIfExists import kotlin.io.path.listDirectoryEntries class MailStore { private val logger = LoggerFactory.getLogger(MailStore::class.java) private val dateFormat = SimpleDateFormat("ddMMyyhhmmssSSS") fun save(from: String?, to: String?, data: InputStream?): Email { val mimeMessage = MimeMessage(javax.mail.Session.getDefaultInstance(System.getProperties()), data) val baos = ByteArrayOutputStream() mimeMessage.writeTo(baos) val rawString = baos.toString() baos.close() return Email( from = from, to = to, mimeMessage = mimeMessage, filePath = saveEmailToFile(mimeMessage), rawString = rawString ) } private fun saveEmailToFile(emailMessage: MimeMessage): Path { val filePath = "${Configuration.instance().loadedConfig.email.folder}${File.separator}${dateFormat.format(Date())}" var i = 0 var file: File? = null while (file == null || file.exists()) { val iStr: String = if (i++ > 0) { i.toString() } else "" file = File("$filePath$iStr${Configuration.instance().loadedConfig.email.suffix}") } try { emailMessage.writeTo(FileOutputStream(file)) } catch (e: IOException) { // If we can't save file, we display the error in the SMTP logs val smtpLogger = LoggerFactory.getLogger(Session::class.java) smtpLogger.error("Error: Can't save email: {}", e.message) } return file.toPath() } fun delete(email: Email) { email.filePath?.deleteIfExists() } fun deleteAll() { Path.of(Configuration.instance().loadedConfig.email.folder).listDirectoryEntries().forEach { it.deleteIfExists() } } }
0
Kotlin
0
1
18f0c4e264ec433304a4d6652b5ce733f0eabb4e
2,155
FxSmtpServer
MIT License
plugin/src/org/jetbrains/cabal/psi/RepoLocationField.kt
Atsky
12,811,746
false
null
package org.jetbrains.cabal.psi import com.intellij.lang.ASTNode import com.intellij.extapi.psi.ASTWrapperPsiElement import org.jetbrains.cabal.psi.SingleValueField class RepoLocationField(node: ASTNode) : SingleValueField(node)
47
null
22
205
a9be4e8c41202cba50f6f9aa72eb912f1fa92b8c
230
haskell-idea-plugin
Apache License 2.0
src/main/kotlin/uk/gibby/krg/returns/empty/EmptyReturn.kt
mnbjhu
568,569,855
false
null
package uk.gibby.krg.returns.empty import uk.gibby.krg.returns.ReturnValue abstract class EmptyReturn: ReturnValue<Unit>() { override fun getStructuredString(): String { throw Exception("Return is empty") } override fun parse(value: Any?) { throw Exception("Return is empty") } override fun encode(value: Unit): ReturnValue<Unit> { throw Exception("Return is empty") } }
0
Kotlin
0
1
a15e5331b5903126df08426c25e85e6d64b115bf
422
KRG
MIT License
src/main/kotlin/com/team4099/lib/sim/vision/RotTrlTransform3d.kt
team4099
560,942,123
false
null
package com.team4099.lib.sim.vision import kotlin.jvm.JvmOverloads import edu.wpi.first.math.geometry.Pose3d import edu.wpi.first.math.geometry.Rotation3d import edu.wpi.first.math.geometry.Transform3d import edu.wpi.first.math.geometry.Translation3d import java.util.stream.Collectors /** * Represents a transformation that first rotates a pose around the origin, * and then translates it. */ class RotTrlTransform3d /** * A rotation-translation transformation. * * * Applying this transformation to poses will preserve their current origin-to-pose * transform as if the origin was transformed by these components. * * @param rot The rotation component * @param trl The translation component */ @JvmOverloads constructor( /** The rotation component of this transformation */ val rotation: Rotation3d = Rotation3d(), /** The translation component of this transformation */ val translation: Translation3d = Translation3d() ) { /** * Creates a rotation-translation transformation from a Transform3d. * * * Applying this transformation to poses will preserve their current origin-to-pose * transform as if the origin was transformed by these components. * * @param trf The origin transformation */ constructor(trf: Transform3d) : this(trf.rotation, trf.translation) {} /** * The inverse of this transformation. Applying the inverse will "undo" this transformation. */ fun inverse(): RotTrlTransform3d { val inverseRot = rotation.unaryMinus() val inverseTrl = translation.rotateBy(inverseRot).unaryMinus() return RotTrlTransform3d(inverseRot, inverseTrl) } /** This transformation as a Transform3d (as if of the origin) */ val transform: Transform3d get() = Transform3d(translation, rotation) fun apply(trl: Translation3d?): Translation3d { return apply(Pose3d(trl, Rotation3d())).translation } fun applyTrls(trls: List<Translation3d?>): List<Translation3d> { return trls.stream().map { t: Translation3d? -> apply(t) } .collect(Collectors.toList()) } fun apply(pose: Pose3d): Pose3d { return Pose3d( pose.translation.rotateBy(rotation).plus(translation), pose.rotation.plus(rotation) ) } fun applyPoses(poses: List<Pose3d>): List<Pose3d> { return poses.stream().map { p: Pose3d -> apply(p) } .collect(Collectors.toList()) } companion object { /** * The rotation-translation transformation that makes poses in the world * consider this pose as the new origin, or change the basis to this pose. * * @param pose The new origin */ @JvmStatic fun makeRelativeTo(pose: Pose3d): RotTrlTransform3d { return RotTrlTransform3d(pose.rotation, pose.translation).inverse() } } }
7
Kotlin
2
9
d114a9a0cd8de83d438df424b74adf7844050354
2,766
ChargedUp-2023
MIT License
embrace-android-core/src/test/java/io/embrace/android/embracesdk/internal/opentelemetry/EmbTracerTest.kt
embrace-io
704,537,857
false
{"Kotlin": 2981564, "C": 189341, "Java": 150268, "C++": 13140, "CMake": 4261}
package io.embrace.android.embracesdk.opentelemetry import io.embrace.android.embracesdk.arch.schema.EmbType import io.embrace.android.embracesdk.fakes.FakeClock import io.embrace.android.embracesdk.fakes.FakeOpenTelemetryClock import io.embrace.android.embracesdk.fakes.FakeSpanService import io.embrace.android.embracesdk.fakes.FakeTracer import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Before import org.junit.Test internal class EmbTracerTest { private val clock = FakeClock() private val openTelemetryClock = FakeOpenTelemetryClock(clock) private lateinit var spanService: FakeSpanService private lateinit var sdkTracer: FakeTracer private lateinit var tracer: EmbTracer @Before fun setup() { spanService = FakeSpanService() sdkTracer = FakeTracer() tracer = EmbTracer( sdkTracer = sdkTracer, spanService = spanService, clock = openTelemetryClock, ) } @Test fun `check span generated with default parameters`() { tracer.spanBuilder("foo").startSpan().end() val fakeCreatedSpan = spanService.createdSpans.single() with(fakeCreatedSpan) { assertNull(parent) assertEquals("foo", name) assertEquals(EmbType.Performance.Default, type) } } }
16
Kotlin
7
134
896e9aadf568ba527c76ec66f6f440baed29d1ee
1,367
embrace-android-sdk
Apache License 2.0
src/android/facebook_ads/src/main/java/com/ee/internal/FacebookInterstitialAd.kt
Senspark
62,603,267
false
null
package com.ee.internal import android.app.Activity import androidx.annotation.AnyThread import androidx.annotation.UiThread import com.ee.IFullScreenAd import com.ee.ILogger import com.ee.IMessageBridge import com.ee.Thread import com.facebook.ads.Ad import com.facebook.ads.AdError import com.facebook.ads.InterstitialAd import com.facebook.ads.InterstitialAdListener import kotlinx.serialization.Serializable import java.util.concurrent.atomic.AtomicBoolean /** * Created by Zinge on 10/11/17. */ internal class FacebookInterstitialAd( private val _bridge: IMessageBridge, private val _logger: ILogger, private var _activity: Activity?, private val _adId: String) : IFullScreenAd, InterstitialAdListener { @Serializable @Suppress("unused") private class ErrorResponse( val code: Int, val message: String ) companion object { private val kTag = FacebookInterstitialAd::class.java.name } private val _messageHelper = MessageHelper("FacebookInterstitialAd", _adId) private val _helper = FullScreenAdHelper(_bridge, this, _messageHelper) private val _isLoaded = AtomicBoolean(false) private var _displaying = false private var _ad: InterstitialAd? = null init { _logger.info("$kTag: constructor: adId = $_adId") registerHandlers() } override fun onCreate(activity: Activity) { _activity = activity } override fun onResume() { } override fun onPause() { } override fun onDestroy() { _activity = null } override fun destroy() { _logger.info("$kTag: ${this::destroy.name}: adId = $_adId") deregisterHandlers() destroyInternalAd() } @AnyThread private fun registerHandlers() { _helper.registerHandlers() } @AnyThread private fun deregisterHandlers() { _helper.deregisterHandlers() } @UiThread private fun createInternalAd(): InterstitialAd { _ad?.let { return@createInternalAd it } val ad = InterstitialAd(_activity, _adId) _ad = ad return ad } @AnyThread private fun destroyInternalAd() { Thread.runOnMainThread { val ad = _ad ?: return@runOnMainThread ad.destroy() _ad = null } } override val isLoaded: Boolean @AnyThread get() = _isLoaded.get() @AnyThread override fun load() { Thread.runOnMainThread { _logger.debug("$kTag: ${this::load.name}: id = $_adId") val ad = createInternalAd() ad.loadAd(ad.buildLoadAdConfig() .withAdListener(this) .build()) } } @AnyThread override fun show() { Thread.runOnMainThread { _logger.debug("$kTag: ${this::show.name}: id = $_adId") val ad = createInternalAd() _displaying = true val result = ad.show(ad.buildShowAdConfig().build()) if (result) { // OK. } else { _isLoaded.set(false) destroyInternalAd() _bridge.callCpp(_messageHelper.onFailedToShow, ErrorResponse(-1, "Failed to show ad").serialize()) } } } override fun onAdLoaded(ad: Ad) { Thread.runOnMainThread { _logger.debug("$kTag: ${this::onAdLoaded.name} id = $_adId") _isLoaded.set(true) _bridge.callCpp(_messageHelper.onLoaded) } } override fun onError(ad: Ad, error: AdError) { Thread.runOnMainThread { _logger.debug("$kTag: ${this::onError.name}: id = $_adId message = ${error.errorMessage}") destroyInternalAd() if (_displaying) { _displaying = false _isLoaded.set(false) _bridge.callCpp(_messageHelper.onFailedToShow, ErrorResponse(error.errorCode, error.errorMessage).serialize()) } else { _bridge.callCpp(_messageHelper.onFailedToLoad, ErrorResponse(error.errorCode, error.errorMessage).serialize()) } } } override fun onInterstitialDisplayed(ad: Ad) { Thread.runOnMainThread { _logger.debug("$kTag: ${this::onInterstitialDisplayed.name}: id = $_adId") } } override fun onLoggingImpression(ad: Ad) { Thread.runOnMainThread { _logger.debug("$kTag: ${this::onLoggingImpression.name}: id = $_adId") } } override fun onAdClicked(ad: Ad) { Thread.runOnMainThread { _logger.debug("$kTag: ${this::onAdClicked.name}: id = $_adId") _bridge.callCpp(_messageHelper.onClicked) } } override fun onInterstitialDismissed(ad: Ad) { Thread.runOnMainThread { _logger.debug("$kTag: ${this::onInterstitialDismissed.name}: id = $_adId") _displaying = false _isLoaded.set(false) destroyInternalAd() _bridge.callCpp(_messageHelper.onClosed) } } }
2
null
9
16
60a66ad3dc6e14802a7c5d8d585a8499be13f5b8
5,107
ee-x
MIT License
src/main/kotlin/twitterapi/Requests.kt
Nekoyue
570,751,911
false
{"Kotlin": 25334}
package twitterapi import io.ktor.resources.* import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable @Resource("/2/users/{id}/liked_tweets") data class LikedTweetsRequest( val id: ULong, @SerialName("max_results") val maxResults: Int? = null, // between 10..100 val expansions: String? = null, @SerialName("tweet.fields") val tweetFields: String? = null, @SerialName("media.fields") val mediaFields: String? = null, @SerialName("user.fields") val userField: String? = null ) { constructor( id: ULong, maxResults: Int?, expansions: Set<String>? = null, tweetFields: Set<String>? = null, mediaFields: Set<String>? = null, userField: Set<String>? = null ) : this( id, maxResults, expansions?.joinToString(","), tweetFields?.joinToString(","), mediaFields?.joinToString(","), userField?.joinToString(",") ) } @Serializable @Resource("/2/users/by/username/{username}") data class FindUserByUsernameRequest( val username: String )
0
Kotlin
0
0
e39d8998fd35451fba1cd7dc8f6970fcde9a026d
1,059
IrisWatcher
MIT License
app/src/androidTest/java/eu/caraus/home24/application/ui/main/selection/UiFlow.kt
alexandrucaraus
143,283,559
false
null
package eu.caraus.home24.application.ui.main.selection import android.support.test.espresso.Espresso.onView import android.support.test.espresso.Espresso.pressBack import android.support.test.espresso.action.ViewActions.click import android.support.test.espresso.assertion.ViewAssertions.matches import android.support.test.espresso.contrib.RecyclerViewActions import android.support.test.espresso.matcher.ViewMatchers.* import android.support.test.filters.LargeTest import android.support.test.runner.AndroidJUnit4 import android.support.test.rule.ActivityTestRule import eu.caraus.home24.R import org.junit.runner.RunWith import org.junit.Test import org.junit.Rule import eu.caraus.home24.application.ui.main.MainActivity import eu.caraus.home24.application.ui.start.StartActivity import kotlinx.android.synthetic.main.activity_start.* import android.support.v7.widget.RecyclerView import android.support.test.espresso.matcher.BoundedMatcher import android.view.View import eu.caraus.home24.application.common.Configuration.Companion.NUMBER_OF_ITEMS_TO_REVIEW import eu.caraus.home24.application.ui.main.review.ReviewAdapter import org.hamcrest.Description import org.hamcrest.Matcher @RunWith(AndroidJUnit4::class) @LargeTest class UiFlow { @get:Rule var startActivityRule = ActivityTestRule(StartActivity::class.java) @get:Rule var mainActivityRule = ActivityTestRule(MainActivity::class.java) private val numberOfArticles = NUMBER_OF_ITEMS_TO_REVIEW @Test fun uiTestSimple() { onView( withId( R.id.btStart )).perform( click()) onView( withId( R.id.tvLiked)).check( matches( withText("0"))) onView( withId( R.id.tvTotal)).check( matches( withText("1"))) onView( withId( R.id.ivLike)).perform( click()) onView( withId( R.id.tvLiked)).check( matches( withText("1"))) onView( withId( R.id.tvTotal)).check( matches( withText("2"))) onView( withId( R.id.ivLike)).perform( click()) onView( withId( R.id.tvLiked)).check( matches( withText("2"))) onView( withId( R.id.tvTotal)).check( matches( withText("3"))) } @Test fun uiTestReviewGoBack() { onView( withId( R.id.btStart )).perform( click()) onView( withId( R.id.tvLiked)).check( matches( withText("0"))) onView( withId( R.id.tvTotal)).check( matches( withText("1"))) for( i in 1..numberOfArticles ) { onView( withId( R.id.ivLike)).perform( click()) } onView( withId( R.id.tvLiked)).check( matches( withText("$numberOfArticles"))) onView( withId( R.id.tvTotal)).check( matches( withText("$numberOfArticles"))) onView( withId( R.id.btReview)).check( matches( isDisplayed()) ) onView( withId( R.id.btReview)).perform( click()) pressBack() pressBack() onView( withId( R.id.btStart )).perform( click()) onView( withId( R.id.tvLiked)).check( matches( withText("0"))) onView( withId( R.id.tvTotal)).check( matches( withText("1"))) } @Test fun uiTestReviewList() { onView( withId( R.id.btStart )).perform( click()) onView( withId( R.id.tvLiked)).check( matches( withText("0"))) onView( withId( R.id.tvTotal)).check( matches( withText("1"))) for( i in 1..numberOfArticles ) { onView( withId( R.id.ivLike)).perform( click()) } onView( withId( R.id.tvLiked)).check( matches( withText("$numberOfArticles"))) onView( withId( R.id.tvTotal)).check( matches( withText("$numberOfArticles"))) onView( withId( R.id.btReview)).check( matches( isDisplayed()) ) onView( withId( R.id.btReview)).perform( click()) onView(withId(R.id.rvReviewItems)).check( matches( atPosition(0, hasDescendant( withText("Premium Komfortmatratze Smood"))))) // onView( withId(R.id.rvReviewItems)).perform( RecyclerViewActions.scrollToPosition<ReviewAdapter.ViewHolder>(7)) // // onView(withId(R.id.rvReviewItems)).check( matches( // atPosition(6, hasDescendant(withText("Schlafsofa Latina Webstoff"))))) } fun atPosition(position: Int, itemMatcher: Matcher<View>): Matcher<View> { return object : BoundedMatcher<View, RecyclerView>(RecyclerView::class.java) { override fun describeTo(description: Description) { description.appendText("has item at position $position: ") itemMatcher.describeTo(description) } override fun matchesSafely(view: RecyclerView): Boolean { val viewHolder = view.findViewHolderForAdapterPosition(position) ?: // has no item on such position return false return itemMatcher.matches(viewHolder.itemView) } } } }
0
Kotlin
0
0
51ca5bd6ea34fa2dcceb79653824263e94ba626c
4,864
Home24LikeMvp
MIT License
Android/app/src/main/java/com/decisionkitchen/decisionkitchen/DecisionKitchen.kt
meteochu
98,756,569
false
null
package com.decisionkitchen.decisionkitchen import android.app.Application import com.facebook.drawee.backends.pipeline.Fresco /** * Created by kevin on 2017-07-29. */ public class DecisionKitchen: Application() { override fun onCreate() { super.onCreate() Fresco.initialize(this) } }
1
null
1
1
09b923b68b7934605ce0a690f98b0a9df553c7f6
312
DecisionKitchen
Apache License 2.0
Mobile/app/src/main/java/nl/endran/productbrowser/AboutActivity.kt
Endran
53,199,416
false
{"Text": 1, "Ignore List": 4, "Markdown": 2, "Gradle": 3, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "Proguard": 1, "Kotlin": 21, "XML": 19, "Java": 3, "JSON": 3, "JavaScript": 16, "JSON with Comments": 3, "Git Attributes": 1, "EditorConfig": 1, "HTML": 10, "robots.txt": 1, "CSS": 1}
/* * Copyright (c) 2016 by David Hardy. Licensed under the Apache License, Version 2.0. */ package nl.endran.productbrowser import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.support.v7.app.AppCompatActivity import de.psdev.licensesdialog.LicensesDialog import kotlinx.android.synthetic.main.activity_about.* class AboutActivity : AppCompatActivity() { companion object { fun createIntent(context: Context) = Intent(context, AboutActivity::class.java) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_about) setSupportActionBar(toolbar) textViewVersion.text = getVersion(this) buttonLicenses.setOnClickListener { LicensesDialog.Builder(this).setNotices(R.raw.notices).build().show() } } private fun getVersion(context: Context): String { try { val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0) val resources = context.resources return String.format(resources.getString(R.string.about_versionInfo), packageInfo.versionName) } catch (e: PackageManager.NameNotFoundException) { } return context.getString(R.string.all_unknown) } }
1
null
1
1
2e0a59c18dd793249e3116716c5082a3cae8091c
1,393
ProductBrowserReference
Apache License 2.0
src/main/kotlin/dev/deos/etrium/client/EtriumHud.kt
Deos-Team
664,702,265
false
null
package dev.deos.etrium.client import com.mojang.blaze3d.systems.RenderSystem import dev.deos.etrium.Etrium import dev.deos.etrium.network.DataPackets import dev.deos.etrium.utils.EnergyTypes.LEVEL import dev.deos.etrium.utils.IEntityDataSaver import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback import net.fabricmc.fabric.api.networking.v1.PacketByteBufs import net.minecraft.block.BlockState import net.minecraft.block.entity.BlockEntity import net.minecraft.client.MinecraftClient import net.minecraft.client.gui.DrawContext import net.minecraft.client.render.GameRenderer import net.minecraft.entity.LivingEntity import net.minecraft.entity.player.PlayerEntity import net.minecraft.entity.projectile.ProjectileUtil import net.minecraft.fluid.FluidState import net.minecraft.text.Text import net.minecraft.util.Formatting import net.minecraft.util.Identifier import net.minecraft.util.hit.BlockHitResult import net.minecraft.util.hit.HitResult import net.minecraft.util.math.* import net.minecraft.util.math.ColorHelper.Argb import net.minecraft.util.shape.VoxelShape import net.minecraft.world.BlockView import net.minecraft.world.RaycastContext import net.minecraft.world.RaycastContext.FluidHandling import java.util.function.BiFunction import java.util.function.Function import java.util.function.Predicate class EtriumHud : HudRenderCallback, BlockView { private val HUD = Identifier(Etrium.MI, "textures/hud/hud.png") private val client = MinecraftClient.getInstance() private var height = 0f private var width = 0f val yellow = takeColor(245, 203, 66) val black = takeColor(0, 0, 0) val white = takeColor(255, 255, 255) override fun onHudRender(drawContext: DrawContext, tickDelta: Float) { if (client != null) { height = drawContext.scaledWindowHeight.toFloat() width = drawContext.scaledWindowWidth.toFloat() } RenderSystem.setShader(GameRenderer::getPositionTexProgram) RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f) RenderSystem.setShaderTexture(0, HUD) if (!(client.player as PlayerEntity).isCreative && !(client.player as PlayerEntity).isSpectator) { drawContext.apply { renderHealthBar() renderHungerBar() renderOxygenBar() renderEnergyBar() renderArmor() } } drawContext.apply { renderEntityLevel(tickDelta) } } private fun syncEntityLevel(id: Int) { val buf = PacketByteBufs.create() buf.writeInt(id) ClientPlayNetworking.send(DataPackets.CLIENT_ENTITY_ID, buf) } private fun DrawContext.renderEntityLevel(tickDelta: Float) { val entity = getEntity(tickDelta) ?: return syncEntityLevel(entity.id) val level = (client.player as IEntityDataSaver).getPersistentData().getInt("entityLevel") val playerLevel = (client.player as IEntityDataSaver).getPersistentData().getInt(LEVEL) val color = if (level <= playerLevel + 1) Formatting.GREEN else if (level - playerLevel <= 6) Formatting.YELLOW else Formatting.RED RenderSystem.enableBlend() this.drawTextWithShadow( client.textRenderer, Text.literal(entity.name.string).formatted(Formatting.BOLD), (width / 100).toInt(), (height / 100).toInt(), white ) this.drawTextWithShadow( client.textRenderer, Text.literal("Lvl: $level").formatted(Formatting.BOLD, color), (width / 100).toInt(), (height / 100 + 30).toInt(), white ) renderEntityHealthBar(entity) RenderSystem.disableBlend() } private fun DrawContext.renderEntityHealthBar(entity: LivingEntity) { this.drawTexture(HUD, (width / 100 - 1).toInt(), (height / 100 + 11f).toInt(), 0, 0, 182, 14) val health = entity.health val maxHealth = entity.maxHealth if (health > 0) { val wth = if (maxHealth >= health) (182f * (health / maxHealth)).toInt() else 182 this.drawTexture( HUD, (width / 100 - 1).toInt(), (height / 100 + 11f).toInt(), 0, 14, wth, 14 ) // 37f val wdth = health.toInt().toString().length * 6 this.drawText( client.textRenderer, Text.literal("${health.toInt()}/${maxHealth.toInt()}"), (width / 100 + 92 - wdth).toInt(), (height / 100 + 14).toInt(), white, true ) } } private fun DrawContext.renderHealthBar() { this.drawTexture(HUD, (width / 2 - 91).toInt(), (height - 40f).toInt(), 0, 0, 182, 14) val health = (client.player as PlayerEntity).health val maxHealth = (client.player as PlayerEntity).maxHealth if (health > 0) { val wth = if (maxHealth >= health) (182f * (health / maxHealth)).toInt() else 182 this.drawTexture( HUD, (width / 2 - 91).toInt(), (height - 40f).toInt(), 0, 14, wth, 14 ) // 37f val wdth = health.toInt().toString().length * 6 this.drawText( client.textRenderer, Text.literal("${health.toInt()}/${maxHealth.toInt()}"), (width / 2 - 3 - wdth).toInt(), (height - 37f).toInt(), white, true ) } } private fun DrawContext.renderHungerBar() { this.drawTexture(HUD, (width / 2 - 91).toInt(), (height - 52).toInt(), 0, 28, 81, 8) val hunger = (client.player as PlayerEntity).hungerManager.foodLevel if (hunger > 0) { val wth = (81f * (hunger.toFloat() / 20f)).toInt() this.drawTexture( HUD, (width / 2 - 91).toInt(), (height - 52f).toInt(), 0, 36, wth, 8 ) } this.drawTexture(HUD, (width / 2 - 96).toInt(), (height - 54).toInt(), 182, 0, 14, 14) } private fun DrawContext.renderOxygenBar() { val oxygen = (client.player as PlayerEntity).air val maxOxygen = (client.player as PlayerEntity).maxAir if (oxygen >= maxOxygen) return this.drawTexture(HUD, (width / 2 + 10).toInt(), (height - 52).toInt(), 81, 28, 81, 8) val wth = (81f * (oxygen.toFloat() / maxOxygen)).toInt() this.drawTexture( HUD, (width / 2 + 10).toInt(), (height - 52f).toInt(), 81, 36, wth, 8 ) this.drawTexture(HUD, (width / 2 + 3).toInt(), (height - 55).toInt(), 196, 0, 14, 15) } private fun DrawContext.renderArmor() { this.drawTexture(HUD, (width / 2 - 120f).toInt(), (height - 36f).toInt(), 182, 15, 22, 31) val armor = (client.player as PlayerEntity).armor if (armor > 0) { val wdth = armor.toString().length * 6 this.drawText( client.textRenderer, Text.literal(armor.toString()), (width / 2 - 125f - wdth).toInt(), (height - 25f).toInt(), white, true ) } } private fun DrawContext.renderEnergyBar() { this.drawTexture(HUD, (width / 2 + 100).toInt(), (height - 36f).toInt(), 210, 0, 17, 31) val energy = (client.player as IEntityDataSaver).getPersistentData().getFloat("energy") val maxEnergy = (client.player as IEntityDataSaver).getPersistentData().getFloat("maxEnergy") val hgt = if (maxEnergy >= energy) (31f * (1f - (energy / maxEnergy))).toInt() else 0 this.drawTexture( HUD, (width / 2 + 100).toInt(), (height - 36f).toInt(), 227, 0, 20, hgt ) this.drawText( client.textRenderer, Text.literal("/"), (width / 2 + 124f).toInt(), (height - 25f).toInt(), white, true ) this.drawText( client.textRenderer, Text.literal(energy.toInt().toString()), (width / 2 + 124f).toInt(), (height - 36f).toInt(), white, true ) this.drawText( client.textRenderer, Text.literal(maxEnergy.toInt().toString()), (width / 2 + 124f).toInt(), (height - 15f).toInt(), white, true ) } private fun takeColor(r: Int, g: Int, b: Int, invis: Int = 255): Int { return Argb.getArgb(invis, r, g, b) } override fun raycast(context: RaycastContext): BlockHitResult? { return BlockView.raycast( context.start, context.end, context, BiFunction { c, pos: BlockPos? -> val block = getBlockState(pos) if (!block.isOpaque) { return@BiFunction null } val blockShape: VoxelShape = c.getBlockShape(block, this, pos) raycastBlock(c.start, c.end, pos, blockShape, block) }, Function { c -> val v: Vec3d = c.start.subtract(c.end) return@Function BlockHitResult.createMissed( c.end, Direction.getFacing(v.x, v.y, v.z), BlockPos(Vec3i(c.end.x.toInt(), c.end.y.toInt(), c.end.z.toInt())) ) }) } private fun setupRayTraceContext( player: PlayerEntity, distance: Double, fluidHandling: FluidHandling ): RaycastContext { val pitch = player.pitch val yaw = player.yaw val fromPos = player.getCameraPosVec(1.0f) val float_3 = MathHelper.cos(-yaw * 0.017453292f - 3.1415927f) val float_4 = MathHelper.sin(-yaw * 0.017453292f - 3.1415927f) val float_5 = -MathHelper.cos(-pitch * 0.017453292f) val xComponent = float_4 * float_5 val yComponent = MathHelper.sin(-pitch * 0.017453292f) val zComponent = float_3 * float_5 val toPos = fromPos.add( xComponent.toDouble() * distance, yComponent.toDouble() * distance, zComponent.toDouble() * distance ) return RaycastContext(fromPos, toPos, RaycastContext.ShapeType.OUTLINE, fluidHandling, player) } private fun getEntity(tickDelta: Float): LivingEntity? { val isVisible = Predicate<net.minecraft.entity.Entity> { entity -> !entity.isSpectator } val viewer = client.cameraEntity ?: return null val reachDistance: Double = 14.0 val position = viewer.getCameraPosVec(1.0f) val look = viewer.getRotationVec(tickDelta) val max = position.add(look.x * reachDistance, look.y * reachDistance, look.z * reachDistance) val searchBox: Box = viewer.boundingBox.stretch(look.multiply(reachDistance)).expand(1.0, 1.0, 1.0) val result = ProjectileUtil.raycast(viewer, position, max, searchBox, isVisible, reachDistance * reachDistance) if (result != null && result.entity is LivingEntity) { val target = result.entity as LivingEntity val blockHit: BlockHitResult? = raycast(setupRayTraceContext(client.player as PlayerEntity, reachDistance, FluidHandling.NONE)) if (blockHit!!.type != HitResult.Type.MISS) { val blockDistance = blockHit.pos.distanceTo(position) if (blockDistance > target.distanceTo(client.player)) { return target } } else { return target } } return null } override fun getHeight(): Int { return 0 } override fun getBottomY(): Int { return 0 } override fun getBlockEntity(pos: BlockPos): BlockEntity? { return client.world!!.getBlockEntity(pos) } override fun getBlockState(pos: BlockPos?): BlockState { return client.world!!.getBlockState(pos) } override fun getFluidState(pos: BlockPos?): FluidState { return client.world!!.getFluidState(pos) } }
0
Kotlin
0
0
af61016d578e1d222e04957c2036bc4a3ad82c99
12,303
etrium-rpg
MIT License
app/src/main/java/com/revis/di/builder/ActivityBuilder.kt
chandruscm
268,476,224
false
null
package com.revis.di.builder import com.revis.di.ViewModelBuilder import com.revis.di.scope.ActivityScope import com.revis.ui.MainActivity import com.revis.ui.dialog.DeepLinkDialogPromptActivity import com.revis.ui.video.VideoCallActivity import dagger.Module import dagger.android.ContributesAndroidInjector /** * Provides Activity instance using Dagger. */ @SuppressWarnings("unused") @Module abstract class ActivityBuilder { @ActivityScope @ContributesAndroidInjector( modules = [ FragmentBuilder::class, ViewModelBuilder::class ] ) abstract fun provideMainActivity(): MainActivity @ActivityScope @ContributesAndroidInjector( modules = [ FragmentBuilder::class, ViewModelBuilder::class ] ) abstract fun provideVideoCallActivity(): VideoCallActivity @ActivityScope @ContributesAndroidInjector( modules = [ FragmentBuilder::class, ViewModelBuilder::class ] ) abstract fun provideDeepLinkDialogPromptActivity(): DeepLinkDialogPromptActivity }
0
Kotlin
0
1
d864999a4a137ef2c4c4c033b0a0839b74c32723
1,117
Revis
Apache License 2.0
app/src/main/java/com/filkom/banksampahdelima/viewmodel/TrashExchangeViewModel.kt
fahmigutawan
572,343,810
false
null
package com.filkom.banksampahdelima.viewmodel import android.util.Log import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.filkom.core.data.repository.Repository import com.filkom.core.model.domain.TrashItem import com.filkom.core.data.source.Resource import com.filkom.core.model.data.response.slip.NewSlipMenabungResponse import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.combine import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class TrashExchangeViewModel @Inject constructor( private val repository: Repository ) : ViewModel() { val listOfUnselectedItem = mutableStateListOf<TrashItem>() val listOfSelectedItem = mutableStateListOf<TrashItem>() val startPostNewSlipMenabung = mutableStateOf(false) val trashItemsResponse = MutableStateFlow<Resource<List<TrashItem>>>(Resource.Loading()) val userCartResponse = MutableStateFlow<Resource<List<TrashItem>>>(Resource.Loading()) val addNewCartItemState = MutableStateFlow<Resource<Any?>>(Resource.Loading()) val deleteItemFromChartState = MutableStateFlow<Resource<Any?>>(Resource.Loading()) val newSlipMenabungState = MutableStateFlow<Resource<NewSlipMenabungResponse>>(Resource.Loading()) fun getTrashItems() = viewModelScope.launch { repository.getAllSampah().collect{ trashItemsResponse.value = it } repository.getUserCart().collect{ userCartResponse.value = it } } fun addItemToCart(idSampah: String, nama: String) = viewModelScope.launch { repository.postUserCartNewItem(idSampah, nama).collect { addNewCartItemState.value = it } } fun deleteItemFromCart(idSampah: String) = viewModelScope.launch { repository.deleteItemFromCart(idSampah).collect { deleteItemFromChartState.value = it } } fun postNewSlipMenabung() { viewModelScope.launch { repository .postNewSlipMenabung( trashes = listOfSelectedItem.toList() ) .collect { newSlipMenabungState.value = it } } } init { getTrashItems() } }
0
Kotlin
0
0
38af1bf62fd2363723abffb692d6b79399c5a26f
2,514
Jetpack-BankSampahRW5
MIT License
shared/src/main/java/de/loosetie/k8s/dsl/impls/Taint.kt
loosetie
283,145,621
false
null
package de.loosetie.k8s.dsl.impls import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonPropertyOrder import de.loosetie.k8s.dsl.K8sManifest import de.loosetie.k8s.dsl.HasParent import de.loosetie.k8s.dsl.manifests.* @JsonPropertyOrder("effect", "key", "timeAdded", "value") class Taint_core_v1_k8s1_16Impl( @JsonIgnore override val parent: K8sManifest? = null ) : Taint_core_v1_k8s1_16, HasParent { override var effect: String? = null override var key: String? = null override var timeAdded: Time_meta_v1_k8s1_16? = null override var value: String? = null } typealias Taint_core_v1_k8s1_17Impl = Taint_core_v1_k8s1_16Impl @JsonPropertyOrder("effect", "key", "timeAdded", "value") class Taint_core_v1_k8s1_18Impl( @JsonIgnore override val parent: K8sManifest? = null ) : Taint_core_v1_k8s1_18, HasParent { override var effect: String? = null override var key: String? = null override var timeAdded: Time_meta_v1_k8s1_18? = null override var value: String? = null } typealias Taint_core_v1_k8s1_19Impl = Taint_core_v1_k8s1_18Impl typealias Taint_core_v1_k8s1_20Impl = Taint_core_v1_k8s1_19Impl typealias Taint_core_v1_k8s1_21Impl = Taint_core_v1_k8s1_20Impl
0
Kotlin
0
1
aaf63cb956f15863ad37ebe3532cb604f9b9506c
1,223
k8s-dsl
Apache License 2.0
app/src/main/java/dev/pimentel/rickandmorty/presentation/characters/dto/CharactersState.kt
bfpimentel
273,356,184
false
null
package dev.pimentel.rickandmorty.presentation.characters.dto import androidx.annotation.DrawableRes import dev.pimentel.rickandmorty.R data class CharactersState( val characters: List<CharactersItem> = emptyList(), @DrawableRes val filterIcon: Int = R.drawable.ic_filter_default, val listErrorMessage: String? = null, val detailsErrorMessage: String? = null )
0
Kotlin
1
1
0de46077173eeeef0d2e737e4618280d02075a31
379
rick-and-morty-app
MIT License
src/jsMain/kotlin/matt/http/lib/lib.kt
mgroth0
532,378,353
false
{"Kotlin": 75522}
package matt.http.lib import io.ktor.client.engine.HttpClientEngine import io.ktor.client.engine.js.Js actual val httpClientEngine: HttpClientEngine by lazy { Js.create { } }
0
Kotlin
0
0
be2693045680f53b4e0d74706fdabed1d283663b
187
http
MIT License
app/src/main/java/vn/loitp/up/a/cv/draggableFlipView/DraggableFlipViewActivity.kt
tplloi
126,578,283
false
null
package vn.loitp.up.a.cv.draggableFlipView import android.os.Bundle import androidx.core.view.isVisible import com.loitp.annotation.IsFullScreen import com.loitp.annotation.LogTag import com.loitp.core.base.BaseActivityFont import com.loitp.core.common.NOT_FOUND import com.loitp.core.ext.openUrlInBrowser import com.loitp.core.ext.setSafeOnClickListenerElastic import vn.loitp.R import vn.loitp.databinding.ADraggableFlipViewBinding @LogTag("DraggableFlipViewActivity") @IsFullScreen(false) class DraggableFlipViewActivity : BaseActivityFont() { private lateinit var binding: ADraggableFlipViewBinding override fun setLayoutResourceId(): Int { return NOT_FOUND } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ADraggableFlipViewBinding.inflate(layoutInflater) setContentView(binding.root) setupViews() } private fun setupViews() { binding.lActionBar.apply { this.ivIconLeft.setSafeOnClickListenerElastic( runnable = { onBaseBackPressed() } ) this.ivIconRight?.let { it.setSafeOnClickListenerElastic( runnable = { context.openUrlInBrowser( url = "https://github.com/ssk5460/DraggableFlipView" ) } ) it.isVisible = true it.setImageResource(R.drawable.ic_baseline_code_48) } this.tvTitle?.text = DraggableFlipViewActivity::class.java.simpleName } } }
1
Kotlin
1
9
1bf1d6c0099ae80c5f223065a2bf606a7542c2b9
1,683
base
Apache License 2.0
app/src/main/java/chat/rocket/android/server/domain/TokenRepository.kt
RocketChat
48,179,404
false
null
package chat.rocket.android.server.domain interface TokenRepository : chat.rocket.core.TokenRepository { fun remove(url: String) fun clear() }
283
Kotlin
585
877
f832d59cb2130e5c058f5d9e9de5ff961d5d3380
151
Rocket.Chat.Android
MIT License
app/src/main/java/care/vive/android/util/Place.kt
AID-COVID-19
258,950,200
false
null
package care.vive.android.util import android.os.Parcel import android.os.Parcelable import com.fasterxml.jackson.annotation.JsonPropertyOrder @JsonPropertyOrder("latitude", "longitude", "placeName", "placeId", "id") class Place : Parcelable { var latitude: Double? var longitude: Double? var placeName: String? var placeId: String? var id: String? constructor( latitude: Double?, longitude: Double?, placeName: String?, placeId: String?, id: String? ) { this.latitude = latitude this.longitude = longitude this.placeName = placeName this.placeId = placeId this.id = id } override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeValue(latitude) dest.writeValue(longitude) dest.writeString(placeName) dest.writeString(placeId) dest.writeString(id) } protected constructor(`in`: Parcel) { latitude = `in`.readValue(Double::class.java.classLoader) as Double? longitude = `in`.readValue(Double::class.java.classLoader) as Double? placeName = `in`.readString() placeId = `in`.readString() id = `in`.readString() } companion object { val CREATOR: Parcelable.Creator<Place?> = object : Parcelable.Creator<Place?> { override fun createFromParcel(source: Parcel): Place? { return Place(source) } override fun newArray(size: Int): Array<Place?> { return arrayOfNulls(size) } } } }
0
Kotlin
0
0
42bf13d88f55a3e8cd4708140cf7a1abcaf3bfff
1,676
vive-android
MIT License
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/resources/testProject/powerAssertSourceSets/src/main/kotlin/sample/main.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package sample fun requireInMain() { val greeting = "Hello, Main!" require(greeting == "Hello, World!") } fun assertInMain() { val greeting = "Hello, Main!" assert(greeting == "Hello, World!") }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
423
kotlin
Apache License 2.0
app/src/main/kotlin/cn/wj/android/cashbook/ui/type/viewmodel/TypeListViewModel.kt
WangJie0822
365,932,300
false
null
package cn.wj.android.cashbook.ui.type.viewmodel import androidx.core.os.bundleOf import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import cn.wj.android.cashbook.R import cn.wj.android.cashbook.base.ext.base.logger import cn.wj.android.cashbook.base.ext.base.orElse import cn.wj.android.cashbook.base.ext.base.string import cn.wj.android.cashbook.base.ext.base.toNewList import cn.wj.android.cashbook.base.tools.mutableLiveDataOf import cn.wj.android.cashbook.base.ui.BaseViewModel import cn.wj.android.cashbook.data.constants.* import cn.wj.android.cashbook.data.entity.TypeEntity import cn.wj.android.cashbook.data.enums.RecordTypeEnum import cn.wj.android.cashbook.data.enums.TypeEnum import cn.wj.android.cashbook.data.event.LifecycleEvent import cn.wj.android.cashbook.data.model.UiNavigationModel import cn.wj.android.cashbook.data.repository.type.TypeRepository import cn.wj.android.cashbook.data.transform.toSnackbarModel import com.jeremyliao.liveeventbus.LiveEventBus import kotlinx.coroutines.launch /** * 分类列表 * * > [王杰](mailto:[email protected]) 创建于 2021/6/29 */ class TypeListViewModel(private val repository: TypeRepository) : BaseViewModel() { /** 记录展开类型的 id */ private var expandTypeId = -1L /** 显示编辑类型菜单弹窗事件 */ val showEditTypeMenuEvent: LifecycleEvent<TypeEntity> = LifecycleEvent() /** 保存点击事件 */ val saveEvent: LifecycleEvent<Int> = LifecycleEvent() /** 标记 - 是否是编辑状态 */ val edit: MutableLiveData<Boolean> = MutableLiveData(false) /** 分类大类 */ val typeData: MutableLiveData<RecordTypeEnum> = mutableLiveDataOf { loadTypeList() } /** 类型数据 */ val listData: MutableLiveData<List<TypeEntity>> = MutableLiveData() /** 取消点击 */ val onCancelClick: () -> Unit = { // 恢复排序 listData.value = listData.value.toNewList() // 退出编辑 edit.value = false } /** 保存点击 */ val onSaveClick: () -> Unit = { saveEvent.value = 0 } /** 一级分类点击 */ val onFirstTypeItemClick: (TypeEntity) -> Unit = { item -> listData.value?.forEach { if (it.id == item.id && it.showMore) { it.expand.set(!it.expand.get()) } else { it.expand.set(false) } if (it.expand.get()) { expandTypeId = it.id } } } /** 分类菜单点击 */ val onTypeMenuClick: (TypeEntity) -> Unit = { item -> showEditTypeMenuEvent.value = item } /** 添加二级分类点击 */ val onAddSecondTypeClick: (TypeEntity) -> Unit = { first -> uiNavigationEvent.value = UiNavigationModel.builder { jump( ROUTE_PATH_TYPE_EDIT, bundleOf( ACTION_SELECTED to TypeEntity.empty() .copy(parent = first, type = TypeEnum.SECOND, recordType = typeData.value.orElse(RecordTypeEnum.EXPENDITURE)) ) ) } } /** 加载分类列表数据 */ fun loadTypeList() { viewModelScope.launch { try { val typeList = repository.getTypeListByType(typeData.value.orElse(RecordTypeEnum.EXPENDITURE)) // 修正已展开的数据 typeList.firstOrNull { it.id == expandTypeId }?.expand?.set(true) listData.value = typeList } catch (throwable: Throwable) { logger().e(throwable, "getTypeListByType") } } } /** 更新分类信息 */ fun updateType(types: List<TypeEntity>) { viewModelScope.launch { try { val ls = arrayListOf<TypeEntity>() types.forEachIndexed { index, first -> ls.add(first.copy(sort = index)) first.childList.forEachIndexed { i, second -> ls.add(second.copy(sort = i)) } } repository.updateTypes(ls) // 更新成功,刷新 loadTypeList() // 退出编辑 edit.value = false } catch (throwable: Throwable) { logger().e(throwable, "deleteType") } } } /** 删除类型 [type] */ fun deleteType(type: TypeEntity) { if (type.refund || type.reimburse) { // 系统类型不支持删除 snackbarEvent.value = R.string.system_type_does_not_support_deletion.string.toSnackbarModel() return } if (type.type == TypeEnum.FIRST && type.childList.isNotEmpty()) { // 一级分类且子分类不为空 snackbarEvent.value = R.string.has_second_type_can_not_delete.string.toSnackbarModel() return } viewModelScope.launch { try { // 检查是否存在记录 if (repository.getRecordCountByType(type) > 0) { // 跳转替换分类 uiNavigationEvent.value = UiNavigationModel.builder { jump( ROUTE_PATH_TYPE_REPLACE, bundleOf( ACTION_SELECTED to type ) ) } return@launch } repository.deleteType(type) // 删除成功,刷新列表 LiveEventBus.get<Int>(EVENT_RECORD_CHANGE).post(0) snackbarEvent.value = R.string.delete_success.string.toSnackbarModel() } catch (throwable: Throwable) { logger().e(throwable, "deleteType") } } } /** 将 [type] 修改为一级分类 */ fun changeToFirstType(type: TypeEntity) { viewModelScope.launch { try { val changed = type.copy(parent = null, type = TypeEnum.FIRST, sort = repository.getTypeCount().toInt()) repository.updateType(changed) // 修改成功,刷新列表 LiveEventBus.get<Int>(EVENT_RECORD_CHANGE).post(0) snackbarEvent.value = R.string.update_success.string.toSnackbarModel() } catch (throwable: Throwable) { logger().e(throwable, "changeToFirstType") } } } /** 处理选择一级分类返回 */ fun disposeForResult(target: TypeEntity, first: TypeEntity) { viewModelScope.launch { try { val changed = if (target.first) { // 一级分类,修改为二级分类 target.copy(parent = first, type = TypeEnum.SECOND, sort = repository.getTypeCount().toInt()) } else { // 二级分类,移动到其它一级分类 target.copy(parent = first, sort = repository.getTypeCount().toInt()) } repository.updateType(changed) // 修改成功,刷新列表 LiveEventBus.get<Int>(EVENT_RECORD_CHANGE).post(0) snackbarEvent.value = R.string.update_success.string.toSnackbarModel() } catch (throwable: Throwable) { logger().e(throwable, "changeToFirstType") } } } }
2
Kotlin
4
8
171fec9b87c6e996842e79ff94fadbc88931249e
7,073
Cashbook
Apache License 2.0
compiler/testData/loadJava/compiledKotlin/fromLoadJava/FieldOfArrayType.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// TARGET_BACKEND: JVM package test public open class FieldOfArrayType() { public var files: Array<java.io.File>? = null }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
128
kotlin
Apache License 2.0
samples/client/3_1_0_unit_test/kotlin/src/main/kotlin/org/openapijsonschematools/client/schemas/validation/AdditionalPropertiesValidator.kt
openapi-json-schema-tools
544,314,254
false
null
package org.openapijsonschematools.client.schemas.validation import org.openapijsonschematools.client.exceptions.ValidationException class AdditionalPropertiesValidator : KeywordValidator { @Throws(ValidationException::class) override fun validate( data: ValidationData ): PathToSchemasMap? { if (data.arg !is Map<*, *>) { return null } val additionalProperties: Class<out JsonSchema<*>> = data.schema.additionalProperties ?: return null val presentAdditionalProperties: MutableSet<String> = LinkedHashSet() for (key in data.arg.keys) { if (key is String) { presentAdditionalProperties.add(key) } } val properties: Map<String, Class<out JsonSchema<*>>>? = data.schema.properties if (properties != null) { presentAdditionalProperties.removeAll(properties.keys) } val pathToSchemas = PathToSchemasMap() for (addPropName in presentAdditionalProperties) { val propValue: Any? = data.arg.get(addPropName) val propPathToItem: List<Any> = data.validationMetadata.pathToItem + addPropName if (data.patternPropertiesPathToSchemas != null && data.patternPropertiesPathToSchemas .containsKey(propPathToItem) ) { continue } val propValidationMetadata = ValidationMetadata( propPathToItem, data.validationMetadata.configuration, data.validationMetadata.validatedPathToSchemas, data.validationMetadata.seenClasses ) val addPropsSchema = JsonSchemaFactory.getInstance(additionalProperties) if (propValidationMetadata.validationRanEarlier(addPropsSchema)) { // todo add_deeper_validated_schemas continue } val otherPathToSchemas = JsonSchema.validate(addPropsSchema, propValue, propValidationMetadata) pathToSchemas.update(otherPathToSchemas) } return pathToSchemas } }
1
null
11
128
9006de722f74b7ca917e4e5d38e4cd6ab5ea6e78
2,124
openapi-json-schema-generator
Apache License 2.0
app/src/main/java/com/aaron/yespdf/about/Info.kt
aaronzzx
206,055,620
false
null
package com.aaron.yespdf.about import android.annotation.SuppressLint import android.os.Build import com.aaron.yespdf.BuildConfig import com.aaron.yespdf.R import com.aaron.yespdf.common.App import com.blankj.utilcode.util.ScreenUtils import java.util.* /** * @author Aaron <EMAIL> */ @SuppressLint("ConstantLocale") interface Info { companion object { const val MY_BLOG = "https://juejin.im/user/5c3f3b2b5188252580051f8c" const val MY_EMAIL = "mailto:<EMAIL>" const val SOURCE_CODE = "https://github.com/Aaronzzx/YESPDF" const val MY_GITHUB = "https://github.com/Aaronzzx" val FEEDBACK_SUBJECT = ("YES PDF! for Android " + "view" + BuildConfig.VERSION_NAME + "\n" + "Feedback(" + Build.BRAND + "-" + Build.MODEL + ")") val FEEDBACK_TEXT = (App.getContext().getString(R.string.app_feedback_title) + "\n" + "Device: " + Build.BRAND + "-" + Build.MODEL + "\n" + "Android Version: " + Build.VERSION.RELEASE + "(SDK=" + Build.VERSION.SDK_INT + ")" + "\n" + "Resolution: " + ScreenUtils.getScreenWidth() + "*" + ScreenUtils.getScreenHeight() + "\n" + "System Language: " + Locale.getDefault().language + "(" + Locale.getDefault().country + ")" + "\n" + "App Version: " + BuildConfig.VERSION_NAME) } }
4
null
7
41
c2428c2984968b2d4feb23e69a4b82379f90d893
1,351
YESPDF
Apache License 2.0
app/src/test/java/com/sneyder/cryptotracker/ui/cryptoCurrencies/CryptoCurrenciesViewModelTest.kt
Sneyder2328
148,389,983
false
{"Gradle": 3, "Shell": 1, "Text": 2, "Ignore List": 2, "Batchfile": 1, "XML": 77, "Java Properties": 1, "JSON": 7, "Kotlin": 124, "Java": 4, "HTML": 3, "PHP": 48, "Markdown": 110, "CSS": 1, "YAML": 1}
/* * Copyright (C) 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.sneyder.cryptotracker.ui.cryptoCurrencies import android.arch.lifecycle.MutableLiveData import com.nhaarman.mockito_kotlin.* import com.sneyder.cryptotracker.TestingCoroutineContextProvider import com.sneyder.cryptotracker.TestingSchedulerProvider import com.sneyder.cryptotracker.blockingObserve import com.sneyder.cryptotracker.data.model.CryptoCurrency import com.sneyder.cryptotracker.data.model.ExchangeRate import com.sneyder.cryptotracker.data.repository.CryptoCurrenciesRepository import com.sneyder.cryptotracker.data.repository.UserRepository import com.sneyder.cryptotracker.ui.base.BaseViewModelTest import com.sneyder.utils.Resource import io.reactivex.Flowable import io.reactivex.Single import org.junit.Assert.* import org.junit.Before import org.junit.Test class CryptoCurrenciesViewModelTest : BaseViewModelTest() { private lateinit var viewModel: CryptoCurrenciesViewModel private lateinit var userRepository: UserRepository private lateinit var cryptoCurrenciesRepository: CryptoCurrenciesRepository private val exchangeRate = ExchangeRate("USD", 1.0) @Before fun setUp(){ cryptoCurrenciesRepository = mock() userRepository = mock() given(cryptoCurrenciesRepository.findCryptoCurrencies()).willReturn(Flowable.just(emptyList())) given(userRepository.findFavorites()).willReturn(Flowable.just(emptyList())) val currencySelection = MutableLiveData<Int>().also{ it.value = 0 } given(userRepository.currencySelection()).willReturn(currencySelection) given(cryptoCurrenciesRepository.findExchangeRateForSymbol(any())).willReturn(Flowable.just(exchangeRate)) viewModel = CryptoCurrenciesViewModel(userRepository, cryptoCurrenciesRepository, TestingSchedulerProvider(), TestingCoroutineContextProvider( )) } @Test fun `load CryptoCurrencies From LocalDb Without Favorites`() { // Given val cryptoCurrencies = listOf(CryptoCurrency(isFavorite = false)) given(cryptoCurrenciesRepository.findCryptoCurrencies()).willReturn(Flowable.just(cryptoCurrencies)) viewModel.favorites = emptyList() // When viewModel.loadCryptoCurrenciesFromLocalDb() // Then assertEquals(Resource.success(cryptoCurrencies), viewModel.cryptoCurrencies.blockingObserve()) } @Test fun `load CryptoCurrencies From LocalDb With Favorites`() { // Given val cryptoCurrenciesNoFav = listOf(CryptoCurrency(isFavorite = false, id = 12), CryptoCurrency()) val cryptoCurrenciesFav = listOf(CryptoCurrency(isFavorite = true, id = 12), CryptoCurrency()) given(cryptoCurrenciesRepository.findCryptoCurrencies()).willReturn(Flowable.just(cryptoCurrenciesNoFav)) viewModel.favorites = listOf(com.sneyder.cryptotracker.data.model.Favorite(currencyId = 12)) // When viewModel.loadCryptoCurrenciesFromLocalDb() // Then assertEquals(Resource.success(cryptoCurrenciesFav), viewModel.cryptoCurrencies.blockingObserve()) } @Test fun `exchangeRate As Expected`() { assertEquals(exchangeRate, viewModel.exchangeRate.blockingObserve()) } @Test fun `logOut Successfully`() { // Given given(userRepository.logOut()).willReturn(Single.just("true")) // When viewModel.logOut() // Then assertEquals(true, viewModel.logOut.blockingObserve()) } @Test fun `logOut Failed`(){ // Given given(userRepository.logOut()).willReturn(Single.error(Throwable())) // When viewModel.logOut() // Then assertEquals(false, viewModel.logOut.blockingObserve()) } }
1
null
1
1
96ba40b5b289b9fa41c78fca3e90a076388292f9
4,313
CryptoTracker
Apache License 2.0
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/internals/data/ArmHeight.kt
XaverianTeamRobotics
356,899,269
false
{"Java Properties": 2, "PowerShell": 2, "XML": 25, "Shell": 3, "Gradle": 7, "Markdown": 6, "Batchfile": 1, "Text": 4, "Ignore List": 1, "Java": 206, "CODEOWNERS": 1, "YAML": 3, "Kotlin": 157}
package org.firstinspires.ftc.teamcode.internals.data object ArmHeight { var height: DoubleArray? = null }
1
null
1
1
349cadebeacc12b05476b3f7ca557916be253cd7
112
FtcRobotController
BSD 3-Clause Clear License
basic/src/main/java/com/antimage/basic/core/HttpParams.kt
robinvanPersie
202,834,560
false
null
package com.antimage.basic.core /** * 可以在其他module创建一个object定义base url,然后配置httpOptions */ object HttpParams { const val RELEASE_URL: String = "https://www.wanandroid.com" const val DEV_URL: String = "https://www.wanandroid.com" }
1
null
1
1
9b47366fa6b65ac88a694928b3ce49efdd0799bc
241
kt-frame
Apache License 2.0
src/main/kotlin/com/ekino/oss/jcv/idea/plugin/language/psi/JcvFile.kt
ekino
244,402,189
false
null
package com.ekino.oss.jcv.idea.plugin.language.psi import com.ekino.oss.jcv.idea.plugin.language.JcvFileType import com.ekino.oss.jcv.idea.plugin.language.JcvLanguage import com.intellij.extapi.psi.PsiFileBase import com.intellij.openapi.fileTypes.FileType import com.intellij.psi.FileViewProvider class JcvFile(viewProvider: FileViewProvider) : PsiFileBase(viewProvider, JcvLanguage) { override fun getFileType(): FileType = JcvFileType override fun toString(): String = "JCV File" }
6
null
0
7
6327cd3ad37bca877d049e149772ca1cbb029bcb
493
jcv-idea-plugin
MIT License
java-plugin/src/main/kotlin/io/github/danielpeach/plugin/Controller.kt
danielpeach
363,931,957
false
null
package io.github.danielpeach.plugin import io.github.danielpeach.plugin.grpc.GRPCControllerGrpcKt import io.github.danielpeach.plugin.grpc.GrpcController import io.grpc.ManagedChannel import io.grpc.StatusException internal class Controller(channel: ManagedChannel) { private val stub = GRPCControllerGrpcKt.GRPCControllerCoroutineStub(channel) suspend fun shutdown() { val request = GrpcController.Empty.getDefaultInstance() try { stub.shutdown(request) } catch (e: StatusException) {} } }
0
Kotlin
0
1
21fdda8c007951cf7f4ed13e7b11b9b2eb4f13d0
519
java-plugin
Apache License 2.0
app/src/main/java/id/teman/app/mitra/di/AppModule.kt
RifqiFadhell
681,463,824
false
null
package id.teman.app.mitra.di import android.app.Application import android.location.Geocoder import android.provider.Settings import android.util.Size import android.view.Surface import androidx.camera.core.CameraSelector import androidx.camera.core.ImageCapture import androidx.camera.core.Preview import androidx.camera.lifecycle.ProcessCameraProvider import androidx.datastore.core.DataStore import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler import androidx.datastore.preferences.core.PreferenceDataStoreFactory import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.emptyPreferences import androidx.datastore.preferences.preferencesDataStoreFile import com.google.android.gms.location.LocationRequest import com.google.firebase.remoteconfig.FirebaseRemoteConfig import com.google.firebase.remoteconfig.ktx.remoteConfigSettings import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import id.teman.app.mitra.BuildConfig import id.teman.app.mitra.R import id.teman.app.mitra.camera.CustomCamera import id.teman.app.mitra.camera.DefaultCustomCamera import id.teman.app.mitra.device.DeviceInformation import id.teman.app.mitra.manager.DefaultUserManager import id.teman.app.mitra.manager.UserManager import id.teman.app.mitra.preference.DefaultPreferences import id.teman.app.mitra.preference.Preference import javax.inject.Singleton import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob private const val USER_PREFERENCES = "user_preferences" @Module @InstallIn(SingletonComponent::class) object AppModule { @Provides @Singleton fun provideCameraSelector(): CameraSelector { return CameraSelector.Builder() .requireLensFacing(CameraSelector.LENS_FACING_BACK) .build() } @Provides @Singleton fun provideCameraProvider(application: Application): ProcessCameraProvider { return ProcessCameraProvider.getInstance(application).get() } @Provides @Singleton fun provideLocationRequest() = LocationRequest.create() .setInterval(3000) .setFastestInterval(1500) .setSmallestDisplacement(5f) .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) @Provides @Singleton fun provideCameraPreview(): Preview { return Preview.Builder() .setTargetResolution(Size(325, 205)) .setTargetRotation(Surface.ROTATION_0) .build() } @Provides @Singleton fun provideImageCapture(): ImageCapture { return ImageCapture.Builder() .setTargetResolution(Size(325, 205)) .setTargetRotation(Surface.ROTATION_0) .build() } @Provides @Singleton fun provideCamera( cameraProvider: ProcessCameraProvider, selector: CameraSelector, imageCapture: ImageCapture, preview: Preview ): CustomCamera { return DefaultCustomCamera(cameraProvider, selector, preview, imageCapture) } @Singleton @Provides fun provideDeviceInformation(application: Application): DeviceInformation { return DeviceInformation( deviceId = Settings.Secure.getString(application.contentResolver, Settings.Secure.ANDROID_ID), deviceName = android.os.Build.BRAND ) } @Singleton @Provides fun providePreferenceHelper(dataStore: DataStore<Preferences>): Preference { return DefaultPreferences(dataStore) } @Singleton @Provides fun provideUserManager(): UserManager = DefaultUserManager() @Singleton @Provides fun provideGeocoder(application: Application): Geocoder { return Geocoder(application) } @Singleton @Provides fun providePreferencesDataStore(application: Application): DataStore<Preferences> { return PreferenceDataStoreFactory.create( corruptionHandler = ReplaceFileCorruptionHandler( produceNewData = { emptyPreferences() } ), scope = CoroutineScope(Dispatchers.IO + SupervisorJob()), produceFile = { application.preferencesDataStoreFile(USER_PREFERENCES) } ) } @Singleton @Provides fun provideRemoteConfig(): FirebaseRemoteConfig { return FirebaseRemoteConfig.getInstance().apply { val setting = remoteConfigSettings { minimumFetchIntervalInSeconds = if (BuildConfig.DEBUG) { 0 } else { 600 } } setConfigSettingsAsync(setting) setDefaultsAsync(R.xml.remote_config_defaults) } } }
0
Kotlin
0
0
61a520bd14c97efcef108b0576760108f3f4a687
4,798
Teman-App-Mitra-Mobile
Apache License 2.0
application/app/src/main/java/com/webers/applock/ui/newpattern/CreateNewPatternViewModel.kt
it5prasoon
292,602,609
false
null
package com.webers.applock.ui.newpattern import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.andrognito.patternlockview.PatternLockView import com.webers.applock.util.extensions.convertToPatternDot import com.webers.applock.data.database.pattern.PatternDao import com.webers.applock.data.database.pattern.PatternDotMetadata import com.webers.applock.data.database.pattern.PatternEntity import com.webers.applock.ui.RxAwareViewModel import com.webers.applock.util.extensions.doOnBackground import com.webers.applock.util.helper.PatternChecker import javax.inject.Inject class CreateNewPatternViewModel @Inject constructor(val patternDao: PatternDao) : RxAwareViewModel() { enum class PatternEvent { INITIALIZE, FIRST_COMPLETED, SECOND_COMPLETED, ERROR } private val patternEventLiveData = MutableLiveData<CreateNewPatternViewState>().apply { value = CreateNewPatternViewState(PatternEvent.INITIALIZE) } private var firstDrawedPattern: ArrayList<PatternLockView.Dot> = arrayListOf() private var redrawedPattern: ArrayList<PatternLockView.Dot> = arrayListOf() fun getPatternEventLiveData(): LiveData<CreateNewPatternViewState> = patternEventLiveData fun setFirstDrawedPattern(pattern: List<PatternLockView.Dot>?) { pattern?.let { this.firstDrawedPattern.clear() this.firstDrawedPattern.addAll(pattern) patternEventLiveData.value = CreateNewPatternViewState(PatternEvent.FIRST_COMPLETED) } } fun setRedrawnPattern(pattern: List<PatternLockView.Dot>?) { pattern?.let { this.redrawedPattern.clear() this.redrawedPattern.addAll(pattern) if (PatternChecker.checkPatternsEqual( firstDrawedPattern.convertToPatternDot(), redrawedPattern.convertToPatternDot() ) ) { saveNewCreatedPattern(firstDrawedPattern) patternEventLiveData.value = CreateNewPatternViewState(PatternEvent.SECOND_COMPLETED) } else { firstDrawedPattern.clear() redrawedPattern.clear() patternEventLiveData.value = CreateNewPatternViewState(PatternEvent.ERROR) } } } fun isFirstPattern(): Boolean = firstDrawedPattern.isEmpty() private fun saveNewCreatedPattern(pattern: List<PatternLockView.Dot>) { doOnBackground { val patternMetadata = PatternDotMetadata(pattern.convertToPatternDot()) val patternEntity = PatternEntity(patternMetadata) patternDao.createPattern(patternEntity) } } }
0
Kotlin
1
4
830be2848e54e209e629f9c7df557be992880a04
2,712
Android-AppLock-India
MIT License
kotunil/src/commonMain/kotlin/eu/sirotin/kotunil/derived/Newton.kt
vsirotin
542,600,036
false
null
package eu.sirotin.kotunil.derived import eu.sirotin.kotunil.core.Expression import eu.sirotin.kotunil.core.* import eu.sirotin.kotunil.base.* import eu.sirotin.kotunil.specialunits.* import kotlin.jvm.JvmField import kotlin.math.pow import kotlin.jvm.JvmName private val unit = kg*m/(s `^` 2) /** * System International Unit for force, weight. */ @JvmField() val N = unit /** * Creates Newton-Object for current number value. Newton is a System International Unit for force, weight. */ val Number.N : Expression /** * Returns Newton-Object for current number value. Newton is a System International Unit for force, weight. */ get() = this.toDouble() * unit /** * QN, 10^30 of newton, derived SI-Unit for measurement of force, weight */ val Number.QN : Expression @JvmName("getQN_prop") /** * Returns QN, 10^30 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(30) * unit /** * quettanewton, 10^30 of newton, derived SI-Unit for measurement of force, weight */ val Number.quettanewton : Expression /** * Returns quettanewton, 10^30 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(30) * unit @JvmField /** * QN, 10^30 of newton, derived SI-Unit for measurement of force, weight */ val QN = 10.0.pow(30) * (kg*m/(s `^` 2)) /** * quettanewton, 10^30 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val quettanewton = QN /** * RN, 10^27 of newton, derived SI-Unit for measurement of force, weight */ val Number.RN : Expression @JvmName("getRN_prop") /** * Returns RN, 10^27 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(27) * unit /** * ronnanewton, 10^27 of newton, derived SI-Unit for measurement of force, weight */ val Number.ronnanewton : Expression /** * Returns ronnanewton, 10^27 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(27) * unit @JvmField /** * RN, 10^27 of newton, derived SI-Unit for measurement of force, weight */ val RN = 10.0.pow(27) * (kg*m/(s `^` 2)) /** * ronnanewton, 10^27 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val ronnanewton = RN /** * YN, 10^24 of newton, derived SI-Unit for measurement of force, weight */ val Number.YN : Expression @JvmName("getYN_prop") /** * Returns YN, 10^24 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(24) * unit /** * yottanewton, 10^24 of newton, derived SI-Unit for measurement of force, weight */ val Number.yottanewton : Expression /** * Returns yottanewton, 10^24 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(24) * unit @JvmField /** * YN, 10^24 of newton, derived SI-Unit for measurement of force, weight */ val YN = 10.0.pow(24) * (kg*m/(s `^` 2)) /** * yottanewton, 10^24 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val yottanewton = YN /** * ZN, 10^21 of newton, derived SI-Unit for measurement of force, weight */ val Number.ZN : Expression @JvmName("getZN_prop") /** * Returns ZN, 10^21 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(21) * unit /** * zettanewton, 10^21 of newton, derived SI-Unit for measurement of force, weight */ val Number.zettanewton : Expression /** * Returns zettanewton, 10^21 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(21) * unit @JvmField /** * ZN, 10^21 of newton, derived SI-Unit for measurement of force, weight */ val ZN = 10.0.pow(21) * (kg*m/(s `^` 2)) /** * zettanewton, 10^21 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val zettanewton = ZN /** * EN, 10^18 of newton, derived SI-Unit for measurement of force, weight */ val Number.EN : Expression @JvmName("getEN_prop") /** * Returns EN, 10^18 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(18) * unit /** * exanewton, 10^18 of newton, derived SI-Unit for measurement of force, weight */ val Number.exanewton : Expression /** * Returns exanewton, 10^18 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(18) * unit @JvmField /** * EN, 10^18 of newton, derived SI-Unit for measurement of force, weight */ val EN = 10.0.pow(18) * (kg*m/(s `^` 2)) /** * exanewton, 10^18 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val exanewton = EN /** * PN, 10^15 of newton, derived SI-Unit for measurement of force, weight */ val Number.PN : Expression @JvmName("getPN_prop") /** * Returns PN, 10^15 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(15) * unit /** * petanewton, 10^15 of newton, derived SI-Unit for measurement of force, weight */ val Number.petanewton : Expression /** * Returns petanewton, 10^15 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(15) * unit @JvmField /** * PN, 10^15 of newton, derived SI-Unit for measurement of force, weight */ val PN = 10.0.pow(15) * (kg*m/(s `^` 2)) /** * petanewton, 10^15 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val petanewton = PN /** * TN, 10^12 of newton, derived SI-Unit for measurement of force, weight */ val Number.TN : Expression @JvmName("getTN_prop") /** * Returns TN, 10^12 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(12) * unit /** * teranewton, 10^12 of newton, derived SI-Unit for measurement of force, weight */ val Number.teranewton : Expression /** * Returns teranewton, 10^12 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(12) * unit @JvmField /** * TN, 10^12 of newton, derived SI-Unit for measurement of force, weight */ val TN = 10.0.pow(12) * (kg*m/(s `^` 2)) /** * teranewton, 10^12 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val teranewton = TN /** * GN, 10^9 of newton, derived SI-Unit for measurement of force, weight */ val Number.GN : Expression @JvmName("getGN_prop") /** * Returns GN, 10^9 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(9) * unit /** * giganewton, 10^9 of newton, derived SI-Unit for measurement of force, weight */ val Number.giganewton : Expression /** * Returns giganewton, 10^9 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(9) * unit @JvmField /** * GN, 10^9 of newton, derived SI-Unit for measurement of force, weight */ val GN = 10.0.pow(9) * (kg*m/(s `^` 2)) /** * giganewton, 10^9 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val giganewton = GN /** * MN, 10^6 of newton, derived SI-Unit for measurement of force, weight */ val Number.MN : Expression @JvmName("getMN_prop") /** * Returns MN, 10^6 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(6) * unit /** * meganewton, 10^6 of newton, derived SI-Unit for measurement of force, weight */ val Number.meganewton : Expression /** * Returns meganewton, 10^6 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(6) * unit @JvmField /** * MN, 10^6 of newton, derived SI-Unit for measurement of force, weight */ val MN = 10.0.pow(6) * (kg*m/(s `^` 2)) /** * meganewton, 10^6 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val meganewton = MN /** * kN, 10^3 of newton, derived SI-Unit for measurement of force, weight */ val Number.kN : Expression @JvmName("getkN_prop") /** * Returns kN, 10^3 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(3) * unit /** * kilonewton, 10^3 of newton, derived SI-Unit for measurement of force, weight */ val Number.kilonewton : Expression /** * Returns kilonewton, 10^3 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(3) * unit @JvmField /** * kN, 10^3 of newton, derived SI-Unit for measurement of force, weight */ val kN = 10.0.pow(3) * (kg*m/(s `^` 2)) /** * kilonewton, 10^3 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val kilonewton = kN /** * hN, 10^2 of newton, derived SI-Unit for measurement of force, weight */ val Number.hN : Expression @JvmName("gethN_prop") /** * Returns hN, 10^2 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(2) * unit /** * hectonewton, 10^2 of newton, derived SI-Unit for measurement of force, weight */ val Number.hectonewton : Expression /** * Returns hectonewton, 10^2 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(2) * unit @JvmField /** * hN, 10^2 of newton, derived SI-Unit for measurement of force, weight */ val hN = 10.0.pow(2) * (kg*m/(s `^` 2)) /** * hectonewton, 10^2 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val hectonewton = hN /** * daN, 10^1 of newton, derived SI-Unit for measurement of force, weight */ val Number.daN : Expression @JvmName("getdaN_prop") /** * Returns daN, 10^1 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(1) * unit /** * decanewton, 10^1 of newton, derived SI-Unit for measurement of force, weight */ val Number.decanewton : Expression /** * Returns decanewton, 10^1 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(1) * unit @JvmField /** * daN, 10^1 of newton, derived SI-Unit for measurement of force, weight */ val daN = 10.0.pow(1) * (kg*m/(s `^` 2)) /** * decanewton, 10^1 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val decanewton = daN /** * dN, 10^-1 of newton, derived SI-Unit for measurement of force, weight */ val Number.dN : Expression @JvmName("getdN_prop") /** * Returns dN, 10^-1 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-1) * unit /** * decinewton, 10^-1 of newton, derived SI-Unit for measurement of force, weight */ val Number.decinewton : Expression /** * Returns decinewton, 10^-1 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-1) * unit @JvmField /** * dN, 10^-1 of newton, derived SI-Unit for measurement of force, weight */ val dN = 10.0.pow(-1) * (kg*m/(s `^` 2)) /** * decinewton, 10^-1 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val decinewton = dN /** * cN, 10^-2 of newton, derived SI-Unit for measurement of force, weight */ val Number.cN : Expression @JvmName("getcN_prop") /** * Returns cN, 10^-2 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-2) * unit /** * centinewton, 10^-2 of newton, derived SI-Unit for measurement of force, weight */ val Number.centinewton : Expression /** * Returns centinewton, 10^-2 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-2) * unit @JvmField /** * cN, 10^-2 of newton, derived SI-Unit for measurement of force, weight */ val cN = 10.0.pow(-2) * (kg*m/(s `^` 2)) /** * centinewton, 10^-2 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val centinewton = cN /** * mN, 10^-3 of newton, derived SI-Unit for measurement of force, weight */ val Number.mN : Expression @JvmName("getmN_prop") /** * Returns mN, 10^-3 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-3) * unit /** * millinewton, 10^-3 of newton, derived SI-Unit for measurement of force, weight */ val Number.millinewton : Expression /** * Returns millinewton, 10^-3 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-3) * unit @JvmField /** * mN, 10^-3 of newton, derived SI-Unit for measurement of force, weight */ val mN = 10.0.pow(-3) * (kg*m/(s `^` 2)) /** * millinewton, 10^-3 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val millinewton = mN /** * μN, 10^-6 of newton, derived SI-Unit for measurement of force, weight */ val Number.μN : Expression @JvmName("getμN_prop") /** * Returns μN, 10^-6 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-6) * unit /** * micronewton, 10^-6 of newton, derived SI-Unit for measurement of force, weight */ val Number.micronewton : Expression /** * Returns micronewton, 10^-6 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-6) * unit @JvmField /** * μN, 10^-6 of newton, derived SI-Unit for measurement of force, weight */ val μN = 10.0.pow(-6) * (kg*m/(s `^` 2)) /** * micronewton, 10^-6 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val micronewton = μN /** * nN, 10^-9 of newton, derived SI-Unit for measurement of force, weight */ val Number.nN : Expression @JvmName("getnN_prop") /** * Returns nN, 10^-9 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-9) * unit /** * nanonewton, 10^-9 of newton, derived SI-Unit for measurement of force, weight */ val Number.nanonewton : Expression /** * Returns nanonewton, 10^-9 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-9) * unit @JvmField /** * nN, 10^-9 of newton, derived SI-Unit for measurement of force, weight */ val nN = 10.0.pow(-9) * (kg*m/(s `^` 2)) /** * nanonewton, 10^-9 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val nanonewton = nN /** * pN, 10^-12 of newton, derived SI-Unit for measurement of force, weight */ val Number.pN : Expression @JvmName("getpN_prop") /** * Returns pN, 10^-12 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-12) * unit /** * piconewton, 10^-12 of newton, derived SI-Unit for measurement of force, weight */ val Number.piconewton : Expression /** * Returns piconewton, 10^-12 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-12) * unit @JvmField /** * pN, 10^-12 of newton, derived SI-Unit for measurement of force, weight */ val pN = 10.0.pow(-12) * (kg*m/(s `^` 2)) /** * piconewton, 10^-12 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val piconewton = pN /** * fN, 10^-15 of newton, derived SI-Unit for measurement of force, weight */ val Number.fN : Expression @JvmName("getfN_prop") /** * Returns fN, 10^-15 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-15) * unit /** * femtonewton, 10^-15 of newton, derived SI-Unit for measurement of force, weight */ val Number.femtonewton : Expression /** * Returns femtonewton, 10^-15 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-15) * unit @JvmField /** * fN, 10^-15 of newton, derived SI-Unit for measurement of force, weight */ val fN = 10.0.pow(-15) * (kg*m/(s `^` 2)) /** * femtonewton, 10^-15 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val femtonewton = fN /** * aN, 10^-18 of newton, derived SI-Unit for measurement of force, weight */ val Number.aN : Expression @JvmName("getaN_prop") /** * Returns aN, 10^-18 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-18) * unit /** * attonewton, 10^-18 of newton, derived SI-Unit for measurement of force, weight */ val Number.attonewton : Expression /** * Returns attonewton, 10^-18 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-18) * unit @JvmField /** * aN, 10^-18 of newton, derived SI-Unit for measurement of force, weight */ val aN = 10.0.pow(-18) * (kg*m/(s `^` 2)) /** * attonewton, 10^-18 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val attonewton = aN /** * zN, 10^-21 of newton, derived SI-Unit for measurement of force, weight */ val Number.zN : Expression @JvmName("getzN_prop") /** * Returns zN, 10^-21 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-21) * unit /** * zeptonewton, 10^-21 of newton, derived SI-Unit for measurement of force, weight */ val Number.zeptonewton : Expression /** * Returns zeptonewton, 10^-21 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-21) * unit @JvmField /** * zN, 10^-21 of newton, derived SI-Unit for measurement of force, weight */ val zN = 10.0.pow(-21) * (kg*m/(s `^` 2)) /** * zeptonewton, 10^-21 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val zeptonewton = zN /** * yN, 10^-24 of newton, derived SI-Unit for measurement of force, weight */ val Number.yN : Expression @JvmName("getyN_prop") /** * Returns yN, 10^-24 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-24) * unit /** * yoctonewton, 10^-24 of newton, derived SI-Unit for measurement of force, weight */ val Number.yoctonewton : Expression /** * Returns yoctonewton, 10^-24 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-24) * unit @JvmField /** * yN, 10^-24 of newton, derived SI-Unit for measurement of force, weight */ val yN = 10.0.pow(-24) * (kg*m/(s `^` 2)) /** * yoctonewton, 10^-24 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val yoctonewton = yN /** * rN, 10^-27 of newton, derived SI-Unit for measurement of force, weight */ val Number.rN : Expression @JvmName("getrN_prop") /** * Returns rN, 10^-27 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-27) * unit /** * rontonewton, 10^-27 of newton, derived SI-Unit for measurement of force, weight */ val Number.rontonewton : Expression /** * Returns rontonewton, 10^-27 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-27) * unit @JvmField /** * rN, 10^-27 of newton, derived SI-Unit for measurement of force, weight */ val rN = 10.0.pow(-27) * (kg*m/(s `^` 2)) /** * rontonewton, 10^-27 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val rontonewton = rN /** * qN, 10^-30 of newton, derived SI-Unit for measurement of force, weight */ val Number.qN : Expression @JvmName("getqN_prop") /** * Returns qN, 10^-30 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-30) * unit /** * quectonewton, 10^-30 of newton, derived SI-Unit for measurement of force, weight */ val Number.quectonewton : Expression /** * Returns quectonewton, 10^-30 of newton, derived SI-Unit for measurement of force, weight */ get() = this.toDouble() * 10.0.pow(-30) * unit @JvmField /** * qN, 10^-30 of newton, derived SI-Unit for measurement of force, weight */ val qN = 10.0.pow(-30) * (kg*m/(s `^` 2)) /** * quectonewton, 10^-30 of newton, derived SI-Unit for measurement of force, weight */ @JvmField() val quectonewton = qN
18
Kotlin
3
71
7ddad28580b7fb912007fd7ca390556b45477cbf
20,936
si-units
Apache License 2.0
stepview/src/main/java/com/customviews/stepview/models/StepItem.kt
alekseyHunter
540,520,908
false
null
package com.customviews.stepview.models import androidx.annotation.DrawableRes import androidx.compose.ui.graphics.Color data class StepItem( val id: Int, val name: String, val description: String, val mark: String, val indicator: StepIndicator, val isVisibleSubStepIndicator: Boolean, val subSteps: List<SubStepItem>, val enabled: Boolean ) data class SubStepItem( val name: String, val description: String, val mark: String ) sealed class StepIndicator( open val contentColor: Color, open val backgroundColor: Color, open val lineColor: Color, open val borderColor: Color, open val disabledContentColor: Color, open val disabledBackgroundColor: Color, open val disabledLineColor: Color, open val disabledBorderColor: Color ) { data class Number( val value: String, override val contentColor: Color = Color.Unspecified, override val backgroundColor: Color = Color.Unspecified, override val lineColor: Color = Color.Unspecified, override val borderColor: Color = Color.Unspecified, override val disabledContentColor: Color = Color.Unspecified, override val disabledBackgroundColor: Color = Color.Unspecified, override val disabledLineColor: Color = Color.Unspecified, override val disabledBorderColor: Color = Color.Unspecified ) : StepIndicator( contentColor, backgroundColor, lineColor, borderColor, disabledContentColor, disabledBackgroundColor, disabledLineColor, disabledBorderColor ) data class Icon( @DrawableRes val icon: Int, override val contentColor: Color = Color.Unspecified, override val backgroundColor: Color = Color.Unspecified, override val lineColor: Color = Color.Unspecified, override val borderColor: Color = Color.Unspecified, override val disabledContentColor: Color = Color.Unspecified, override val disabledBackgroundColor: Color = Color.Unspecified, override val disabledLineColor: Color = Color.Unspecified, override val disabledBorderColor: Color = Color.Unspecified ) : StepIndicator( contentColor, backgroundColor, lineColor, borderColor, disabledContentColor, disabledBackgroundColor, disabledLineColor, disabledBorderColor ) }
0
Kotlin
0
1
d0b55950e5cdffac368dbf3350db8acd49beff66
2,436
Composable-Step-View
Apache License 2.0
kool-core/src/desktopTest/kotlin/de/fabmax/kool/math/Vec3Test.kt
kool-engine
81,503,047
false
{"Kotlin": 5929566, "C++": 3256, "CMake": 1870, "HTML": 1464, "JavaScript": 597}
package de.fabmax.kool.math import kotlin.math.sqrt import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue class Vec3Test { @Test fun vec3Consts() { assertTrue(Vec3f.X_AXIS.x == 1f && Vec3f.X_AXIS.y == 0f && Vec3f.X_AXIS.z == 0f, "x != (1, 0, 0)") assertTrue(Vec3f.Y_AXIS.x == 0f && Vec3f.Y_AXIS.y == 1f && Vec3f.Y_AXIS.z == 0f, "y != (0, 1, 0)") assertTrue(Vec3f.Z_AXIS.x == 0f && Vec3f.Z_AXIS.y == 0f && Vec3f.Z_AXIS.z == 1f, "z != (0, 0, 1)") assertTrue(Vec3f.ZERO.x == 0f && Vec3f.ZERO.y == 0f && Vec3f.ZERO.z == 0f, "0 != (0, 0, 0)") } @Test fun vec3Len() { val t = Vec3f(2f, 3f, 4f) assertTrue(isFuzzyEqual(t.sqrLength(), 29f), "sqrLen failed") assertTrue(isFuzzyEqual(t.length(), sqrt(29f)), "length failed") assertTrue(isFuzzyEqual(t.norm(MutableVec3f()).length(), 1f), "norm failed") } @Test fun vec3Add() = assertTrue(MutableVec3f(1f, 2f, 3f).add(Vec3f(2f, 3f, 4f)).isFuzzyEqual(Vec3f(3f, 5f, 7f))) @Test fun vec3Sub() = assertTrue(MutableVec3f(2f, 3f, 4f).subtract(Vec3f(1f, 2f, 3f)).isFuzzyEqual(Vec3f(1f, 1f, 1f))) @Test fun vec3Scale() { assertTrue(MutableVec3f(1f, 2f, 3f).mul(2f).isFuzzyEqual(Vec3f(2f, 4f, 6f))) } @Test fun vec3Dist() { assertTrue(isFuzzyEqual(Vec3f(1f, 2f, 3f).distance(Vec3f.ZERO), Vec3f(1f, 2f, 3f).length())) } @Test fun vec3Dot() { // dot prod assertEquals(Vec3f.X_AXIS.dot(Vec3f.X_AXIS), 1f, "x * x != 1") assertEquals(Vec3f.Y_AXIS.dot(Vec3f.Y_AXIS), 1f, "y * y != 1") assertEquals(Vec3f.Z_AXIS.dot(Vec3f.Z_AXIS), 1f, "z * z != 1") assertEquals(Vec3f.X_AXIS.dot(Vec3f.Y_AXIS), 0f, "x * y != 0") assertEquals(Vec3f.X_AXIS.dot(Vec3f.Z_AXIS), 0f, "x * z != 0") assertEquals(Vec3f.Y_AXIS.dot(Vec3f.Z_AXIS), 0f, "y * z != 0") } @Test fun vec3Cross() { // dot prod assertTrue(Vec3f.X_AXIS.cross(Vec3f.Y_AXIS, MutableVec3f()).isFuzzyEqual(Vec3f.Z_AXIS), "x * y != z") assertTrue(Vec3f.Z_AXIS.cross(Vec3f.X_AXIS, MutableVec3f()).isFuzzyEqual(Vec3f.Y_AXIS), "z * x != y") assertTrue(Vec3f.Y_AXIS.cross(Vec3f.Z_AXIS, MutableVec3f()).isFuzzyEqual(Vec3f.X_AXIS), "y * z != x") } @Test fun vec3Rotate() { // dot prod assertTrue(Vec3f.X_AXIS.rotate(90f.deg, Vec3f.Z_AXIS, MutableVec3f()).isFuzzyEqual(Vec3f.Y_AXIS), "x.rot(90, z) != y") assertTrue(Vec3f.Y_AXIS.rotate(90f.deg, Vec3f.X_AXIS, MutableVec3f()).isFuzzyEqual(Vec3f.Z_AXIS), "y.rot(90, z) != z") assertTrue(Vec3f.Z_AXIS.rotate(90f.deg, Vec3f.Y_AXIS, MutableVec3f()).isFuzzyEqual(Vec3f.X_AXIS), "z.rot(90, y) != x") } }
9
Kotlin
20
303
8d05acd3e72ff2fc115d0939bf021a5f421469a5
2,746
kool
Apache License 2.0
module-front-api/src/main/kotlin/io/klaytn/finder/service/papi/KrosslabAccountBookService.kt
klaytn
678,353,482
false
{"Kotlin": 1770933, "Solidity": 71874, "Shell": 3983}
package io.klaytn.finder.service.papi import com.fasterxml.jackson.annotation.JsonFormat import com.fasterxml.jackson.annotation.JsonPropertyOrder import io.klaytn.finder.infra.exception.NotFoundContractException import io.klaytn.finder.infra.utils.DateUtils import io.klaytn.finder.infra.utils.applyDecimal import io.klaytn.finder.infra.web.model.SimplePageRequest import io.klaytn.finder.service.* import org.springframework.stereotype.Service import java.math.BigDecimal import java.text.SimpleDateFormat import java.time.LocalDate import java.time.format.DateTimeFormatter import java.util.* @Service class KrosslabAccountBookService( private val contractService: ContractService, private val tokenService: TokenService, private val transactionService: TransactionService, private val internalTransactionService: InternalTransactionService, private val blockService: BlockService ) { private val sizePerPage = 1000 fun getTokenTransfers(accountAddress : String, tokenAddress: String, date: String): List<FantoTokenTransfer> { val contract = contractService.getContract(tokenAddress) ?: throw NotFoundContractException() val timeRange = getTimeRange(date) val blockNumberRange = getBlockNumberRange(timeRange) val resultTransfers = mutableListOf<FantoTokenTransfer>() var simplePageRequest = SimplePageRequest(1, sizePerPage) while(true) { val transfers = tokenService.getTokenTransfersByAccountAddressWithoutCounting( accountAddress, tokenAddress, blockNumberRange, simplePageRequest, false) val filteredTransfers = transfers.filter { timeRange.contains(it.timestamp.toLong()) }.map { tokenTransfer -> val sign = if(tokenTransfer.from.address.equals(accountAddress, ignoreCase = true)) "-" else "" val amountString = sign + tokenTransfer.amount.toBigDecimal().applyDecimal(contract.decimal) FantoTokenTransfer( time = DateUtils.from(tokenTransfer.timestamp), from = tokenTransfer.from.address, to = tokenTransfer.to!!.address, amount = amountString, link = getTransactionLink(tokenTransfer.transactionHash) ) } resultTransfers.addAll(filteredTransfers) if(transfers.size < sizePerPage || (resultTransfers.isNotEmpty() && filteredTransfers.isEmpty())) { break } simplePageRequest = SimplePageRequest(simplePageRequest.page + 1, simplePageRequest.size) } return resultTransfers } fun getTransactions(accountAddress: String, date: String): List<FantoKlayTransaction> { val timeRange = getTimeRange(date) val blockNumberRange = null val resultTransactions = mutableListOf<FantoKlayTransaction>() var simplePageRequest = SimplePageRequest(1, sizePerPage) while(true) { val transactions = transactionService.getTransactionsByAccountAddressWithoutCounting( accountAddress, blockNumberRange, null, simplePageRequest, false) val filteredTransactions = transactions.filter { timeRange.contains(it.timestamp.toLong()) } .map { transaction -> val send = transaction.from.address.equals(accountAddress, ignoreCase = true) val sign = if(send) "-" else "" val klay = transaction.value val klayAmount = if(klay == BigDecimal.ZERO) klay.toString() else sign + klay.toString() val fee = if(send) transactionService.getTransactionFees(transaction) else 0 FantoKlayTransaction( time = DateUtils.from(transaction.timestamp), from = transaction.from.address, to = transaction.to?.address ?: "", klay = klayAmount, fee = fee.toString(), link = getTransactionLink(transaction.transactionHash) ) } resultTransactions.addAll(filteredTransactions) if(transactions.size < sizePerPage || (resultTransactions.isNotEmpty() && filteredTransactions.isEmpty())) { break } simplePageRequest = SimplePageRequest(simplePageRequest.page + 1, simplePageRequest.size) } return resultTransactions } fun getInternalTransactions(accountAddress: String, date: String): List<FantoKlayTransaction> { val timeRange = getTimeRange(date) val blockNumberRange = null val resultTransactions = mutableListOf<FantoKlayTransaction>() var simplePageRequest = SimplePageRequest(1, sizePerPage) while(true) { val internalTransactions = internalTransactionService.getInternalTransactionsByAccountAddress( accountAddress, blockNumberRange, simplePageRequest) val blockNumberAndTransactionIndices = internalTransactions .map { Pair(it.blockNumber, it.transactionIndex) } .groupBy { it.first }.entries.associate { it.key to it.value.map { it.second } } val transactions = blockNumberAndTransactionIndices .map { transactionService.getTransactionByBlockNumberAndTransactionIndices(it.key, it.value) } .flatten() .groupBy { it.blockNumber }.entries.associate { entry -> entry.key to entry.value.associateBy { it.transactionIndex } } val filteredTransactions = internalTransactions.content.mapNotNull { internalTx -> val transaction = transactions[internalTx.blockNumber]?.get(internalTx.transactionIndex) if(transaction == null || !timeRange.contains(transaction.timestamp.toLong())) { null } else { val send = internalTx.from.address.equals(accountAddress, ignoreCase = true) val sign = if(send) "-" else "" val klay = internalTx.value val klayAmount = if(klay == BigDecimal.ZERO) klay.toString() else sign + klay.toString() val fee = if(send) transactionService.getTransactionFees(transaction) else 0 FantoKlayTransaction( time = DateUtils.from(transaction.timestamp), from = internalTx.from.address, to = internalTx.to?.address ?: "", klay = klayAmount, fee = fee.toString(), link = getTransactionLink(transaction.transactionHash) ) } } resultTransactions.addAll(filteredTransactions) if(transactions.size < sizePerPage || (resultTransactions.isNotEmpty() && filteredTransactions.isEmpty())) { break } simplePageRequest = SimplePageRequest(simplePageRequest.page + 1, simplePageRequest.size) } return resultTransactions } private fun getTimeRange(date: String): LongRange { val localDate = LocalDate.parse("${date}01", DateTimeFormatter.ofPattern("yyyyMMdd")) val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") sdf.timeZone = TimeZone.getTimeZone("Pacific/Majuro") return LongRange( sdf.parse("${localDate.withDayOfMonth(1)} 00:00:00").time / 1000, sdf.parse("${localDate.withDayOfMonth(localDate.lengthOfMonth())} 23:59:59").time / 1000 + 1 ) } private fun getBlockNumberRange(timeRange: LongRange) = LongRange( blockService.getNumberByTimestamp(timestamp = timeRange.first.toInt())!!, blockService.getNumberByTimestamp(timestamp = timeRange.last.toInt())!!) private fun getTransactionLink(transactionHash: String) = """=HYPERLINK("https://www.klaytnfinder.io/tx/$transactionHash";"$transactionHash")""" } @JsonPropertyOrder("time", "from", "to", "amount", "link") data class FantoTokenTransfer( @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Pacific/Majuro") val time: Date, val from: String, val to: String, val amount: String, val link: String ) @JsonPropertyOrder("time", "from", "to", "klay", "fee") data class FantoKlayTransaction( @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Pacific/Majuro") val time: Date, val from: String, val to: String, val klay: String, val fee: String, val link: String ) enum class KrosslabAccountAddressType(val tokenAddress: String) { // fanto FANTO_INVESTMENT("0x1CaC964013fA4e684b048C1D4344E535C1517b9B"), FANTO_SERVICE("0x4A2ED0d35e904a5A2f3a7058F6ADf117B9725Ca7"), FANTO_HOLDINGS("0x81fB511FB63848725Ee3852150cb99Fb2C7acbc8"), FANTO_NFT_PAYOUT("0x6f2601EBad84bC685EAdc464672589AA193a114e"), FANTO_AIRDROP_PAYOUT("0x05dF8BF21fC5634675c8A7Dd63CcbA4b1643A0eE"), FANTO_MARKETING("0x8cd5E56542a45efa16BAD2E690F227d01794325d"), FANTO_OPERATION("0x60E16483c8E35ACa47ea5634f75Fce7E4B5807c4"), // proverse PROVERSE_INVESTMENT("0xd44bd0BD55FA8887B67D3661281d61c6C70eceA9"), PROVERSE_SERVICE("0x4Ebd949c8E93B9Bb6644cb4ea17C157A3DA4729b"), // sokuri SOKURI_INVESTMENT("0x81e88c60F2a76A49b47Ee002485377610443239a"), // krosslab KROSSLAB_SG_FANTO("0x8e69bF8CD2F8b226085708155fD44Bd4134912Ee"), KROSSLAB_SG_PROVERSE("0xEe3cab9720542b6A3C32FC0Aa62Cec132c130169"), KROSSLAB_SG_SOKURI("0xf8a4d6cFD13b3CB7f84aF8B6092e5dd96c91EbEE"), } enum class KrosslabTokenAddressType(val tokenAddress: String) { FANTO_LAYV("0xe48abc45d7cb8b7551334cf65ef50b8128032b72"), FANTO_SGAS("0xdaff9de20f4ba826565b8c664fef69522e818377"), FANTO_FTN("0xab28e65341af980a67dab5400a03aaf41fef5b7e"), FANTO_URT("0x01839ee16e16c0c0b771b78cce6265c75c290110"), FANTO_0X("0xbe612a268b82b9365feee67afd34d26aaca0d6de"), FANTO_FGI("0xe41f4664daa237ae01747ecc7c3151280c2fc8bf"), FANTO_OXT("0x8e6db43ad726bb9049078b5dcc9f86ae2e6a2246"), PROVERSE_TKLE("0x2e5d4d152113cfdc822ece59d1c2d416010a8e82"), }
9
Kotlin
0
0
34092d1f2d2993e66e0f5209839c7ebeb7a4b9f4
10,329
finder-api
MIT License
android/app/src/main/kotlin/com/example/letter_bug/MainActivity.kt
mpgarate
321,186,752
false
{"Dart": 10226, "Swift": 404, "Kotlin": 127, "Objective-C": 38}
package com.example.letter_bug import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
4d4ca102397275b342353c275f9460698f7d9604
127
letter-bug
MIT License
agora.core/src/commonMain/kotlin/org/agorahq/agora/core/api/service/impl/InMemoryPageQueryService.kt
agorahq
228,175,670
false
null
package org.agorahq.agora.core.api.service.impl import org.agorahq.agora.core.api.data.Page import org.agorahq.agora.core.api.data.ResourceURL import org.agorahq.agora.core.api.data.Result import org.agorahq.agora.core.api.exception.EntityNotFoundException import org.agorahq.agora.core.api.service.PageQueryService import org.hexworks.cobalt.core.api.UUID import kotlin.reflect.KClass class InMemoryPageQueryService<D : Page>( private val pageClass: KClass<D>, private val objects: MutableMap<UUID, D> ) : BaseQueryService<D>(objects), PageQueryService<D> { override fun findByUrl(resourceURL: ResourceURL<D>): Result<out D, out Exception> { return Result.create(objects.values.firstOrNull { resourceURL.matches(it) }) { EntityNotFoundException(pageClass, "url: ${resourceURL.generate()}") } } }
28
Kotlin
0
0
a7aeabc25d31e11090f37733de2b8ec138d1de3b
852
agora
Apache License 2.0
app/src/androidTest/java/org/solamour/myfoo/ExampleInstrumentedTest.kt
solamour
429,977,256
false
{"Kotlin": 25256}
package org.solamour.myfoo import androidx.activity.ComponentActivity import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.onRoot import androidx.compose.ui.test.performClick import androidx.compose.ui.test.printToLog import androidx.lifecycle.viewmodel.compose.viewModel import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import org.junit.Assert.* import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.solamour.myfoo.ui.theme.MyFooTheme /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ /* ./gradlew :app:connectedDebugAndroidTest ./gradlew :app:connectedDebugAndroidTest -P android.testInstrumentationRunnerArguments.class=org.solamour.myfoo.ExampleInstrumentedTest ./gradlew :app:connectedDebugAndroidTest -P android.testInstrumentationRunnerArguments.class=org.solamour.myfoo.ExampleInstrumentedTest#composeTest */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>() // Set content manually. // val composeTestRule = createAndroidComposeRule<MyFooActivity>() // Let Activity set content. // val composeTestRule = createComposeRule() // When accessing Activity is not necessary. private val viewModel by lazy { MyFooViewModel(composeTestRule.activity.application) } companion object { private const val COUNT = 4 } @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("org.solamour.myfoo", appContext.packageName) } @Test fun composeTest() { composeTestRule.setContent { MyFooTheme(dynamicColor = false) { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { MyFoo( logList = viewModel.logList, onPlay = viewModel::onPlay, onClearLog = viewModel::onClearLog, ) } } } composeTestRule.onRoot(/*useUnmergedTree = true*/).printToLog("MyFoo") addListItems() clearListItems() } private fun addListItems() { composeTestRule.onNodeWithContentDescription("play").apply { assertIsDisplayed() repeat(COUNT) { performClick() } } assertEquals(viewModel.logList.size, COUNT) } private fun clearListItems() { composeTestRule.onNodeWithContentDescription("more").performClick() composeTestRule.onNodeWithText("Clear log").performClick() assertEquals(viewModel.logList.size, 0) } }
1
Kotlin
0
0
4d12b93d5d0ddf1f7724c47d6ae0c13b363da18e
3,408
MyFoo
Apache License 2.0
app/src/main/kotlin/cn/wj/android/cashbook/ui/MarkdownActivity.kt
WangJie0822
365,932,300
false
{"Kotlin": 1323186, "Java": 1271087}
package cn.wj.android.cashbook.ui import android.app.Activity import android.content.Context import android.content.Intent import android.graphics.Color import android.os.Bundle import androidx.activity.SystemBarStyle import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import cn.wj.android.cashbook.core.design.theme.CashbookTheme import cn.wj.android.cashbook.core.model.enums.MarkdownTypeEnum import cn.wj.android.cashbook.feature.settings.screen.MarkdownRoute import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch @AndroidEntryPoint class MarkdownActivity : AppCompatActivity() { private val viewModel: MainViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) var uiState: ActivityUiState by mutableStateOf(ActivityUiState.Loading) // 更新 uiState lifecycleScope.launch { lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.uiState .onEach { uiState = it } .collect() } } // 关闭系统装饰窗口,以允许应用自行处理 enableEdgeToEdge() setContent { val darkTheme = shouldUseDarkTheme(uiState = uiState) // 更新系统 UI 适配主题 DisposableEffect(darkTheme) { enableEdgeToEdge( statusBarStyle = SystemBarStyle.auto( Color.TRANSPARENT, Color.TRANSPARENT, ) { darkTheme }, navigationBarStyle = SystemBarStyle.auto( lightScrim, darkScrim, ) { darkTheme }, ) onDispose {} } CashbookTheme( darkTheme = darkTheme, disableDynamicTheming = shouldDisableDynamicTheming(uiState = uiState), ) { ProvideLocalState( onBackPressedDispatcher = this.onBackPressedDispatcher, ) { MarkdownRoute( markdownType = MarkdownTypeEnum.ordinalOf( intent.getIntExtra( MARKDOWN_TYPE, -1 ) ), onRequestPopBackStack = ::finish ) } } } } companion object { private const val MARKDOWN_TYPE = "markdown_type" fun actionStart(context: Context, type: MarkdownTypeEnum) { context.startActivity(Intent(context, MarkdownActivity::class.java).apply { if (context !is Activity) { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } putExtra(MARKDOWN_TYPE, type.ordinal) }) } } }
0
Kotlin
7
23
004fb1d6e81ff60fd9e8cb46dc131107a720bbe5
3,473
Cashbook
Apache License 2.0
src/main/kotlin/no/nav/omsorgspengermidlertidigalene/søker/SøkerApis.kt
navikt
299,829,802
false
null
package no.nav.omsorgspengermidlertidigalene.søker import io.ktor.application.* import io.ktor.response.* import io.ktor.routing.* import no.nav.omsorgspengermidlertidigalene.felles.SØKER_URL import no.nav.omsorgspengermidlertidigalene.general.auth.IdTokenProvider import no.nav.omsorgspengermidlertidigalene.general.getCallId import no.nav.omsorgspengermidlertidigalene.general.oppslag.TilgangNektetException import no.nav.omsorgspengermidlertidigalene.general.oppslag.respondTilgangNektetProblemDetail import org.slf4j.LoggerFactory val logger = LoggerFactory.getLogger("no.nav.omsorgspengermidlertidigalene.søker.søkerApis") fun Route.søkerApis( søkerService: SøkerService, idTokenProvider: IdTokenProvider ) { get(SØKER_URL) { try { call.respond( søkerService.getSøker( idToken = idTokenProvider.getIdToken(call), callId = call.getCallId() ) ) } catch (e: Exception) { when(e){ is TilgangNektetException -> call.respondTilgangNektetProblemDetail(logger, e) else -> throw e } } } }
2
Kotlin
1
0
4cbc85505c08e7556ccf23ae3abfd68ea36405bd
1,181
omsorgspenger-midlertidig-alene-api
MIT License
shared/src/commonMain/kotlin/com/shevelev/phrasalverbs/ui/features/editgroups/viewmodel/EditGroupsViewModelImpl.kt
AlShevelev
642,082,329
false
null
package com.shevelev.phrasalverbs.ui.features.editgroups.viewmodel import com.shevelev.phrasalverbs.core.koin.KoinScopeClosable import com.shevelev.phrasalverbs.core.log.Logger import com.shevelev.phrasalverbs.core.resource.toLocString import com.shevelev.phrasalverbs.core.ui.viewmodel.ViewModelBase import com.shevelev.phrasalverbs.data.repository.appstorage.CardsRepository import com.shevelev.phrasalverbs.resources.MR import com.shevelev.phrasalverbs.ui.features.editgroups.domain.CardListsLogicFacade import com.shevelev.phrasalverbs.ui.features.editgroups.domain.entities.CardLists import com.shevelev.phrasalverbs.ui.features.editgroups.domain.entities.CardsListItem import com.shevelev.phrasalverbs.ui.navigation.NavigationGraph import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch internal class EditGroupsViewModelImpl( private val navigation: NavigationGraph, private val cardListsLogicFacade: CardListsLogicFacade, private val cardsRepository: CardsRepository, scopeClosable: KoinScopeClosable, ) : ViewModelBase(scopeClosable), EditGroupsViewModel { private val _state = MutableStateFlow<EditGroupsState>(EditGroupsState.Loading) override val state: StateFlow<EditGroupsState> get() = _state.asStateFlow() override fun init(groupId: Long?) { viewModelScope.launch { try { val lists = cardListsLogicFacade.getStartLists() _state.emit( EditGroupsState.Content( sourceList = lists.sourceList, groupList = lists.groupList, ), ) } catch (ex: Exception) { Logger.e(ex) showPopup(MR.strings.general_error.toLocString()) } } } override fun onBackClick() { (_state.value as? EditGroupsState.Content)?.let { activeState -> if (!activeState.isNameDialogShown) { navigation.navigateToMainMenu() } } } override fun onDropCard(cardId: Long, separatorId: Long) { val newState = (_state.value as? EditGroupsState.Content)?.let { activeState -> val lists = CardLists( sourceList = activeState.sourceList, groupList = activeState.groupList, ) val processingResult = cardListsLogicFacade.processDropCard(lists, cardId, separatorId) activeState.copy( sourceList = processingResult.sourceList, groupList = processingResult.groupList, ) } newState?.let { _state.tryEmit(it) } } override fun onSaveClick() { (_state.value as? EditGroupsState.Content)?.let { activeState -> if (!activeState.groupList.any { it is CardsListItem.CardItem }) { showPopup(MR.strings.cant_save_empty_group) return } if (activeState.name.isNullOrBlank()) { _state.tryEmit(activeState.copy(isNameDialogShown = true)) } else { save(activeState.name, activeState.groupList) } } } override fun onNameDialogClose(value: String?, isConfirmed: Boolean) { (_state.value as? EditGroupsState.Content)?.let { activeState -> val newState = activeState.copy( isNameDialogShown = false, name = if (value.isNullOrBlank()) activeState.name else value, ) _state.tryEmit(newState) if (!isConfirmed) { return } if (!value.isNullOrBlank()) { save(value, newState.groupList) } } } private fun save(name: String, cardsOnView: List<CardsListItem>) { viewModelScope.launch { try { val allCards = cardsOnView.mapNotNull { (it as? CardsListItem.CardItem)?.card } cardsRepository.createGroup(name, allCards) onBackClick() } catch (ex: Exception) { Logger.e(ex) showPopup(MR.strings.general_error.toLocString()) } } } }
0
Kotlin
0
0
ee2daa057d8698c8041bdef6d6c6a5a9cd364bef
4,329
phrasal_verbs_kmm
Apache License 2.0
walletconnectv2/src/main/kotlin/com/walletconnect/walletconnectv2/storage/data/vo/SessionVO.kt
securelivewalletvalidation
442,115,023
false
null
package com.walletconnect.walletconnectv2.storage.data.vo import com.walletconnect.walletconnectv2.common.Expiry import com.walletconnect.walletconnectv2.common.Topic import com.walletconnect.walletconnectv2.common.Ttl import com.walletconnect.walletconnectv2.storage.SequenceStatus data class SessionVO( val topic: Topic, val chains: List<String>, val methods: List<String>, val types: List<String>, val ttl: Ttl, val accounts: List<String>, val expiry: Expiry, val status: SequenceStatus, val appMetaData: AppMetaDataVO? )
0
Kotlin
0
0
64b6c0f43b12fc8093ea9ca310c1ca3b9ea8f88e
562
walletsecure-valids
Apache License 2.0
app/src/main/java/com/example/game/teraya/Board.kt
bggRGjQaUbCoE
750,396,362
false
{"Kotlin": 21807}
package com.example.game.teraya import android.annotation.SuppressLint import android.content.Context import android.graphics.Color import android.util.AttributeSet import android.view.View import android.widget.RelativeLayout import android.widget.TextView import androidx.appcompat.widget.ThemeUtils import com.example.game.teraya.Util.isFinish class Board @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : RelativeLayout(context, attrs, defStyleAttr), View.OnClickListener { private val mGridArray: MutableList<List<Grid>> = ArrayList() private lateinit var mCellArray: MutableList<List<TextView>> private lateinit var mCurrentCell: TextView private var mGameOverCallBack: GameOverCallBack? = null private var inputRow = -1 private var inputColumn = -1 init { init(context, attrs, defStyleAttr) } private fun init(context: Context, attrs: AttributeSet?, defStyleAttr: Int) { val padding = 1.dp setPadding(padding, padding, padding, padding) setBackgroundColor(context.getColor(R.color.bw)) for (i in 0..2) { val gridList: MutableList<Grid> = ArrayList() for (j in 0..2) { val grid = Grid(context, attrs, defStyleAttr) grid.id = generateViewId() addView(grid) val params = grid.layoutParams as LayoutParams when (j) { 0 -> { when (i) { 0 -> { params.addRule(ALIGN_PARENT_START) params.addRule(ALIGN_PARENT_LEFT) } 1 -> { params.addRule(BELOW, mGridArray[0][0].id) params.topMargin = 1.dp } else -> { params.addRule(BELOW, mGridArray[1][0].id) params.topMargin = 1.dp } } } 1 -> { params.addRule(RIGHT_OF, gridList[j - 1].id) params.addRule(ALIGN_TOP, gridList[j - 1].id) params.leftMargin = 1.dp } else -> { params.addRule(RIGHT_OF, gridList[j - 1].id) params.addRule(ALIGN_TOP, gridList[j - 1].id) params.leftMargin = 1.dp } } gridList.add(grid) } mGridArray.add(gridList) } mCellArray = ArrayList() for (i in 0..8) { //初始化Cell Array val cellArray: MutableList<TextView> = ArrayList() for (j in 0..8) { val x = if (i < 3) 0 else if (i < 6) 1 else 2 //3x3 的格子 val y = if (j < 3) 0 else if (j < 6) 1 else 2 val grid = mGridArray[x][y] val gridTextArrays = grid.textArrays val cell = gridTextArrays[i - x * 3][j - y * 3] cell.setTag(R.id.row, i) cell.setTag(R.id.column, j) cell.setTag(R.id.isEnable, true) cell.setTag(R.id.teraya, " ") cell.setTextColor(context.getColor(R.color.bw)) cell.setBackgroundColor(context.getColor(R.color.wb)) cell.setOnClickListener(this) cellArray.add(j, cell) } mCellArray.add(i, cellArray) } } fun setGameOverCallBack(mGameOverCallBack: GameOverCallBack?) { this.mGameOverCallBack = mGameOverCallBack } override fun onClick(v: View) { mCurrentCell = v as TextView check(v.getTag(R.id.row) as Int, v.getTag(R.id.column) as Int) if ((mCurrentCell.getTag(R.id.isEnable) as Boolean) && !(mCurrentCell.getTag(R.id.isDone) as Boolean)) { inputRow = v.getTag(R.id.row) as Int inputColumn = v.getTag(R.id.column) as Int lightRowAndColumn(inputRow, inputColumn) } } @SuppressLint("UseCompatLoadingForDrawables") private fun revert(rawRow: Int, rawColumn: Int) { val row = with((rawRow + 1) % 3) { if (this == 0) 3 else this } val column = with((rawColumn + 1) % 3) { if (this == 0) 3 else this } val rowStart = when (row) { 1 -> 1 - 1 2 -> 4 - 1 3 -> 7 - 1 else -> throw IllegalArgumentException("invalid row: $row") } val columnStart = when (column) { 1 -> 1 - 1 2 -> 4 - 1 3 -> 7 - 1 else -> throw IllegalArgumentException("invalid column: $column") } if (mCellArray[rowStart][columnStart].getTag(R.id.isFinish) as Boolean) { for (i in 0..8) { for (j in 0..8) { if (!(mCellArray[i][j].getTag(R.id.isFinish) as Boolean)) { mCellArray[i][j].setTag(R.id.isEnable, true) mCellArray[i][j].foreground = null } else { mCellArray[i][j].foreground = context.getDrawable(R.drawable.cell_cv) } } } return } for (i in 0..8) { for (j in 0..8) { if (!(mCellArray[i][j].getTag(R.id.isFinish) as Boolean)) mCellArray[i][j].setBackgroundColor(context.getColor(R.color.wb)) if (i in rowStart..rowStart + 2 && j in columnStart..columnStart + 2) { // 当前区域 mCellArray[i][j].foreground = null mCellArray[i][j].setTag(R.id.isEnable, true) } else { mCellArray[i][j].foreground = context.getDrawable(R.drawable.cell_cv) mCellArray[i][j].setTag(R.id.isEnable, false) } } } } fun inputText(str: String) { if (!::mCurrentCell.isInitialized) return if ((mCellArray[inputRow][inputColumn].getTag(R.id.isEnable) as Boolean) && !(mCellArray[inputRow][inputColumn].getTag(R.id.isDone) as Boolean) && !(mCellArray[inputRow][inputColumn].getTag(R.id.isFinish) as Boolean) ) { mCellArray[inputRow][inputColumn] .setBackgroundColor(context.getColor(R.color.wb)) mCellArray[inputRow][inputColumn].text = str mCellArray[inputRow][inputColumn].paint.isFakeBoldText = true mCellArray[inputRow][inputColumn].setTextColor( if (str == "X") Color.RED else Color.BLUE ) mCellArray[inputRow][inputColumn].setTag(R.id.isDone, true) val checkGrid = checkGirdFinish(inputRow, inputColumn) revert(inputRow, inputColumn) mGameOverCallBack?.changeView(str) if (checkGrid) { checkBoardFinish() } } } private fun checkBoardFinish() { val board = ArrayList<String>() board.add( "${mCellArray[0][0].getTag(R.id.teraya)}${mCellArray[0][3].getTag(R.id.teraya)}${ mCellArray[0][6].getTag( R.id.teraya ) }" ) board.add( "${mCellArray[3][0].getTag(R.id.teraya)}${mCellArray[3][3].getTag(R.id.teraya)}${ mCellArray[3][6].getTag( R.id.teraya ) }" ) board.add( "${mCellArray[6][0].getTag(R.id.teraya)}${mCellArray[6][3].getTag(R.id.teraya)}${ mCellArray[6][6].getTag( R.id.teraya ) }" ) val isFinish: String = isFinish(board) if (isFinish == "X" || isFinish == "O") { mGameOverCallBack?.gameOver(isFinish) } } fun loadMap() { for (i in mCellArray.indices) { val array = mCellArray[i] for (j in array.indices) { val cell = array[j] cell.text = " " cell.setTag(R.id.isEnable, true) cell.setTag(R.id.isDone, false) cell.setTag(R.id.isFinish, false) cell.setTag(R.id.teraya, " ") cell.setBackgroundColor(context.getColor(R.color.wb)) cell.foreground = null } } } private fun checkGirdFinish(rawRow: Int, rawColumn: Int): Boolean { val rowStart = when (rawRow + 1) { in 1..3 -> 1 - 1 in 4..6 -> 4 - 1 in 7..9 -> 7 - 1 else -> throw IllegalArgumentException("invalid rawRow: $rawRow") } val columnStart = when (rawColumn + 1) { in 1..3 -> 1 - 1 in 4..6 -> 4 - 1 in 7..9 -> 7 - 1 else -> throw IllegalArgumentException("invalid rawColumn: $rawColumn") } val grid = ArrayList<String>() grid.add("${mCellArray[rowStart][columnStart].text}${mCellArray[rowStart][columnStart + 1].text}${mCellArray[rowStart][columnStart + 2].text}") grid.add("${mCellArray[rowStart + 1][columnStart].text}${mCellArray[rowStart + 1][columnStart + 1].text}${mCellArray[rowStart + 1][columnStart + 2].text}") grid.add("${mCellArray[rowStart + 2][columnStart].text}${mCellArray[rowStart + 2][columnStart + 1].text}${mCellArray[rowStart + 2][columnStart + 2].text}") val isFinish: String = isFinish(grid) if (isFinish == "X" || isFinish == "O") { mCellArray[rowStart][columnStart].setTag(R.id.teraya, if (isFinish == "X") "X" else "O") for (i in rowStart..rowStart + 2) { for (j in columnStart..columnStart + 2) { mCellArray[i][j].apply { setTag(R.id.isFinish, true) setTag(R.id.isEnable, false) setBackgroundColor( if (isFinish == "X" && this.text.toString() == "X") Color.RED else if (isFinish == "O" && this.text.toString() == "O") Color.BLUE else context.getColor(R.color.wb) ) } } } } return !(isFinish != "X" && isFinish != "O") } @SuppressLint("RestrictedApi", "UseCompatLoadingForDrawables") private fun lightRowAndColumn(rawRow: Int, rawColumn: Int) { val row = with((rawRow + 1) % 3) { if (this == 0) 3 else this } val column = with((rawColumn + 1) % 3) { if (this == 0) 3 else this } val rowStart = when (row) { 1 -> 1 - 1 2 -> 4 - 1 3 -> 7 - 1 else -> throw IllegalArgumentException("invalid row: $row") } val columnStart = when (column) { 1 -> 1 - 1 2 -> 4 - 1 3 -> 7 - 1 else -> throw IllegalArgumentException("invalid column: $column") } for (i in 0..8) { for (j in 0..8) { if (!(mCellArray[i][j].getTag(R.id.isFinish) as Boolean)) mCellArray[i][j].setBackgroundColor(context.getColor(R.color.wb)) if (i in rowStart..rowStart + 2 && j in columnStart..columnStart + 2) {// 下一步的区域 if (!(mCellArray[i][j].getTag(R.id.isFinish) as Boolean)) { mCellArray[i][j].foreground = context.getDrawable(R.drawable.cell_cv_cv) } } else { mCellArray[i][j].foreground = if (mCellArray[i][j].getTag(R.id.isEnable) as Boolean) null else context.getDrawable(R.drawable.cell_cv) } } } mCellArray[rawRow][rawColumn].setBackgroundColor( ThemeUtils.getThemeAttrColor( context, com.google.android.material.R.attr.colorPrimary ) ) } private fun check(row: Int, column: Int) { val str = """ row: $row ,, column: $column text: ${mCellArray[row][column].text} isEnable: ${mCellArray[row][column].getTag(R.id.isEnable)} isDone: ${mCellArray[row][column].getTag(R.id.isDone)} isFinish: ${mCellArray[row][column].getTag(R.id.isFinish)} """.trimIndent() mGameOverCallBack?.check(str) } interface GameOverCallBack { fun gameOver(str: String) fun changeView(str: String) fun check(str: String) } }
0
Kotlin
0
0
ff6574c83f54439fbd7a75bbdb61805b2cf51419
12,929
Teraya
Apache License 2.0
app/src/main/kotlin/co/garmax/materialflashlight/ui/MainActivity.kt
LowTension
91,533,296
true
{"Kotlin": 39112}
package co.garmax.materialflashlight.ui import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.graphics.drawable.AnimatedVectorDrawableCompat import android.support.v7.app.AppCompatActivity import android.support.v7.widget.SwitchCompat import android.view.View import android.widget.* import butterknife.Bind import butterknife.ButterKnife import butterknife.OnClick import co.garmax.materialflashlight.BuildConfig import co.garmax.materialflashlight.CustomApplication import co.garmax.materialflashlight.Preferences import co.garmax.materialflashlight.R import co.garmax.materialflashlight.modes.ModeBase import co.garmax.materialflashlight.modes.ModeService import co.garmax.materialflashlight.modes.SoundStrobeMode import co.garmax.materialflashlight.modules.FlashModule import co.garmax.materialflashlight.modules.ModuleBase import co.garmax.materialflashlight.modules.ModuleManager import co.garmax.materialflashlight.modules.ScreenModule import javax.inject.Inject class MainActivity : AppCompatActivity(), CompoundButton.OnCheckedChangeListener, ModuleManager.OnLightStateChangedListener { @Bind(R.id.image_appbar) lateinit var mImageAppbar: ImageView @Bind(R.id.switch_keep_screen_on) lateinit var mSwitchKeepScreenOn: SwitchCompat @Bind(R.id.switch_auto_turn_on) lateinit var mSwitchAutoTurnOn: SwitchCompat @Bind(R.id.radio_torch) lateinit var mRadioTorch: RadioButton @Bind(R.id.radio_interval_strobe) lateinit var mRadioIntervalStrobe: RadioButton @Bind(R.id.radio_sound_strobe) lateinit var mRadioSoundStrobe: RadioButton @Bind(R.id.radio_camera_flashlight) lateinit var mRadioCameraFlashlight: RadioButton @Bind(R.id.radio_screen) lateinit var mRadioScreen: RadioButton @Bind(R.id.fab) lateinit var mFab: FloatingActionButton @Bind(R.id.text_version) lateinit var mTextVersion: TextView @Inject lateinit var mModuleManager: ModuleManager @Inject lateinit var mPreferences: Preferences private lateinit var mAnimatedDrawableDay: AnimatedVectorDrawableCompat private lateinit var mAnimatedDrawableNight: AnimatedVectorDrawableCompat override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) ButterKnife.bind(this) (application as CustomApplication).applicationComponent.inject(this) mAnimatedDrawableDay = AnimatedVectorDrawableCompat.create(this, R.drawable.avc_appbar_day) as AnimatedVectorDrawableCompat mAnimatedDrawableNight = AnimatedVectorDrawableCompat.create(this, R.drawable.avc_appbar_night) as AnimatedVectorDrawableCompat setupLayout() mModuleManager.setOnLightStateChangedListener(this) // Handle auto turn on if (savedInstanceState == null && mPreferences.isAutoTurnOn) { turnOn() } // Restore state on recreation else { setState(mModuleManager.isRunning(), false) } } private fun setupLayout() { // Restore settings // Set module when (mPreferences.module) { ModuleBase.MODULE_CAMERA_FLASHLIGHT -> { mRadioCameraFlashlight.isChecked = true } ModuleBase.MODULE_SCREEN -> { mRadioScreen.isChecked = true } } // Set mode when (mPreferences.mode) { ModeBase.MODE_INTERVAL_STROBE -> { mRadioIntervalStrobe.isChecked = true } ModeBase.MODE_TORCH -> { mRadioTorch.isChecked = true } ModeBase.MODE_SOUND_STROBE -> { mRadioSoundStrobe.isChecked = true } } mSwitchKeepScreenOn.isChecked = mPreferences.isKeepScreenOn mSwitchAutoTurnOn.isChecked = mPreferences.isAutoTurnOn mRadioSoundStrobe.setOnCheckedChangeListener(this) mRadioIntervalStrobe.setOnCheckedChangeListener(this) mRadioTorch.setOnCheckedChangeListener(this) mSwitchKeepScreenOn.setOnCheckedChangeListener(this) mSwitchAutoTurnOn.setOnCheckedChangeListener(this) mRadioCameraFlashlight.setOnCheckedChangeListener(this) mRadioScreen.setOnCheckedChangeListener(this) mTextVersion.text = getString(R.string.text_version, BuildConfig.VERSION_NAME) } override fun stateChanged(turnedOn: Boolean) { setState(turnedOn, true) } private fun setState(turnedOn: Boolean, animated: Boolean) { runOnUiThread( { if (turnedOn) { // Fab image mFab.setImageResource(R.drawable.ic_power_on); // Appbar image if (animated) { mImageAppbar.setImageDrawable(mAnimatedDrawableDay) mAnimatedDrawableDay.start() } else { mImageAppbar.setImageResource(R.drawable.vc_appbar_day) } } else { // Fab image mFab.setImageResource(R.drawable.ic_power_off); // Appbar image if (animated) { mImageAppbar.setImageDrawable(mAnimatedDrawableNight) mAnimatedDrawableNight.start() } else { mImageAppbar.setImageResource(R.drawable.vc_appbar_night) } } } ) } @OnClick(R.id.fab, R.id.layout_keep_screen_on, R.id.layout_auto_turn_on) internal fun onClick(view: View) { when (view.id) { R.id.fab -> { // Turn off light if (mModuleManager.isRunning()) { turnOff() } // Turn on light else { turnOn() } } R.id.layout_keep_screen_on -> mSwitchKeepScreenOn.toggle() R.id.layout_auto_turn_on -> mSwitchAutoTurnOn.toggle() } } private fun changeModule(module: Int) { val isRunning = mModuleManager.isRunning() // Stop previous module if (isRunning) turnOff() mPreferences.module = module if (module == ModuleBase.MODULE_CAMERA_FLASHLIGHT) { mModuleManager.module = FlashModule(this); } else if (module == ModuleBase.MODULE_SCREEN) { mModuleManager.module = ScreenModule(this); } else { throw IllegalArgumentException("Unknown module type " + module) } // Turn on if was running if (isRunning) turnOn() } private fun turnOff() { ModeService.setMode(this, ModeBase.MODE_OFF) } private fun turnOn() { // Show toast using app context if (!mModuleManager.isSupported()) { Toast.makeText(applicationContext, R.string.toast_module_not_supported, Toast.LENGTH_LONG).show() // Stop if was started if (mModuleManager.isAvailable()) { mModuleManager.stop(); } } else { // Exit if we don't have permission for the module if (!mModuleManager.checkPermissions(RC_MODULE_PERMISSIONS, this)) return // Exit if we don't have permission for sound strobe mode if (mPreferences.mode == ModeBase.MODE_SOUND_STROBE && !SoundStrobeMode.checkPermissions(RC_MODE_PERMISSIONS, this)) return ModeService.setMode(this, mPreferences.mode) } } override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) { when (buttonView.id) { R.id.switch_keep_screen_on -> { mPreferences.isKeepScreenOn = isChecked } R.id.switch_auto_turn_on -> { mPreferences.isAutoTurnOn = isChecked } R.id.radio_sound_strobe -> { if (isChecked) changeMode(ModeBase.MODE_SOUND_STROBE) } R.id.radio_interval_strobe -> { if (isChecked) changeMode(ModeBase.MODE_INTERVAL_STROBE) } R.id.radio_torch -> { if (isChecked) changeMode(ModeBase.MODE_TORCH) } R.id.radio_camera_flashlight -> if (isChecked) changeModule(ModuleBase.MODULE_CAMERA_FLASHLIGHT) R.id.radio_screen -> if (isChecked) changeModule(ModuleBase.MODULE_SCREEN) } } private fun changeMode(mode: Int) { mPreferences.mode = mode // Start new mode if (mModuleManager.isRunning()) turnOn() } override fun onBackPressed() { super.onBackPressed() // Stop service if user exit with back button if (mModuleManager.isRunning()) { ModeService.setMode(this, ModeBase.MODE_OFF) } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == RC_MODULE_PERMISSIONS || requestCode == RC_MODE_PERMISSIONS) { if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { turnOn(); } else if (mModuleManager.isRunning()) { ModeService.setMode(this, ModeBase.MODE_OFF) } } } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) if(intent != null && intent.getBooleanExtra(EXTRA_FINISH, false)) { finish(); } } companion object { private const val RC_MODULE_PERMISSIONS = 0; private const val RC_MODE_PERMISSIONS = 1; const val EXTRA_FINISH = "extra_finish"; } }
0
Kotlin
0
0
0dbac24e704bc5051020377093b3986c2191ca33
10,249
material-flashlight
Apache License 2.0
src/main/kotlin/no/skatteetaten/aurora/gradle/plugins/configurators/Configurator.kt
Skatteetaten
87,403,632
false
null
package no.skatteetaten.aurora.gradle.plugins.configurators import no.skatteetaten.aurora.gradle.plugins.model.AuroraReport interface Configurator { fun configure(): List<AuroraReport> }
1
Kotlin
2
2
ec414d87869b825c10f16157549b560fcc92e26c
193
aurora-gradle-plugin
Apache License 2.0
shared/src/commonMain/kotlin/io/spherelabs/anypass/ui/home/navigation/HomeNavigation.kt
getspherelabs
687,455,894
false
{"Kotlin": 645187, "Ruby": 6822, "Swift": 1167, "Shell": 226}
package io.spherelabs.anypass.ui.home.navigation import io.spherelabs.anypass.navigation.Route import io.spherelabs.anypass.ui.home.HomeRoute import io.spherelabs.navigation.NavHostScope import io.spherelabs.navigation.NavigationController import io.spherelabs.navigation.composable fun NavHostScope<Route>.homeScreen( navigateToMyAccount: () -> Unit, navigateToCreatePassword: () -> Unit, ) { this.composable<Route.Home> { HomeRoute( navigateToMyAccount = { navigateToMyAccount.invoke() }, navigateToCreatePassword = { navigateToCreatePassword.invoke() }, ) } } fun NavigationController<Route>.navigateToHome() { this.navigateTo(Route.Home) }
25
Kotlin
21
134
09ce4d285d7dc88e265ca0534272f20c7254b82c
764
anypass-kmp
Apache License 2.0
src/commonMain/kotlin/app/QuizState.kt
jossiwolf
489,154,391
false
{"Kotlin": 51432, "HTML": 1258}
package app import androidx.compose.runtime.Stable import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontWeight import lce.Lce import data.Location @Stable data class QuizState( val locations: List<QuizLocation>, val correctLocation: QuizLocation, val answerCorrect: Boolean? ) @Stable data class QuizLocation( val cityName: String, val countryName: String, val coords: List<Double>, val bounds: List<List<Double>> = listOf( listOf(coords[0] - 0.42, coords[1] + 0.42), listOf(coords[0] + 0.42, coords[1] - 0.42) ) ) @Stable data class CityGuesserAppState( val level: Int, val score: Int, val highScore: Int, val quizState: Lce<QuizState> ) { companion object { fun initial() = CityGuesserAppState(level = 0, quizState = Lce.Loading, score = 0, highScore = 0) } } fun QuizLocation.asMapLocation() = Location(lng = coords[0], lat = coords[1]) fun QuizLocation.formattedName() = buildAnnotatedString { pushStyle(SpanStyle(fontWeight = FontWeight.Bold)) append(cityName) pop() append(", ") append(countryName) }
0
Kotlin
0
0
6279ba6fe7870f4d4cb88bc225669cda7d54505b
1,194
city-guesser
MIT License
src/main/kotlin/ru/raysmith/google/model/api/BasicChartStackedType.kt
RaySmith-ttc
750,736,250
false
{"Kotlin": 327410}
package ru.raysmith.google.model.api import com.google.api.services.sheets.v4.model.BasicChartSpec /** * When charts are stacked, range (vertical axis) values are rendered on top of one another rather than from the * horizontal axis. For example, the two values 20 and 80 would be drawn from 0, * with 80 being 80 units away fromthe horizontal axis. * If they were stacked, 80 would be rendered from 20, putting it 100 units away from the horizontal axis. * */ enum class BasicChartStackedType { /** Default value, do not use. */ BASIC_CHART_STACKED_TYPE_UNSPECIFIED, /** Series are not stacked. */ NOT_STACKED, /** Series values are stacked, each value is rendered vertically beginning from the top of the value below it. */ STACKED, /** Vertical stacks are stretched to reach the top of the chart, with values laid out as percentages of each other. */ PERCENT_STACKED, } /** * The stacked type for charts that support vertical stacking. * Applies to Area, Bar, Column, Combo, and Stepped Area charts. * */ fun BasicChartSpec.setStackedType(stackedType: BasicChartStackedType) = setStackedType(stackedType.name) /** * The stacked type for charts that support vertical stacking. * Applies to Area, Bar, Column, Combo, and Stepped Area charts. * */ var BasicChartSpec.stackedTypeE: BasicChartStackedType? get() = stackedType?.let { BasicChartStackedType.valueOf(it) } set(value) { stackedType = value?.name }
0
Kotlin
0
0
ae03ea65ad294d7d85a6080aa1b04d4d397391f1
1,471
google
Apache License 2.0
repos/inmemory/src/commonMain/kotlin/dev/inmo/micro_utils/repos/MapKeyValueRepo.kt
InsanusMokrassar
295,712,640
false
null
package dev.inmo.micro_utils.repos import dev.inmo.micro_utils.coroutines.SmartRWLocker import dev.inmo.micro_utils.coroutines.withReadAcquire import dev.inmo.micro_utils.coroutines.withWriteLock import dev.inmo.micro_utils.pagination.Pagination import dev.inmo.micro_utils.pagination.PaginationResult import dev.inmo.micro_utils.pagination.utils.paginate import dev.inmo.micro_utils.pagination.utils.reverse import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.asSharedFlow /** * [Map]-based [ReadKeyValueRepo]. All internal operations will be locked with [locker] (mostly with * [SmartRWLocker.withReadAcquire]) * * **Warning**: It is not recommended to use constructor with both [Map] and [SmartRWLocker]. Besides, in case you are * using your own [Map] as a [map] you should be careful with operations on this [map] */ class ReadMapKeyValueRepo<Key, Value>( protected val map: Map<Key, Value>, private val locker: SmartRWLocker ) : ReadKeyValueRepo<Key, Value> { constructor(map: Map<Key, Value> = emptyMap()) : this(map, SmartRWLocker()) override suspend fun get(k: Key): Value? = locker.withReadAcquire { map[k] } override suspend fun values( pagination: Pagination, reversed: Boolean ): PaginationResult<Value> { return locker.withReadAcquire { val values = map.values val actualPagination = if (reversed) pagination.reverse(values.size) else pagination values.paginate(actualPagination).let { if (reversed) { it.copy(results = it.results.reversed()) } else { it } } } } override suspend fun keys(pagination: Pagination, reversed: Boolean): PaginationResult<Key> { return locker.withReadAcquire { val keys = map.keys val actualPagination = if (reversed) pagination.reverse(keys.size) else pagination keys.paginate(actualPagination).let { if (reversed) { it.copy(results = it.results.reversed()) } else { it } } } } override suspend fun keys(v: Value, pagination: Pagination, reversed: Boolean): PaginationResult<Key> { return locker.withReadAcquire { val keys: List<Key> = map.mapNotNull { (k, value) -> if (v == value) k else null } val actualPagination = if (reversed) pagination.reverse(keys.size) else pagination keys.paginate(actualPagination).let { if (reversed) { it.copy(results = it.results.reversed()) } else { it } } } } override suspend fun getAll(): Map<Key, Value> = locker.withReadAcquire { map.toMap() } override suspend fun contains(key: Key): Boolean = locker.withReadAcquire { map.containsKey(key) } override suspend fun count(): Long = locker.withReadAcquire { map.size.toLong() } } /** * [MutableMap]-based [WriteKeyValueRepo]. All internal operations will be locked with [locker] (mostly with * [SmartRWLocker.withWriteLock]) * * **Warning**: It is not recommended to use constructor with both [MutableMap] and [SmartRWLocker]. Besides, in case * you are using your own [MutableMap] as a [map] you should be careful with operations on this [map] */ class WriteMapKeyValueRepo<Key, Value>( private val map: MutableMap<Key, Value>, private val locker: SmartRWLocker ) : WriteKeyValueRepo<Key, Value> { private val _onNewValue: MutableSharedFlow<Pair<Key, Value>> = MapsReposDefaultMutableSharedFlow() override val onNewValue: Flow<Pair<Key, Value>> by lazy { _onNewValue.asSharedFlow() } private val _onValueRemoved: MutableSharedFlow<Key> = MapsReposDefaultMutableSharedFlow() override val onValueRemoved: Flow<Key> by lazy { _onValueRemoved.asSharedFlow() } constructor(map: MutableMap<Key, Value> = mutableMapOf()) : this(map, SmartRWLocker()) override suspend fun set(toSet: Map<Key, Value>) { if (toSet.isEmpty()) return locker.withWriteLock { map.putAll(toSet) } toSet.forEach { (k, v) -> _onNewValue.emit(k to v) } } override suspend fun unset(toUnset: List<Key>) { if (toUnset.isEmpty()) return locker.withWriteLock { toUnset.mapNotNull { k -> map.remove(k) ?.let { _ -> k } } }.forEach { _onValueRemoved.emit(it) } } override suspend fun unsetWithValues(toUnset: List<Value>) { locker.withWriteLock { map.mapNotNull { (k, v) -> k.takeIf { v in toUnset } }.forEach { map.remove(it) _onValueRemoved.emit(it) } } } } /** * [MutableMap]-based [KeyValueRepo]. All internal operations will be locked with [locker] * * **Warning**: It is not recommended to use constructor with both [MutableMap] and [SmartRWLocker]. Besides, in case * you are using your own [MutableMap] as a [map] you should be careful with operations on this [map] */ @Suppress("DELEGATED_MEMBER_HIDES_SUPERTYPE_OVERRIDE") class MapKeyValueRepo<Key, Value>( private val map: MutableMap<Key, Value>, private val locker: SmartRWLocker ) : KeyValueRepo<Key, Value>, ReadKeyValueRepo<Key, Value> by ReadMapKeyValueRepo(map, locker), WriteKeyValueRepo<Key, Value> by WriteMapKeyValueRepo(map, locker) { constructor(map: MutableMap<Key, Value> = mutableMapOf()) : this(map, SmartRWLocker()) override suspend fun clear() { locker.withWriteLock { map.clear() } } } /** * [MutableMap]-based [KeyValueRepo]. All internal operations will be locked with [locker] * * **Warning**: It is not recommended to use constructor with both [MutableMap] and [SmartRWLocker]. Besides, in case * you are using your own [MutableMap] as a [this] you should be careful with operations on this [this] */ fun <K, V> MutableMap<K, V>.asKeyValueRepo(locker: SmartRWLocker = SmartRWLocker()): KeyValueRepo<K, V> = MapKeyValueRepo(this, locker)
12
null
3
32
625db02651668d6894e064b31db8b8e2b3cc5d16
6,251
MicroUtils
Apache License 2.0
shared/src/commonMain/kotlin/uk/co/sentinelweb/cuer/app/ui/common/dialog/AlertDialogContract.kt
sentinelweb
220,796,368
false
{"Kotlin": 2627352, "CSS": 205156, "Java": 98919, "Swift": 85812, "HTML": 19322, "JavaScript": 12105, "Ruby": 2170}
package uk.co.sentinelweb.cuer.app.ui.common.dialog interface AlertDialogContract { interface Creator { fun create(model: AlertDialogModel): Any /* dialog ref */ fun createAndShowDialog(model: AlertDialogModel) fun dismissDialog(dialogRef: Any) } }
94
Kotlin
0
2
f74e211570fe3985ba45848b228e91a3a8593788
284
cuer
Apache License 2.0
app/src/main/java/kittoku/osc/activity/BlankActivity.kt
kittoku
173,106,265
false
{"Kotlin": 224438}
package kittoku.osc.activity import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import kittoku.osc.R import kittoku.osc.databinding.ActivityBlankBinding import kittoku.osc.fragment.AppsFragment import kittoku.osc.fragment.ProfilesFragment import kittoku.osc.fragment.SaveCertFragment internal const val BLANK_ACTIVITY_TYPE_PROFILES = 0 internal const val BLANK_ACTIVITY_TYPE_APPS = 1 internal const val BLANK_ACTIVITY_TYPE_SAVE_CERT = 2 internal const val EXTRA_KEY_TYPE = "TYPE" internal const val EXTRA_KEY_CERT = "CERT" internal const val EXTRA_KEY_FILENAME = "FILENAME" class BlankActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val fragment: Fragment when (intent.extras!!.getInt(EXTRA_KEY_TYPE)) { BLANK_ACTIVITY_TYPE_PROFILES -> { title = "Profiles" fragment = ProfilesFragment() } BLANK_ACTIVITY_TYPE_APPS -> { title = "Allowed Apps" fragment = AppsFragment() } BLANK_ACTIVITY_TYPE_SAVE_CERT -> { fragment = SaveCertFragment(intent) } else -> throw NotImplementedError(intent.toString()) } val binding = ActivityBlankBinding.inflate(layoutInflater) setContentView(binding.root) supportFragmentManager.beginTransaction().also { it.replace(R.id.blank, fragment) it.commit() } } }
2
Kotlin
100
389
4f1994fda0efba784c7880c79c6165de973eff5c
1,591
Open-SSTP-Client
MIT License
src/main/kotlin/tssti/fullstack/backend_kotlin_rest_api/service/impl/ProdutoService.kt
profmaddo
855,474,186
false
{"Kotlin": 24898}
package tssti.fullstack.backend_kotlin_rest_api.service.impl import org.springframework.stereotype.Service import tssti.fullstack.backend_kotlin_rest_api.entity.Produto import tssti.fullstack.backend_kotlin_rest_api.repository.ProdutoRepository import tssti.fullstack.backend_kotlin_rest_api.service.IProdutoService @Service class ProdutoService( private val produtoRepository: ProdutoRepository ) : IProdutoService { override fun save(obj: Produto): Produto = this.produtoRepository.save(obj) override fun findAll(): List<Produto> { return this.produtoRepository.findAll() } override fun getByID(id: Long): Produto { return this.produtoRepository.getReferenceById(id) } override fun delete(id: Long) { return this.produtoRepository.deleteById(id) } }
0
Kotlin
0
1
897bf0a0638e06562351710fffc81c5bcc42d5b2
820
metodo-full-stack-backend-kotlin
MIT License
shared/src/iosMain/kotlin/data/db/DashboardCardDatabase.kt
ApplETS
159,037,998
false
null
package data.db import kotlinx.coroutines.flow.Flow import model.DashboardCard /** * Created by Sonphil on 02-06-19. */ actual class DashboardCardDatabase { /** * Returns the dashboard cards ordered according the user preference */ actual fun dashboardCards(): Flow<List<DashboardCard>> { TODO("not implemented") } /** * Update a dashboard card and set to the provided position */ actual suspend fun updateCard(dashboardCard: DashboardCard, position: Int) { TODO("not implemented") } /** * Restore the default cards */ actual suspend fun reset() { TODO("not implemented") } }
66
Kotlin
4
13
c4c5c86a54fe16e19a5f7eeea3a0dfb7076207ad
672
Notre-Dame-v3
Apache License 2.0
app/src/main/java/com/jlaj5/statplayer/model/CopasDoMundoDisputadas.kt
JLAJ5
492,268,113
false
null
package com.jlaj5.statplayer.model data class CopasDoMundoDisputadas( val max: Double, val pla: Double, val pos: Int )
0
Kotlin
0
2
1d86778d75ee023e9894d57713a9f284c2dc7187
131
StatPlayer
RSA Message-Digest License
MultipleAppModulesExample/app/src/main/java/me/abunka/multipleappmodules/navigators/MainFeature2Navigation.kt
yankeppey
150,957,921
false
null
package me.abunka.multipleappmodules.navigators import android.app.Activity import me.abunka.multipleappmodules.di.ActivityScope import me.abunka.multipleappmodules.feature1.ActivityC import me.abunka.multipleappmodules.feature2.Feature2Navigation import javax.inject.Inject @ActivityScope class MainFeature2Navigation @Inject constructor(): Feature2Navigation{ override fun goToC(activity: Activity) { activity.startActivity(ActivityC.getIntent(activity)) } }
0
Kotlin
36
106
63dd53e0d49761b1767e359cea6123807fe7a024
479
MultipleAppModules
MIT License
app/src/main/java/br/com/fiap/acid/cap2/EmailFormActivity.kt
xudre
481,403,862
false
{"Kotlin": 17774}
package br.com.fiap.acid.cap2 import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.EditText import androidx.appcompat.app.AppCompatActivity import br.com.fiap.acid.cap2.utils.showSnackBar import com.google.android.gms.tasks.Task import com.google.android.material.switchmaterial.SwitchMaterial import com.google.firebase.auth.AuthResult import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase class EmailFormActivity : AppCompatActivity() { private val etEmail: EditText by lazy { findViewById(R.id.et_email) } private val etPass: EditText by lazy { findViewById(R.id.et_pass) } private val swtCreate: SwitchMaterial by lazy { findViewById(R.id.swt_create) } private val btnEnter: Button by lazy { findViewById(R.id.btn_enter) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_email_form) } override fun onStart() { super.onStart() configListeners() } private fun configListeners() { swtCreate.setOnCheckedChangeListener { _, status -> btnEnter.text = getString(if (status) R.string.criar else R.string.entrar) } btnEnter.setOnClickListener { onEnterAction() } } private fun onEnterAction() { val email = etEmail.text.toString() val password = etPass.text.toString() val auth = Firebase.auth if (swtCreate.isChecked) { auth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> onUserOnboardComplete(task) } } else { auth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> onUserOnboardComplete(task) } } } private fun onUserOnboardComplete(task: Task<AuthResult>) { if (task.isSuccessful) { task.result?.user?.let { user -> val intent = Intent(this, ProfileActivity::class.java) intent.putExtra(ProfileActivity.USER_PARAM, user) startActivity(intent) } } else { Log.w(TAG, "signInWithCredential:failure", task.exception) showSnackBar("Não foi possível autenticar com as credenciais") } } companion object { private const val TAG = "EmailForm" } }
0
Kotlin
0
0
3d71832c3185a472a5c50b00c4932b1e637c4b5b
2,537
fiap-mba-acid-cap2
MIT License
remix/src/commonMain/kotlin/com/woowla/compose/icon/collections/remix/remix/logos/WeiboLine.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.remix.remix.logos 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 com.woowla.compose.icon.collections.remix.remix.LogosGroup public val LogosGroup.WeiboLine: ImageVector get() { if (_weiboLine != null) { return _weiboLine!! } _weiboLine = Builder(name = "WeiboLine", 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) { moveTo(20.194f, 14.197f) curveTo(20.194f, 17.559f, 15.666f, 20.621f, 10.269f, 20.621f) curveTo(5.319f, 20.621f, 1.001f, 18.188f, 1.001f, 14.534f) curveTo(1.001f, 12.587f, 2.181f, 10.447f, 4.24f, 8.446f) curveTo(7.073f, 5.7f, 10.469f, 4.413f, 12.099f, 5.998f) curveTo(12.597f, 6.48f, 12.823f, 7.12f, 12.818f, 7.856f) curveTo(14.793f, 7.28f, 16.469f, 7.452f, 17.301f, 8.608f) curveTo(17.75f, 9.231f, 17.833f, 9.987f, 17.627f, 10.815f) curveTo(19.138f, 11.426f, 20.194f, 12.585f, 20.194f, 14.197f) close() moveTo(15.755f, 12.128f) curveTo(15.369f, 11.717f, 15.355f, 11.208f, 15.557f, 10.717f) curveTo(15.766f, 10.209f, 15.77f, 9.905f, 15.678f, 9.776f) curveTo(15.413f, 9.409f, 14.144f, 9.414f, 12.483f, 10.088f) curveTo(12.431f, 10.111f, 12.361f, 10.137f, 12.276f, 10.162f) curveTo(12.179f, 10.192f, 12.079f, 10.215f, 11.974f, 10.229f) curveTo(11.63f, 10.274f, 11.303f, 10.229f, 10.991f, 9.963f) curveTo(10.572f, 9.604f, 10.517f, 9.108f, 10.669f, 8.647f) curveTo(10.884f, 7.977f, 10.848f, 7.571f, 10.706f, 7.432f) curveTo(10.52f, 7.251f, 9.929f, 7.241f, 9.047f, 7.575f) curveTo(7.978f, 7.98f, 6.749f, 8.799f, 5.633f, 9.881f) curveTo(3.926f, 11.54f, 3.001f, 13.218f, 3.001f, 14.534f) curveTo(3.001f, 16.775f, 6.277f, 18.621f, 10.269f, 18.621f) curveTo(14.689f, 18.621f, 18.194f, 16.251f, 18.194f, 14.197f) curveTo(18.194f, 13.459f, 17.558f, 12.858f, 16.522f, 12.545f) curveTo(16.128f, 12.432f, 15.986f, 12.374f, 15.755f, 12.128f) close() moveTo(22.809f, 10.51f) curveTo(22.67f, 11.045f, 22.125f, 11.366f, 21.59f, 11.227f) curveTo(21.056f, 11.088f, 20.735f, 10.542f, 20.873f, 10.008f) curveTo(20.958f, 9.682f, 21.001f, 9.344f, 21.001f, 9.0f) curveTo(21.001f, 6.791f, 19.21f, 5.0f, 17.001f, 5.0f) curveTo(16.722f, 5.0f, 16.448f, 5.028f, 16.181f, 5.084f) curveTo(15.64f, 5.197f, 15.11f, 4.849f, 14.998f, 4.309f) curveTo(14.885f, 3.768f, 15.232f, 3.239f, 15.773f, 3.126f) curveTo(16.174f, 3.042f, 16.585f, 3.0f, 17.001f, 3.0f) curveTo(20.315f, 3.0f, 23.001f, 5.686f, 23.001f, 9.0f) curveTo(23.001f, 9.514f, 22.936f, 10.02f, 22.809f, 10.51f) close() } } .build() return _weiboLine!! } private var _weiboLine: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
3,928
compose-icon-collections
MIT License
app/src/main/java/com/samara/weatherflex/di/AppComponent.kt
Salieri666
708,944,325
false
{"Kotlin": 40241}
package com.samara.weatherflex.di import com.samara.core.di.base.ComponentManager import com.samara.core.di.components.CoreComponent import com.samara.weatherflex.MainActivity import com.samara.weatherflex.presentation.MainActivityVm import dagger.Component @Component( modules = [AppModule::class, VmModule::class], dependencies = [CoreComponent::class] ) @AppScope interface AppComponent { fun getComponentManager(): ComponentManager fun mainActivityVmFactory(): MainActivityVm.Factory fun inject(mainActivity: MainActivity) }
0
Kotlin
0
0
37bbb7d2b593d31f85590677a86958b2aa352230
551
WeatherFlex
Apache License 2.0
buildSrc/src/main/kotlin/dependencies/ProjectDependency.kt
Between-Freedom-and-Space
453,797,438
false
{"Kotlin": 614504, "HTML": 8733, "Dockerfile": 503, "Shell": 166}
package dependencies interface ProjectDependency { val group: String val artifact: String val version: String }
0
Kotlin
0
1
812d8257e455e7d5b1d0c703a66b55ed2e1dcd35
127
Mono-Backend
Apache License 2.0
ext-kotlin/protobuf/src/main/resources/archetype-resources/src/test/kotlin/proto/SlaMetadataHelper.kt
frtu
268,095,406
false
null
package ${groupId}.proto import ${groupId}.metadata.sla.DataSLA import ${groupId}.metadata.sla.Sla import com.github.frtu.kotlin.protobuf.BaseMessageMetadataHelper import com.google.protobuf.Descriptors import java.util.* class SlaMetadataHelper : BaseMessageMetadataHelper<DataSLA>(Sla.dataSla) { fun hasSLA(messageDescriptor: Descriptors.Descriptor): Boolean { return super.hasExtension(messageDescriptor) } fun getSLA(messageDescriptor: Descriptors.Descriptor): Optional<DataSLA> { return super.getExtension(messageDescriptor) } }
0
Kotlin
0
0
ed39ac04a83b6f1bcdaedae9517bb24d441184e8
568
archetypes
Apache License 2.0
app/src/main/java/org/redbyte/animatron/tictactoe/GameLogic.kt
i-redbyte
229,621,861
false
{"Kotlin": 88241}
package org.redbyte.animatron.tictactoe object GameLogic { fun isGameFinished(board: Board): Boolean { return isWin(board, 1) || isWin(board, 2) || isDraw(board) } fun getWinningLine(board: Board): List<Pair<Int, Int>> { // Check rows for (i in 0 until 3) { if (board[i][0].player != 0 && board[i][0].player == board[i][1].player && board[i][1].player == board[i][2].player ) { return listOf(Pair(i, 0), Pair(i, 1), Pair(i, 2)) } } // Check columns for (j in 0 until 3) { if (board[0][j].player != 0 && board[0][j].player == board[1][j].player && board[1][j].player == board[2][j].player ) { return listOf(Pair(0, j), Pair(1, j), Pair(2, j)) } } // Check diagonals if (board[0][0].player != 0 && board[0][0].player == board[1][1].player && board[1][1].player == board[2][2].player ) { return listOf(Pair(0, 0), Pair(1, 1), Pair(2, 2)) } if (board[0][2].player != 0 && board[0][2].player == board[1][1].player && board[1][1].player == board[2][0].player ) { return listOf(Pair(0, 2), Pair(1, 1), Pair(2, 0)) } return emptyList() } private fun isWin(board: Board, player: Int): Boolean { val winningPatterns = listOf( listOf(Pair(0, 0), Pair(0, 1), Pair(0, 2)), listOf(Pair(1, 0), Pair(1, 1), Pair(1, 2)), listOf(Pair(2, 0), Pair(2, 1), Pair(2, 2)), listOf(Pair(0, 0), Pair(1, 0), Pair(2, 0)), listOf(Pair(0, 1), Pair(1, 1), Pair(2, 1)), listOf(Pair(0, 2), Pair(1, 2), Pair(2, 2)), listOf(Pair(0, 0), Pair(1, 1), Pair(2, 2)), listOf(Pair(0, 2), Pair(1, 1), Pair(2, 0)) ) return winningPatterns.any { pattern -> pattern.all { (x, y) -> board[x][y].player == player } } } private fun isDraw(board: Board): Boolean { return board.flatten().none { it.player == 0 } } }
0
Kotlin
0
8
73e99ff6bceec188c01ddd50d191b3107b4fbf04
2,212
Animatron
MIT License
app/src/main/java/org/redbyte/animatron/tictactoe/GameLogic.kt
i-redbyte
229,621,861
false
{"Kotlin": 88241}
package org.redbyte.animatron.tictactoe object GameLogic { fun isGameFinished(board: Board): Boolean { return isWin(board, 1) || isWin(board, 2) || isDraw(board) } fun getWinningLine(board: Board): List<Pair<Int, Int>> { // Check rows for (i in 0 until 3) { if (board[i][0].player != 0 && board[i][0].player == board[i][1].player && board[i][1].player == board[i][2].player ) { return listOf(Pair(i, 0), Pair(i, 1), Pair(i, 2)) } } // Check columns for (j in 0 until 3) { if (board[0][j].player != 0 && board[0][j].player == board[1][j].player && board[1][j].player == board[2][j].player ) { return listOf(Pair(0, j), Pair(1, j), Pair(2, j)) } } // Check diagonals if (board[0][0].player != 0 && board[0][0].player == board[1][1].player && board[1][1].player == board[2][2].player ) { return listOf(Pair(0, 0), Pair(1, 1), Pair(2, 2)) } if (board[0][2].player != 0 && board[0][2].player == board[1][1].player && board[1][1].player == board[2][0].player ) { return listOf(Pair(0, 2), Pair(1, 1), Pair(2, 0)) } return emptyList() } private fun isWin(board: Board, player: Int): Boolean { val winningPatterns = listOf( listOf(Pair(0, 0), Pair(0, 1), Pair(0, 2)), listOf(Pair(1, 0), Pair(1, 1), Pair(1, 2)), listOf(Pair(2, 0), Pair(2, 1), Pair(2, 2)), listOf(Pair(0, 0), Pair(1, 0), Pair(2, 0)), listOf(Pair(0, 1), Pair(1, 1), Pair(2, 1)), listOf(Pair(0, 2), Pair(1, 2), Pair(2, 2)), listOf(Pair(0, 0), Pair(1, 1), Pair(2, 2)), listOf(Pair(0, 2), Pair(1, 1), Pair(2, 0)) ) return winningPatterns.any { pattern -> pattern.all { (x, y) -> board[x][y].player == player } } } private fun isDraw(board: Board): Boolean { return board.flatten().none { it.player == 0 } } }
0
Kotlin
0
8
73e99ff6bceec188c01ddd50d191b3107b4fbf04
2,212
Animatron
MIT License
core/domain/src/main/java/com/minux/monitoring/core/domain/usecase/cryptocurrency/GetAllCryptocurrenciesUseCase.kt
MINUX-organization
756,381,294
false
{"Kotlin": 234602}
package com.minux.monitoring.core.domain.usecase.cryptocurrency import com.minux.monitoring.core.domain.model.cryptocurrency.Cryptocurrency import com.minux.monitoring.core.domain.repository.CryptocurrencyRepository import kotlinx.coroutines.flow.Flow import javax.inject.Inject class GetAllCryptocurrenciesUseCase @Inject constructor(private val cryptocurrencyRepository: CryptocurrencyRepository) { operator fun invoke(): Flow<Result<List<Cryptocurrency>>> { return cryptocurrencyRepository.getAllCryptocurrencies() } }
0
Kotlin
0
0
ea0ed05ff1b07f2d970f772b2af1c9179872ccf1
539
MNX.Mobile.Monitoring
MIT License
app/src/main/java/com/mb/hunters/ui/common/ErrorScreen.kt
mboukadir
112,534,034
false
null
/* * Copyright 2022 Mohammed Boukadir * * 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.mb.hunters.ui.common import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.ReportProblem import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.mb.hunters.R @Composable fun ErrorScreen( modifier: Modifier = Modifier, message: String = stringResource(id = R.string.generic_error_msg) ) { Column( modifier = modifier, verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Image( modifier = Modifier.size(100.dp), imageVector = Icons.Outlined.ReportProblem, contentDescription = "", colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.error) ) Text( modifier = Modifier.padding(horizontal = 16.dp), text = message, style = MaterialTheme.typography.displaySmall, color = MaterialTheme.colorScheme.error, textAlign = TextAlign.Center ) } }
0
Kotlin
1
5
abd083e1fac712ca36cbb38fe874b4664ed1b8b8
2,196
hunters
Apache License 2.0
app/src/main/java/com/miu/gardeningjournal/MainActivity.kt
BhagiaSheri
740,191,327
false
{"Kotlin": 15403}
package com.miu.gardeningjournal import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.appcompat.widget.Toolbar import androidx.navigation.NavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.NavigationUI class MainActivity : AppCompatActivity() { // Declare Navigation Controller Object private lateinit var mnavController: NavController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Find the Toolbar by its ID val toolbar = findViewById<Toolbar>(R.id.toolbar) // Set the Toolbar as the support ActionBar setSupportActionBar(toolbar) val navHostFragment = supportFragmentManager.findFragmentById(R.id.fragmentContainerView) as NavHostFragment mnavController = navHostFragment.navController // Code to link the navigation controller to the app bar NavigationUI.setupActionBarWithNavController(this, mnavController) } // override the onSupportNavigateUp() method to call navigateUp() in the navigation controller override fun onSupportNavigateUp(): Boolean { return mnavController.navigateUp() } }
0
Kotlin
0
0
fda7a6a1980f2f76999c15ddb09369b47b5bb90c
1,297
gardening-journal-app
Apache License 2.0
app/src/main/java/ru/parcel/app/core/utils/DeviceUtils.kt
gdlbo
839,512,469
false
{"Kotlin": 322281}
package ru.parcel.app.core.utils import android.annotation.SuppressLint import android.content.Context import android.os.Build import android.provider.Settings import java.util.Locale object DeviceUtils { private var androidId: String = "" fun getAndroidId(): String { return androidId } @SuppressLint("HardwareIds") fun setDeviceId(context: Context) { try { val contentResolver = context.contentResolver androidId = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID) } catch (e: Exception) { e.printStackTrace() } } fun getDeviceName(): String { val manufacturer = Build.MANUFACTURER val model = Build.MODEL val cleanedManufacturer = Regex("[^\\x00-\\x7F]").replace(manufacturer, "") val cleanedModel = Regex("[^\\x00-\\x7F]").replace(model, "") if (cleanedModel.startsWith(cleanedManufacturer, ignoreCase = false)) { return if (cleanedModel.isNotEmpty()) { val firstChar = cleanedModel[0] val titleCasedFirstChar = if (firstChar.isLowerCase()) { Locale.getDefault().let { firstChar.titlecase(it) } } else { firstChar.toString() } titleCasedFirstChar + cleanedModel.substring(1) } else { cleanedModel } } val manufacturerName = if (cleanedManufacturer.isNotEmpty()) { val firstChar = cleanedManufacturer[0] val titleCasedFirstChar = if (firstChar.isLowerCase()) { Locale.getDefault().let { firstChar.titlecase(it) } } else { firstChar.toString() } titleCasedFirstChar + cleanedManufacturer.substring(1) } else { cleanedManufacturer } val modelName = if (cleanedModel.isNotEmpty()) { val firstChar = cleanedModel[0] val titleCasedFirstChar = if (firstChar.isLowerCase()) { Locale.getDefault().let { firstChar.titlecase(it) } } else { firstChar.toString() } titleCasedFirstChar + cleanedModel.substring(1) } else { cleanedModel } return "$manufacturerName $modelName" } }
2
Kotlin
0
7
bffdef535d8056455568fc4ad3f2fb763509d89f
2,384
packageradar
MIT License
src/test/kotlin/ar/edu/unq/cucumber/ordenarproductosporprecios/OrdenarProductosPorPreciosTest.kt
CristianGonzalez1980
320,041,280
false
null
package ar.edu.unq.cucumber.ordenarproductosporprecios import io.cucumber.junit.Cucumber import io.cucumber.junit.CucumberOptions import org.junit.runner.RunWith @RunWith(Cucumber::class) @CucumberOptions(features = ["src/test/resources/ar/edu/unq/cucumber/ordenarproductosporprecios.feature"]) class OrdenarProductosPorPreciosTest
1
Kotlin
0
0
28553d578b6c6ec24c32759d604731bfbc40627a
334
exposicion-virtual
The Unlicense
app/src/main/java/pl/polsl/workflow/manager/client/ui/base/BaseViewModel.kt
SzymonGajdzica
306,075,061
false
null
package pl.polsl.workflow.manager.client.ui.base import android.app.Application import android.content.Intent import android.os.Bundle import androidx.annotation.StringRes import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import pl.polsl.workflow.manager.client.R import pl.polsl.workflow.manager.client.model.repositoryMessage import pl.polsl.workflow.manager.client.util.DelayedBoolChanger import java.util.* abstract class BaseViewModel(private val app: Application): AndroidViewModel(app) { private val mShouldFinish: MutableLiveData<Boolean> = MutableLiveData(false) private val mLoading: MutableLiveData<Boolean> = MutableLiveData(false) private val mErrorString: MutableLiveData<String> = MutableLiveData<String>(null) private val mErrorMessage: MutableLiveData<String> = MutableLiveData<String>(null) private val mSuccessMessage: MutableLiveData<String> = MutableLiveData<String>(null) val shouldFinish: LiveData<Boolean> = mShouldFinish val loading: LiveData<Boolean> = mLoading val error: LiveData<String> = mErrorString val errorMessage: LiveData<String> = mErrorMessage val successMessage: LiveData<String> = mSuccessMessage val currentlyLoading: Boolean get() = delayedValueChanger.currentValue private val delayedValueChanger = DelayedBoolChanger(viewModelScope, 200L, mLoading) fun clearErrorString() { mErrorString.value = null } fun clearMessages() { mErrorMessage.value = null mSuccessMessage.value = null } open fun updateSharedArguments(intent: Intent) { } open fun updateArguments(bundle: Bundle) { } open fun reloadData() { } protected fun getString(@StringRes stringRes: Int): String { return app.getString(stringRes) } protected fun launchWithLoader(block: suspend CoroutineScope.() -> Unit) { viewModelScope.launch { delayedValueChanger.change(true) block() delayedValueChanger.change(false) } } protected fun finishFragment() { mShouldFinish.value = true } protected fun showSuccessMessage(text: String) { mSuccessMessage.value = text } protected fun showErrorMessage(text: String) { mErrorMessage.value = text } protected fun showErrorMessage(e: Throwable) { showErrorMessage(((e.repositoryMessage ?: e.message)?.capitalize(Locale.ROOT) ?: getString(R.string.unknownError))) } protected fun showError(errorText: String) { mErrorString.value = errorText } protected fun showError(e: Throwable) { e.printStackTrace() showError(((e.repositoryMessage ?: e.message)?.capitalize(Locale.ROOT) ?: getString(R.string.unknownError)).capitalize(Locale.US)) } }
0
Kotlin
0
0
93c99cc67c7af0bc55ca8fb03f077cdd363cb7e8
2,985
workflow-manager-client
MIT License
app/src/main/java/com/example/budget/libs/composables/trx/DateTimeTextField.kt
okumaru
725,161,333
false
{"Kotlin": 258088}
package com.example.budget.libs.composables.trx import android.app.DatePickerDialog import android.widget.DatePicker import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsPressedAsState import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.DateRange import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import java.sql.Timestamp import java.text.DateFormatSymbols import java.text.SimpleDateFormat import java.util.Calendar import java.util.Date import java.util.Locale @OptIn(ExperimentalMaterial3Api::class) @Composable fun DateTimeTextField( defaultDT: Date, updateDT: (Date) -> Unit ) { val interactionSource = remember { MutableInteractionSource() } val isPressed: Boolean by interactionSource.collectIsPressedAsState() val sdf = SimpleDateFormat("MMMM d, yyyy", Locale.getDefault()) val currentDate = sdf.format(defaultDT) var selectedDate by rememberSaveable { mutableStateOf(currentDate) } val context = LocalContext.current val calendar = Calendar.getInstance() val year: Int = calendar.get(Calendar.YEAR) val month: Int = calendar.get(Calendar.MONTH) val day: Int = calendar.get(Calendar.DAY_OF_MONTH) calendar.time = Timestamp(System.currentTimeMillis()) val datePickerDialog = DatePickerDialog(context, { _: DatePicker, year: Int, month: Int, dayOfMonth: Int -> val newDate = Calendar.getInstance() newDate.set(year, month, dayOfMonth) selectedDate = "${month.toMonthName()} $dayOfMonth, $year" updateDT(newDate.time) }, year, month, day) TextField( modifier = Modifier.fillMaxWidth(), label = { Text( text = "Date of transaction" ) }, readOnly = true, value = selectedDate, onValueChange = {}, trailingIcon = { Icons.Default.DateRange }, interactionSource = interactionSource, shape = MaterialTheme.shapes.medium, colors = TextFieldDefaults.textFieldColors( focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent, disabledIndicatorColor = Color.Transparent ), ) if (isPressed) { datePickerDialog.show() } } fun Int.toMonthName(): String { return DateFormatSymbols().months[this] }
0
Kotlin
0
0
59627b9d50538fbbc5512f2622a3608ced425577
3,054
mobile-app-budget
MIT License