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
feature/account/data/src/test/java/br/com/jwar/sharedbill/account/data/repositories/DefaultUserRepositoryTest.kt
wellingtonrib
535,153,218
false
{"Kotlin": 448034, "JavaScript": 2075}
package br.com.jwar.sharedbill.account.data.repositories import br.com.jwar.sharedbill.account.data.datasources.UserDataSource import br.com.jwar.sharedbill.account.domain.model.User import br.com.jwar.sharedbill.testing.CoroutinesTestRule import br.com.jwar.sharedbill.testing.fakes.FakeFactory import io.mockk.coEvery import io.mockk.coVerify import io.mockk.mockk import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import org.junit.Rule import org.junit.Test import kotlin.test.assertEquals @OptIn(ExperimentalCoroutinesApi::class) internal class DefaultUserRepositoryTest { @get:Rule val coroutineRule = CoroutinesTestRule() private val userDataSource = mockk<UserDataSource>() private val repository = DefaultUserRepository( userDataSource = userDataSource ) @Test fun `getCurrentUser should call userDataSource getCurrentUser and return it`() = runTest { val currentUser = FakeFactory.makeUser() prepareScenario(currentUser = currentUser) val result = repository.getCurrentUser() coVerify { userDataSource.getCurrentUser() } assertEquals(currentUser, result) } @Test fun `saveUser should call userDataSource saveUser`() = runTest { val user = FakeFactory.makeUser() prepareScenario() repository.saveUser(user) coVerify { userDataSource.saveUser(user) } } @Test fun `createUser should call userDataSource createUser`() = runTest { val userName = "User name" prepareScenario() repository.createUser(userName) coVerify { userDataSource.createUser(userName) } } private fun prepareScenario( currentUser: User = FakeFactory.makeUser() ) { coEvery { userDataSource.getCurrentUser() } returns currentUser coEvery { userDataSource.saveUser(any()) } returns mockk() coEvery { userDataSource.createUser(any()) } returns mockk() } }
17
Kotlin
0
0
5343aac247f77437164505e3b977e4ef8fe764da
1,994
SharedBill
Creative Commons Attribution 4.0 International
main/src/main/kotlin/com/hcl/tool/Tool.kt
HCl8
776,484,856
false
{"Kotlin": 53975}
package com.hcl.tool import com.fasterxml.jackson.databind.ObjectMapper import com.hcl.Config import kotlinx.coroutines.* import kotlinx.coroutines.flow.* import okhttp3.internal.closeQuietly import java.io.Closeable import java.io.File import java.io.InputStream import java.text.SimpleDateFormat import java.util.* import java.util.zip.GZIPInputStream import java.util.zip.ZipFile import java.util.zip.ZipInputStream import kotlin.coroutines.EmptyCoroutineContext import kotlin.io.use object Tool { val dateFotmat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") private fun dumpMemory(): Flow<String> { return flow { val date = SimpleDateFormat("yyyyMMddHHmmss").format(Date()) val fileName = "${date}.hprof" emit("file name $fileName") val exec = "adb shell pidof ${Config.memDumpProcess}".exec() exec.emitAll(this) if (exec.exit != 0) { return@flow } val pid = exec.out.first().trim() emit("get xaee pid $pid") "adb shell am dumpheap $pid /data/local/tmp/${fileName}".exec().emitAll(this) "adb pull /data/local/tmp/${fileName} file/${fileName}".exec().emitAll(this) val handleName = fileName.replace(".hprof", "_conv.hprof") if (!File("file").exists()) { File("file").mkdirs() } "hprof-conv file/${fileName} file/$handleName".exec().emitAll(this) File("file/$handleName").copyTo(File(Config.memDumpPath / fileName.replace(".hprof", "") / handleName)) File("file/${fileName}").delete() File("file/${handleName}").delete() emit("dump file $fileName") }.flowOn(Dispatchers.IO) } private fun searchBugreport(rule: Regex, file: File) = flow { val zf = ZipFile(file) val entries = zf.entries().toList() entries.asSequence() .filter { isLogFile(it.name) } .flatMap { extractLog(it.name, zf.getInputStream(it)) } .map { it.use { it.name to it .mapIndexedNotNull { index, s -> if (rule.containsMatchIn(s)) index to s else null } .count() } } .filter { it.second > 0 } .sortedByDescending { it.second } .forEach { emit("file: ${it.first} text line number: ${it.second}") } zf.closeQuietly() emit("finish!") System.gc() }.flowOn(Dispatchers.IO) data class LogStream(val name: String, private val stream: InputStream) : Sequence<String> by stream.bufferedReader().lineSequence(), Closeable by stream private fun extractLog(name: String, input: InputStream): List<LogStream> { return when { name.endsWith(".txt") || name.endsWith(".log") -> listOf(LogStream(name, input)) name.endsWith(".gz") -> listOf(LogStream(name, GZIPInputStream(input))) name.endsWith(".zip") -> run { val r = mutableListOf<LogStream>() val zipStream = ZipInputStream(input) while (true) { val nextEntry = zipStream.nextEntry ?: break val entryName = nextEntry.name if (isLogFile(entryName)) { extractLog(entryName, zipStream.readAllBytes().inputStream()).forEach { r.add(it.copy(name = "${name}:${entryName}")) } } } r } else -> emptyList() } } private fun isLogFile(name: String): Boolean { return name.endsWith(".log") || name.endsWith(".txt") || (name.contains("logcat") && name.endsWith(".gz")) || name.endsWith(".zip") } private fun logcatFile(): String { val date = SimpleDateFormat("MMdd").format(Date()) val logPath = Config.logcatPath val index = logPath.toFile().list()?.filter { it.startsWith(date) && it.endsWith(".log") }?.mapNotNull { it.substring(4, it.length - 4).toIntOrNull() }?.maxOrNull() ?: 1 val finaName = "${date}${(index + 1).toString().padStart(2, '0')}.log" return logPath / finaName } fun adb() = createSimpleCommand { simpleSubCommand("TestActivity") { async { "adb shell am start -n com.mi.car.voiceassist/.activity.TestEnvSettingActivity".exec() } } simpleSubCommand("Scrcpy") { Runtime.getRuntime().exec("cmd /c scrcpy") } subCommand("Install") { flow { val apkFile = it.file.toFile() emit("try install ${apkFile.name}") emit("modify time " + dateFotmat.format(apkFile.lastModified())) "adb install -d \"${it.file}\"".exec().emitAll(this) }.flowOn(Dispatchers.IO) } subCommand("InstallBuild") { installLastModifyApk(Config.botBuildPath) } subCommand("InstallDl") { installLastModifyApk(Config.downLoadPath) } subCommand("installCi") { val flow = MutableSharedFlow<String>() CoroutineScope(Dispatchers.IO).launch { try { val f = getGitlabBuildApk(it.input.content) { launch { flow.emit(it) } } installLastModifyApk(f).collect { flow.emit(it) } } catch (e: Exception) { e.printStackTrace() flow.emit("download fail! ${e.message}") } } return@subCommand flow } } fun adbLog() = createCommand { val exec = Runtime.getRuntime().exec("adb logcat") val logFile = logcatFile().toFile() async { logFile.deleteIfExist() logFile.bufferedWriter().use { bw -> exec.inputStream.bufferedReader().lineSequence().forEach { bw.write(it + "\n") } } } simpleSubCommand("stop") { exec.destroy() } onExit { println("destory on exit!") exec.destroyForcibly() } flow { emit("start logcat") exec.errorStream.asFlow().collect { emit(it) } exec.waitFor() emit("finish logcat, write to ${logFile.name}") clearExitHook() clearSubCommand() simpleSubCommand("open") { Runtime.getRuntime().exec(arrayOf(Config.notepadPath, logFile.absolutePath)) } }.flowOn(Dispatchers.IO) } inline fun async(crossinline action: () -> Unit) { Dispatchers.IO.dispatch(EmptyCoroutineContext) { action.invoke() } } fun formatJson() = createCommand { flow { val formatContent = format(ObjectMapper().readTree(it.input)).toString() emit(formatContent) simpleSubCommand("vscode open") { val random = UUID.randomUUID().toString().substring(0, 8) val file = File(Config.toolTempPath / random + ".json") file.deleteIfExist() file.writeText(formatContent) file.deleteOnExit() Runtime.getRuntime().exec(arrayOf(Config.vscodePath, file.absolutePath)) } }.flowOn(Dispatchers.Default) } fun simpleTool() = createSimpleCommand { subCommand("dumpMem") { dumpMemory() } subCommand("searchTxt") { val file = it.file.toFile() if (!file.exists()) { return@subCommand "file ${file.absolutePath} don't exist!".toFlow() } searchBugreport(it.input.content.toRegex(), file) } subCommand("linkLog") { flow { val pattern = it.input.content val headPattern = Regex(".*\\[Speech .+] [^ ]+ ") val feature = Regex("\\[Speech \\d+-.+]").find(pattern)?.value ?: "null" println(feature) val result = it.file.toFile() .bufferedReader() .lineSequence() .dropWhile { !it.startsWith(pattern) } .filter { it.contains(feature) } .zipWithNext() .takeWhile { it.first.length > 3000 } .flatMap { if (it.second.length > 3000) listOf(it.first) else listOf(it.first, it.second) } .map { val head = headPattern.find(it)?.value ?: "" it.substring(head.length) } .joinToString(separator = "") emit(result) println("link log finish!") }.flowOn(Dispatchers.IO) } } } fun installLastModifyApk(path: String) = flow { val file = if (path.endsWith(".apk")) { path.toFile() } else { val f = path.toFile().listFiles()?.toList() ?.filter { it.name.endsWith("apk") || it.name.endsWith(".zip") } ?.sortedByDescending { it.lastModified() } ?.first { it.name.endsWith("apk") || ZipFile(it).use { it.entries().toList().any { it.name.endsWith(".apk") } } } if (f?.name?.endsWith(".zip") == true) { ZipFile(f).use { val entry = it.entries().toList().firstOrNull { it.name.endsWith(".apk") } if (entry == null) { emit("can't find apk in zip file!") return@use null } else { emit("try install ${f.name} of ${entry.name}!") val extraName = entry.name.substringAfterLast("/") val apkFile = File(path.toFile(), extraName) emit("apk name $extraName oringin modify time ${Tool.dateFotmat.format(Date(entry.time))}") it.getInputStream(entry).use { inputStream -> val outputStream = apkFile.outputStream() inputStream.copyTo(outputStream) outputStream.close() } apkFile } } } else f } if (file == null) { emit("can't find file!") return@flow } emit("try install ${file.name} modify time ${Tool.dateFotmat.format(Date(file.lastModified()))}") val exec = "adb install -d \"${file.absolutePath}\"".exec() exec.err.plus(exec.out).forEach { emit(it) } emit("return value ${exec.exit}") }.flowOn(Dispatchers.IO)
0
Kotlin
0
0
eaf32de57a719f3e6937e999ce2a1b8fa0bbc459
11,175
simple-tool
Apache License 2.0
app/src/main/java/com/example/juandavid/timegram/activities/DetailActivity.kt
Juan7655
137,006,663
false
{"Python": 495153, "Kotlin": 23727, "Java": 3061}
package com.example.juandavid.timegram.activities import RecyclerViewFragment import android.os.AsyncTask import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v7.app.AppCompatActivity import com.example.juandavid.timegram.R import com.example.juandavid.timegram.database.AppDatabase import com.example.juandavid.timegram.pojo.Event import com.google.firebase.database.FirebaseDatabase import com.shashank.sony.fancytoastlib.FancyToast import kotlinx.android.synthetic.main.activity_detail.* import kotlinx.android.synthetic.main.content_detail.* import java.lang.Integer.parseInt class DetailActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_detail) setSupportActionBar(toolbar) val pos = intent.getIntExtra("POSITION", 0) val e = RecyclerViewFragment.adapter.getItem(pos) val tempTime = e.objective.split(":") detail_time.hour = parseInt(tempTime[0]) detail_time.minute = parseInt(tempTime[1]) detail_date.text = e.date detail_title.text = e.objective detail_descr.text = e.description detail_cat.text = e.category detail_img.setImageResource(when(e.category){ "Personal" -> R.drawable.ic_person_black_24dp "Family" -> R.drawable.ic_wc_black_24dp "Work" -> R.drawable.ic_business_center_black_24dp "Work2" -> R.drawable.ic_drive_eta_black_24dp "Friends" -> R.drawable.ic_people_black_24dp "Health" -> R.drawable.ic_healing_black_24dp "Dentist" -> R.drawable.ic_insert_emoticon_black_24dp else -> R.drawable.ic_person_black_24dp }) detail_fab.setOnClickListener { view -> val minute = (if (detail_time.minute < 10) "0" else "") + detail_time.minute.toString() e.realtime = detail_time.hour.toString() + ":"+ minute AsyncUpdate().execute(e) FancyToast.makeText(view.context, "Item updated", Snackbar.LENGTH_LONG, FancyToast.INFO, false).show() RecyclerViewFragment.adapter.deleteItem(pos) finish() } supportActionBar?.setDisplayHomeAsUpEnabled(true) } private inner class AsyncUpdate : AsyncTask<Event, Void, Int>() { override fun doInBackground(vararg params: Event): Int? { AppDatabase.getInstance(baseContext).eventDao() .update(params[0].date, params[0].objective, params[0].description, params[0].category, params[0].realtime) val database = FirebaseDatabase.getInstance().getReference("TIMEGRAM_EVENTS") val list = AppDatabase.getInstance(baseContext).eventDao().doneAppointments for (i in list) database.child(i.id.toString() + "-").setValue(i) return 0 } } }
0
Python
0
0
faa4f8059b5e182fe93c5e6cfc630b8f5d867c68
3,145
timegram
MIT License
app/src/main/java/com/example/chatsupport/activity/Login.kt
prathmesh444
716,429,070
false
{"Kotlin": 21873}
package com.example.chatsupport.activity import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.example.chatsupport.R import com.example.chatsupport.R.layout.login_layout import com.example.chatsupport.dao.loginDao import com.example.chatsupport.utilis.Constants import com.example.chatsupport.utilis.Resource import com.example.chatsupport.utilis.SharedPreferences import com.example.chatsupport.viewModel.NetworkViewModel import com.google.gson.Gson class Login : AppCompatActivity(){ private lateinit var _editTextEmail: EditText private lateinit var _editTextPassword: EditText private lateinit var _buttonLogin: Button private lateinit var viewModel: NetworkViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(login_layout) if(SharedPreferences.get(Constants.LOGIN_AUTH,this) != "-1"){ startActivity(Intent(this, MainActivity::class.java)) finishAffinity() } this._editTextEmail = findViewById(R.id.editTextEmail) this._editTextPassword = findViewById(R.id.editTextPassword) this._buttonLogin = findViewById(R.id.buttonLogin) this.viewModel = NetworkViewModel() _buttonLogin.setOnClickListener{ val username = _editTextEmail.text.toString().trim() val password = _editTextPassword.text.toString().trim() if (username.isNotBlank()){ viewModel.login(loginDao(username,password)) }else{ Toast.makeText(this,"Please input proper value", Toast.LENGTH_SHORT).show() } } setObservers() } private fun setObservers() { viewModel.loginResp.observe(this) { when (it) { is Resource.Success -> { it.data?.let { it -> SharedPreferences.insert(Constants.USER_DATA, Gson().toJson(it),this) SharedPreferences.insert(Constants.LOGIN_AUTH,it.auth_token,this) } startActivity(Intent(this, MainActivity::class.java)) finishAffinity() } is Resource.Error -> { Toast.makeText(this, "Login Failed", Toast.LENGTH_SHORT).show() } is Resource.Loading -> { Toast.makeText(this, "Loading", Toast.LENGTH_SHORT).show() } else -> {} } } } }
0
Kotlin
0
0
a8e9e9dae99287b958fcf7c31744c010ab6afffc
2,688
Customer-Support-Chat-App
MIT License
kotest-core/src/jvmMain/kotlin/io/kotest/core/sourceRef.kt
junron
214,570,871
false
{"Gradle": 30, "YAML": 2, "Markdown": 12, "Java Properties": 2, "Shell": 3, "Text": 1, "Ignore List": 1, "Batchfile": 2, "EditorConfig": 1, "INI": 4, "Kotlin": 574, "Maven POM": 1, "XML": 10, "JavaScript": 1, "Java": 1, "JSON": 1}
package io.kotest.core actual fun sourceRef(): SourceRef { val stack = Throwable().stackTrace return stack.dropWhile { it.className.startsWith("io.kotest") }[0].run { SourceRef(lineNumber, fileName) } }
1
null
1
1
3a00e967d50a43e6200060f7c3df44c730d02610
214
kotlintest
Apache License 2.0
kotlin/src/main/kotlin/com/pbh/soft/Main.kt
phansen314
579,463,173
false
{"Kotlin": 32722}
package com.pbh.soft import com.pbh.soft.common.runner.DayRunner import com.pbh.soft.common.runner.DayRunner.* import com.pbh.soft.common.runner.Part import com.pbh.soft.common.runner.Part.P1 import com.pbh.soft.common.runner.Part.P2 fun main(args: Array<String>) { Main().run() } class Main : Runnable { override fun run() { // Day1.run(P1.example(), P1.problem(), P2.other("overlap"), P2.example(), P2.problem()) // Day2.run(P1.example(), P1.problem(), P2.example(), P2.problem()) // Day3.run(P1.example(), P1.problem(), P2.example(), P2.problem()) // Day4.run(P1.example(), P1.problem(), P2.example(), P2.problem()) // Day5.run(P2.problem())//, P2.example(), P2.problem()) // Day6.run(P2.example(), P2.problem()) // Day7.run(P1.problem(), P2.problem()) Day8.run(P1.example()) } }
0
Kotlin
0
0
0788047263e9d79a1e43e8cd0965a04d2b49b98d
820
advent-of-code
MIT License
app-start/src/test/java/com/example/android/cheesepage/api/CheeseApiTest.kt
yaraki
182,204,814
false
null
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.cheesepage.api import com.google.common.truth.Truth.assertThat import org.junit.Test class CheeseApiTest { @Test fun pages() { val api = CheeseApi((0 until 1000).map { "Cheese$it" }) api.dummySleepInterval = 0L api.fetchPage(0, 10).let { page -> assertThat(page).hasSize(10) assertThat(page[0].name).isEqualTo("Cheese0") } api.fetchPage(10, 10).let { page -> assertThat(page).hasSize(10) assertThat(page[0].name).isEqualTo("Cheese10") } } }
0
Kotlin
4
21
7595f051c07e3ad5b3e93659a75b0bbe8245b884
1,202
CheesePage
Apache License 2.0
media/src/main/kotlin/fr/nihilus/music/media/tracks/DeleteTracksResult.kt
thibseisel
80,150,620
false
null
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package fr.nihilus.music.media.provider import android.app.PendingIntent /** * Describes the possible outcomes of a "delete tracks" operation. */ sealed class DeleteTracksResult { /** * Tracks have been successfully deleted. * @param count Number of tracks that have been deleted. * This might be less than the actual number of tracks you requested to delete, * if some of them did not exist. */ class Deleted(val count: Int) : DeleteTracksResult() /** * No tracks have been deleted because the app lacks required runtime permissions. * The operation may be re-attempted after granting them. * @param permission Name of the required Android runtime permission. */ class RequiresPermission(val permission: String) : DeleteTracksResult() /** * User should explicitly consent to delete the selected tracks. * @param intent Intent to display a system popup granting this app the permission * to delete tracks. * If the permission has been granted, there is no need to re-attempt the operation. */ class RequiresUserConsent(val intent: PendingIntent) : DeleteTracksResult() }
23
null
8
67
f097bcda052665dc791bd3c26880adb0545514dc
1,762
android-odeon
Apache License 2.0
desmond-bank/src/main/kotlin/br/com/wirecard/desmond/bank/validator/BankAccountValidator.kt
wirecardBrasil
151,141,503
false
null
package br.com.wirecard.desmond.bank.validator import br.com.wirecard.desmond.bank.BankAccount interface BankAccountValidator { fun validate(bankAccount: BankAccount): Boolean }
7
Kotlin
1
3
f4dbd94e7a0821ca5913e729dcf1d9a664aba262
183
desmond
MIT License
remix/src/commonMain/kotlin/com/woowla/compose/icon/collections/remix/remix/development/Puzzle2Line.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.remix.remix.development 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.DevelopmentGroup public val DevelopmentGroup.Puzzle2Line: ImageVector get() { if (_puzzle2Line != null) { return _puzzle2Line!! } _puzzle2Line = Builder(name = "Puzzle2Line", 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(7.0f, 5.0f) curveTo(7.0f, 2.791f, 8.791f, 1.0f, 11.0f, 1.0f) curveTo(13.209f, 1.0f, 15.0f, 2.791f, 15.0f, 5.0f) horizontalLineTo(20.0f) curveTo(20.552f, 5.0f, 21.0f, 5.448f, 21.0f, 6.0f) verticalLineTo(10.171f) curveTo(21.0f, 10.495f, 20.842f, 10.8f, 20.577f, 10.987f) curveTo(20.312f, 11.175f, 19.973f, 11.222f, 19.667f, 11.113f) curveTo(19.459f, 11.04f, 19.236f, 11.0f, 19.0f, 11.0f) curveTo(17.895f, 11.0f, 17.0f, 11.895f, 17.0f, 13.0f) curveTo(17.0f, 14.105f, 17.895f, 15.0f, 19.0f, 15.0f) curveTo(19.236f, 15.0f, 19.459f, 14.96f, 19.667f, 14.887f) curveTo(19.973f, 14.778f, 20.312f, 14.825f, 20.577f, 15.013f) curveTo(20.842f, 15.2f, 21.0f, 15.505f, 21.0f, 15.829f) verticalLineTo(20.0f) curveTo(21.0f, 20.552f, 20.552f, 21.0f, 20.0f, 21.0f) horizontalLineTo(4.0f) curveTo(3.448f, 21.0f, 3.0f, 20.552f, 3.0f, 20.0f) verticalLineTo(6.0f) curveTo(3.0f, 5.448f, 3.448f, 5.0f, 4.0f, 5.0f) horizontalLineTo(7.0f) close() moveTo(11.0f, 3.0f) curveTo(9.895f, 3.0f, 9.0f, 3.895f, 9.0f, 5.0f) curveTo(9.0f, 5.236f, 9.04f, 5.46f, 9.114f, 5.667f) curveTo(9.222f, 5.973f, 9.175f, 6.312f, 8.987f, 6.577f) curveTo(8.8f, 6.842f, 8.495f, 7.0f, 8.171f, 7.0f) horizontalLineTo(5.0f) verticalLineTo(19.0f) horizontalLineTo(19.0f) verticalLineTo(17.0f) curveTo(16.791f, 17.0f, 15.0f, 15.209f, 15.0f, 13.0f) curveTo(15.0f, 10.791f, 16.791f, 9.0f, 19.0f, 9.0f) verticalLineTo(7.0f) horizontalLineTo(13.829f) curveTo(13.505f, 7.0f, 13.2f, 6.842f, 13.013f, 6.577f) curveTo(12.825f, 6.312f, 12.778f, 5.973f, 12.887f, 5.667f) curveTo(12.96f, 5.46f, 13.0f, 5.236f, 13.0f, 5.0f) curveTo(13.0f, 3.895f, 12.105f, 3.0f, 11.0f, 3.0f) close() } } .build() return _puzzle2Line!! } private var _puzzle2Line: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
3,557
compose-icon-collections
MIT License
src/main/kotlin/com/fugisawa/kotlinspringdemo/repository/UserRepository.kt
lucasfugisawa
779,676,655
false
{"Kotlin": 5790}
package com.fugisawa.kotlinspringdemo.repository import com.fugisawa.kotlinspringdemo.entity.User import org.springframework.data.jpa.repository.JpaRepository import org.springframework.data.jpa.repository.Query import java.time.Instant interface UserRepository: JpaRepository<User, Long> { fun findByEmailIgnoreCase(email: String): User? fun findByCreatedAtAfter(date: Instant): List<User> fun findByActive(active: Boolean): List<User> }
0
Kotlin
0
0
21be3be753ff78dd062394e4ec6935c8207c084e
452
kotlin-spring-boot-demo-epicpixel
MIT License
lib_base/src/main/java/com/quyunshuo/wanandroid/base/mvvm/v/BaseFrameFragment.kt
Quyunshuo
389,148,840
false
null
package com.quyunshuo.wanandroid.base.mvvm.v import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.viewbinding.ViewBinding import com.alibaba.android.arouter.launcher.ARouter import com.quyunshuo.wanandroid.base.mvvm.vm.BaseViewModel import com.quyunshuo.wanandroid.base.utils.BindingReflex import com.quyunshuo.wanandroid.base.utils.EventBusRegister import com.quyunshuo.wanandroid.base.utils.EventBusUtils import com.quyunshuo.wanandroid.base.utils.ViewRecreateHelper /** * Fragment基类 * * @author <NAME> * @since 8/27/20 */ abstract class BaseFrameFragment<VB : ViewBinding, VM : BaseViewModel> : Fragment(), FrameView<VB> { /** * 私有的 ViewBinding 此写法来自 Google Android 官方 */ private var _binding: VB? = null protected val mBinding get() = _binding!! protected abstract val mViewModel: VM /** * fragment状态保存工具类 */ private var mStatusHelper: FragmentStatusHelper? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = BindingReflex.reflexViewBinding(javaClass, layoutInflater) return _binding?.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) //处理恢复 mStatusHelper?.onRestoreInstanceStatus(savedInstanceState) // ARouter 依赖注入 ARouter.getInstance().inject(this) // 注册EventBus if (javaClass.isAnnotationPresent(EventBusRegister::class.java)) EventBusUtils.register(this) mBinding.initView() initObserve() initRequestData() } override fun isRecreate(): Boolean = mStatusHelper?.isRecreate ?: false /** * 页面可能重建的时候回执行此方法,进行当前页面状态保存 */ override fun onSaveInstanceState(outState: Bundle) { if (mStatusHelper == null) { //仅当触发重建需要保存状态时创建对象 mStatusHelper = FragmentStatusHelper(outState) } else { mStatusHelper?.onSaveInstanceState(outState) } super.onSaveInstanceState(outState) } /** * - fragment状态保存帮助类; * - 暂时没有其他需要保存的--空继承 */ private class FragmentStatusHelper(savedInstanceState: Bundle? = null) : ViewRecreateHelper(savedInstanceState) override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onDestroy() { if (javaClass.isAnnotationPresent(EventBusRegister::class.java)) EventBusUtils.unRegister( this ) super.onDestroy() } }
1
Kotlin
7
34
b00274fb9ad349dc8b9d2f32ed1af5e2864246c6
2,714
WanAndroidMVVM
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/redshift/ParameterPropertyDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.redshift import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.redshift.CfnClusterParameterGroup @Generated public fun buildParameterProperty(initializer: @AwsCdkDsl CfnClusterParameterGroup.ParameterProperty.Builder.() -> Unit): CfnClusterParameterGroup.ParameterProperty = CfnClusterParameterGroup.ParameterProperty.Builder().apply(initializer).build()
1
Kotlin
0
0
b22e397ff37c5fce365a5430790e5d83f0dd5a64
495
aws-cdk-kt
Apache License 2.0
src/main/kotlin/com/enderdincer/okey/game/engine/event/handler/GameEventHandlers.kt
enderdincer
498,879,253
false
null
package com.enderdincer.okey.game.engine.event.handler import com.enderdincer.okey.game.engine.domain.GameEventType import com.enderdincer.okey.game.engine.event.validator.GameEventValidators object GameEventHandlers { @JvmStatic fun getGameEventHandler(gameEventType: GameEventType): GameEventHandler { val gameEventValidator = GameEventValidators.getDefaultGameEventValidator() return when (gameEventType) { GameEventType.CREATE_GAME -> CreateGameEventHandler(gameEventValidator) GameEventType.ADD_PLAYER -> AddPlayerGameEventHandler(gameEventValidator) GameEventType.START_GAME -> StartGameEventHandler(gameEventValidator) GameEventType.DRAW_TILE_FROM_CENTER_TILE_STACK -> DrawFromCenterTileStackGameEventHandler(gameEventValidator) GameEventType.DRAW_TILE_FROM_DISCARD_TILE_STACK -> DrawFromDiscardTileStackGameEventHandler(gameEventValidator) GameEventType.DISCARD_TILE -> DiscardTileGameEventHandler(gameEventValidator) GameEventType.DECLARE_WIN -> DeclareWinGameEventHandler(gameEventValidator) } } }
0
Kotlin
0
0
66166dc4cc44d78504c16aea00fce739cd5f5ae5
1,131
okey-game-engine
MIT License
src/main/kotlin/io/grimlocations/ui/view/component/ComboPopup.kt
recursivelftr
336,897,177
false
null
package io.grimlocations.ui.view.component import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Menu import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.WindowPosition import androidx.compose.ui.window.WindowSize import androidx.compose.ui.window.rememberDialogState import io.grimlocations.ui.view.GrimLocationsTheme import kotlinx.coroutines.ExperimentalCoroutinesApi private val transparentColor = Color(0, 0, 0, 0) private val dropDownBackgroundColorDark = Color(47, 47, 47) private val dropDownBackgroundColorLight = Color(224, 224, 224) private val dropDownButtonWidth = 40.dp private val dropDownItemHeight = 32.dp private val dropDownSpacerHeight = 5.dp private val dropDownAverageItemHeight = dropDownItemHeight + dropDownSpacerHeight private val dropDownHeaderHeight = dropDownAverageItemHeight + 5.dp @ExperimentalComposeUiApi @ExperimentalFoundationApi @ExperimentalCoroutinesApi @Composable fun <K> ComboPopup( title: String, selected: Triple<K, String, Color?>?, items: List<Triple<K, String, Color?>>, emptyItemsMessage: String = "None", width: Dp, popupMaxHeight: Dp = 560.dp, textFieldHeight: Dp = 56.dp, //Minimum height for a text field defined by compose onSelect: (Triple<K, String, Color?>) -> Unit, disabled: Boolean = false, controlOnLeft: Boolean = false, ) { val labelColor = MaterialTheme.colors.onSurface.let { val isLightColors = MaterialTheme.colors.isLight remember { val offset = if (isLightColors) .3f else -.3f it.copy(red = it.red + offset, blue = it.blue + offset, green = it.green + offset) } } val primaryColor = MaterialTheme.colors.primary val dropDownBackgroundColor: Color val textColor: Color if (MaterialTheme.colors.isLight) { dropDownBackgroundColor = dropDownBackgroundColorLight textColor = Color.Unspecified } else { dropDownBackgroundColor = dropDownBackgroundColorDark textColor = Color.White } val maxColumnWidth = width + dropDownButtonWidth val displayValue = if (items.isEmpty()) emptyItemsMessage else selected?.second ?: items[0].second var isPopupOpen by remember { mutableStateOf(false) } val openPopup = { if(items.isNotEmpty() && !disabled) { isPopupOpen = true } } val closePopup = { if(items.isNotEmpty() && !disabled) { isPopupOpen = false } } if (items.isNotEmpty() && !disabled && isPopupOpen) { val possibleHeight = dropDownHeaderHeight + (items.size * dropDownAverageItemHeight.value).dp openPopupWindow( title, labelColor, width, if (possibleHeight < popupMaxHeight) possibleHeight else popupMaxHeight, items, primaryColor, dropDownBackgroundColor, textColor, closePopup, onSelect, ) } Column( verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.CenterHorizontally, ) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, modifier = Modifier.width(maxColumnWidth) ) { if(controlOnLeft) { IconButton( modifier = Modifier.size(dropDownButtonWidth), onClick = openPopup, ) { Icon( Icons.Default.Menu, "Open", tint = primaryColor ) } Spacer(modifier = Modifier.width(10.dp)) } Box { TextField( value = displayValue, readOnly = true, enabled = !disabled, onValueChange = {}, singleLine = true, textStyle = selected?.third?.let { LocalTextStyle.current.copy(color = it) } ?: LocalTextStyle.current, label = { Text( title, color = labelColor ) }, modifier = Modifier.width(width).height(textFieldHeight) ) Box( modifier = Modifier .background(color = transparentColor) .height(textFieldHeight) .width(width) .clickable(onClick = openPopup) ) } if(!controlOnLeft) { Spacer(modifier = Modifier.width(10.dp)) IconButton( modifier = Modifier.size(dropDownButtonWidth), onClick = openPopup, ) { Icon( Icons.Default.Menu, "Open", tint = primaryColor ) } } } } } @ExperimentalComposeUiApi @ExperimentalFoundationApi @ExperimentalCoroutinesApi @Composable private fun <K> openPopupWindow( title: String, titleColor: Color, width: Dp, height: Dp, items: List<Triple<K, String, Color?>>, primaryColor: Color, dropDownBackgroundColor: Color, textColor: Color, onClose: () -> Unit, onSelect: (Triple<K, String, Color?>) -> Unit, ) { val dialogState = rememberDialogState(size = WindowSize(width, height), position = WindowPosition.Aligned(Alignment.Center)) Dialog( state = dialogState, title = title, onCloseRequest = onClose, undecorated = true, ) { GrimLocationsTheme { // val primaryColor = MaterialTheme.colors.primary // val dropDownBackgroundColor = MaterialTheme.colors.surface.let { remember { it.copy(alpha = ContainerAlpha) } } val scrollBarStyle = LocalScrollbarStyle.current.let { remember { it.copy( unhoverColor = primaryColor, hoverColor = primaryColor ) } } val stateVertical = rememberLazyListState() Surface( color = dropDownBackgroundColor, modifier = Modifier.fillMaxSize() ) { Column { Row( horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, modifier = Modifier.height(dropDownAverageItemHeight).fillMaxWidth() ) { Row { Spacer(modifier = Modifier.width(15.dp)) //Amount of padding between the left most bound of the text field and the first letter of text Text(text = title, color = titleColor) } IconButton( onClick = onClose, modifier = Modifier.size(30.dp) ) { Icon( Icons.Default.Close, "Close", tint = primaryColor ) } } Row { Spacer(modifier = Modifier.width(15.dp)) Box(modifier = Modifier.fillMaxWidth().height(1.dp).background(titleColor)) } Spacer(modifier = Modifier.height(dropDownSpacerHeight)) Box( modifier = Modifier .fillMaxSize() ) { LazyColumn(state = stateVertical) { items(items.size) { index -> val (_, text, color) = items[index] TextBox(text, color ?: textColor, width - 10.dp) { onSelect(items[index]) onClose() } Spacer(modifier = Modifier.height(dropDownSpacerHeight)) } } VerticalScrollbar( modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight(), adapter = rememberScrollbarAdapter( scrollState = stateVertical, ), style = scrollBarStyle ) } } } } } } @Composable private fun TextBox(text: String, textColor: Color, width: Dp, onClick: () -> Unit) { Box( modifier = Modifier.height(dropDownItemHeight) .width(width) .background(color = transparentColor) .clickable(onClick = onClick), contentAlignment = Alignment.CenterStart ) { Row { Spacer(modifier = Modifier.width(15.dp)) //Amount of padding between the left most bound of the text field and the first letter of text Text(text = text, color = textColor) } } }
0
Kotlin
0
6
b3626b643a39e2fb625a90f75b0288712da81ab2
10,172
Grim-Locations
MIT License
core/data/src/main/kotlin/cn/wj/android/cashbook/core/data/di/DataModule.kt
WangJie0822
365,932,300
false
{"Kotlin": 1658612, "Java": 1405038, "Batchfile": 535}
/* * Copyright 2021 The Cashbook 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 cn.wj.android.cashbook.core.data.di import cn.wj.android.cashbook.core.data.repository.AssetRepository import cn.wj.android.cashbook.core.data.repository.BooksRepository import cn.wj.android.cashbook.core.data.repository.RecordRepository import cn.wj.android.cashbook.core.data.repository.SettingRepository import cn.wj.android.cashbook.core.data.repository.TagRepository import cn.wj.android.cashbook.core.data.repository.TypeRepository import cn.wj.android.cashbook.core.data.repository.impl.AssetRepositoryImpl import cn.wj.android.cashbook.core.data.repository.impl.BooksRepositoryImpl import cn.wj.android.cashbook.core.data.repository.impl.RecordRepositoryImpl import cn.wj.android.cashbook.core.data.repository.impl.SettingRepositoryImpl import cn.wj.android.cashbook.core.data.repository.impl.TagRepositoryImpl import cn.wj.android.cashbook.core.data.repository.impl.TypeRepositoryImpl import cn.wj.android.cashbook.core.data.uitl.NetworkMonitor import cn.wj.android.cashbook.core.data.uitl.impl.ConnectivityManagerNetworkMonitor import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Suppress("unused") @Module @InstallIn(SingletonComponent::class) interface DataModule { @Binds fun bindNetworkMonitor( networkMonitor: ConnectivityManagerNetworkMonitor, ): NetworkMonitor @Binds fun bindTypeRepository( repository: TypeRepositoryImpl, ): TypeRepository @Binds fun bindTagRepository( repository: TagRepositoryImpl, ): TagRepository @Binds fun bindAssetRepository( repository: AssetRepositoryImpl, ): AssetRepository @Binds fun bindRecordRepository( repository: RecordRepositoryImpl, ): RecordRepository @Binds fun bindBooksRepository( repository: BooksRepositoryImpl, ): BooksRepository @Binds fun bindSettingRepository( repository: SettingRepositoryImpl, ): SettingRepository }
7
Kotlin
11
71
6c39b443a1e1e46cf3c4533db3ab270df1f1b9e8
2,627
Cashbook
Apache License 2.0
shakytweaks/src/main/java/com/mindsea/shakytweaks/ui/tweakgroups/TweakGroupsFragment.kt
MindSea
256,023,206
false
null
/* * MIT License * * Copyright (c) 2019 MindSea * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mindsea.shakytweaks.ui.tweakgroups import android.content.Context import android.os.Bundle import android.view.* import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.recyclerview.widget.DividerItemDecoration import com.mindsea.shakytweaks.R import com.mindsea.shakytweaks.ShakyTweaks import kotlinx.android.synthetic.main.fragment_tweak_groups.* internal class TweakGroupsFragment : Fragment() { private var listener: TweakGroupsFragmentListener? = null private lateinit var viewModel: TweakGroupsViewModel private lateinit var adapter: TweakGroupsAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { setHasOptionsMenu(true) return inflater.inflate(R.layout.fragment_tweak_groups, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupRecyclerView() val libraryModule = ShakyTweaks.module() viewModel = TweakGroupsViewModel(libraryModule.tweakProvider(), libraryModule.tweakValueResolver()) viewModel.onUpdate = this::updateView } override fun onDestroyView() { super.onDestroyView() viewModel.onUpdate = null } override fun onAttach(context: Context) { super.onAttach(context) if (context is TweakGroupsFragmentListener) { listener = context } else { throw RuntimeException("$context must implement TweakGroupsFragmentListener") } } override fun onDetach() { listener = null super.onDetach() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.tweaks_menu, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.menu_reset_tweaks -> { displayResetTweaksConfirmationDialog() true } else -> super.onOptionsItemSelected(item) } } private fun setupRecyclerView() { adapter = TweakGroupsAdapter() adapter.onTweakGroupSelected = { groupId -> listener?.onGroupSelected(groupId) } tweakGroupsRecyclerView.adapter = adapter tweakGroupsRecyclerView.addItemDecoration( DividerItemDecoration( context, DividerItemDecoration.VERTICAL ) ) } private fun updateView(state: TweakGroupsState) { adapter.setTweakGroups(state.groups) } private fun displayResetTweaksConfirmationDialog() = context?.let { AlertDialog.Builder(it) .setTitle(R.string.dialog_title) .setPositiveButton(R.string.dialog_confirm_action) { _, _ -> viewModel.resetTweaks() } .setNegativeButton(R.string.dialog_cancel_action) { _, _ -> // Do nothing } .create() .show() } interface TweakGroupsFragmentListener { fun onGroupSelected(groupId: String) } }
2
Kotlin
0
7
d67fdd19b354af37369052739013c8a384b55266
4,438
ShakyTweaksAndroid
MIT License
core/src/jvmMain/kotlin/zakadabar/stack/backend/setting/SettingProvider.kt
wiltonlazary
378,492,647
true
{"Kotlin": 1162402, "JavaScript": 2042, "HTML": 1390, "Shell": 506}
/* * Copyright © 2020-2021, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license. */ package zakadabar.stack.backend.setting import kotlinx.serialization.KSerializer import zakadabar.stack.data.BaseBo interface SettingProvider { fun <T : BaseBo> get(default: T, namespace: String, serializer: KSerializer<T>) : T }
0
null
0
0
1eabec93db32f09cf715048c6cffd0a7948f4d9c
369
zakadabar-stack
Apache License 2.0
shared/src/commonMain/kotlin/com/intive/picover/shared/images/view/ImagesScreen.kt
Android-Guild
719,500,100
false
{"Kotlin": 116975, "Swift": 760}
package com.intive.picover.shared.images.view import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells import androidx.compose.foundation.lazy.staggeredgrid.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.PhotoCamera import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.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.layout.ContentScale import androidx.compose.ui.unit.dp import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.koin.getScreenModel import com.intive.picover.shared.common.image.PicoverImage import com.intive.picover.shared.common.result.rememberTakePictureOrPickImageResultContract import com.intive.picover.shared.common.state.DefaultStateDispatcher import com.intive.picover.shared.common.uri.Uri import com.intive.picover.shared.images.viewmodel.ImagesViewModel import com.intive.picover.shared.photos.model.Photo class ImagesScreen : Screen { @Composable override fun Content() { val viewModel = getScreenModel<ImagesViewModel>() val state by viewModel.state.collectAsState() DefaultStateDispatcher( state = state.type, onRetryClick = null, ) { PhotosGrid(state.photos, viewModel::scheduleUploadPhoto) } } } @Composable private fun PhotosGrid(photos: List<Photo>, onImageTaken: (Uri) -> Unit) { val takePictureOrPickImageLauncher = rememberTakePictureOrPickImageResultContract(onImageTaken) Box(Modifier.fillMaxSize()) { LazyVerticalStaggeredGrid( columns = StaggeredGridCells.Adaptive(minSize = 120.dp), verticalItemSpacing = 4.dp, horizontalArrangement = Arrangement.spacedBy(4.dp), ) { items(photos) { PicoverImage( modifier = Modifier.size(it.width.dp, it.height.dp), imageModel = it.url, contentScale = ContentScale.Crop, ) } } FloatingActionButton( modifier = Modifier .padding(12.dp) .align(Alignment.BottomEnd), onClick = takePictureOrPickImageLauncher::invoke, containerColor = MaterialTheme.colorScheme.secondaryContainer, contentColor = MaterialTheme.colorScheme.secondary, ) { Icon(Icons.Filled.PhotoCamera, null) } } }
9
Kotlin
0
0
1f771fae115eb790b7e7b2140026b0dad2fcd27a
2,741
Picover-KMP
Apache License 2.0
app/src/main/java/com/isscroberto/onebreath/BaseView.kt
roberto-o-r
115,487,574
false
{"Kotlin": 17073}
package com.isscroberto.onebreath /** * Created by roberto.orozco on 07/02/2018. */ interface BaseView<T> { fun setPresenter(presenter: T); }
9
Kotlin
1
3
7e63289ff9d8567a6bf214c76f592b29b6d9a165
148
one-breath-android
MIT License
src/test/kotlin/com/ahmed/schedulebot/ScheduleBotApplicationTests.kt
Ahmed-no-oil
637,725,671
false
{"Kotlin": 42956, "Dockerfile": 298}
package com.ahmed.schedulebot import com.ahmed.schedulebot.entities.Week import com.ahmed.schedulebot.repositories.ScheduleEntryRepository import com.ahmed.schedulebot.repositories.WeekRepository import com.ahmed.schedulebot.services.ImageService import com.ahmed.schedulebot.services.ScheduleImageBuilder import io.mockk.mockk import io.mockk.every import io.mockk.verify import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.util.AssertionErrors.assertEquals @SpringBootTest( classes = [ScheduleBotApplication::class], webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT ) class ImageServiceTests { val scheduleEntryRepository= mockk<ScheduleEntryRepository>() val weekRepository= mockk<WeekRepository>() val scheduleImageBuilder= ScheduleImageBuilder() @Test fun givenNoScheduleData_whenCallingGetImage_thenNoImageIsCached() { // given: val arbitraryYear = 2024 val arbitraryWeekNumber =1 every { weekRepository.findByYearAndWeekNumber(arbitraryYear, arbitraryWeekNumber) } returns null every { scheduleEntryRepository.findByWeek(Week(arbitraryYear, arbitraryWeekNumber)) } returns null val imageService = ImageService(scheduleEntryRepository,weekRepository,scheduleImageBuilder) // when: val result: ByteArray = imageService.getImage(arbitraryYear, arbitraryWeekNumber) imageService.getImage(arbitraryYear, arbitraryWeekNumber) // then: assertEquals("The byte array from getImage", 0, result.size) //Verify that no caching has happened verify(exactly = 2) { weekRepository.findByYearAndWeekNumber(arbitraryYear, arbitraryWeekNumber) } } }
0
Kotlin
0
0
36c90866f9b7b3d3eff166a56961046b11c3f866
1,764
Schedule-Bot
MIT No Attribution
testomania/src/main/kotlin/com/earth/testomania/quiz_categories/usecase/GetQuizUseCase.kt
Nodrex
469,365,691
false
null
package com.earth.testomania.quiz_categories.usecase import com.earth.testomania.common.data.DataState import com.earth.testomania.common.data.ErrorMetaData import com.earth.testomania.common.data.LoadingMetaData import com.earth.testomania.common.data.SuccessMetaData import com.earth.testomania.common.log import com.earth.testomania.common.model.Quiz import com.earth.testomania.common.model.QuizUIState import kotlinx.coroutines.flow.* import java.util.concurrent.CancellationException abstract class GetQuizUseCase { abstract suspend fun getRepResult(): Flow<DataState<List<Quiz>>> abstract fun getAPIUrl(): String suspend operator fun invoke(): Flow<DataState<List<QuizUIState>>> = flow { try { emit(DataState.Loading(LoadingMetaData())) getRepResult().map { when (it) { is DataState.Success -> emit(success(it.payload)) is DataState.Error -> emit(error(it)) is DataState.Loading -> emit(loading(it)) } }.catch { emit(DataState.Error(ErrorMetaData(it.cause as Exception?))) }.collect() } catch (e: Exception) { if (e is CancellationException) throw e emit(DataState.Error(ErrorMetaData(e))) } } private fun success(list: List<Quiz>?): DataState.Success<List<QuizUIState>> { val quizUIStateList = mutableListOf<QuizUIState>() list?.forEach { if (it.correctAnswerCount == 0) logProblematicQuiz(it, "Without correct answer") else if (!it.hasMultiAnswer) { if (it.correctAnswerCount > 1) logProblematicQuiz( it, "Quiz is single choice, but has multiple correct answers" ) else quizUIStateList += QuizUIState(quiz = it) } //TODO hasMultiAnswer filter is temporarily to disable multi answer quiz, // but we wel remove this constraint for future on next releases of App } return DataState.Success( SuccessMetaData(), quizUIStateList ) } private fun error(dataState: DataState<List<Quiz>>) = DataState.Error( dataState.metaData as ErrorMetaData, emptyList<QuizUIState>() ) private fun loading(dataState: DataState<List<Quiz>>) = DataState.Loading( dataState.metaData as LoadingMetaData, emptyList<QuizUIState>() ) private fun logProblematicQuiz(quiz: Quiz, errorDescription: String) = log( """!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! |Problematic Quiz ($errorDescription) from: ${getAPIUrl()} | $quiz |"[Please report to API creators] ------------------------------------------------""" ) }
64
Kotlin
3
49
c91c7496ad2a8e4b499becb56c042f4e7480e012
2,925
Testomania
Creative Commons Zero v1.0 Universal
explanation/src/main/kotlin/explanation/Simulator.kt
pikalab-unibo-students
489,310,107
false
{"Kotlin": 250038, "HTML": 7328, "Python": 3746}
package explanation import core.Plan import core.State import explanation.impl.SimulatorImpl /** * A [Simulator] able to simulate the execution of a [Plan]. */ interface Simulator { /** * Method used to simulate the execution of a [Plan]. */ fun simulate(plan: Plan, state: State): List<State> companion object { /** * Factory method for a [Simulator] creation. */ fun of(): Simulator = SimulatorImpl() } }
5
Kotlin
1
0
351cf30081300f7f91b18b21c69fae365fee20a5
471
xaip-lib
Apache License 2.0
app/src/main/java/com/stocksexchange/android/data/repositories/freshdatahandlers/concrete/OrdersFreshDataHandlerImpl.kt
nscoincommunity
277,168,471
true
{"Kotlin": 2814235}
package com.stocksexchange.android.data.repositories.freshdatahandlers.concrete import com.stocksexchange.android.data.repositories.freshdatahandlers.interfaces.OrdersFreshDataHandler import com.stocksexchange.api.model.rest.parameters.OrderParameters class OrdersFreshDataHandlerImpl : AdvancedFreshDataHandlerImpl<OrderParameters>(), OrdersFreshDataHandler
0
null
0
0
52766afab4f96506a2d9ed34bf3564b6de7af8c3
364
Android-app
MIT License
server/src/main/kotlin/net/eiradir/server/persistence/DatabasePersistencePlugin.kt
Eiradir
635,460,745
false
null
package net.eiradir.server.persistence import com.badlogic.ashley.core.EntitySystem import net.eiradir.server.persistence.json.JsonInventoryStorage import net.eiradir.server.persistence.json.JsonCharacterStorage import net.eiradir.server.plugin.EiradirPlugin import org.koin.core.module.dsl.singleOf import org.koin.dsl.bind import org.koin.dsl.module class DatabasePersistencePlugin : EiradirPlugin { override fun provide() = module { singleOf(::DatabasePersistenceSystem) bind EntitySystem::class singleOf(::JsonCharacterStorage) bind CharacterStorage::class singleOf(::JsonInventoryStorage) bind InventoryStorage::class } }
12
Kotlin
0
0
7ae18b87a37ebd9f20766796b9fa94e2dd6dafc6
661
eiradir-server
MIT License
app/src/main/java/eu/kanade/tachiyomi/widget/NpaLinearLayoutManager.kt
icanit
46,806,713
true
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "YAML": 1, "Markdown": 3, "Proguard": 1, "Java": 54, "Kotlin": 141, "XML": 138}
package eu.kanade.tachiyomi.widget import android.content.Context import android.support.v7.widget.LinearLayoutManager import android.util.AttributeSet /** * No Predictive Animations LinearLayoutManager */ open class NpaLinearLayoutManager : LinearLayoutManager { constructor(context: Context): super(context) {} constructor(context: Context, orientation: Int, reverseLayout: Boolean) : super(context, orientation, reverseLayout) {} constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {} /** * Disable predictive animations. There is a bug in RecyclerView which causes views that * are being reloaded to pull invalid ViewHolders from the internal recycler stack if the * adapter size has decreased since the ViewHolder was recycled. */ override fun supportsPredictiveItemAnimations() = false }
0
Kotlin
0
2
29761a73793eed09bfbfe6b9b4216e99fbad01e6
945
mangafeed
Apache License 2.0
lib/src/jvmMain/kotlin/injection/Injection.kt
Aotios
854,360,247
false
{"Kotlin": 14077}
package injection import aotiosinject.summon fun <T> summon(): Lazy<T> = lazy { summon() }
2
Kotlin
0
0
585bbb7a2fbe9a01b37e381bcca3745c5e130ec8
92
aotios-inject
Apache License 2.0
application/KotlinConcepts/app/src/main/java/com/istudio/app/modules/module_demos/flows/modules/flow_basics/data/api/MockApiBehavior.kt
devrath
339,281,472
false
{"Kotlin": 478593, "Java": 3273}
package com.istudio.app.modules.module_demos.flows.modules.flow_basics.data.api import android.content.Context import com.google.gson.Gson import com.istudio.app.data.mock.MockNetworkInterceptor import com.istudio.app.data.mock.createFlowMockApi import com.istudio.app.data.mock.fakeCurrentStockPrices fun mockApi(context: Context) = createFlowMockApi( MockNetworkInterceptor() .mock( path = "/current-stock-prices", body = { Gson().toJson(fakeCurrentStockPrices(context)) }, status = 200, delayInMs = 1500, ) )
0
Kotlin
22
246
b87ccbc3cba789ec81744acde724274137204283
617
KotlinAlchemy
Apache License 2.0
http/src/main/java/wang/leal/ahel/http/upload/UploadService.kt
wangleal
186,962,942
false
{"Java": 263143, "Kotlin": 100023}
package wang.leal.ahel.http.upload import wang.leal.ahel.http.api.converter.ResponseHelper import wang.leal.ahel.http.api.create.HttpException import wang.leal.ahel.http.okhttp.OkHttpManager import io.reactivex.rxjava3.core.Observable import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.MultipartBody import okhttp3.Request import okhttp3.RequestBody.Companion.asRequestBody import java.io.File class UploadService(val url: String) { private val partList = mutableListOf<MultipartBody.Part>() fun image(name: String, image: File):UploadService{ return file(name, image, "image/*") } fun video(name: String, video: File):UploadService{ return file(name, video, "video/*") } fun audio(name: String, audio: File):UploadService{ return file(name, audio, "audio/*") } fun file(name: String, file: File):UploadService{ return file(name, file, "") } private fun file(name: String, file: File, mimeType: String):UploadService{ if (!file.exists()){ return this } val requestBody = file.asRequestBody(mimeType.toMediaTypeOrNull()) val part = if (name.isBlank()){ MultipartBody.Part.create(requestBody) }else{ MultipartBody.Part.createFormData(name, file.name, requestBody) } partList.add(part) return this } fun field(name: String, value: String):UploadService{ if (name.isBlank()||value.isBlank()){ return this } val part = MultipartBody.Part.createFormData(name, value) partList.add(part) return this } fun <T> upload(clazz: Class<T>): Observable<T> { return Observable.create{ val multipartBuilder: MultipartBody.Builder = MultipartBody.Builder() .setType(MultipartBody.FORM) partList.forEach { part -> multipartBuilder.addPart(part) } val requestBody = multipartBuilder.build() val request: Request = Request.Builder().url(url).post(requestBody).build() val response = OkHttpManager.uploadOkHttpClient.newCall(request).execute() if (response.isSuccessful){ it.onNext(ResponseHelper.convert(response.body,clazz)) }else{ it.onError(HttpException(response.code, response.message)) } } } }
1
Java
1
1
046797e64376cb2de93166db4940ed6b452c3944
2,443
AHEL
Apache License 2.0
app/src/main/java/com/littlegnal/accounting/ui/addedit/AddOrEditViewState.kt
littleGnAl
108,265,759
false
null
package com.littlegnal.accounting.ui.addedit import android.os.Parcelable import com.airbnb.mvrx.Async import com.airbnb.mvrx.MvRxState import com.airbnb.mvrx.Uninitialized import com.littlegnal.accounting.db.Accounting import kotlinx.android.parcel.Parcelize @Parcelize data class AddOrEditMvRxStateArgs(val id: Int = -1) : Parcelable data class AddOrEditMvRxViewState( val id: Int = -1, val amount: String? = null, val tagName: String? = null, val dateTime: String? = null, val remarks: String? = null, val accounting: Async<Accounting> = Uninitialized ) : MvRxState { constructor(args: AddOrEditMvRxStateArgs): this(id = args.id) }
0
Kotlin
8
30
253e4da6a95a10064a240670ae82b54ceb19e9c2
652
Accounting
Apache License 2.0
app/src/main/java/com/example/ranich/di/BackgroudModule.kt
NoraHeithur
791,614,008
false
{"Kotlin": 164741}
package com.example.ranich.di import android.app.Service import android.content.Context import com.example.ranich.common.NotificationMaster import com.example.ranich.common.NotificationMasterImpl import com.example.ranich.common.SensorObserverManager import com.example.ranich.common.SessionManager import com.example.ranich.common.SessionManagerImpl import com.example.ranich.data.MyFirebaseMessagingService import com.example.ranich.data.network.RanichApi import com.example.ranich.data.network.RanichServicesClient import com.example.ranich.data.network.UnsafeOkHttpClient import com.example.ranich.domain.common.SensorObserver import com.markodevcic.peko.PermissionRequester import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.koin.core.module.dsl.bind import org.koin.core.module.dsl.singleOf import org.koin.dsl.module import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory typealias DispatcherIO = CoroutineDispatcher val networkModule = module { singleOf(::provideMoshi) singleOf(::provideIOCoroutineDispatcher) singleOf(::provideHttpLoggingInterceptor) singleOf(::provideOkHttpClient) singleOf(::provideRetrofit) singleOf(::providePermissionRequestInstance) singleOf(::NotificationMasterImpl) { bind<NotificationMaster>() } singleOf(::RanichServicesClient) { bind<RanichApi>() } singleOf(::SensorObserverManager) { bind<SensorObserver>() } singleOf(::SessionManagerImpl) { bind<SessionManager>() } single<Service> { MyFirebaseMessagingService() } } private fun provideRetrofit( moshi: Moshi, client: OkHttpClient, ): Retrofit { return Retrofit.Builder() .baseUrl("https://172.16.17.32/api/v1/") .client(client) .addConverterFactory(MoshiConverterFactory.create(moshi)) .build() } private fun provideOkHttpClient( loggingInterceptor: HttpLoggingInterceptor, ): OkHttpClient { val unsafeOkHttpClient = UnsafeOkHttpClient return unsafeOkHttpClient.getUnsafeOkHttpClient() .addInterceptor(loggingInterceptor) .build() } private fun provideHttpLoggingInterceptor(): HttpLoggingInterceptor { return HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT) .setLevel(HttpLoggingInterceptor.Level.BODY) } private fun provideMoshi(): Moshi { return Moshi.Builder().add(KotlinJsonAdapterFactory()).build() } private fun provideIOCoroutineDispatcher(): DispatcherIO { return Dispatchers.IO } private fun providePermissionRequestInstance(context: Context): PermissionRequester { PermissionRequester.initialize(context) return PermissionRequester.instance() }
0
Kotlin
0
0
1bf6fe606862a7d29d2598f60d9abe89fba2b572
2,854
Ranich
MIT License
core/ui/src/main/kotlin/com/kevlina/budgetplus/core/ui/Switch.kt
kevinguitar
517,537,183
false
{"Kotlin": 686513}
package com.kevlina.budgetplus.core.ui import androidx.compose.material3.SwitchDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.kevlina.budgetplus.core.theme.LocalAppColors import com.kevlina.budgetplus.core.theme.ThemeColors import androidx.compose.material3.Switch as MaterialSwitch @Composable fun Switch( checked: Boolean, onCheckedChange: (Boolean) -> Unit, modifier: Modifier = Modifier, ) { MaterialSwitch( checked = checked, onCheckedChange = onCheckedChange, colors = SwitchDefaults.colors( checkedThumbColor = LocalAppColors.current.light, checkedTrackColor = LocalAppColors.current.dark, uncheckedThumbColor = LocalAppColors.current.dark, uncheckedTrackColor = LocalAppColors.current.light, uncheckedBorderColor = LocalAppColors.current.dark ), modifier = modifier ) } @Preview @Composable private fun Switch_Preview() = AppTheme(themeColors = ThemeColors.NemoSea) { var checked by remember { mutableStateOf(false) } Switch(checked = checked, onCheckedChange = { checked = !checked }) }
0
Kotlin
0
9
ba738370c0a04e5105c4907ac4aabeeb64cada1c
1,400
budgetplus-android
MIT License
app/src/main/java/dev/vdbroek/nekos/api/Api.kt
Pepijn98
128,682,310
false
{"Kotlin": 201259}
package dev.vdbroek.nekos.api import com.github.kittinunf.fuel.core.FuelError import com.google.gson.Gson import dev.vdbroek.nekos.models.ApiException import dev.vdbroek.nekos.models.HttpException import dev.vdbroek.nekos.utils.Response import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import okhttp3.OkHttpClient open class Api { val client = OkHttpClient() val coroutine = CoroutineScope(Dispatchers.IO) fun <T> handleException(exception: FuelError?, label: String = "UNKNOWN"): Response<T?, Exception> { return if (exception != null) { val httpException: HttpException? = try { Gson().fromJson(String(exception.errorData), HttpException::class.java) } catch (e: Exception) { null } Response(null, if (httpException != null) ApiException(httpException, label) else exception) } else { Response(null, Exception("[$label]: Invalid response from API")) } } }
0
Kotlin
3
14
bce519f49a76dae3938af8e5e194ec144b99f3e8
1,024
Nekos
MIT License
src/ui/MainFrame.kt
iamfacetheflames
376,225,731
false
null
package ui import data.Word import model.Configuration import model.Database import java.awt.Dimension import java.awt.EventQueue import java.awt.event.WindowAdapter import java.awt.event.WindowEvent import java.io.BufferedReader import java.io.InputStreamReader import javax.swing.JFrame import javax.swing.JMenuBar import javax.swing.JScrollPane import javax.swing.JTextArea import kotlin.system.exitProcess class Presenter( private val config: Configuration, private val database: Database ) { fun getLastWordList(): List<Word> { return database.getSomeLastWords() } fun getPopularWordList(): List<Word> = database.getMostFrequentWords() fun deleteWord(word: Word) { database.deleteWord(word) } fun initUi(frame: JFrame) { config.swingComponentStateFromConfigItem(frame) frame.isVisible = true } fun closeApp(frame: JFrame) { config.setSwingComponentState(frame) config.save() exitProcess(0) } fun requestData(dataForShow: ((String) -> Unit)) { try { primaryClipboard { clipboard -> database.saveWord(clipboard) translate(clipboard) { translated -> val dataForUi = translated + getPopularWordsInString() dataForShow.invoke(dataForUi) } } } catch (e: Exception) { exitProcess(1) } } fun translate(input: String, output: ((String) -> Unit)) { val command = "sdcv $input" val proc = Runtime.getRuntime().exec(command) val reader = BufferedReader(InputStreamReader(proc.inputStream)) val allText = reader.use(BufferedReader::readText) proc.waitFor() output.invoke(allText) } fun getPopularWordsInString(): String = getMostFrequentWordsInString(database) // apt-get install xclip sdcv private fun primaryClipboard(output: ((String) -> Unit)) { val command = "xclip -o" val proc = Runtime.getRuntime().exec(command) val reader = BufferedReader(InputStreamReader(proc.inputStream)) val allText = reader.use(BufferedReader::readText) proc.waitFor() val result = allText.trim().split(" ").firstOrNull() ?: "" output.invoke(result.toUpperCase()) } private fun getMostFrequentWordsInString(database: Database): String { val result = StringBuilder() for ((index, wordObject) in database.getMostFrequentWords().withIndex()) { wordObject.apply { val item = "#${index + 1}\t count=$numberSaves\t $word \n" result.append(item) } } return result.toString() } } class MainFrame(val presenter: Presenter) { private var frame: JFrame = JFrame() private lateinit var textArea: JTextArea init { createTextArea() frame.apply { pack() title = "clipdict" size = Dimension(800, 400) setLocationRelativeTo(null) addWindowListener(object : WindowAdapter() { override fun windowClosing(p0: WindowEvent?) { presenter.closeApp(frame) } }) } } fun showFrame() { presenter.requestData { text -> showText(text) createMenu() } presenter.initUi(frame) } private fun showText(text: String) { textArea.apply { selectAll() replaceSelection("") append(text) caretPosition = 0 } } private fun createTextArea() { textArea = JTextArea() textArea.lineWrap = true textArea.wrapStyleWord = true val scroll = JScrollPane( textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER ) frame.add(scroll) } private fun createMenu() { val menuBar = JMenuBar().apply { val deleteItems = mutableListOf<MenuItem>() presenter.getLastWordList().forEach { word -> deleteItems.add( MenuItem( word.word ) { presenter.deleteWord(word) EventQueue.invokeLater(::createMenu) } ) } val translateItems = mutableListOf<MenuItem>() presenter.getPopularWordList().forEach { word -> translateItems.add( MenuItem( word.word ) { presenter.translate(word.word) { text -> showText(text + presenter.getPopularWordsInString()) } } ) } addMenuGroup(MenuGroup( name = "Translate", items = translateItems )) addMenuGroup(MenuGroup( name = "Delete", items = deleteItems )) } frame.jMenuBar = menuBar frame.jMenuBar.revalidate() frame.jMenuBar.repaint() } }
0
Kotlin
0
0
eaf6f654f0d847620b20479a4f6dc4aeea5d7fbd
5,281
clipdict
Apache License 2.0
src/main/kotlin/com/coditory/gradle/build/JacocoConfiguration.kt
coditory
250,102,071
false
null
package com.coditory.gradle.build import org.gradle.api.Project import org.gradle.testing.jacoco.tasks.JacocoReport internal object JacocoConfiguration { fun configure(project: Project) { project.plugins.withId("jacoco") { project.tasks.withType(JacocoReport::class.java) { if (it.name == "jacocoTestReport") { it.executionData.setFrom(project.fileTree(project.buildDir).include("/jacoco/*.exec")) it.reports.xml.required.set(true) it.reports.html.required.set(true) } } } } }
0
Kotlin
0
2
3338ffc75c905a3f01c44f9c130c26585342918d
619
gradle-build-plugin
MIT License
app/src/main/java/io/github/edgardobarriam/techkandroidchallenge/ui/activity/GalleriesActivity.kt
edgardobarriam
148,704,226
true
{"Kotlin": 34163}
package io.github.edgardobarriam.techkandroidchallenge.ui.activity import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.MenuItem import io.github.edgardobarriam.techkandroidchallenge.R import io.github.edgardobarriam.techkandroidchallenge.ui.fragment.GalleriesFragment import kotlinx.android.synthetic.main.activity_tag_galleries.* /** * An activity representing a single Tag detail screen. This * activity is only used on narrow width devices. */ class GalleriesActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_tag_galleries) val tagName = intent.getStringExtra(GalleriesFragment.ARG_TAG_DISPLAY_NAME) setSupportActionBar(toolbar) supportActionBar?.title = tagName supportActionBar?.setDisplayHomeAsUpEnabled(true) // Show the Up button in the action bar. // savedInstanceState is non-null when there is fragment state // saved from previous configurations of this activity (when rotating the screen). // In this case, the fragment will automatically be re-added to its container. // http://developer.android.com/guide/components/fragments.html if (savedInstanceState == null) { setupGalleriesFragment() } } private fun setupGalleriesFragment() { val fragment = GalleriesFragment().apply { arguments = Bundle().apply { putString(GalleriesFragment.ARG_TAG_DISPLAY_NAME, intent.getStringExtra(GalleriesFragment.ARG_TAG_DISPLAY_NAME)) putString(GalleriesFragment.ARG_TAG_NAME, intent.getStringExtra(GalleriesFragment.ARG_TAG_NAME)) } } supportFragmentManager.beginTransaction() .add(R.id.tag_galleries_container, fragment) .commit() } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { android.R.id.home -> { // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. // http://developer.android.com/design/patterns/navigation.html#up-vs-back navigateUpTo(Intent(this, TagsActivity::class.java)) true } else -> super.onOptionsItemSelected(item) } }
0
Kotlin
0
1
abadcb984c9f2f852a7e29eca1f305403f2daf18
2,561
android-challenge
MIT License
app/src/main/java/com/example/apla/runpanyapp/viewmodels/product/ProductListViewModel.kt
yoko-yan
171,531,455
false
null
package com.example.apla.runpanyapp.viewmodels.product import android.app.Application import androidx.lifecycle.* import com.example.apla.runpanyapp.BaseApplication import com.example.apla.runpanyapp.data.DataRepository import com.example.apla.runpanyapp.data.local.db.entities.ProductEntity import com.example.apla.runpanyapp.viewmodels.BaseViewModel class ProductListViewModel(application: Application) : BaseViewModel(application) { private val mRepository: DataRepository // MediatorLiveData can observe other LiveData objects and react on their emissions. private val mObservableProducts: MediatorLiveData<List<ProductEntity>> /** * Expose the LiveData Products query so the UI can observe it. */ val products: LiveData<List<ProductEntity>> get() = mObservableProducts init { mObservableProducts = MediatorLiveData() // set by default null, until we get data from the database. mObservableProducts.value = null mRepository = (application as BaseApplication).getRepository() val products = mRepository.products // observe the changes of the products from the database and forward them mObservableProducts.addSource(products, mObservableProducts::setValue) } fun searchProducts(query: String): LiveData<List<ProductEntity>> { return mRepository.searchProducts(query) } /** * A creator is used to inject the product ID into the ViewModel * * * This creator is to showcase how to inject dependencies into ViewModels. It's not * actually necessary in this case, as the product ID can be passed in a public method. */ class Factory(private val mApplication: Application, private val mProductId: Int) : ViewModelProvider.NewInstanceFactory() { private val mRepository: DataRepository init { mRepository = (mApplication as BaseApplication).getRepository() } override fun <T : ViewModel> create(modelClass: Class<T>): T { return ProductListViewModel(mApplication) as T } } }
0
Kotlin
0
0
bfc020e4f207737af0ac9e240284d78b9ffbcea5
2,110
android-architecture-components-mvvm-kotlin
Apache License 2.0
bignum/src/commonTest/kotlin/com/ionspin/kotlin/bignum/integer/ByteArrayConversionTest.kt
ionspin
176,085,256
false
null
/* * Copyright 2019 <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.ionspin.kotlin.bignum.integer import com.ionspin.kotlin.bignum.integer.base63.array.BigInteger63Arithmetic import kotlin.test.Ignore import kotlin.test.Test import kotlin.test.assertTrue /** * Created by <NAME> * <EMAIL> * on 31-Jul-2019 */ class ByteArrayConversionTest { @Ignore // Travis can't run this test on JS for some reason but they pass locally. @Test fun testToAndFromByteArray() { assertTrue { val bigIntOriginal = BigInteger.fromULong(ULong.MAX_VALUE) val byteArray = bigIntOriginal.toUByteArray() val reconstructed = BigInteger.fromUByteArray(byteArray, Sign.POSITIVE) bigIntOriginal == reconstructed } assertTrue { val bigIntOriginal = BigInteger.fromLong(Long.MIN_VALUE) val byteArray = bigIntOriginal.toUByteArray() val reconstructed = BigInteger.fromUByteArray(byteArray, Sign.NEGATIVE) bigIntOriginal.equals(reconstructed) } assertTrue { val bigIntOriginal = BigInteger.fromULong(ULong.MAX_VALUE) + BigInteger.fromULong(ULong.MAX_VALUE) val byteArray = bigIntOriginal.toUByteArray() val reconstructed = BigInteger.fromUByteArray(byteArray, Sign.POSITIVE) bigIntOriginal.equals(reconstructed) } } @Test fun toUByteArray() { assertTrue { val expected = ubyteArrayOf( 0x00U, 0x11U, 0x22U, 0x33U, 0x44U, 0x55U, 0x66U, 0x77U, 0x88U, 0x99U, 0xAAU, 0xBBU, 0xCCU, 0xDDU, 0xEEU, 0xFFU ) val bigIntOriginal = BigInteger.parseString("00112233445566778899AABBCCDDEEFF", 16) val byteArray = bigIntOriginal.toUByteArray() byteArray.contentEquals(expected) } } @Test fun fromUByteArray() { assertTrue { val expected = BigInteger.parseString("112233445566778899AABBCCDDEEFF00", 16) val bigInt = BigInteger.fromUByteArray( ubyteArrayOf( 0x11U, 0x22U, 0x33U, 0x44U, 0x55U, 0x66U, 0x77U, 0x88U, 0x99U, 0xAAU, 0xBBU, 0xCCU, 0xDDU, 0xEEU, 0xFFU, 0x00U ), Sign.POSITIVE ) bigInt == expected } } @Test fun testConversionFrom64bit() { assertTrue { val input = ulongArrayOf(0b1111000000000000000000000000000000000000000000000000000000011111UL) val expected = ulongArrayOf(0b0111000000000000000000000000000000000000000000000000000000011111UL, 0b1UL) val result = BigInteger63Arithmetic.convertFrom64BitRepresentation(input) expected.contentEquals(result) } assertTrue { val input = ulongArrayOf(0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b101UL) val expected = ulongArrayOf(0b0111000000000000000000000000000000000000000000000000000000011111UL, 0b1011UL) val result = BigInteger63Arithmetic.convertFrom64BitRepresentation(input) expected.contentEquals(result) } assertTrue { val input = ulongArrayOf( 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL ) val expected = ulongArrayOf( 0b0111000000000000000000000000000000000000000000000000000000011111UL, 0b0110000000000000000000000000000000000000000000000000000000111111UL, 0b11UL ) val result = BigInteger63Arithmetic.convertFrom64BitRepresentation(input) expected.contentEquals(result) } assertTrue { val input = ulongArrayOf( 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL, 0b1111000000000000000000000000000000000000000000000000000000011111UL ) val expected = ulongArrayOf( 0b0111000000000000000000000000000000000000000000000000000000011111UL, 0b0110000000000000000000000000000000000000000000000000000000111111UL, 0b0100000000000000000000000000000000000000000000000000000001111111UL, 0b0000000000000000000000000000000000000000000000000000000011111111UL, 0b0000000000000000000000000000000000000000000000000000000111111111UL, 0b0000000000000000000000000000000000000000000000000000001111111110UL, 0b0000000000000000000000000000000000000000000000000000011111111100UL, 0b0000000000000000000000000000000000000000000000000000111111111000UL, 0b0000000000000000000000000000000000000000000000000001111111110000UL, 0b0000000000000000000000000000000000000000000000000011111111100000UL, 0b0000000000000000000000000000000000000000000000000111111111000000UL, 0b0000000000000000000000000000000000000000000000001111111110000000UL, 0b0000000000000000000000000000000000000000000000011111111100000000UL, 0b0000000000000000000000000000000000000000000000111111111000000000UL, 0b0000000000000000000000000000000000000000000001111111110000000000UL, 0b0000000000000000000000000000000000000000000011111111100000000000UL, 0b0000000000000000000000000000000000000000000111111111000000000000UL, 0b0000000000000000000000000000000000000000001111111110000000000000UL, 0b0000000000000000000000000000000000000000011111111100000000000000UL, 0b0000000000000000000000000000000000000000111111111000000000000000UL, 0b0000000000000000000000000000000000000001111111110000000000000000UL, 0b0000000000000000000000000000000000000011111111100000000000000000UL, 0b0000000000000000000000000000000000000111111111000000000000000000UL, 0b0000000000000000000000000000000000001111111110000000000000000000UL, 0b0000000000000000000000000000000000011111111100000000000000000000UL, 0b0000000000000000000000000000000000111111111000000000000000000000UL, 0b0000000000000000000000000000000001111111110000000000000000000000UL, 0b0000000000000000000000000000000011111111100000000000000000000000UL, 0b0000000000000000000000000000000111111111000000000000000000000000UL, 0b0000000000000000000000000000001111111110000000000000000000000000UL, 0b0000000000000000000000000000011111111100000000000000000000000000UL, 0b0000000000000000000000000000111111111000000000000000000000000000UL, 0b0000000000000000000000000001111111110000000000000000000000000000UL, 0b0000000000000000000000000011111111100000000000000000000000000000UL, 0b0000000000000000000000000111111111000000000000000000000000000000UL, 0b0000000000000000000000001111111110000000000000000000000000000000UL, 0b0000000000000000000000011111111100000000000000000000000000000000UL, 0b0000000000000000000000111111111000000000000000000000000000000000UL, 0b0000000000000000000001111111110000000000000000000000000000000000UL, 0b0000000000000000000011111111100000000000000000000000000000000000UL, 0b0000000000000000000111111111000000000000000000000000000000000000UL, 0b0000000000000000001111111110000000000000000000000000000000000000UL, 0b0000000000000000011111111100000000000000000000000000000000000000UL, 0b0000000000000000111111111000000000000000000000000000000000000000UL, 0b0000000000000001111111110000000000000000000000000000000000000000UL, 0b0000000000000011111111100000000000000000000000000000000000000000UL, 0b0000000000000111111111000000000000000000000000000000000000000000UL, 0b0000000000001111111110000000000000000000000000000000000000000000UL, 0b0000000000011111111100000000000000000000000000000000000000000000UL, 0b0000000000111111111000000000000000000000000000000000000000000000UL, 0b0000000001111111110000000000000000000000000000000000000000000000UL, 0b0000000011111111100000000000000000000000000000000000000000000000UL, 0b0000000111111111000000000000000000000000000000000000000000000000UL, 0b0000001111111110000000000000000000000000000000000000000000000000UL, 0b0000011111111100000000000000000000000000000000000000000000000000UL, 0b0000111111111000000000000000000000000000000000000000000000000000UL, 0b0001111111110000000000000000000000000000000000000000000000000000UL, 0b0011111111100000000000000000000000000000000000000000000000000000UL, 0b0111111111000000000000000000000000000000000000000000000000000000UL, 0b0111111110000000000000000000000000000000000000000000000000000000UL, 0b0111111100000000000000000000000000000000000000000000000000000001UL, 0b0111111000000000000000000000000000000000000000000000000000000011UL, 0b0111110000000000000000000000000000000000000000000000000000000111UL, 0b0111100000000000000000000000000000000000000000000000000000001111UL, 0b0111000000000000000000000000000000000000000000000000000000011111UL, 0b0110000000000000000000000000000000000000000000000000000000111111UL, 0b0100000000000000000000000000000000000000000000000000000001111111UL, 0b0000000000000000000000000000000000000000000000000000000011111111UL, 0b0000000000000000000000000000000000000000000000000000000000001111UL ) val result = BigInteger63Arithmetic.convertFrom64BitRepresentation(input) expected.contentEquals(result) } } @Test fun fromUByteArraySpecific() { assertTrue { val uByteArray = "19191919191919191919191919191919".chunked(2).map { it.toUByte(16) }.toUByteArray() val bigInt = BigInteger.fromUByteArray( uByteArray, Sign.POSITIVE ) val reconstructed = bigInt.toUByteArray() uByteArray.contentEquals(reconstructed) } } @Test fun testTwosComplementHelperConversion() { } }
27
null
42
366
e2ec7901443ace456ca457fc70b9707b9e0af478
16,856
kotlin-multiplatform-bignum
Apache License 2.0
common/src/main/kotlin/toshio/network/Network.kt
gtosh4
435,545,152
false
null
package toshio.network import net.minecraft.world.level.Level import toshio.connector.Cable import java.util.concurrent.ConcurrentHashMap import toshio.connector.ConnectorEntity import toshio.part.Part import java.util.function.Predicate class Network { private val cables = ConcurrentHashMap.newKeySet<Cable>() private val connectors = ConcurrentHashMap.newKeySet<ConnectorEntity>() private var lastTick: Long = 0 fun addCable(cable: Cable) = cables.add(cable) fun removeCable(cable: Cable) = cables.remove(cable) fun removeCable(predicate: Predicate<Cable>) = cables.removeIf(predicate) fun addConnector(connector: ConnectorEntity) = connectors.add(connector) fun removeConnector(connector: ConnectorEntity) = connectors.remove(connector) fun removeConnector(predicate: Predicate<ConnectorEntity>) = connectors.removeIf(predicate) operator fun plus(other: Network): Network { val net = Network() net.cables.addAll(other.cables) net.cables.addAll(this.cables) net.connectors.addAll(other.connectors) net.connectors.addAll(this.connectors) return net } operator fun plus(cable: Cable) = this.also { addCable(cable) } operator fun plus(connector: ConnectorEntity) = this.also { addConnector(connector) } fun tick(level: Level?) { if (level?.isClientSide != false) return if (lastTick == level.gameTime) return lastTick = level.gameTime } }
0
Kotlin
0
0
92c052ac9b8a2f66c5312d2b649f1562785f31d3
1,478
Tosh-IO
MIT License
modules/model/model/src/main/java/com/project/model/SearchModel.kt
dev-darck
499,210,154
false
null
package com.project.model interface SearchModel { fun isEmpty(): Boolean }
1
Kotlin
0
0
d6b0e8f79a8b229f7cec3907547bd05b01af606d
79
PicPicker
Apache License 2.0
graphql-dgs-codegen-core/src/main/kotlin/com/netflix/graphql/dgs/codegen/generators/kotlin/KotlinDataTypeGenerator.kt
deweyjose
337,171,389
true
{"Kotlin": 304095, "Java": 4151, "Dockerfile": 244}
/* * * Copyright 2020 Netflix, Inc. * * 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.netflix.graphql.dgs.codegen.generators.kotlin import com.netflix.graphql.dgs.codegen.CodeGenConfig import com.netflix.graphql.dgs.codegen.KotlinCodeGenResult import com.netflix.graphql.dgs.codegen.filterSkipped import com.netflix.graphql.dgs.codegen.shouldSkip import com.squareup.kotlinpoet.* import graphql.language.* @ExperimentalStdlibApi class KotlinDataTypeGenerator(private val config: CodeGenConfig, private val document: Document): AbstractKotlinDataTypeGenerator(config) { private val typeUtils = KotlinTypeUtils(getPackageName(), config) fun generate(definition: ObjectTypeDefinition, extensions: List<ObjectTypeExtensionDefinition>): KotlinCodeGenResult { if(definition.shouldSkip()) { return KotlinCodeGenResult() } val fields = definition.fieldDefinitions .filterSkipped() .filter(ReservedKeywordFilter.filterInvalidNames) .map { Field(it.name, typeUtils.findReturnType(it.type), typeUtils.isNullable(it.type)) } .plus(extensions.flatMap { it.fieldDefinitions } .filterSkipped() .map { Field(it.name, typeUtils.findReturnType(it.type), typeUtils.isNullable(it.type)) }) val interfaces = definition.implements return generate(definition.name, fields, interfaces, false, document) } override fun getPackageName(): String { return config.packageName + ".types" } } @ExperimentalStdlibApi class KotlinInputTypeGenerator(private val config: CodeGenConfig, private val document: Document): AbstractKotlinDataTypeGenerator(config) { private val typeUtils = KotlinTypeUtils(getPackageName(), config) fun generate(definition: InputObjectTypeDefinition, extensions: List<InputObjectTypeExtensionDefinition>): KotlinCodeGenResult { val fields = definition.inputValueDefinitions .filter(ReservedKeywordFilter.filterInvalidNames) .map { val defaultValue: Any if (it.defaultValue != null) { defaultValue = when (it.defaultValue) { is BooleanValue -> (it.defaultValue as BooleanValue).isValue is IntValue -> (it.defaultValue as IntValue).value is StringValue -> (it.defaultValue as StringValue).value is FloatValue -> (it.defaultValue as FloatValue).value else -> it.defaultValue } Field(it.name, typeUtils.findReturnType(it.type), typeUtils.isNullable(it.type), defaultValue) } else { Field(it.name, typeUtils.findReturnType(it.type), typeUtils.isNullable(it.type)) } }.plus(extensions.flatMap { it.inputValueDefinitions }.map { Field(it.name, typeUtils.findReturnType(it.type), typeUtils.isNullable(it.type)) }) val interfaces = emptyList<Type<*>>() return generate(definition.name, fields, interfaces, true, document) } override fun getPackageName(): String { return config.packageName + ".types" } } internal data class Field(val name: String, val type: com.squareup.kotlinpoet.TypeName, val nullable: Boolean, val default: Any? = null) abstract class AbstractKotlinDataTypeGenerator(private val config: CodeGenConfig) { internal fun generate(name: String, fields: List<Field>, interfaces: List<Type<*>>, isInputType: Boolean, document: Document): KotlinCodeGenResult { val kotlinType = TypeSpec.classBuilder(name) if(fields.isNotEmpty()) { kotlinType.addModifiers(KModifier.DATA) } val constructorBuilder = FunSpec.constructorBuilder() val interfaceTypes = document.getDefinitionsOfType(InterfaceTypeDefinition::class.java) if (interfaceTypes.isNotEmpty()) { kotlinType.addAnnotation(disableJsonTypeInfoAnnotation()) } fields.forEach { field -> val returnType = if(field.nullable) field.type.copy(nullable = true) else field.type val parameterSpec = ParameterSpec.builder(field.name, returnType) .addAnnotation(jsonPropertyAnnotation(field.name)) if (field.default != null) { val initializerBlock = if (field.type.toString().contains("String")) { "\"${field.default}\"" } else { "${field.default}" } parameterSpec.defaultValue(initializerBlock) } else { when (returnType) { STRING -> if (field.nullable) parameterSpec.defaultValue("null") INT -> if (field.nullable) parameterSpec.defaultValue("null") FLOAT -> if (field.nullable) parameterSpec.defaultValue("null") DOUBLE -> if (field.nullable) parameterSpec.defaultValue("null") BOOLEAN -> if (field.nullable) parameterSpec.defaultValue("null") else -> if (field.nullable) parameterSpec.defaultValue("null") } } val interfaceNames = interfaces.map { it as NamedNode<*> }.map { it.name }.toSet() val implementedInterfaces = interfaceTypes.filter { interfaceNames.contains(it.name) } val interfaceFields = implementedInterfaces.flatMap { it.fieldDefinitions }.map { it.name }.toSet() if (interfaceFields.contains(field.name)) { parameterSpec.addModifiers(KModifier.OVERRIDE) } constructorBuilder.addParameter(parameterSpec.build()) val propertySpecBuilder = PropertySpec.builder(field.name, returnType) propertySpecBuilder.initializer(field.name) kotlinType.addProperty(propertySpecBuilder.build()) } val unionTypes = document.getDefinitionsOfType(UnionTypeDefinition::class.java).filter { union -> union.memberTypes.map { it as graphql.language.TypeName }.map { it.name }.contains(name) } interfaces.plus(unionTypes).forEach { if(it is NamedNode<*>) { kotlinType.addSuperinterface(ClassName.bestGuess("${getPackageName()}.${it.name}")) } } kotlinType.primaryConstructor(constructorBuilder.build()) if (isInputType) { kotlinType.addFunction(FunSpec.builder("toString") .returns(STRING) .addCode(addToString(fields, kotlinType)) .addModifiers(KModifier.PUBLIC) .addModifiers(KModifier.OVERRIDE) .build()) } val typeSpec = kotlinType.build() val fileSpec = FileSpec.builder(getPackageName(), typeSpec.name!!).addType(typeSpec).build() return KotlinCodeGenResult(listOf(fileSpec)) } private fun addToString(fields: List<Field>, kotlinType: TypeSpec.Builder): String { val toStringBody = StringBuilder("return \"{\" + ") fields.mapIndexed { index, field -> when (val fieldTypeName = field.type) { is ParameterizedTypeName -> { if (fieldTypeName.typeArguments[0] is ClassName && (fieldTypeName.typeArguments[0] as ClassName).simpleName == STRING.simpleName) { addToStringForListOfStrings(field, kotlinType) """ "${field.name}:" + serializeListOfStrings(${field.name}) + "${if (index < fields.size - 1) "," else ""}" + """.trimIndent() } else { defaultString(field, index, fields) } } is ClassName -> { when(fieldTypeName.simpleName) { STRING.simpleName -> { if (field.nullable) { """ "${field.name}:" + "${'$'}{if(${field.name} != null) "\"" else ""}" + ${field.name} + "${'$'}{if(${field.name} != null) "\"" else ""}" + "${if (index < fields.size - 1) "," else ""}" + """.trimIndent() } else { """ "${field.name}:" + "\"" + ${field.name} + "\"" + "${if (index < fields.size - 1) "," else ""}" + """.trimIndent() } } else -> { defaultString(field, index, fields) } } } else -> { defaultString(field, index, fields) } } }.forEach { toStringBody.append(it)} return toStringBody.append(""" "}" """.trimIndent()).toString() } private fun defaultString(field: Field, index: Int, fields: List<Field>): String { return """ "${field.name}:" + ${field.name} + "${if (index < fields.size - 1) "," else ""}" + """.trimIndent() } private fun addToStringForListOfStrings(field: Field, kotlinType: TypeSpec.Builder) { if (kotlinType.funSpecs.any { it.name == "serializeListOfStrings" }) return val methodBuilder = FunSpec.builder("serializeListOfStrings") .addModifiers(KModifier.PRIVATE) .addParameter(field.name, field.type) .returns(STRING.copy(nullable = true)) val toStringBody = StringBuilder() if (field.nullable) { toStringBody.append(""" if (${field.name} == null) { return null } """.trimIndent() ) } toStringBody.append( """ val builder = java.lang.StringBuilder() builder.append("[") if (! ${field.name}.isEmpty()) { val result = ${field.name}.joinToString() {"\"" + it + "\""} builder.append(result) } builder.append("]") return builder.toString() """.trimIndent() ) methodBuilder.addStatement(toStringBody.toString()) kotlinType.addFunction(methodBuilder.build()) } abstract fun getPackageName(): String }
0
null
0
0
d41bba9a05f5cbdf8a3bec781d3444781acbc765
11,058
dgs-codegen
Apache License 2.0
src/main/kotlin/dokerplp/bot/controller/UpdateHandler.kt
dokerplp
407,882,967
false
{"Kotlin": 55171}
package dokerplp.bot.controller import dokerplp.bot.controller.handler.HandleInvoker import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component import org.telegram.telegrambots.meta.api.methods.PartialBotApiMethod import org.telegram.telegrambots.meta.api.objects.Message import org.telegram.telegrambots.meta.api.objects.Update @Component class UpdateHandler( @Autowired val invoker: HandleInvoker ) { fun newUpdate(update: Update): Array<PartialBotApiMethod<Message>>? { if (update.hasMessage()) { val message = update.message if (message.hasText()) { return invoker.handleText(update) } else if (message.hasVoice()) { return invoker.handleVoice(update) } } else if (update.hasCallbackQuery()) { return invoker.handleCallBack(update) } return null } }
0
Kotlin
0
0
b3c530a3c7aff82a9072348ba036b364f33d0769
943
abit-vt-bot
Apache License 2.0
src/main/kotlin/org/wfanet/measurement/kingdom/batch/MeasurementSystemProber.kt
world-federation-of-advertisers
349,561,061
false
{"Kotlin": 10143809, "Starlark": 951001, "C++": 627937, "CUE": 193010, "HCL": 162357, "TypeScript": 101485, "Python": 77600, "Shell": 20877, "CSS": 9620, "Go": 8063, "JavaScript": 5305, "HTML": 2489}
/* * Copyright 2023 The Cross-Media Measurement Authors * * 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.wfanet.measurement.kingdom.batch import com.google.protobuf.Any import com.google.type.interval import io.grpc.StatusException import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import io.opentelemetry.api.metrics.DoubleGauge import java.io.File import java.security.SecureRandom import java.time.Clock import java.time.Duration import java.util.logging.Logger import org.wfanet.measurement.api.v2alpha.CanonicalRequisitionKey import org.wfanet.measurement.api.v2alpha.DataProvider import org.wfanet.measurement.api.v2alpha.DataProvidersGrpcKt import org.wfanet.measurement.api.v2alpha.EventGroup import org.wfanet.measurement.api.v2alpha.EventGroupsGrpcKt import org.wfanet.measurement.api.v2alpha.ListEventGroupsRequestKt import org.wfanet.measurement.api.v2alpha.ListMeasurementsResponse import org.wfanet.measurement.api.v2alpha.ListRequisitionsResponse import org.wfanet.measurement.api.v2alpha.Measurement import org.wfanet.measurement.api.v2alpha.MeasurementConsumer import org.wfanet.measurement.api.v2alpha.MeasurementConsumersGrpcKt import org.wfanet.measurement.api.v2alpha.MeasurementKt import org.wfanet.measurement.api.v2alpha.MeasurementKt.dataProviderEntry import org.wfanet.measurement.api.v2alpha.MeasurementSpecKt import org.wfanet.measurement.api.v2alpha.MeasurementSpecKt.vidSamplingInterval import org.wfanet.measurement.api.v2alpha.Requisition import org.wfanet.measurement.api.v2alpha.RequisitionSpecKt import org.wfanet.measurement.api.v2alpha.RequisitionSpecKt.EventGroupEntryKt import org.wfanet.measurement.api.v2alpha.RequisitionSpecKt.eventGroupEntry import org.wfanet.measurement.api.v2alpha.RequisitionsGrpcKt import org.wfanet.measurement.api.v2alpha.createMeasurementRequest import org.wfanet.measurement.api.v2alpha.differentialPrivacyParams import org.wfanet.measurement.api.v2alpha.getDataProviderRequest import org.wfanet.measurement.api.v2alpha.getMeasurementConsumerRequest import org.wfanet.measurement.api.v2alpha.listEventGroupsRequest import org.wfanet.measurement.api.v2alpha.listMeasurementsRequest import org.wfanet.measurement.api.v2alpha.listRequisitionsRequest import org.wfanet.measurement.api.v2alpha.measurement import org.wfanet.measurement.api.v2alpha.measurementSpec import org.wfanet.measurement.api.v2alpha.requisitionSpec import org.wfanet.measurement.api.v2alpha.unpack import org.wfanet.measurement.api.withAuthenticationKey import org.wfanet.measurement.common.Instrumentation import org.wfanet.measurement.common.crypto.Hashing import org.wfanet.measurement.common.crypto.SigningKeyHandle import org.wfanet.measurement.common.crypto.readCertificate import org.wfanet.measurement.common.crypto.readPrivateKey import org.wfanet.measurement.common.readByteString import org.wfanet.measurement.common.toInstant import org.wfanet.measurement.common.toProtoTime import org.wfanet.measurement.consent.client.measurementconsumer.encryptRequisitionSpec import org.wfanet.measurement.consent.client.measurementconsumer.signMeasurementSpec import org.wfanet.measurement.consent.client.measurementconsumer.signRequisitionSpec class MeasurementSystemProber( private val measurementConsumerName: String, private val dataProviderNames: List<String>, private val apiAuthenticationKey: String, private val privateKeyDerFile: File, private val measurementLookbackDuration: Duration, private val durationBetweenMeasurement: Duration, private val measurementConsumersStub: MeasurementConsumersGrpcKt.MeasurementConsumersCoroutineStub, private val measurementsStub: org.wfanet.measurement.api.v2alpha.MeasurementsGrpcKt.MeasurementsCoroutineStub, private val dataProvidersStub: DataProvidersGrpcKt.DataProvidersCoroutineStub, private val eventGroupsStub: EventGroupsGrpcKt.EventGroupsCoroutineStub, private val requisitionsStub: RequisitionsGrpcKt.RequisitionsCoroutineStub, private val clock: Clock = Clock.systemUTC(), ) { private val lastTerminalMeasurementTimeGauge: DoubleGauge = Instrumentation.meter .gaugeBuilder("${PROBER_NAMESPACE}.last_terminal_measurement.timestamp") .setUnit("s") .setDescription( "Unix epoch timestamp (in seconds) of the update time of the most recently issued and completed prober Measurement" ) .build() private val lastTerminalRequisitionTimeGauge: DoubleGauge = Instrumentation.meter .gaugeBuilder("${PROBER_NAMESPACE}.last_terminal_requisition.timestamp") .setUnit("s") .setDescription( "Unix epoch timestamp (in seconds) of the update time of requisition associated with a particular EDP for the most recently issued Measurement" ) .build() suspend fun run() { val lastUpdatedMeasurement = getLastUpdatedMeasurement() if (lastUpdatedMeasurement != null) { updateLastTerminalRequisitionGauge(lastUpdatedMeasurement) lastTerminalMeasurementTimeGauge.set( lastUpdatedMeasurement.updateTime.toInstant().toEpochMilli() / MILLISECONDS_PER_SECOND ) } if (shouldCreateNewMeasurement(lastUpdatedMeasurement)) { createMeasurement() } } private suspend fun createMeasurement() { val dataProviderNameToEventGroup: Map<String, EventGroup> = buildDataProviderNameToEventGroup(dataProviderNames, dataProvidersStub, apiAuthenticationKey) val measurementConsumer: MeasurementConsumer = try { measurementConsumersStub .withAuthenticationKey(apiAuthenticationKey) .getMeasurementConsumer(getMeasurementConsumerRequest { name = measurementConsumerName }) } catch (e: StatusException) { throw Exception("Unable to get measurement consumer $measurementConsumerName", e) } val measurementConsumerCertificate = readCertificate(measurementConsumer.certificateDer) val measurementConsumerPrivateKey = readPrivateKey( privateKeyDerFile.readByteString(), measurementConsumerCertificate.publicKey.algorithm, ) val measurementConsumerSigningKey = SigningKeyHandle(measurementConsumerCertificate, measurementConsumerPrivateKey) val packedMeasurementEncryptionPublicKey = measurementConsumer.publicKey.message val measurement = measurement { this.measurementConsumerCertificate = measurementConsumer.certificate dataProviders += dataProviderNames.map { getDataProviderEntry( it, dataProviderNameToEventGroup[it]!!, measurementConsumerSigningKey, packedMeasurementEncryptionPublicKey, ) } val unsignedMeasurementSpec = measurementSpec { measurementPublicKey = packedMeasurementEncryptionPublicKey nonceHashes += [email protected] { it.value.nonceHash } vidSamplingInterval = vidSamplingInterval { start = 0f width = 1f } reachAndFrequency = MeasurementSpecKt.reachAndFrequency { reachPrivacyParams = differentialPrivacyParams { epsilon = 0.005 delta = 1e-15 } frequencyPrivacyParams = differentialPrivacyParams { epsilon = 0.005 delta = 1e-15 } maximumFrequency = 1 } } this.measurementSpec = signMeasurementSpec(unsignedMeasurementSpec, measurementConsumerSigningKey) } val response = try { measurementsStub .withAuthenticationKey(apiAuthenticationKey) .createMeasurement( createMeasurementRequest { this.parent = measurementConsumerName this.measurement = measurement } ) } catch (e: StatusException) { throw Exception("Unable to create a prober measurement", e) } logger.info( "A new prober measurement for measurement consumer $measurementConsumerName is created: $response" ) } private suspend fun buildDataProviderNameToEventGroup( dataProviderNames: List<String>, dataProvidersStub: DataProvidersGrpcKt.DataProvidersCoroutineStub, apiAuthenticationKey: String, ): MutableMap<String, EventGroup> { val dataProviderNameToEventGroup = mutableMapOf<String, EventGroup>() for (dataProviderName in dataProviderNames) { val getDataProviderRequest = getDataProviderRequest { name = dataProviderName } val dataProvider: DataProvider = try { dataProvidersStub .withAuthenticationKey(apiAuthenticationKey) .getDataProvider(getDataProviderRequest) } catch (e: StatusException) { throw Exception("Unable to get DataProvider with name $dataProviderName", e) } // TODO(@roaminggypsy): Implement QA event group logic using simulatorEventGroupName val listEventGroupsRequest = listEventGroupsRequest { parent = dataProviderName filter = ListEventGroupsRequestKt.filter { measurementConsumers += measurementConsumerName dataProviders += dataProviderName } } val eventGroups: List<EventGroup> = try { eventGroupsStub .withAuthenticationKey(apiAuthenticationKey) .listEventGroups(listEventGroupsRequest) .eventGroupsList .toList() } catch (e: StatusException) { throw Exception( "Unable to get event groups associated with measurement consumer $measurementConsumerName and data provider $dataProviderName", e, ) } if (eventGroups.size != 1) { throw IllegalStateException( "here should be exactly 1:1 mapping between a data provider and an event group, but data provider $dataProvider is related to ${eventGroups.size} event groups" ) } dataProviderNameToEventGroup[dataProviderName] = eventGroups[0] } return dataProviderNameToEventGroup } private fun shouldCreateNewMeasurement(lastUpdatedMeasurement: Measurement?): Boolean { if (lastUpdatedMeasurement == null) { return true } if (lastUpdatedMeasurement.state !in COMPLETED_MEASUREMENT_STATES) { return false } val updateInstant = lastUpdatedMeasurement.updateTime.toInstant() val nextMeasurementEarliestInstant = updateInstant.plus(durationBetweenMeasurement) return clock.instant() >= nextMeasurementEarliestInstant } private suspend fun getLastUpdatedMeasurement(): Measurement? { var nextPageToken = "" do { val response: ListMeasurementsResponse = try { measurementsStub.listMeasurements( listMeasurementsRequest { parent = measurementConsumerName this.pageSize = 1 pageToken = nextPageToken } ) } catch (e: StatusException) { throw Exception( "Unable to list measurements for measurement consumer $measurementConsumerName", e, ) } if (response.measurementsList.isNotEmpty()) { return response.measurementsList.single() } nextPageToken = response.nextPageToken } while (nextPageToken.isNotEmpty()) return null } private suspend fun getRequisitionsForMeasurement(measurementName: String): List<Requisition> { var nextPageToken = "" val requisitions = mutableListOf<Requisition>() do { val response: ListRequisitionsResponse = try { requisitionsStub.listRequisitions( listRequisitionsRequest { parent = measurementName pageToken = nextPageToken } ) } catch (e: StatusException) { throw Exception("Unable to list requisitions for measurement $measurementName", e) } requisitions.addAll(response.requisitionsList) nextPageToken = response.nextPageToken } while (nextPageToken.isNotEmpty()) return requisitions } private suspend fun getDataProviderEntry( dataProviderName: String, eventGroup: EventGroup, measurementConsumerSigningKey: SigningKeyHandle, packedMeasurementEncryptionPublicKey: Any, ): Measurement.DataProviderEntry { return dataProviderEntry { val requisitionSpec = requisitionSpec { events = RequisitionSpecKt.events { this.eventGroups += eventGroupEntry { eventGroupEntry { key = eventGroup.name value = EventGroupEntryKt.value { collectionInterval = interval { startTime = clock.instant().minus(measurementLookbackDuration).toProtoTime() endTime = clock.instant().plus(Duration.ofDays(1)).toProtoTime() } } } } } measurementPublicKey = packedMeasurementEncryptionPublicKey nonce = secureRandom.nextLong() } key = dataProviderName val dataProvider = try { dataProvidersStub .withAuthenticationKey(apiAuthenticationKey) .getDataProvider(getDataProviderRequest { name = dataProviderName }) } catch (e: StatusException) { throw Exception( "Unable to get event groups associated with measurement consumer $measurementConsumerName and data provider $dataProviderName", e, ) } value = MeasurementKt.DataProviderEntryKt.value { dataProviderCertificate = dataProvider.certificate dataProviderPublicKey = dataProvider.publicKey.message encryptedRequisitionSpec = encryptRequisitionSpec( signRequisitionSpec(requisitionSpec, measurementConsumerSigningKey), dataProvider.publicKey.unpack(), ) nonceHash = Hashing.hashSha256(requisitionSpec.nonce) } } } private suspend fun updateLastTerminalRequisitionGauge(lastUpdatedMeasurement: Measurement) { val requisitions = getRequisitionsForMeasurement(lastUpdatedMeasurement.name) for (requisition in requisitions) { if (requisition.state == Requisition.State.FULFILLED) { val requisitionKey = CanonicalRequisitionKey.fromName(requisition.name) require(requisitionKey != null) { "CanonicalRequisitionKey cannot be null" } val dataProviderName: String = requisitionKey.dataProviderId val attributes = Attributes.of(DATA_PROVIDER_ATTRIBUTE_KEY, dataProviderName) lastTerminalRequisitionTimeGauge.set( requisition.updateTime.toInstant().toEpochMilli() / MILLISECONDS_PER_SECOND, attributes, ) } } } companion object { private const val MILLISECONDS_PER_SECOND = 1000.0 private val logger: Logger = Logger.getLogger(this::class.java.name) private val secureRandom = SecureRandom.getInstance("SHA1PRNG") private val COMPLETED_MEASUREMENT_STATES = listOf(Measurement.State.SUCCEEDED, Measurement.State.FAILED, Measurement.State.CANCELLED) private const val PROBER_NAMESPACE = "${Instrumentation.ROOT_NAMESPACE}.prober" private val DATA_PROVIDER_ATTRIBUTE_KEY = AttributeKey.stringKey("${Instrumentation.ROOT_NAMESPACE}.data_provider") } }
145
Kotlin
11
36
ba2d2d8d3d4527d844e6d168273b1c2fabfd5d4e
15,967
cross-media-measurement
Apache License 2.0
sykepenger-model/src/test/kotlin/no/nav/helse/serde/SerialiseringAvDagerFraSøknadTest.kt
navikt
193,907,367
false
null
package no.nav.helse.serde import no.nav.helse.april import no.nav.helse.dsl.ArbeidsgiverHendelsefabrikk import no.nav.helse.hendelser.Sykmeldingsperiode import no.nav.helse.hendelser.Søknad.Søknadsperiode.Arbeid import no.nav.helse.hendelser.Søknad.Søknadsperiode.Ferie import no.nav.helse.hendelser.Søknad.Søknadsperiode.Permisjon import no.nav.helse.hendelser.Søknad.Søknadsperiode.Sykdom import no.nav.helse.hendelser.Søknad.Søknadsperiode.Utdanning import no.nav.helse.januar import no.nav.helse.person.aktivitetslogg.Aktivitetslogg import no.nav.helse.person.Person import no.nav.helse.person.etterlevelse.MaskinellJurist import no.nav.helse.somPersonidentifikator import no.nav.helse.økonomi.Prosentdel.Companion.prosent import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test internal class SerialiseringAvDagerFraSøknadTest { @Test fun `perioder fra søknaden skal serialiseres og deserialiseres riktig - jackson`() { val person = person val jsonBuilder = JsonBuilder() person.accept(jsonBuilder) val personDeserialisert = SerialisertPerson(jsonBuilder.toString()) .deserialize(MaskinellJurist()) assertJsonEquals(person, personDeserialisert) } @Test fun `perioder fra søknaden skal serialiseres og deserialiseres riktig`() { val jsonBuilder = JsonBuilder() person.accept(jsonBuilder) val json = jsonBuilder.toString() val result = SerialisertPerson(json).deserialize(MaskinellJurist()) val jsonBuilder2 = JsonBuilder() result.accept(jsonBuilder2) val json2 = jsonBuilder2.toString() assertEquals(json, json2) assertJsonEquals(person, result) } private val aktørId = "12345" private val fnr = "12029240045" private val orgnummer = "987654321" private val hendelsefabrikk = ArbeidsgiverHendelsefabrikk( aktørId = aktørId, personidentifikator = fnr.somPersonidentifikator(), organisasjonsnummer = orgnummer ) private lateinit var aktivitetslogg: Aktivitetslogg private lateinit var person: Person @BeforeEach internal fun setup() { aktivitetslogg = Aktivitetslogg() person = Person.fraHendelse(sykmelding, MaskinellJurist()).apply { håndter(sykmelding) håndter(søknad) } } private val sykmelding get() = hendelsefabrikk.lagSykmelding( sykeperioder = arrayOf(Sykmeldingsperiode(1.januar, 2.januar, 100.prosent)), sykmeldingSkrevet = 4.april.atStartOfDay() ) private val søknad get() = hendelsefabrikk.lagSøknad( perioder = arrayOf( Sykdom(1.januar, 5.januar, 100.prosent), Arbeid(3.januar, 3.januar), Ferie(4.januar, 4.januar), Permisjon(5.januar, 5.januar), Utdanning(5.januar, 5.januar) ), sendtTilNAVEllerArbeidsgiver = 5.januar ) }
2
Kotlin
6
5
a1d4ace847a123e6bf09754ea0640116caf6ceb7
3,003
helse-spleis
MIT License
service/src/main/kotlin/io/provenance/explorer/web/v2/AccountController.kt
provenance-io
332,035,574
false
null
package io.provenance.explorer.web.v2 import io.provenance.explorer.service.AccountService import io.swagger.annotations.Api import io.swagger.annotations.ApiOperation import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.validation.annotation.Validated import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController import javax.validation.constraints.Min @Validated @RestController @RequestMapping(path = ["/api/v2/accounts"], produces = [MediaType.APPLICATION_JSON_VALUE]) @Api(value = "Account controller", produces = "application/json", consumes = "application/json", tags = ["Accounts"]) class AccountController(private val accountService: AccountService) { @ApiOperation("Returns account detail for account address") @GetMapping("/{address}") fun getAccount(@PathVariable address: String) = ResponseEntity.ok(accountService.getAccountDetail(address)) @ApiOperation("Returns account balances for account address") @GetMapping("/{address}/balances") fun getAccountBalances( @PathVariable address: String, @RequestParam(required = false, defaultValue = "10") @Min(1) count: Int, @RequestParam(required = false, defaultValue = "1") @Min(1) page: Int ) = ResponseEntity.ok(accountService.getAccountBalances(address, page, count)) @ApiOperation("Returns delegations for account address") @GetMapping("/{address}/delegations") fun getAccountDelegations( @PathVariable address: String, @RequestParam(required = false, defaultValue = "10") @Min(1) count: Int, @RequestParam(required = false, defaultValue = "1") @Min(1) page: Int ) = ResponseEntity.ok(accountService.getDelegations(address, page, count)) @ApiOperation("Returns unbonding delegations for account address") @GetMapping("/{address}/unbonding") fun getAccountUnbondingDelegations(@PathVariable address: String) = ResponseEntity.ok(accountService.getUnbondingDelegations(address)) @ApiOperation("Returns redelegations for account address") @GetMapping("/{address}/redelegations") fun getAccountRedelegations(@PathVariable address: String) = ResponseEntity.ok(accountService.getRedelegations(address)) @ApiOperation("Returns total rewards for account address") @GetMapping("/{address}/rewards") fun getAccountRewards(@PathVariable address: String) = ResponseEntity.ok(accountService.getRewards(address)) @ApiOperation("Returns attribute names owned by the account address") @GetMapping("/{address}/attributes/owned") fun getAccountNamesOwned( @PathVariable address: String, @RequestParam(required = false, defaultValue = "10") @Min(1) count: Int, @RequestParam(required = false, defaultValue = "1") @Min(1) page: Int ) = ResponseEntity.ok(accountService.getNamesOwnedByAccount(address, page, count)) }
15
Kotlin
1
4
f90c3b406561965b8ce08359d703a9ad5a54a928
3,163
explorer-service
Apache License 2.0
kbomberx-io/src/main/kotlin/kbomberx/io/routing/AbstractChannelRouter.kt
LM-96
517,382,094
false
{"Kotlin": 253830}
package kbomberx.io.routing import kbomberx.concurrency.coroutineserver.CmdServerRequest import kbomberx.concurrency.coroutineserver.ServerReply import kbomberx.concurrency.coroutineserver.requestWithParameter import kbomberx.io.IoScope import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.selects.SelectBuilder import kotlinx.coroutines.selects.select import java.io.Closeable import java.util.* /** * Abstract class for routers that implements the part of adding * and managing routes and creates and start the job associated * with the router. The default [CoroutineScope] is [IoScope] */ abstract class AbstractChannelRouter<L>( private val scope : CoroutineScope = IoScope ) : ChannelRouter<L>(), Closeable, AutoCloseable { companion object { private const val START_ROUTER_CODE = 0 private const val ADD_ROUTE_CODE = 1 private const val REMOVE_ROUTE_CODE = 2 private const val GET_ROUTE_CODE = 3 private const val TERMINATE_ROUTER_CODE = 4 } private val cmdChannel = Channel<CmdServerRequest>() protected var terminated = false protected abstract fun onJobTermination() abstract fun SelectBuilder<Unit>.routerJob(routes : MutableMap<String, ChannelRoute<L>>) private val job = scope.launch { var started = false val routes = mutableMapOf<String, ChannelRoute<L>>() while(isActive && !terminated) { select { cmdChannel.onReceive { request -> try { when(request.requestCode) { START_ROUTER_CODE -> { started = true replyWithOk(request) } ADD_ROUTE_CODE -> { val route = request.requestParams[0] as ChannelRoute<L> routes[route.name] = route replyWithOk(request) } REMOVE_ROUTE_CODE -> { val removed = routes.remove(request.requestParams[0] as String) replyWithRoute(request, removed) } GET_ROUTE_CODE -> { val route = routes[request.requestParams[0] as String] replyWithRoute(request, route) } TERMINATE_ROUTER_CODE -> { terminated = true replyWithOk(request) } } } catch (e : Exception) { replyWithException(request, e) } }//On receive of command channel if(started) this.routerJob(routes) } } //Termination routes.forEach { it.value.channel.close() } routes.clear() onJobTermination() } protected fun terminate() { } private suspend fun performRequest(code : Int, vararg params : Any) : ServerReply { val req = CmdServerRequest(code, Channel(), params) cmdChannel.send(req) return req.responseChannel.receive() } private suspend fun replyWithOk(request : CmdServerRequest) { try { request.responseChannel.send(ServerReply(ServerReply.OK_CODE)) request.responseChannel.close() } catch (_ : Exception) {/*Send fails -> ignoring*/} } private suspend fun replyWithRoute(request : CmdServerRequest, route : ChannelRoute<L>?) { try { request.responseChannel.send(ServerReply(ServerReply.OK_CODE, arrayOf(Optional.ofNullable(route)))) request.responseChannel.close() } catch (_ : Exception) {/*Send fails -> ignoring*/} } private suspend fun replyWithException(request: CmdServerRequest, exception : Exception) { try { request.responseChannel.send(ServerReply(ServerReply.ERR_CODE, arrayOf(exception))) request.responseChannel.close() } catch (_ : Exception) {/* Send fails -> ignoring */} } override suspend fun start() { performRequest(START_ROUTER_CODE) } override suspend fun newRoute(name: String, routeChannelCapacity: Int, passage: (L) -> Boolean): ChannelRoute<L> { val route = ChannelRoute(name, Channel<L>(routeChannelCapacity), passage) val res = performRequest(ADD_ROUTE_CODE, route) res.throwError() return route } override suspend fun registerRoute(route: ChannelRoute<L>) { performRequest(ADD_ROUTE_CODE, route) } override suspend fun getRoute(name: String): ChannelRoute<L>? { val res = performRequest(GET_ROUTE_CODE, name) val route = res.throwErrorOrGetFirstParameter() as Optional<ChannelRoute<L>> if(route.isEmpty) return null return route.get() } override suspend fun removeRoute(name: String): ChannelRoute<L>? { val res = performRequest(REMOVE_ROUTE_CODE, name) val route = res.throwErrorOrGetFirstParameter() as Optional<ChannelRoute<L>> if(route.isEmpty) return null return route.get() } override fun close() { runBlocking { val res = performRequest(TERMINATE_ROUTER_CODE) res.throwError() job.join() } } }
0
Kotlin
0
2
f5c087635ffcb4cea4fea71a4738adf9d3dbfc74
5,799
KBomber
MIT License
kbomberx-io/src/main/kotlin/kbomberx/io/routing/AbstractChannelRouter.kt
LM-96
517,382,094
false
{"Kotlin": 253830}
package kbomberx.io.routing import kbomberx.concurrency.coroutineserver.CmdServerRequest import kbomberx.concurrency.coroutineserver.ServerReply import kbomberx.concurrency.coroutineserver.requestWithParameter import kbomberx.io.IoScope import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.selects.SelectBuilder import kotlinx.coroutines.selects.select import java.io.Closeable import java.util.* /** * Abstract class for routers that implements the part of adding * and managing routes and creates and start the job associated * with the router. The default [CoroutineScope] is [IoScope] */ abstract class AbstractChannelRouter<L>( private val scope : CoroutineScope = IoScope ) : ChannelRouter<L>(), Closeable, AutoCloseable { companion object { private const val START_ROUTER_CODE = 0 private const val ADD_ROUTE_CODE = 1 private const val REMOVE_ROUTE_CODE = 2 private const val GET_ROUTE_CODE = 3 private const val TERMINATE_ROUTER_CODE = 4 } private val cmdChannel = Channel<CmdServerRequest>() protected var terminated = false protected abstract fun onJobTermination() abstract fun SelectBuilder<Unit>.routerJob(routes : MutableMap<String, ChannelRoute<L>>) private val job = scope.launch { var started = false val routes = mutableMapOf<String, ChannelRoute<L>>() while(isActive && !terminated) { select { cmdChannel.onReceive { request -> try { when(request.requestCode) { START_ROUTER_CODE -> { started = true replyWithOk(request) } ADD_ROUTE_CODE -> { val route = request.requestParams[0] as ChannelRoute<L> routes[route.name] = route replyWithOk(request) } REMOVE_ROUTE_CODE -> { val removed = routes.remove(request.requestParams[0] as String) replyWithRoute(request, removed) } GET_ROUTE_CODE -> { val route = routes[request.requestParams[0] as String] replyWithRoute(request, route) } TERMINATE_ROUTER_CODE -> { terminated = true replyWithOk(request) } } } catch (e : Exception) { replyWithException(request, e) } }//On receive of command channel if(started) this.routerJob(routes) } } //Termination routes.forEach { it.value.channel.close() } routes.clear() onJobTermination() } protected fun terminate() { } private suspend fun performRequest(code : Int, vararg params : Any) : ServerReply { val req = CmdServerRequest(code, Channel(), params) cmdChannel.send(req) return req.responseChannel.receive() } private suspend fun replyWithOk(request : CmdServerRequest) { try { request.responseChannel.send(ServerReply(ServerReply.OK_CODE)) request.responseChannel.close() } catch (_ : Exception) {/*Send fails -> ignoring*/} } private suspend fun replyWithRoute(request : CmdServerRequest, route : ChannelRoute<L>?) { try { request.responseChannel.send(ServerReply(ServerReply.OK_CODE, arrayOf(Optional.ofNullable(route)))) request.responseChannel.close() } catch (_ : Exception) {/*Send fails -> ignoring*/} } private suspend fun replyWithException(request: CmdServerRequest, exception : Exception) { try { request.responseChannel.send(ServerReply(ServerReply.ERR_CODE, arrayOf(exception))) request.responseChannel.close() } catch (_ : Exception) {/* Send fails -> ignoring */} } override suspend fun start() { performRequest(START_ROUTER_CODE) } override suspend fun newRoute(name: String, routeChannelCapacity: Int, passage: (L) -> Boolean): ChannelRoute<L> { val route = ChannelRoute(name, Channel<L>(routeChannelCapacity), passage) val res = performRequest(ADD_ROUTE_CODE, route) res.throwError() return route } override suspend fun registerRoute(route: ChannelRoute<L>) { performRequest(ADD_ROUTE_CODE, route) } override suspend fun getRoute(name: String): ChannelRoute<L>? { val res = performRequest(GET_ROUTE_CODE, name) val route = res.throwErrorOrGetFirstParameter() as Optional<ChannelRoute<L>> if(route.isEmpty) return null return route.get() } override suspend fun removeRoute(name: String): ChannelRoute<L>? { val res = performRequest(REMOVE_ROUTE_CODE, name) val route = res.throwErrorOrGetFirstParameter() as Optional<ChannelRoute<L>> if(route.isEmpty) return null return route.get() } override fun close() { runBlocking { val res = performRequest(TERMINATE_ROUTER_CODE) res.throwError() job.join() } } }
0
Kotlin
0
2
f5c087635ffcb4cea4fea71a4738adf9d3dbfc74
5,799
KBomber
MIT License
Sample/components/src/main/java/com/steamclock/components/components/ThemedDivider.kt
steamclock
439,159,037
false
null
package com.steamclock.components.components import androidx.compose.material.Divider import androidx.compose.material.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.steamclock.components.theme.Config import com.steamclock.components.theme.CurrentConfig import com.steamclock.components.theme.NiceComponentsDarkColors import com.steamclock.components.theme.NiceComponentsTheme /** * Sample * Created by jake on 2021-12-17, 12:16 p.m. */ @Composable fun ThemedDivider( modifier: Modifier = Modifier ) { Divider( modifier = modifier.alpha(0.6f), color = CurrentConfig.colorTheme.onPrimary, thickness = 1.dp ) } @Preview @Composable fun ScreenTitlePreview() { NiceComponentsTheme { Surface { ThemedDivider() } } } @Preview @Composable fun ScreenTitlePreviewDark() { NiceComponentsTheme(Config(colorTheme = NiceComponentsDarkColors)) { Surface { ThemedDivider() } } }
0
null
0
1
7958b122b0bbfd1b2c07676d43f5a1b44d79f26f
1,153
compose_components
MIT License
app/src/main/java/com/alessandrofarandagancio/nycschools/utils/Constants.kt
alexs60
608,871,839
false
null
package com.alessandrofarandagancio.nycschools.utils object Constants { const val BASE_SODA_API_URL: String = "https://data.cityofnewyork.us/" const val HIGH_SCHOOL_DIRECTORY_2017: String = "s3k6-pzi2" const val SAT_RESULTS_2012: String = "f9bf-2cp4" }
0
Kotlin
0
0
842212bdff31702e8f8958fd965dab0fb94c7cc0
266
20230302-AlessandroFarandaGancio-NYCSchools
Apache License 2.0
Music/src/main/java/com/yichen/music/net/MusicApiClient.kt
yichen454
172,859,605
false
null
package com.yichen.music.net import com.yichen.music.BuildConfig import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit /** * Created by Chen on 2019/2/28 */ class MusicApiClient private constructor() { companion object { val INSTANCE: MusicApiClient by lazy { MusicApiClient() } } private val interceptor: Interceptor private val retrofit: Retrofit var netService: MusicNetService init { //通用拦截器 interceptor = Interceptor { chain -> var request = chain.request() .newBuilder() // .addHeader("content-type", "application/json") // .addHeader("user-agent", "Summer/2.9.8 (iPhone; iOS 12.1.3; Scale/2.00)") // .addHeader("authorization", "qdQ7vdxyiabbiAKcGxBFo1sK") // .addHeader("summerplatform", "ios") // .addHeader("summerversion", "2.9.8") // .addHeader("devicebrand", "iphone") .build() chain.proceed(request) } //创建Retrofit的实例 retrofit = Retrofit.Builder() .baseUrl(MusicApi.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(initClient()) .build() netService = retrofit.create(MusicNetService::class.java) } /** * 创建请求客户端 */ private fun initClient(): OkHttpClient { return OkHttpClient.Builder() .addInterceptor(interceptor) .addInterceptor(initLogInterceptor()) .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS) .build() } /** *日志拦截器 */ private fun initLogInterceptor(): HttpLoggingInterceptor { val interceptor = HttpLoggingInterceptor() if (BuildConfig.DEBUG) interceptor.level = HttpLoggingInterceptor.Level.BODY else interceptor.level = HttpLoggingInterceptor.Level.NONE return interceptor } }
1
null
1
3
9c592e2e6bb9dee907fe4f8a22c8b9fd835579b8
2,294
Android-KotlinExp
Apache License 2.0
app/src/main/java/com/vitorpamplona/amethyst/ui/screen/UserFeedState.kt
vitorpamplona
587,850,619
false
{"Kotlin": 3170921, "Shell": 1485, "Java": 921}
package com.vitorpamplona.amethyst.ui.screen import androidx.compose.runtime.MutableState import com.vitorpamplona.amethyst.model.User import kotlinx.collections.immutable.ImmutableList sealed class UserFeedState { object Loading : UserFeedState() class Loaded(val feed: MutableState<ImmutableList<User>>) : UserFeedState() object Empty : UserFeedState() class FeedError(val errorMessage: String) : UserFeedState() }
157
Kotlin
141
981
2de3d19a34b97c012e39b203070d9c1c0b1f0520
435
amethyst
MIT License
modules/domain/map/src/main/kotlin/kekmech/ru/domain_map/MapService.kt
tonykolomeytsev
203,239,594
false
null
package kekmech.ru.domain_map import kekmech.ru.common_annotations.BackendServiceUrl import kekmech.ru.common_annotations.EndpointUrl import kekmech.ru.domain_map.dto.MapMarker import retrofit2.http.GET @EndpointUrl(BackendServiceUrl.MAP) internal interface MapService { @GET("markers.json") suspend fun getMapMarkers(): List<MapMarker> }
18
Kotlin
4
28
209f34745458e150136c3cd6acb1fcad2e12ef9c
350
mpeiapp
MIT License
judokit-android/src/main/java/com/judopay/judokit/android/api/model/response/OrderStatus.kt
Judopay
261,378,339
false
{"Kotlin": 898212}
package com.judokit.android.api.model.response enum class OrderStatus { FAILED, SUCCEEDED, PENDING }
1
Kotlin
6
4
8264188dc87c882848866058ed869d674ae45628
114
JudoKit-Android
MIT License
src/main/kotlin/dev/shtanko/patterns/structural/decorator/examples/example2/DistinctStream.kt
ashtanko
203,993,092
false
{"Kotlin": 7429739, "Shell": 1168, "Makefile": 1144}
/* * Copyright 2023 Oleksii Shtanko * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.patterns.structural.decorator.examples.example2 import kotlin.streams.toList // Concrete decorator class DistinctStream<T>(decoratedStream: StreamDecorator<T>) : StreamDecorator<T> { private var stream = decoratedStream.collect().stream().distinct() override fun filter(predicate: (T) -> Boolean): StreamDecorator<T> { stream = stream.filter(predicate) return this } override fun collect(): List<T> { return stream.toList() } }
6
Kotlin
0
19
c6e2befdce892e9f2caf1d98f54dc1dd9b2c89ba
1,096
kotlab
Apache License 2.0
src/main/java/net/ccbluex/liquidbounce/utils/SettingsUtils.kt
2946257770
693,652,489
false
{"Java": 1812636, "Kotlin": 1801560, "GLSL": 13689, "JavaScript": 9199, "HTML": 850}
/* * LiquidBounce+ Hacked Client * A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge. * https://github.com/WYSI-Foundation/LiquidBouncePlus/ */ package net.ccbluex.liquidbounce.utils import net.ccbluex.liquidbounce.LiquidBounce import net.ccbluex.liquidbounce.features.module.ModuleCategory import net.ccbluex.liquidbounce.features.module.modules.render.NameProtect import net.ccbluex.liquidbounce.features.module.modules.world.Spammer import net.ccbluex.liquidbounce.features.special.MacroManager import net.ccbluex.liquidbounce.utils.misc.HttpUtils.get import net.ccbluex.liquidbounce.utils.misc.StringUtils import net.ccbluex.liquidbounce.utils.render.ColorUtils.translateAlternateColorCodes import net.ccbluex.liquidbounce.value.* import org.lwjgl.input.Keyboard object SettingsUtils { /** * Execute settings [script] */ fun executeScript(script: String) { script.lines().filter { it.isNotEmpty() && !it.startsWith('#') }.forEachIndexed { index, s -> val args = s.split(" ").toTypedArray() if (args.size <= 1) { ClientUtils.displayChatMessage("§7[§3§lAutoSettings§7] §cSyntax error at line '$index' in setting script.\n§8§lLine: §7$s") return@forEachIndexed } when (args[0]) { "chat" -> ClientUtils.displayChatMessage("§7[§3§lAutoSettings§7] §e${translateAlternateColorCodes(StringUtils.toCompleteString(args, 1))}") "unchat" -> ClientUtils.displayChatMessage(translateAlternateColorCodes(StringUtils.toCompleteString(args, 1))) "load" -> { val urlRaw = StringUtils.toCompleteString(args, 1) val url = urlRaw try { ClientUtils.displayChatMessage("§7[§3§lAutoSettings§7] §7Loading settings from §a§l$url§7...") executeScript(get(url)) ClientUtils.displayChatMessage("§7[§3§lAutoSettings§7] §7Loaded settings from §a§l$url§7.") } catch (e: Exception) { ClientUtils.displayChatMessage("§7[§3§lAutoSettings§7] §7Failed to load settings from §a§l$url§7.") } } "macro" -> { if (args[1] != "0") { val macroBind = args[1] val macroCommand = StringUtils.toCompleteString(args, 2) try { MacroManager.addMacro(macroBind.toInt(), macroCommand) ClientUtils.displayChatMessage("§7[§3§lAutoSettings§7] Macro §c§l$macroCommand§7 has been bound to §a§l$macroBind§7.") } catch (e: Exception) { ClientUtils.displayChatMessage("§7[§3§lAutoSettings§7] §a§l${e.javaClass.name}§7(${e.message}) §cAn Exception occurred while importing macro with keybind §a§l$macroBind§c to §a§l$macroCommand§c.") } } } "targetPlayer", "targetPlayers" -> { EntityUtils.targetPlayer = args[1].equals("true", ignoreCase = true) ClientUtils.displayChatMessage("§7[§3§lAutoSettings§7] §a§l${args[0]}§7 set to §c§l${EntityUtils.targetPlayer}§7.") } "targetMobs" -> { EntityUtils.targetMobs = args[1].equals("true", ignoreCase = true) ClientUtils.displayChatMessage("§7[§3§lAutoSettings§7] §a§l${args[0]}§7 set to §c§l${EntityUtils.targetMobs}§7.") } "targetAnimals" -> { EntityUtils.targetAnimals = args[1].equals("true", ignoreCase = true) ClientUtils.displayChatMessage("§7[§3§lAutoSettings§7] §a§l${args[0]}§7 set to §c§l${EntityUtils.targetAnimals}§7.") } "targetInvisible" -> { EntityUtils.targetInvisible = args[1].equals("true", ignoreCase = true) ClientUtils.displayChatMessage("§7[§3§lAutoSettings§7] §a§l${args[0]}§7 set to §c§l${EntityUtils.targetInvisible}§7.") } "targetDead" -> { EntityUtils.targetDead = args[1].equals("true", ignoreCase = true) ClientUtils.displayChatMessage("§7[§3§lAutoSettings§7] §a§l${args[0]}§7 set to §c§l${EntityUtils.targetDead}§7.") } else -> { if (args.size != 3) { ClientUtils.displayChatMessage("§7[§3§lAutoSettings§7] §cSyntax error at line '$index' in setting script.\n§8§lLine: §7$s") return@forEachIndexed } val moduleName = args[0] val valueName = args[1] val value = args[2] val module = LiquidBounce.moduleManager.getModule(moduleName) if (module == null) { ClientUtils.displayChatMessage("§7[§3§lAutoSettings§7] §cModule §a§l$moduleName§c was not found!") return@forEachIndexed } if (valueName.equals("toggle", ignoreCase = true)) { module.state = value.equals("true", ignoreCase = true) ClientUtils.displayChatMessage("§7[§3§lAutoSettings§7] §a§l${module.name} §7was toggled §c§l${if (module.state) "on" else "off"}§7.") return@forEachIndexed } if (valueName.equals("bind", ignoreCase = true)) { module.keyBind = Keyboard.getKeyIndex(value) ClientUtils.displayChatMessage("§7[§3§lAutoSettings§7] §a§l${module.name} §7was bound to §c§l${Keyboard.getKeyName(module.keyBind)}§7.") return@forEachIndexed } val moduleValue = module.getValue(valueName) if (moduleValue == null) { ClientUtils.displayChatMessage("§7[§3§lAutoSettings§7] §cValue §a§l$valueName§c don't found in module §a§l$moduleName§c.") return@forEachIndexed } try { when (moduleValue) { is BoolValue -> moduleValue.changeValue(value.toBoolean()) is FloatValue -> moduleValue.changeValue(value.toFloat()) is IntegerValue -> moduleValue.changeValue(value.toInt()) is TextValue -> moduleValue.changeValue(value) is ListValue -> moduleValue.changeValue(value) } ClientUtils.displayChatMessage("§7[§3§lAutoSettings§7] §a§l${module.name}§7 value §8§l${moduleValue.name}§7 set to §c§l$value§7.") } catch (e: Exception) { ClientUtils.displayChatMessage("§7[§3§lAutoSettings§7] §a§l${e.javaClass.name}§7(${e.message}) §cAn Exception occurred while setting §a§l$value§c to §a§l${moduleValue.name}§c in §a§l${module.name}§c.") } } } } LiquidBounce.fileManager.saveConfig(LiquidBounce.fileManager.valuesConfig) } /** * Generate settings script */ fun generateScript(values: Boolean, binds: Boolean, states: Boolean): String { val stringBuilder = StringBuilder() MacroManager.macroMapping.filter { it.key != 0 }.forEach { stringBuilder.append("macro ${it.key} ${it.value}").append("\n") } LiquidBounce.moduleManager.modules.filter { it.category !== ModuleCategory.RENDER && it !is NameProtect && it !is Spammer }.forEach { if (values) it.values.forEach { value -> stringBuilder.append("${it.name} ${value.name} ${value.get()}").append("\n") } if (states) stringBuilder.append("${it.name} toggle ${it.state}").append("\n") if (binds) stringBuilder.append("${it.name} bind ${Keyboard.getKeyName(it.keyBind)}").append("\n") } return stringBuilder.toString() } }
1
null
1
1
4e111df6cd3ca03da3b285eb8572ef79a9ff8695
8,307
VulgarSense
Apache License 2.0
features/logout/impl/src/main/kotlin/io/element/android/features/logout/impl/LogoutState.kt
element-hq
546,522,002
false
{"Kotlin": 6336555, "Shell": 34289, "Python": 14833, "Java": 9607, "JavaScript": 8220, "Ruby": 44, "Gherkin": 32}
/* * Copyright (c) 2023 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.element.android.features.logout.impl import io.element.android.libraries.architecture.Async import io.element.android.libraries.matrix.api.encryption.BackupState import io.element.android.libraries.matrix.api.encryption.BackupUploadState import io.element.android.libraries.matrix.api.encryption.RecoveryState data class LogoutState( val isLastSession: Boolean, val backupState: BackupState, val doesBackupExistOnServer: Boolean, val recoveryState: RecoveryState, val backupUploadState: BackupUploadState, val showConfirmationDialog: Boolean, val logoutAction: Async<String?>, val eventSink: (LogoutEvents) -> Unit, )
199
Kotlin
84
690
2bed671c0057b368728e6fe00734e6519de9e472
1,266
element-x-android
Apache License 2.0
core/data/src/main/kotlin/com/mitch/safevault/core/data/remote/AuthApi.kt
seve-andre
697,908,054
false
{"Kotlin": 163920}
package com.mitch.safevault.core.data.remote import com.mitch.safevault.core.data.remote.request.CreateAccountRequest import com.mitch.safevault.core.data.remote.request.LogInRequest interface AuthApi { suspend fun signUp( request: CreateAccountRequest ): Result<Unit> suspend fun logIn( request: LogInRequest ): AuthApiResponse }
0
Kotlin
0
0
27dee91525d80ffd028a50d72878795e82e2af03
367
safevault
MIT License
kotlin/technical-interview/src/main/kotlin/fr/codeworks/kata/TechnicalWorkshop.kt
CodeWorksFrance
504,489,016
false
null
package fr.codeworks.kata import com.google.gson.Gson import com.google.gson.reflect.TypeToken import java.io.File data class Question( val label: String, val answer: String,val difficulty: Int) data class CategorizedQuestions(val label: String, val questions: List<Question>) data class CandidateResponse(val response : String, val question: Question) data class Candidate(var firstname: String, var lastname: String, var email: String) {} class TechnicalWorkshop { internal var categories = mutableSetOf<String>() internal var candidate: Candidate? = null fun addCat(c: String) { println("Adding $c as categories") categories.add(c) } fun addCan(lastname: String, fistname: String, email: String) { println("Adding $fistname as candidate") this.candidate = Candidate(lastname, fistname, email) } fun runCodeTest(c: String): Double { val resource = javaClass.getResource("/categories.json") val file = File(resource.path) val allCategoriesAsRaw = file.bufferedReader().use { it.readText() } val categoryType = object : TypeToken<List<CategorizedQuestions>>() {}.type val list = Gson().fromJson<List<CategorizedQuestions>?>(allCategoriesAsRaw, categoryType) val questions = list.find { q -> q.label == c } val cq = questions val question: List<Question>? = cq?.questions val responses = mutableListOf<CandidateResponse>() var s = 0.0 // s is for score println("Welcome to the interview game. You'll have ${question?.size} questions on ${c}") print("Are you ready? (y) to start?\n") val value = readLine() //response of the user if (value == "y") { println("Let's go!") print("***************** Questions *****************\n") question?.forEach { q -> print(q.label) val a = readLine() if (a != null) { responses.add(CandidateResponse(a, q)) } } println("Thank you for your participation!") } println("***************** Response from: ${this.candidate?.firstname} *****************\n") responses.forEach { candidateResponse -> val currentQuestion = candidateResponse.question println("> Question: ${candidateResponse.question} ? \n") println(">>> Response: ${candidateResponse.response}. \n") print("----> What is your evaluation: t=true or f=false ?\n") val answer = readLine() if (answer != null) { if (answer.equals("t") || answer.equals("T")) { when (currentQuestion.difficulty) { 1 -> s += 0.25 2 -> s += 0.5 3 -> s += 0.75 4 -> s += 1 } } } } return s } } fun main() { val codeTest = TechnicalWorkshop() codeTest.addCat("SQL") codeTest.addCan("Toto", "Titi", "<EMAIL>") val score = codeTest.runCodeTest("Java") println("The candidate as a total of $score points.") }
0
Kotlin
1
3
a7d522e23887d80332f907e0cfe53ba56086a21e
3,213
workshop-technical-interview
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsactivitiesmanagementapi/repository/refdata/PrisonPayBandRepository.kt
ministryofjustice
533,838,017
false
{"Kotlin": 3860948, "Shell": 9529, "Dockerfile": 1514}
package uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.repository.refdata import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.entity.refdata.PrisonPayBand @Repository interface PrisonPayBandRepository : JpaRepository<PrisonPayBand, Long> { fun findByPrisonCode(code: String): List<PrisonPayBand> }
4
Kotlin
0
1
0b256291fee343920d560c06676322d5d97e2279
436
hmpps-activities-management-api
MIT License
app/src/main/java/com/nicktra/moviedex/ui/detail/DetailViewModel.kt
nicktra
337,432,817
false
null
package com.nicktra.moviedex.ui.detail import androidx.lifecycle.ViewModel import com.nicktra.moviedex.core.domain.model.Movie import com.nicktra.moviedex.core.domain.usecase.MovieUseCase class DetailViewModel(private val movieUseCase: MovieUseCase) : ViewModel() { fun setFavoriteMovie(movie: Movie, newStatus:Boolean) = movieUseCase.setFavoriteMovie(movie, newStatus) }
0
Kotlin
0
0
4f6769d5bb1beebce97cb517fa810a6ab0ecccdb
389
moviedex
MIT License
app/src/main/java/com/suatzengin/iloveanimals/ui/auth/login/LoginViewModel.kt
iamsuatzengin
709,487,931
false
{"Kotlin": 263485}
package com.suatzengin.iloveanimals.ui.auth.login import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.suatzengin.iloveanimals.data.auth.IlaAuthHandler import com.suatzengin.iloveanimals.data.network.NetworkResult import com.suatzengin.iloveanimals.domain.repository.AuthRepository import com.suatzengin.iloveanimals.domain.usecase.CreatePushNotifDeviceUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class LoginViewModel @Inject constructor( private val repository: AuthRepository, private val authHandler: IlaAuthHandler, private val createPushNotifDeviceUseCase: CreatePushNotifDeviceUseCase ) : ViewModel() { private val _uiState = MutableStateFlow(LoginUiState()) val uiState = _uiState.asStateFlow() private val _uiEvent = MutableSharedFlow<LoginUiEvent>() val uiEvent = _uiEvent.asSharedFlow() fun login() { viewModelScope.launch { if (uiState.value.isEmailValid.not()) { _uiEvent.emit(LoginUiEvent.Error(message = "Geçersiz email girişi!")) return@launch } when ( val response = repository.login(email = uiState.value.email, password = uiState.value.password) ) { is NetworkResult.Success -> { authHandler.saveJWT(token = response.data.token.orEmpty()) createPushNotifDeviceUseCase() _uiEvent.emit(LoginUiEvent.NavigateToHome) } is NetworkResult.Error -> { _uiEvent.emit(LoginUiEvent.Error(message = response.error.message)) } is NetworkResult.Exception -> { _uiEvent.emit(LoginUiEvent.Error(message = response.message)) } } } } fun setEmail(email: String) { _uiState.update { it.copy(email = email) } } fun setPassword(password: String) { _uiState.update { it.copy(password = password) } } }
0
Kotlin
0
0
444669b09860bcee7ba2407a1f9171fdf09a0cd3
2,364
i-love-animals-android
MIT License
features/cities/src/main/java/com/shamlou/featureone/ui/MainActivity.kt
keivanshamlu
453,712,116
false
null
package com.shamlou.featureone.ui import androidx.appcompat.app.AppCompatActivity import com.shamlou.featureone.R class MainActivity : AppCompatActivity(R.layout.activity_main)
0
Kotlin
0
0
631b1d7bd0997d985866f42e25db4f1cc4e11297
178
All-cities
Apache License 2.0
muckpot-infra/src/main/kotlin/com/yapp/muckpot/email/EmailHtmlConstant.kt
YAPP-Github
634,126,237
false
null
package com.yapp.muckpot.email private const val HEADER_TITLE = "<span style=\"font-weight: bold;font-size: 48px;\">" + "먹팟 for <span style=\"color:#007bd9\">Samsung</span>\n" + "</span>\n" private const val TAIL = "<hr>\n" + "<br>\n" + "<span style=\"font-size:12px;\">해당 이메일은 발신 전용입니다. 기타 문의사항은 하기의 카카오톡 채널을 통해 연락주시길 바랍니다. <br>\n" + " <a href=\"http://pf.kakao.com/_NVcQxj\">http://pf.kakao.com/_NVcQxj </a>\n" + " <br>\n" + " <br>감사합니다. <br> 먹팟 코리아 " + "</span>\n" const val MAIL_BASIC_FORMAT = "<span style=\"font-family:Arial,sans-serif\">\n" + HEADER_TITLE + "%s" + TAIL + "</span>" const val BOARD_UPDATE_ROW = "<br>\n" + " <br>\n" + " <span style=\"font-size:14px;\">\n" + " %s 변경되었습니다.\n" + " <br>\n" + " 변경 전 : %s\n" + " <br>\n" + " 변경 후 : %s\n" + " </span>\n"
0
Kotlin
1
7
ae74183c06b7d642fc37ab3cde22e7992903f5c5
878
mukpat-server
Apache License 2.0
template/app/src/main/kotlin/app/userflow/update/google/GoogleUpdateProvider.kt
kotlitecture
738,057,168
false
{"Kotlin": 316837, "HTML": 891}
package app.userflow.update.google import androidx.compose.runtime.Composable import app.provideHiltViewModel @Composable fun GoogleUpdateProvider() { provideHiltViewModel<GoogleUpdateViewModel>(activityScoped = true) }
0
Kotlin
0
0
2f09ff83c7864fb15aca22ac7a9419b7881e5d15
225
template-android-compose
MIT License
common/src/main/java/com/teko/common/base/BaseViewModel.kt
rsilvallana
661,504,875
false
null
package com.teko.common.base import androidx.lifecycle.ViewModel import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject abstract class BaseViewModel : ViewModel() { open val disposables: CompositeDisposable by lazy { CompositeDisposable() } @Inject lateinit var schedulers: BaseSchedulerProvider override fun onCleared() { super.onCleared() disposables.clear() } }
0
Kotlin
0
0
70efb0ffe0e620ff993c75315ec100d96dfead85
442
TekoTechV1
Apache License 2.0
client_support/common/src/commonMain/kotlin/org/thechance/common/presentation/chat/ChatUIState.kt
TheChance101
671,967,732
false
{"Kotlin": 2473455, "Ruby": 8872, "HTML": 6083, "Swift": 4726, "JavaScript": 3082, "CSS": 1436, "Dockerfile": 1407, "Shell": 1140}
package org.thechance.common.presentation.chat import org.thechance.common.domain.entity.Message import org.thechance.common.domain.entity.Ticket data class ChatUIState( val ticket: TicketUIState = TicketUIState(), val messages: List<MessageUIState> = emptyList(), val appbar: AppbarUIState = AppbarUIState(), val message: String = "", val loading: Boolean = true, val idle: Boolean = false, ) { data class TicketUIState( val id: String = "", val username: String = "", val userAvatarUrl: String = "", val openedAt: String = "", ) data class MessageUIState( val id: String, val message: String, val isMe: Boolean, val avatarUrl: String, val showAvatar: Boolean = false, ) data class AppbarUIState( val username: String = "John Doe", val isDropdownMenuExpanded: Boolean = false, ) } // region Mappers fun Message.toUIState(): ChatUIState.MessageUIState { return ChatUIState.MessageUIState( id = id, message = message, isMe = isMe, avatarUrl = avatarUrl, ) } fun Ticket.toUIState(): ChatUIState.TicketUIState { return ChatUIState.TicketUIState( id = id, username = username, userAvatarUrl = avatar, openedAt = openedAt, ) } fun List<Ticket>.toUIState(): List<ChatUIState.TicketUIState> { return map { it.toUIState() } } // endregion
4
Kotlin
55
572
1d2e72ba7def605529213ac771cd85cbab832241
1,459
beep-beep
Apache License 2.0
term-2/block-4/task-7/app-compose-desktop/src/main/kotlin/meteo/app/presentation/views/Screen.kt
AzimMuradov
626,118,027
false
null
package meteo.app.presentation.views import androidx.compose.foundation.layout.* import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import meteo.app.presentation.MeteoComposeMessagesWizard.isLoading import meteo.presentation.state.MeteoState @Composable fun Screen(state: MeteoState, onLoad: () -> Unit) { Column(modifier = Modifier.fillMaxSize()) { Spacer(Modifier.height(64.dp)) Content(state) } Header(isLoading = state.isLoading, onLoad = onLoad) }
0
Kotlin
0
0
20d712d69d19a399072ce997fe11f3066dc01354
546
computer-workshop-spbu
Apache License 2.0
src/main/kotlin/at/ac/tuwien/ifs/semsys/ontologydefectheuristics/OntologyDefectHeuristicsApplication.kt
wu-semsys
861,724,524
false
{"Kotlin": 38982}
package at.ac.tuwien.ifs.semsys.ontologydefectheuristics import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class OntologyDefectHeuristicsApplication fun main(args: Array<String>) { runApplication<OntologyDefectHeuristicsApplication>(*args) }
0
Kotlin
0
0
58346ccbc0544ea47a87c3576386eea03a01a7d1
334
ontology-defect-heuristics
MIT License
common/src/main/java/top/wangchenyan/common/storage/IPreferencesFile.kt
wangchenyan
625,252,978
false
null
package top.wangchenyan.common.storage import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty /** * Created by wcy on 2021/2/1. */ interface IPreferencesFile { fun remove(key: String) fun remove(keys: List<String>) fun removeExcept(exceptKeys: List<String>) fun clear() fun getBoolean(key: String, defValue: Boolean = false): Boolean fun putBoolean(key: String, value: Boolean) fun getInt(key: String, defValue: Int = 0): Int fun putInt(key: String, value: Int) fun getLong(key: String, defValue: Long = 0): Long fun putLong(key: String, value: Long) fun getFloat(key: String, defValue: Float = 0f): Float fun putFloat(key: String, value: Float) fun getString(key: String, defValue: String = ""): String fun putString(key: String, value: String) fun <T> getModel(key: String, clazz: Class<T>): T? fun <T> putModel(key: String, t: T?) fun <T> getList(key: String, clazz: Class<T>): List<T>? fun <T> putList(key: String, list: List<T>?) class BooleanProperty(private val key: String, private val defValue: Boolean = false) : ReadWriteProperty<IPreferencesFile, Boolean> { override fun getValue(thisRef: IPreferencesFile, property: KProperty<*>): Boolean { return thisRef.getBoolean(key, defValue) } override fun setValue(thisRef: IPreferencesFile, property: KProperty<*>, value: Boolean) { thisRef.putBoolean(key, value) } } class IntProperty(private val key: String, private val defValue: Int = 0) : ReadWriteProperty<IPreferencesFile, Int> { override fun getValue(thisRef: IPreferencesFile, property: KProperty<*>): Int { return thisRef.getInt(key, defValue) } override fun setValue(thisRef: IPreferencesFile, property: KProperty<*>, value: Int) { thisRef.putInt(key, value) } } class LongProperty(private val key: String, private val defValue: Long = 0L) : ReadWriteProperty<IPreferencesFile, Long> { override fun getValue(thisRef: IPreferencesFile, property: KProperty<*>): Long { return thisRef.getLong(key, defValue) } override fun setValue(thisRef: IPreferencesFile, property: KProperty<*>, value: Long) { thisRef.putLong(key, value) } } class FloatProperty(private val key: String, private val defValue: Float = 0F) : ReadWriteProperty<IPreferencesFile, Float> { override fun getValue(thisRef: IPreferencesFile, property: KProperty<*>): Float { return thisRef.getFloat(key, defValue) } override fun setValue(thisRef: IPreferencesFile, property: KProperty<*>, value: Float) { thisRef.putFloat(key, value) } } class StringProperty(private val key: String, private val defValue: String = "") : ReadWriteProperty<IPreferencesFile, String> { override fun getValue(thisRef: IPreferencesFile, property: KProperty<*>): String { return thisRef.getString(key, defValue) } override fun setValue(thisRef: IPreferencesFile, property: KProperty<*>, value: String) { thisRef.putString(key, value) } } class ObjectProperty<T>(private val key: String, private val clazz: Class<T>) : ReadWriteProperty<IPreferencesFile, T?> { override fun getValue(thisRef: IPreferencesFile, property: KProperty<*>): T? { return thisRef.getModel(key, clazz) } override fun setValue(thisRef: IPreferencesFile, property: KProperty<*>, value: T?) { thisRef.putModel(key, value) } } class ListProperty<T>(private val key: String, private val clazz: Class<T>) : ReadWriteProperty<IPreferencesFile, List<T>?> { override fun getValue(thisRef: IPreferencesFile, property: KProperty<*>): List<T>? { return thisRef.getList(key, clazz) } override fun setValue(thisRef: IPreferencesFile, property: KProperty<*>, value: List<T>?) { thisRef.putList(key, value) } } }
0
null
2
8
de242ff37ffd0a1093d8688d0beceab83331310d
4,162
android-common
Apache License 2.0
app/src/main/java/com/kennyc/pi_hole/di/modules/ViewModelFactoryModule.kt
Kennyc1012
347,626,187
false
null
package com.kennyc.pi_hole.di.modules import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.kennyc.pi_hole.MainViewModel import com.kennyc.pi_hole.di.DaggerViewModelFactory import com.kennyc.pi_hole.di.ViewModelKey import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap @Module abstract class ViewModelFactoryModule { @Binds abstract fun bindViewModelFactory(viewModelFactory: DaggerViewModelFactory): ViewModelProvider.Factory @Binds @IntoMap @ViewModelKey(MainViewModel::class) abstract fun bindCreatePinViewModel(viewModel: MainViewModel): ViewModel }
0
Kotlin
0
0
847fbbddd303a0189e9497254e7b13f7f7fa2332
642
Pi-Hole-Compose
Apache License 2.0
app/src/main/java/ng/mint/ocrscanner/dao/OfflineCardDao.kt
dalafiarisamuel
287,741,636
false
{"Kotlin": 112819}
package ng.mint.ocrscanner.dao import androidx.lifecycle.LiveData import androidx.room.* import kotlinx.coroutines.flow.Flow import ng.mint.ocrscanner.model.OfflineCard import ng.mint.ocrscanner.model.RecentCard @Dao interface OfflineCardDao : BaseDao<OfflineCard> { @Query("SELECT * FROM OfflineCard ORDER BY `_id` DESC") override fun getDataListLive(): Flow<MutableList<OfflineCard>> @Query("SELECT * FROM OfflineCard ORDER BY `_id` DESC") suspend fun getDataList(): MutableList<OfflineCard> @Query("SELECT * FROM OfflineCard ORDER BY `_id` DESC") fun getDataListLiveData(): LiveData<MutableList<OfflineCard>> @Insert(onConflict = OnConflictStrategy.IGNORE) override suspend fun insertSingle(data: OfflineCard) @Delete override suspend fun delete(data: OfflineCard) @Query("DELETE FROM OfflineCard") override suspend fun cleanTable() @Query("SELECT COUNT(*) FROM OfflineCard") override suspend fun getCount(): Long }
0
Kotlin
0
2
e80d87a0f272c24d1f7f7ab913e7ff418c4810c0
983
ocr-scan
MIT License
unrealengine/src/main/kotlin/dev/dexsr/gmod/palworld/trainer/ue/gvas/rawdata/Character.kt
flammky
758,310,188
false
{"Kotlin": 1015888}
package dev.dexsr.gmod.palworld.trainer.ue.gvas.rawdata import dev.dexsr.gmod.palworld.trainer.ue.gvas.* import dev.dexsr.gmod.palworld.trainer.ue.util.cast import java.io.ByteArrayOutputStream import java.nio.ByteBuffer import java.nio.ByteOrder object Character sealed class CharacterDict : CustomGvasDict() class GvasCharacterData( // @FieldName("object") val obj: GvasMap<String, GvasProperty>, val unknownBytes: ByteArray, val groupId: String ): CharacterDict() fun Character.decode( reader: GvasReader, typeName: String, size: Int, path: String ): GvasProperty { check(typeName == "ArrayProperty") { "CharacterKt.encode: Expected ArrayProperty, got$typeName" } val value = reader.property(typeName, size, path, nestedCallerPath = path) val arrayDict = value .value.cast<GvasArrayDict>() val dataBytes = arrayDict.value .cast<GvasAnyArrayPropertyValue>().values .cast<GvasByteArrayValue>().value value.value = CustomByteArrayRawData( customType = path, id = arrayDict.id, value = GvasArrayDict( arrayType = arrayDict.arrayType, id = arrayDict.id, value = GvasTransformedArrayValue(decodeBytes(reader, dataBytes)) ) ) return value } private fun Character.decodeBytes( parentReader: GvasReader, bytes: ByteArray ): GvasCharacterData { val reader = parentReader.copy(ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)) val data = GvasCharacterData( obj = reader.properties(""), unknownBytes = reader.readBytes(4), groupId = reader.uuid().toString() ) check(reader.isEof()) { "EOF not reached while decoding Character bytes" } return data } fun Character.encode( writer: GvasWriter, typeName: String, data: GvasProperty ): Int { require(typeName == "ArrayProperty") { "Expected ArrayProperty, got $typeName instead" } val arrayDict = data.value .cast<CustomByteArrayRawData>().value .cast<GvasArrayDict>() val characterData = arrayDict.value .cast<GvasTransformedArrayValue>().value .cast<GvasCharacterData>() val encodedBytes = encodeBytes(characterData) val copy = GvasProperty( data.type, value = GvasArrayDict( arrayDict.arrayType, arrayDict.id, value = GvasAnyArrayPropertyValue( values = GvasByteArrayValue( typeName = "ByteProperty", value = encodedBytes ) ) ) ) /*data.value = GvasArrayDict( arrayDict.arrayType, arrayDict.id, value = GvasAnyArrayPropertyValue( values = GvasByteArrayValue( typeName = "ByteProperty", value = encodedBytes ) ) )*/ return writer.writePropertyInner(typeName, copy).also { println("Character Encoded") } } private fun Character.encodeBytes(data: GvasCharacterData): ByteArray { val out = ByteArrayOutputStream() val writer = GvasWriter(output = out) writer.writeGvasPropertyMap(data.obj) writer.writeRawBytes(data.unknownBytes) writer.writeUId(data.groupId) return out.toByteArray() }
0
Kotlin
0
4
cd07163868b5ee8d3f46d106d467d211b8f3c5d8
3,324
PalToolbox
Apache License 2.0
PRACTICE_JETPACK/app/src/main/java/nlab/practice/jetpack/util/lifecycle/ActivityLifecycle.kt
skaengus2012
153,380,376
false
null
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nlab.practice.jetpack.util.lifecycle /** * Activity LifeCycle 종류 정의 * * @author Doohyun */ enum class ActivityLifecycle { ON_CREATE, ON_START, ON_RESUME, ON_PAUSE, ON_STOP, ON_DESTROY, FINISH } typealias ActivityLifecycleBinder = LifeCycleBinder<ActivityLifecycle>
2
Kotlin
0
0
6c742e0888f5e01e0d7f0f1dd3d57707c62716b0
929
Practice-Jetpack
Apache License 2.0
domain/src/main/java/br/ufs/hiring/stone/domain/GiveawayStatus.kt
ubiratansoares
114,146,491
false
null
package br.ufs.hiring.stone.domain /** * * Created by @ubiratanfsoares * */ sealed class GiveawayStatus { object Available : GiveawayStatus() object Received : GiveawayStatus() }
0
Kotlin
1
17
6f008f29d31a7a83e49ad157511b77ea970d0c7d
192
kryptokarteira-mobile
MIT License
sundowner-service/data/src/main/kotlin/de/tkoeppel/sundowner/basetype/SpotType.kt
tkoeppel
849,831,922
false
{"Kotlin": 10633, "TypeScript": 3993, "Nix": 1580, "HTML": 753, "SCSS": 153}
package de.tkoeppel.sundowner.basetype enum class SpotType { SUNSET }
5
Kotlin
0
0
f28be88e170b01b0b4e16f73dafdbe25b07560e2
71
sundowner
Boost Software License 1.0
src/main/kotlin/utils/Extensions.kt
jskako
686,469,615
false
{"Kotlin": 160737, "VBScript": 410, "Batchfile": 108}
package utils import notifications.ExportData import notifications.InfoManagerData import utils.Colors.darkRed import java.awt.Desktop import java.awt.Toolkit import java.awt.datatransfer.Clipboard import java.awt.datatransfer.StringSelection import java.io.File import java.io.FileWriter fun String.copyToClipboard(): InfoManagerData { if (this.trim().isEmpty()) { return InfoManagerData( message = getStringResource("error.clipboard.message.empty.data"), color = darkRed ) } return if (copyToClipboard(this)) { InfoManagerData( message = getStringResource("success.clipboard.message") ) } else { InfoManagerData( message = getStringResource("error.clipboard.message.failed"), color = darkRed ) } } private fun copyToClipboard(text: String): Boolean { return runCatching { val clipboard: Clipboard = Toolkit.getDefaultToolkit().systemClipboard clipboard.setContents(StringSelection(text), null) }.isSuccess } fun String.exportToFile( exportPath: String? = null ): ExportData { if (this.isBlank()) { return ExportData( infoManagerData = InfoManagerData( message = getStringResource("error.export.empty.data"), color = darkRed ) ) } val path = exportPath ?: pickDirectoryDialog() if (path.isNullOrBlank()) { return ExportData( infoManagerData = InfoManagerData( message = getStringResource("error.export.empty.path"), color = darkRed ) ) } val result = runCatching { val file = File(path) file.parentFile?.mkdirs() FileWriter(file, false).use { writer -> writer.write(this) } } return if (result.isFailure) { ExportData( infoManagerData = InfoManagerData( message = getStringResource("error.export.general"), color = darkRed ) ) } else { ExportData( infoManagerData = InfoManagerData( message = "${getStringResource("success.export.general")}: $path", duration = null, buttonVisible = true ), path = path ) } } fun openFolderAtPath(path: String): InfoManagerData { val result = runCatching { val file = File(path) if (file.exists() && Desktop.isDesktopSupported()) { Desktop.getDesktop().open(file) } else { throw IllegalArgumentException("${getStringResource("error.folder.not.found")} - $path") } } return if (result.isFailure) { InfoManagerData( message = result.exceptionOrNull()?.message ?: "", color = darkRed ) } else { InfoManagerData( message = "${getStringResource("success.open.success")}: $path" ) } } fun String.capitalizeFirstChar() = replaceFirstChar(Char::titlecase) fun String.runCommand(): String? = runCatching { ProcessBuilder(this.split("\\s".toRegex())) .redirectErrorStream(true) .start() .inputStream.bufferedReader().use { it.readText().trim() } }.getOrNull() fun String.findPath(): String = "which $this".runCommand()?.trim() ?: ""
7
Kotlin
1
16
4c7cb21a2096e742b3ff45c860048d4a6047aada
3,399
DroidSense
Apache License 2.0
net.akehurst.language/agl-processor/src/commonTest/kotlin/agl/automaton/examples/test_AhoSetiUlman_Ex_4_7_5.kt
dhakehurst
197,245,665
false
null
/** * Copyright (C) 2020 Dr. <NAME> (http://dr.david.h.akehurst.net) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.akehurst.language.agl.automaton import net.akehurst.language.agl.parser.ScanOnDemandParser import net.akehurst.language.agl.runtime.structure.RuntimeRuleChoiceKind import net.akehurst.language.agl.runtime.structure.runtimeRuleSet import net.akehurst.language.api.processor.AutomatonKind import kotlin.test.Test import kotlin.test.assertNotNull internal class test_AhoSetiUlman_Ex_4_7_5 : test_AutomatonAbstract() { // This grammar is LR(1) but not LALR(1) // TODO...from where? // S = A a | b A c | B c | b B a ; // A = d ; // B = d ; // // S = S1 | S2 | S3 | S4 // S1 = A a ; // S2 = b A c ; // S3 = B c ; // S4 = b B a ; // A = d ; // B = d ; // must be fresh per test or automaton is not correct for different parses (due to caching) private val rrs = runtimeRuleSet { choice("S", RuntimeRuleChoiceKind.LONGEST_PRIORITY) { ref("S1") ref("S2") ref("S3") ref("S4") } concatenation("S1") { ref("A"); literal("a") } concatenation("S2") { literal("b"); ref("A"); literal("c") } concatenation("S3") { ref("B"); literal("c") } concatenation("S4") { literal("b"); ref("B"); literal("a") } concatenation("A") { literal("d") } concatenation("B") { literal("d") } } private val S = rrs.findRuntimeRule("S") private val S1 = rrs.findRuntimeRule("S1") private val S2 = rrs.findRuntimeRule("S2") private val S3 = rrs.findRuntimeRule("S3") private val S4 = rrs.findRuntimeRule("S4") private val rA = rrs.findRuntimeRule("A") private val rB = rrs.findRuntimeRule("B") private val a = rrs.findRuntimeRule("'a'") private val b = rrs.findRuntimeRule("'b'") private val c = rrs.findRuntimeRule("'c'") private val d = rrs.findRuntimeRule("'d'") private val SM = rrs.fetchStateSetFor(S, AutomatonKind.LOOKAHEAD_1) private val s0 = SM.startState private val G = s0.runtimeRules.first() private val lhs_ac = SM.createLookaheadSet(false, false, false, setOf(a, c)) private val lhs_a = SM.createLookaheadSet(false, false, false, setOf(a)) private val lhs_c = SM.createLookaheadSet(false, false, false, setOf(c)) private val lhs_d = SM.createLookaheadSet(false, false, false, setOf(d)) @Test fun parse_da() { val parser = ScanOnDemandParser(rrs) parser.parseForGoal("S", "da", AutomatonKind.LOOKAHEAD_1) val actual = parser.runtimeRuleSet.fetchStateSetFor(S, AutomatonKind.LOOKAHEAD_1) println(rrs.usedAutomatonToString("S")) val expected = automaton(rrs, AutomatonKind.LOOKAHEAD_1, "S", false) { } AutomatonTest.assertEquals(expected, actual) } @Test fun buildFor() { val actual = rrs.buildFor("S", AutomatonKind.LOOKAHEAD_1) println(rrs.usedAutomatonToString("S")) val sentences = setOf("da","bdc","dc","bda") val parser = ScanOnDemandParser(rrs) sentences.forEach { val result = parser.parseForGoal("S", it, AutomatonKind.LOOKAHEAD_1) assertNotNull(result.sppt) } val expected = automaton(rrs, AutomatonKind.LOOKAHEAD_1, "S", false) { val s0 = state(RP(G, 0, SOR)) // G = . S val s1 = state(RP(d, 0, EOR)) // d val s2 = state(RP(b, 0, EOR)) // b val s3 = state(RP(rA, 0, EOR)) // A = d . val s4 = state(RP(rB, 0, EOR)) // B = d . val s5 = state(RP(S1, 0, 1)) // S1 = A . a val s6 = state(RP(a, 0, EOR)) val s7 = state(RP(S1, 0, EOR)) val s8 = state(RP(S, 0, EOR)) val s9 = state(RP(G, 0, ER)) val s10 = state(RP(S3, 0, 1)) val s11 = state(RP(c, 0, ER)) val s12 = state(RP(S3, 0, ER)) val s13 = state(RP(S, 2, ER)) val s14 = state(RP(S2, 0, 1), RP(S4, 0, 1)) val s15 = state(RP(S2, 0, 2)) val s16 = state(RP(S2, 0, ER)) val s17 = state(RP(S, 1, ER)) val s18 = state(RP(S4, 0, 2)) val s19 = state(RP(S4, 0, ER)) val s20 = state(RP(S, 3, ER)) transition(s0, s0, s1, WIDTH, setOf(a, c), setOf(setOf(EOT)), setOf()) transition(s0, s0, s2, WIDTH, setOf(d), setOf(setOf(EOT)), setOf()) transition(s0, s1, s3, HEIGHT, setOf(a), setOf(setOf(a)), setOf(RP(rA, 0, 0))) transition(s0, s1, s4, HEIGHT, setOf(c), setOf(setOf(c)), setOf(RP(rB, 0, 0))) transition(s14, s1, s3, HEIGHT, setOf(c), setOf(setOf(c)), setOf(RP(rA, 0, 0))) transition(s14, s1, s4, HEIGHT, setOf(a), setOf(setOf(a)), setOf(RP(rB, 0, 0))) transition(s0, s2, s4, HEIGHT, setOf(a, c), setOf(setOf(EOT)), setOf()) transition(s0, s0, s1, HEIGHT, setOf(a, c), setOf(setOf(EOT)), setOf()) } AutomatonTest.assertEquals(expected, actual) } @Test fun compare() { val rrs_noBuild = rrs.clone() val rrs_preBuild = rrs.clone() val parser = ScanOnDemandParser(rrs_noBuild) val sentences = listOf("da","bdc","dc","bda") for(sen in sentences) { val result = parser.parseForGoal("S", sen, AutomatonKind.LOOKAHEAD_1) if (result.issues.isNotEmpty()) result.issues.forEach { println(it) } } val automaton_noBuild = rrs_noBuild.usedAutomatonFor("S") val automaton_preBuild = rrs_preBuild.buildFor("S",AutomatonKind.LOOKAHEAD_1) println("--Pre Build--") println(rrs_preBuild.usedAutomatonToString("S")) println("--No Build--") println(rrs_noBuild.usedAutomatonToString("S")) AutomatonTest.assertEquals(automaton_preBuild, automaton_noBuild) } }
3
null
7
45
177abcb60c51efcfc2432174f5d6620a7db89928
6,469
net.akehurst.language
Apache License 2.0
kotlin-electron/src/jsMain/generated/electron/common/DidFrameFinishLoadEvent.kt
JetBrains
93,250,841
false
{"Kotlin": 11411371, "JavaScript": 154302}
package electron.common typealias DidFrameFinishLoadEvent = electron.core.DidFrameFinishLoadEvent
28
Kotlin
173
1,250
9e9dda28cf74f68b42a712c27f2e97d63af17628
100
kotlin-wrappers
Apache License 2.0
richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/model/RichTextConfig.kt
MohamedRejeb
630,584,174
false
{"Kotlin": 512444}
package com.mohamedrejeb.richeditor.model import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextDecoration class RichTextConfig internal constructor( private val updateText: () -> Unit, ) { var linkColor: Color = Color.Blue set(value) { field = value updateText() } var linkTextDecoration: TextDecoration = TextDecoration.Underline set(value) { field = value updateText() } var codeSpanColor: Color = Color.Unspecified set(value) { field = value updateText() } var codeSpanBackgroundColor: Color = Color.Transparent set(value) { field = value updateText() } var codeSpanStrokeColor: Color = Color.LightGray set(value) { field = value updateText() } var listIndent: Int = DefaultListIndent set(value) { field = value updateText() } /** * Whether to preserve the style when the line is empty. * The line can be empty when the user deletes all the characters * or when the user presses `enter` to create a new line. * * Default is `true`. */ var preserveStyleOnEmptyLine: Boolean = true } internal const val DefaultListIndent = 38
56
Kotlin
56
894
c7150e29eea95171701f685e095bfc2cac823620
1,372
Compose-Rich-Editor
Apache License 2.0
psiminer-core/src/test/kotlin/psi/transformations/excludenode/JavaExcludeTransformationTest.kt
JetBrains-Research
248,702,388
false
null
package psi.transformations.excludenode import JavaPsiRequiredTest import com.intellij.openapi.application.ReadAction import com.intellij.psi.PsiElement import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.ValueSource import psi.nodeProperties.isHidden import psi.preOrder import psi.transformations.PsiTreeTransformation import kotlin.reflect.KClass abstract class JavaExcludeTransformationTest : JavaPsiRequiredTest("JavaMethods") { abstract val transformation: PsiTreeTransformation abstract val excludeType: KClass<out PsiElement> @ParameterizedTest @ValueSource( strings = ["abstractMethod", "emptyMethod", "smallMethod", "largeMethod", "recursiveMethod"] ) fun `test ignoring in Java methods`(methodName: String) = ReadAction.run<Exception> { val psiRoot = getMethod(methodName) transformation.transform(psiRoot) val notHiddenNodes = psiRoot.preOrder().count { excludeType.isInstance(it) && !it.isHidden } assertEquals(0, notHiddenNodes) } }
13
Kotlin
11
52
6b647ea5aaa41bbad01806c12cfb0c5a700c7073
1,058
psiminer
Apache License 2.0
app/src/main/java/com/kyoapps/maniac/dagger/modules/DbModule.kt
shamo42
136,873,627
false
{"Kotlin": 86454}
/* * Copyright (c) 2018-present, <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.kyoapps.maniac.dagger.modules import android.content.Context import com.kyoapps.maniac.dagger.scopes.CommonActivityScope import com.kyoapps.maniac.room.DatabaseDefault import dagger.Module import dagger.Provides @Module object DbModule { @Provides @CommonActivityScope fun getDB(context: Context): DatabaseDefault { return DatabaseDefault.getInstance(context) } }
0
Kotlin
0
3
9f1232709ee1ee4c651e205f037635f061608d8f
1,006
maniac
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/visitscheduler/integration/visit/VisitByReferenceTest.kt
ministryofjustice
409,259,375
false
{"Kotlin": 1689208, "PLpgSQL": 167624, "FreeMarker": 14114, "Dockerfile": 1541, "Shell": 238}
package uk.gov.justice.digital.hmpps.visitscheduler.integration.visit import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.springframework.http.HttpHeaders import uk.gov.justice.digital.hmpps.visitscheduler.controller.GET_VISIT_BY_REFERENCE import uk.gov.justice.digital.hmpps.visitscheduler.dto.ContactDto import uk.gov.justice.digital.hmpps.visitscheduler.dto.enums.VisitStatus.BOOKED import uk.gov.justice.digital.hmpps.visitscheduler.dto.enums.VisitStatus.CANCELLED import uk.gov.justice.digital.hmpps.visitscheduler.helper.callVisitByReference import uk.gov.justice.digital.hmpps.visitscheduler.integration.IntegrationTestBase import java.time.LocalDate import java.time.LocalDateTime @DisplayName("GET $GET_VISIT_BY_REFERENCE") class VisitByReferenceTest : IntegrationTestBase() { private val visitTime: LocalDateTime = LocalDateTime.of(LocalDate.now().year + 1, 11, 1, 12, 30, 44) private lateinit var roleVisitSchedulerHttpHeaders: (HttpHeaders) -> Unit @BeforeEach internal fun setUp() { roleVisitSchedulerHttpHeaders = setAuthorisation(roles = listOf("ROLE_VISIT_SCHEDULER")) sessionTemplateDefault = sessionTemplateEntityHelper.create(startTime = visitTime.toLocalTime(), endTime = visitTime.plusHours(1).toLocalTime()) } @Test fun `Booked visit by reference`() { // Given val slotDate = sessionDatesUtil.getFirstBookableSessionDay(sessionTemplateDefault) val createdVisit = visitEntityHelper.create(prisonerId = "FF0000AA", visitStatus = BOOKED, slotDate = slotDate, sessionTemplate = sessionTemplateDefault, visitContact = ContactDto("<NAME>", "01111111111")) val reference = createdVisit.reference // When val responseSpec = callVisitByReference(webTestClient, reference, roleVisitSchedulerHttpHeaders) // Then responseSpec.expectStatus().isOk .expectBody() .jsonPath("$.reference").isEqualTo(reference) } @Test fun `when booked visit has no contact telephone get visit by reference returns contact phone as null`() { // Given val slotDate = sessionDatesUtil.getFirstBookableSessionDay(sessionTemplateDefault) val createdVisit = visitEntityHelper.create(prisonerId = "FF0000AA", visitStatus = BOOKED, slotDate = slotDate, sessionTemplate = sessionTemplateDefault, visitContact = ContactDto("Test User", null)) val reference = createdVisit.reference // When val responseSpec = callVisitByReference(webTestClient, reference, roleVisitSchedulerHttpHeaders) // Then val returnResult = responseSpec.expectStatus().isOk val visit = getVisitDto(returnResult) assertThat(visit.visitContact).isNotNull() assertThat(visit.visitContact.name).isEqualTo("<NAME>") assertThat(visit.visitContact.telephone).isNull() } @Test fun `Canceled visit by reference`() { // Given val slotDate = sessionDatesUtil.getFirstBookableSessionDay(sessionTemplateDefault) val createdVisit = visitEntityHelper.create(prisonerId = "FF0000AA", visitStatus = CANCELLED, slotDate = slotDate, sessionTemplate = sessionTemplateDefault, visitContact = ContactDto("<NAME>", "01111111111")) val reference = createdVisit.reference // When val responseSpec = callVisitByReference(webTestClient, reference, roleVisitSchedulerHttpHeaders) // Then responseSpec.expectStatus().isOk .expectBody() .jsonPath("$.reference").isEqualTo(reference) } @Test fun `Visit by reference - not found`() { // Given val reference = "12345" // When val responseSpec = callVisitByReference(webTestClient, reference, roleVisitSchedulerHttpHeaders) // Then responseSpec.expectStatus().isNotFound } }
2
Kotlin
2
5
9ea90594fe6f124dea8eeebce0129ee3b87497d7
3,792
visit-scheduler
MIT License
api/src/main/kotlin/com/williamtan/helloword/api/LessonApi.kt
williamtan1989
619,193,723
false
null
package com.williamtan.helloword.api import com.william.helloword.commonkey.LanguageId import com.williamtan.helloword.api.dto.lesson.LessonListDto import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.request.get class LessonApi(private val httpClient: HttpClient) { suspend fun getLessonList(languageId: LanguageId): Result<LessonListDto> { val httpResponse = httpClient.get("lesson/${languageId}/lesson_master_list.json") return if (httpResponse.status.value == 200) { Result.success(httpResponse.body()) } else { Result.failure(Throwable("OPs!")) } } }
0
Kotlin
0
0
d5e7a1d05a645ae94472d72c5e1d4f67e80a8de7
656
hello-word-android
Apache License 2.0
android/quest/src/main/java/org/smartregister/fhircore/quest/navigation/MainNavigationScreen.kt
opensrp
339,242,809
false
null
/* * Copyright 2021-2024 Ona Systems, Inc * * 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.smartregister.fhircore.quest.navigation import org.smartregister.fhircore.engine.R sealed class MainNavigationScreen( val titleResource: Int? = null, val iconResource: Int? = null, val route: Int, val showInBottomNav: Boolean = false, ) { data object Home : MainNavigationScreen( R.string.clients, org.smartregister.fhircore.quest.R.drawable.ic_home, org.smartregister.fhircore.quest.R.id.registerFragment, true, ) data object Reports : MainNavigationScreen( R.string.reports, R.drawable.ic_reports, org.smartregister.fhircore.quest.R.id.measureReportFragment, true, ) data object Settings : MainNavigationScreen( R.string.settings, R.drawable.ic_settings, org.smartregister.fhircore.quest.R.id.userSettingFragment, true, ) data object Profile : MainNavigationScreen( titleResource = R.string.profile, route = org.smartregister.fhircore.quest.R.id.profileFragment, ) object GeoWidgetLauncher : MainNavigationScreen(route = org.smartregister.fhircore.quest.R.id.geoWidgetLauncherFragment) data object Insight : MainNavigationScreen(route = org.smartregister.fhircore.quest.R.id.userInsightScreenFragment) data object LocationSelector : MainNavigationScreen( route = org.smartregister.fhircore.quest.R.id.multiSelectBottomSheetFragment, ) data object SummaryBottomSheetFragment : MainNavigationScreen( route = org.smartregister.fhircore.quest.R.id.summaryBottomSheetFragment, ) fun eventId(id: String) = route.toString() + "_" + id }
192
null
56
56
64a55e6920cb6280cf02a0d68152d9c03266518d
2,240
fhircore
Apache License 2.0
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/subassemblies/DriveBase.kt
ManchesterMachineMakers
417,294,104
false
{"Kotlin": 102070, "Java": 46534, "Shell": 5590, "Makefile": 1243}
package org.firstinspires.ftc.teamcode.subassemblies import com.farthergate.ctrlcurve.PID import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode import com.qualcomm.robotcore.hardware.DcMotor import com.qualcomm.robotcore.hardware.DcMotor.RunMode import com.qualcomm.robotcore.hardware.DcMotorEx import com.qualcomm.robotcore.hardware.DcMotorSimple import com.qualcomm.robotcore.hardware.Gamepad import com.qualcomm.robotcore.util.RobotLog import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit import org.firstinspires.ftc.teamcode.util.Subassembly import org.firstinspires.ftc.teamcode.util.log import org.firstinspires.ftc.teamcode.util.powerCurve import kotlin.math.* class DriveBase(opMode: LinearOpMode) : Subassembly(opMode, "Drive Base") { private val leftFront = hardwareMap.dcMotor.get("left_front") private val rightFront = hardwareMap.dcMotor.get("right_front") private val leftRear = hardwareMap.dcMotor.get("left_rear") private val rightRear = hardwareMap.dcMotor.get("right_rear") private val imu = IMUManager(opMode) companion object { const val wheelBaseWidth = 420.0 // mm const val motorEncoderEventsPerRevolution = 537.7 const val wheelCircumference = 310.0 // mm const val motorEncoderEventsPerMM = motorEncoderEventsPerRevolution / wheelCircumference } enum class TurnDirection { LEFT, RIGHT } init { // direction = FORWARD by default //leftFront.direction = DcMotorSimple.Direction.REVERSE rightFront.direction = DcMotorSimple.Direction.REVERSE leftRear.direction = DcMotorSimple.Direction.REVERSE //rightRear.direction = DcMotorSimple.Direction.REVERSE opMode.log("DriveBase successfully initialized") } fun opInit() { setRunMode(RunMode.RUN_WITHOUT_ENCODER) setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE) } fun control(gamepad: Gamepad) { // from https://gm0.org/en/latest/docs/software/tutorials/mecanum-drive.html val leftX: Double = -gamepad.left_stick_x.toDouble() val leftY: Double = gamepad.left_stick_y.toDouble() val rightX: Double = -gamepad.right_stick_x.toDouble() // Denominator is the largest motor power (absolute value) or 1 // This ensures all the powers maintain the same ratio, // but only if at least one is out of the range [-1, 1] // Denominator is the largest motor power (absolute value) or 1 // This ensures all the powers maintain the same ratio, // but only if at least one is out of the range [-1, 1] val denominator = max(abs(leftY) + abs(leftX) + abs(rightX), 1.0) val leftFrontPower = (leftY + leftX + rightX) val rightFrontPower = (leftY - leftX - rightX) val leftRearPower = (leftY - leftX + rightX) val rightRearPower = (leftY + leftX - rightX) leftFront.power = powerCurve(leftFrontPower) rightFront.power = powerCurve(rightFrontPower) leftRear.power = powerCurve(leftRearPower) rightRear.power = powerCurve(rightRearPower) } override fun telemetry() { super.telemetry() telemetry.addLine() } data class MoveRobotCalculations( val x: Double, val y: Double, val yaw: Double, val leftFront: Double = x - y - yaw, val rightFront: Double = x + y + yaw, val leftRear: Double = (x + y - yaw), val rightRear: Double = x - y + yaw ) /** * Taken from the RobotAutoDriveToAprilTagOmni example (2023) Move robot according to desired * axes motions * * Positive X is forward * * Positive Y is strafe left * * Positive Yaw is counter-clockwise */ fun moveRobot(x: Double, y: Double, yaw: Double) { // Calculate wheel powers. var (_, _, _, leftFrontPower, rightFrontPower, leftBackPower, rightBackPower) = MoveRobotCalculations(x, y, yaw) // Normalize wheel powers to be less than 1.0 var max = max(abs(leftFrontPower), abs(rightFrontPower)) max = max(max, abs(leftBackPower)) max = max(max, abs(rightBackPower)) if (max > 1.0) { leftFrontPower /= max rightFrontPower /= max leftBackPower /= max rightBackPower /= max } // Send powers to the wheels. leftFront.power = leftFrontPower rightFront.power = rightFrontPower leftRear.power = leftBackPower rightRear.power = rightBackPower } val motors = listOf(leftFront, rightFront, leftRear, rightRear) fun List<DcMotor>.setMode(mode: RunMode) { map { it.mode = mode } } fun setMode(mode: RunMode) { motors.setMode(mode) } fun setTargetPositions(lf: Int, rf: Int, lr: Int, rr: Int) { leftFront.targetPosition = lf rightFront.targetPosition = rf leftRear.targetPosition = lr rightRear.targetPosition = rr } fun setPower(lf: Double, rf: Double, lr: Double, rr: Double) { leftFront.power = lf rightFront.power = rf leftRear.power = lr rightRear.power = rr } fun setPower(powers: Array<Double>) { motors.forEachIndexed { index, motor -> motor.power = powers[index] } } fun runToPosition(lf: Int, rf: Int, lr: Int, rr: Int) { setMode(RunMode.STOP_AND_RESET_ENCODER) setMode(RunMode.RUN_USING_ENCODER) setTargetPositions(abs(lf), abs(rf), abs(lr), abs(rr)) motors.map { (it as DcMotorEx).targetPositionTolerance = 5 } setMode(RunMode.RUN_TO_POSITION) leftFront.power = if (lf < 0) -0.5 else 0.5 rightFront.power = if (rf < 0) -0.5 else 0.5 leftRear.power = if (lr < 0) -0.5 else 0.5 rightRear.power = if (rr < 0) -0.5 else 0.5 } fun runToPosition(ticks: Int) { runToPosition(ticks, ticks, ticks, ticks) } /** * Drive a number of ticks in a particular direction. Stops on exception. * @param power the power to each motor (we can make this a list if needed) * @param encoderTicks a list of encoder tick values, distances that each motor should go by the * encoders. * @param tolerance the tolerance to set on each motor */ fun go(power: Double, encoderTicks: Array<Int>, tolerance: Int): Double { RobotLog.i("Power: $power Encoder Ticks: $encoderTicks") RobotLog.i("Tolerance: $tolerance") // set each motor, based on drive configuration/travel direction for (i in motors.indices) { motors[i].mode = RunMode.RUN_USING_ENCODER motors[i].targetPosition = encoderTicks[ i] // calcTargetPosition(motors[i].getDirection(), currentPositions[i], // encoderTicks[i])); (motors[i] as DcMotorEx).targetPositionTolerance = tolerance motors[i].mode = RunMode.RUN_TO_POSITION motors[i].power = power } return power } fun yaw(radians: Double, direction: TurnDirection) { setMode(RunMode.STOP_AND_RESET_ENCODER) val angle = when(direction) { TurnDirection.LEFT -> radians TurnDirection.RIGHT -> -radians } val ticks = angle * wheelBaseWidth/2 * motorEncoderEventsPerMM setTargetPositions(ticks.roundToInt(), -ticks.roundToInt(), ticks.roundToInt(), -ticks.roundToInt()) setMode(RunMode.RUN_TO_POSITION) setPower(0.7, 0.7, 0.7, 0.7) while(motors.any { it.isBusy }) opMode.idle() } // fun yawIMU(radians: Double, direction: TurnDirection) { // val telemetryYaw = telemetry.addData("Yaw", imu.imu.robotYawPitchRollAngles.getYaw(AngleUnit.RADIANS)) // setMode(RunMode.RUN_USING_ENCODER) // imu.imu.resetYaw() // // val turnCorrections = arrayOf(1.0, -1.0, 1.0, -1.0) // // opMode.log("current,target,proportional,integral,derivative,correction") // // val pid = PID(0.01, 100.0, 100.0, 10.0, 5.0, when(direction) { // TurnDirection.LEFT -> imu.imu.robotYawPitchRollAngles.getYaw(AngleUnit.RADIANS) // TurnDirection.RIGHT -> -imu.imu.robotYawPitchRollAngles.getYaw(AngleUnit.RADIANS) // }, when(direction) { // TurnDirection.LEFT -> radians // TurnDirection.RIGHT -> -radians // }) // while(pid.shouldContinue() && opMode.opModeIsActive()) { // setPower(turnCorrections.map { it * pid.correction() * when(direction) { // TurnDirection.LEFT -> 1 // TurnDirection.RIGHT -> -1 // } }.toTypedArray()) // opMode.idle() // telemetry.update() // pid.sync() // val newOrientation = imu.imu.robotYawPitchRollAngles.getYaw(AngleUnit.RADIANS).let { // when(direction) { // // The IMU returns values between -180 and 180, so we have to absolute value stuff in order to get there // TurnDirection.LEFT -> // if(radians == PI) // if(it < 0) // PI + (PI - abs(it)) // else it // else it // TurnDirection.RIGHT -> // if(radians == PI) // if(it < 0) // PI + (PI - abs(it)) // else it // else it // } // } // opMode.log("${pid.current},$radians,${pid.proportional()},${pid.integral()},${pid.derivative()},${pid.correction()}") // pid.update(newOrientation) // } // // setPower(0.0, 0.0, 0.0, 0.0) // telemetry.update() // } enum class TravelDirection { // see this link on enum naming convention: https://kotlinlang.org/docs/coding-conventions.html#names-for-backing-properties BASE, FORWARD, REVERSE, PIVOT_LEFT, PIVOT_RIGHT, STRAFE_LEFT, STRAFE_LEFT_FORWARD, STRAFE_LEFT_BACKWARD, STRAFE_RIGHT, STRAFE_RIGHT_FORWARD, STRAFE_RIGHT_BACKWARD, @Deprecated("Newer drive bases do not support pitching") PITCH } fun mecanumCoefficientsForDirection(direction: TravelDirection) = when (direction) { TravelDirection.BASE, TravelDirection.FORWARD -> arrayOf(1, 1, 1, 1) TravelDirection.REVERSE -> arrayOf(-1, -1, -1, -1) TravelDirection.PIVOT_LEFT -> arrayOf(-1, 1, -1, 1) TravelDirection.PIVOT_RIGHT -> arrayOf(1, -1, 1, -1) TravelDirection.STRAFE_LEFT -> arrayOf(-1, 1, 1, -1) TravelDirection.STRAFE_LEFT_FORWARD -> arrayOf(0, 1, 1, 0) TravelDirection.STRAFE_LEFT_BACKWARD -> arrayOf(-1, 0, 0, -1) TravelDirection.STRAFE_RIGHT -> arrayOf(1, -1, -1, 1) TravelDirection.STRAFE_RIGHT_FORWARD -> arrayOf(1, 0, 0, 1) TravelDirection.STRAFE_RIGHT_BACKWARD -> arrayOf(0, -1, -1, 0) TravelDirection.PITCH -> arrayOf(0, 0, 0, 0) } fun setRunMode(runMode: RunMode): Boolean { return try { for (motor in motors) { motor.mode = runMode } true } catch (e: Exception) { RobotLog.i(e.message) false } } fun setZeroPowerBehavior(zeroPowerBehavior: DcMotor.ZeroPowerBehavior): Boolean { return try { for (motor in motors) { motor.zeroPowerBehavior = zeroPowerBehavior } true } catch (e: Exception) { RobotLog.i(e.message) false } } }
1
Kotlin
1
1
a1977d45064293c1c8193f8c6beabdc3f73f580e
11,949
RobotController
BSD 3-Clause Clear License
features/details/src/main/java/com/fappslab/features/details/data/repository/DetailsRepositoryImpl.kt
F4bioo
628,097,763
false
null
package com.fappslab.features.details.data.repository import com.fappslab.features.details.data.source.DetailsDataSource import com.fappslab.features.details.domain.model.App import com.fappslab.features.details.domain.repository.DetailsRepository import io.reactivex.Single internal class DetailsRepositoryImpl( private val dataSource: DetailsDataSource ) : DetailsRepository { override fun getApp(packageName: String): Single<App> = dataSource.getApp(packageName) }
0
Kotlin
0
0
d3e0405eae2038ea13c352daa8bc976da85914a4
487
faurecia-aptoide-challenge
MIT License
android/src/main/java/com/espidfprovisioning/EspIdfProvisioningModule.kt
eSpark-Consultants
730,869,731
false
{"Kotlin": 23486, "Swift": 9703, "TypeScript": 6301, "Objective-C++": 2786, "Ruby": 1761, "Java": 674, "Objective-C": 74}
package com.espidfprovisioning import android.Manifest import android.annotation.SuppressLint import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothManager import android.bluetooth.le.ScanResult import android.content.Context import android.content.pm.PackageManager import android.os.Build import android.util.Log import androidx.core.content.ContextCompat import com.espressif.provisioning.DeviceConnectionEvent import com.espressif.provisioning.ESPConstants import com.espressif.provisioning.ESPDevice import com.espressif.provisioning.ESPProvisionManager import com.espressif.provisioning.WiFiAccessPoint import com.espressif.provisioning.listeners.BleScanListener import com.espressif.provisioning.listeners.ProvisionListener import com.espressif.provisioning.listeners.ResponseListener import com.espressif.provisioning.listeners.WiFiScanListener import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.Promise import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactMethod import com.facebook.react.bridge.WritableMap import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode import java.lang.Exception import java.util.ArrayList import java.util.Base64 class EspIdfProvisioningModule internal constructor(context: ReactApplicationContext?) : EspIdfProvisioningSpec(context) { private val TAG = "EspIdfProvisioningModule" override fun getName(): String { return NAME } companion object { const val NAME = "EspIdfProvisioning" } private val espProvisionManager = ESPProvisionManager.getInstance(context) private val espDevices = HashMap<String, ESPDevice>() private val bluetoothAdapter = (context?.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter private fun hasBluetoothPermissions(): Boolean { if (Build.VERSION.SDK_INT <= 30) { return ContextCompat.checkSelfPermission(reactApplicationContext, Manifest.permission.BLUETOOTH) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(reactApplicationContext, Manifest.permission.BLUETOOTH_ADMIN) == PackageManager.PERMISSION_GRANTED } else if ( ContextCompat.checkSelfPermission(reactApplicationContext, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(reactApplicationContext, Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED ) { return true } return false } private fun hasWifiPermission(): Boolean { if ( ContextCompat.checkSelfPermission(reactApplicationContext, Manifest.permission.CHANGE_WIFI_STATE) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(reactApplicationContext, Manifest.permission.ACCESS_WIFI_STATE) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(reactApplicationContext, Manifest.permission.ACCESS_NETWORK_STATE) == PackageManager.PERMISSION_GRANTED ) { return true } return false } private fun hasFineLocationPermission(): Boolean { return ContextCompat.checkSelfPermission(reactApplicationContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED } @SuppressLint("MissingPermission") @ReactMethod override fun searchESPDevices(devicePrefix: String, transport: String, security: Int, promise: Promise?) { // Permission checks if ( !hasBluetoothPermissions() || !hasFineLocationPermission() ) { promise?.reject(Error("Missing one of the following permissions: BLUETOOTH, BLUETOOTH_ADMIN, BLUETOOTH_CONNECT, BLUETOOTH_SCAN, ACCESS_FINE_LOCATION")) return } val transportEnum = when (transport) { "softap" -> ESPConstants.TransportType.TRANSPORT_SOFTAP "ble" -> ESPConstants.TransportType.TRANSPORT_BLE else -> ESPConstants.TransportType.TRANSPORT_BLE } val securityEnum = when (security) { 0 -> ESPConstants.SecurityType.SECURITY_0 1 -> ESPConstants.SecurityType.SECURITY_1 2 -> ESPConstants.SecurityType.SECURITY_2 else -> ESPConstants.SecurityType.SECURITY_2 } espDevices.clear() Log.i(TAG,"START SCANNING"); val invoked = false if (transport == "softap") { espProvisionManager.searchWiFiEspDevices(devicePrefix, object : WiFiScanListener { override fun onWifiListReceived(wifiList: ArrayList<WiFiAccessPoint>) { Log.i(TAG, "START SCANNING WIFI $wifiList"); if (wifiList.size == 0) { promise?.reject(Error("No device found with given prefix")) return } val resultArray = Arguments.createArray() wifiList?.forEach { item -> Log.i(TAG, "SCANNED DEVICE ${item.wifiName}") Log.i(TAG, "SCANNED DEVICE SECURITY ${item.security}") val resultMap = Arguments.createMap() resultMap.putString("name", item.wifiName) resultMap.putString("transport", transport) resultMap.putInt("security", item.se) resultArray.pushMap(resultMap) } promise?.resolve(resultArray) } override fun onWiFiScanFailed(e: Exception?) { Log.e(TAG,"START SCANNING FAILED"); } }) }else{ espProvisionManager.searchBleEspDevices(devicePrefix, object : BleScanListener { override fun scanStartFailed() { promise?.reject(Error("Scan could not be started.")) } override fun onPeripheralFound(device: BluetoothDevice?, scanResult: ScanResult?) { // Can this happen? if (device == null) { return } val deviceName = scanResult?.scanRecord?.deviceName // No device name if (deviceName.isNullOrEmpty()) { return } var serviceUuid: String? = null if (scanResult.scanRecord?.serviceUuids != null && scanResult.scanRecord?.serviceUuids?.size!! > 0) { serviceUuid = scanResult.scanRecord?.serviceUuids?.get(0).toString() } if (serviceUuid != null && !espDevices.containsKey(deviceName)) { val espDevice = ESPDevice(reactApplicationContext, transportEnum, securityEnum) espDevice.bluetoothDevice = device espDevice.deviceName = deviceName espDevice.primaryServiceUuid = serviceUuid espDevices[deviceName] = espDevice } } override fun scanCompleted() { if (espDevices.size == 0) { promise?.reject(Error("No bluetooth device found with given prefix")) return } val resultArray = Arguments.createArray() espDevices.values.forEach { espDevice -> val resultMap = Arguments.createMap() resultMap.putString("name", espDevice.deviceName) resultMap.putArray("capabilities", Arguments.fromList(espDevice.deviceCapabilities)) resultMap.putInt("security", security) resultMap.putString("transport", transport) resultMap.putString("username", espDevice.userName) resultMap.putString("versionInfo", espDevice.versionInfo) resultMap.putString("address", espDevice.bluetoothDevice.address) resultMap.putString("primaryServiceUuid", espDevice.primaryServiceUuid) resultArray.pushMap(resultMap) } promise?.resolve(resultArray) } override fun onFailure(e: Exception?) { promise?.reject(e) } }) } } @SuppressLint("MissingPermission") @ReactMethod override fun stopESPDevicesSearch() { // Permission checks if ( !hasBluetoothPermissions() || !hasFineLocationPermission() ) { // If we don't have permissions we are probably not scanning either, so just return return } espProvisionManager.stopBleScan() } @SuppressLint("MissingPermission") @ReactMethod override fun createESPDevice( deviceName: String, transport: String, security: Int, proofOfPossession: String?, softAPPassword: String?, username: String?, promise: Promise? ) { // Permission checks if (!hasBluetoothPermissions()) { promise?.reject(Error("Missing one of the following permissions: BLUETOOTH, BLUETOOTH_ADMIN, BLUETOOTH_CONNECT, BLUETOOTH_SCAN")) return } val transportEnum = when (transport) { "softap" -> ESPConstants.TransportType.TRANSPORT_SOFTAP "ble" -> ESPConstants.TransportType.TRANSPORT_BLE else -> ESPConstants.TransportType.TRANSPORT_BLE } val securityEnum = when (security) { 0 -> ESPConstants.SecurityType.SECURITY_0 1 -> ESPConstants.SecurityType.SECURITY_1 2 -> ESPConstants.SecurityType.SECURITY_2 else -> ESPConstants.SecurityType.SECURITY_2 } Log.i(TAG, "espDevices ${espDevices[deviceName]}") // If no ESP device found in list (no scan has been performed), create a new one if (espDevices[deviceName] == null) { val espDevice = espProvisionManager.createESPDevice(transportEnum, securityEnum) var bleDevice = espDevice?.bluetoothDevice // var wifiDevice = espDevice?.connectWiFiDevice() // var wifiDevices = ArrayList<WiFiAccessPoint>(); if (transport == "softap"){ espDevice.deviceName = deviceName espDevice.proofOfPossession = proofOfPossession espDevices[deviceName] = espDevice val result = Arguments.createMap() Log.d(TAG, "WIFI devices before ${espDevices[deviceName]?.proofOfPossession}") promise?.resolve(result) return; // EventBus.getDefault().register(object { // @Subscribe(threadMode = ThreadMode.MAIN) // fun onEvent(event: DeviceConnectionEvent) { // when (event.eventType) { // ESPConstants.EVENT_DEVICE_CONNECTED -> { // Log.d(TAG, "Device Connected Event Received") // Log.i(TAG, "espDevice data ${espDevice.proofOfPossession}") // espDevices[deviceName]?.scanNetworks(object : WiFiScanListener { // override fun onWifiListReceived(wifiList: ArrayList<WiFiAccessPoint>?) { // Log.i(TAG, "wifilists data $wifiList") // if (wifiList != null) { // wifiDevices = wifiList // } // val resultArray = Arguments.createArray() // // wifiList?.forEach { item -> // Log.i(TAG, "wifilists data ${item.wifiName}") // val resultMap = Arguments.createMap() // resultMap.putString("ssid", item.wifiName) // resultMap.putInt("rssi", item.rssi) // resultMap.putInt("auth", item.security) // resultArray.pushMap(resultMap) // } // // promise?.resolve(resultArray) // } // // override fun onWiFiScanFailed(e: Exception?) { // promise?.reject(e) // } // }) // } // ESPConstants.EVENT_DEVICE_CONNECTION_FAILED -> { // Log.d(TAG, "Device connection failed.") // } // else -> { // // Do nothing // } // } // // // Unregister event listener after 1 event received // EventBus.getDefault().unregister(this) // } // }) // // // Log.i(TAG, "WIFI DEV $wifiDevice") // // If the bluetooth device does not contain service uuids, try using the bonded // // one (if it exists) // // if (wifiDevices != null) { // val resultArray = Arguments.createArray() // wifiDevices?.forEach { item -> // Log.i(TAG, "wifiDevices data ${item.wifiName}") // val resultMap = Arguments.createMap() // resultMap.putString("ssid", item.wifiName) // resultMap.putInt("rssi", item.rssi) // resultMap.putInt("auth", item.security) // resultArray.pushMap(resultMap) // } // // promise?.resolve(resultArray) // } } if (bleDevice?.uuids == null) { bleDevice = bluetoothAdapter.bondedDevices.find { bondedDevice -> bondedDevice.name == deviceName } } // If the bluetooth device exists and contains service uuids, we will be able to connect to it if (bleDevice?.uuids != null) { espDevice.bluetoothDevice = bleDevice espDevice.deviceName = deviceName espDevice.proofOfPossession = proofOfPossession if (username != null) { espDevice.userName = username } espDevices[deviceName] = espDevice val result = Arguments.createMap() result.putString("name", espDevice.deviceName) result.putArray("capabilities", Arguments.fromList(espDevice.deviceCapabilities)) result.putInt("security", security) result.putString("transport", transport) result.putString("username", espDevice.userName) result.putString("versionInfo", espDevice.versionInfo) promise?.resolve(result) return } } // Exhausted our other options, perform search in hope of finding the device searchESPDevices(deviceName, transport, security, object : Promise { override fun resolve(p0: Any?) { // If search does not find the device, consider it not found if (espDevices[deviceName] == null) { promise?.reject(Error("Device not found.")) } // Configure proof of possession espDevices[deviceName]?.proofOfPossession = proofOfPossession if (username != null) { espDevices[deviceName]?.userName = username } val result = Arguments.createMap() result.putString("name", espDevices[deviceName]?.deviceName) result.putArray("capabilities", Arguments.fromList(espDevices[deviceName]?.deviceCapabilities)) result.putInt("security", security) result.putString("transport", transport) result.putString("username", espDevices[deviceName]?.userName) result.putString("versionInfo", espDevices[deviceName]?.versionInfo) promise?.resolve(result) } override fun reject(p0: String?, p1: String?) { promise?.reject(p0, p1) } override fun reject(p0: String?, p1: Throwable?) { promise?.reject(p0, p1) } override fun reject(p0: String?, p1: String?, p2: Throwable?) { promise?.reject(p0, p1, p2) } override fun reject(p0: Throwable?) { promise?.reject(p0) } override fun reject(p0: Throwable?, p1: WritableMap?) { promise?.reject(p0, p1) } override fun reject(p0: String?, p1: WritableMap) { promise?.reject(p0, p1) } override fun reject(p0: String?, p1: Throwable?, p2: WritableMap?) { promise?.reject(p0, p1, p2) } override fun reject(p0: String?, p1: String?, p2: WritableMap) { promise?.reject(p0, p1, p2) } override fun reject(p0: String?, p1: String?, p2: Throwable?, p3: WritableMap?) { promise?.reject(p0, p1, p2, p3) } @Deprecated("Deprecated in Java", ReplaceWith("promise?.reject(p0)")) override fun reject(p0: String?) { promise?.reject(p0) } }) } @SuppressLint("MissingPermission") @ReactMethod override fun connect(deviceName: String, promise: Promise?) { Log.i(TAG,"DEv info ${espDevices[deviceName]?.proofOfPossession}") if (espDevices[deviceName] == null) { promise?.reject(Error("No ESP device found. Call createESPDevice first.")) return } if (espDevices[deviceName]?.transportType == ESPConstants.TransportType.TRANSPORT_SOFTAP) { // Permission checks if ( !hasWifiPermission() || !hasFineLocationPermission() ) { promise?.reject(Error("Missing one of the following permissions: CHANGE_WIFI_STATE, ACCESS_WIFI_STATE, ACCESS_NETWORK_STATE, ACCESS_FINE_LOCATION")) return } espDevices[deviceName]?.connectWiFiDevice() }else{ espDevices[deviceName]?.connectToDevice() } EventBus.getDefault().register(object { @Subscribe(threadMode = ThreadMode.MAIN) fun onEvent(event: DeviceConnectionEvent) { when (event.eventType) { ESPConstants.EVENT_DEVICE_CONNECTED -> { val result = Arguments.createMap() result.putString("status", "connected") promise?.resolve(result) } ESPConstants.EVENT_DEVICE_CONNECTION_FAILED -> { promise?.reject(Error("Device connection failed.")) } else -> { // Do nothing } } // Unregister event listener after 1 event received EventBus.getDefault().unregister(this) } }) } @ReactMethod override fun sendData(deviceName: String, path: String, data: String, promise: Promise?) { if (espDevices[deviceName] == null) { promise?.reject(Error("No ESP device found. Call createESPDevice first.")) return } val decodedData = Base64.getDecoder().decode(data) espDevices[deviceName]?.sendDataToCustomEndPoint(path, decodedData, object : ResponseListener { override fun onSuccess(returnData: ByteArray?) { val encodedData = Base64.getEncoder().encode(returnData).toString(Charsets.UTF_8) promise?.resolve(encodedData) } override fun onFailure(e: Exception?) { promise?.reject(e) } }) } @ReactMethod override fun getProofOfPossession(deviceName: String, promise: Promise?) { if (espDevices[deviceName] == null) { promise?.reject(Error("No ESP device found. Call createESPDevice first.")) return } promise?.resolve(espDevices[deviceName]?.proofOfPossession) } @ReactMethod override fun scanWifiList(deviceName: String, promise: Promise?) { if (espDevices[deviceName] == null) { promise?.reject(Error("No ESP device found. Call createESPDevice first.")) return } Log.i(TAG,"Device POP ${espDevices[deviceName]?.proofOfPossession}") espDevices[deviceName]?.scanNetworks(object : WiFiScanListener { override fun onWifiListReceived(wifiList: ArrayList<WiFiAccessPoint>?) { val resultArray = Arguments.createArray() wifiList?.forEach { item -> val resultMap = Arguments.createMap() resultMap.putString("ssid", item.wifiName) resultMap.putInt("rssi", item.rssi) resultMap.putInt("auth", item.security) resultArray.pushMap(resultMap) } promise?.resolve(resultArray) } override fun onWiFiScanFailed(e: Exception?) { promise?.reject(e) } }) } @ReactMethod override fun disconnect(deviceName: String) { espDevices[deviceName]?.disconnectDevice() } @ReactMethod override fun provision(deviceName: String, ssid: String, passphrase: String, promise: Promise?) { Log.d(TAG, "This is a debug message: $ssid $passphrase" ) // if (espDevices[deviceName] == null) { // promise?.reject(Error("No ESP device found. Call createESPDevice first.")) // return // } espDevices[deviceName]!!.provision(ssid, passphrase, object : ProvisionListener { override fun createSessionFailed(e: Exception?) { promise?.reject(e) } override fun wifiConfigSent() { return } override fun wifiConfigFailed(e: Exception?) { promise?.reject(e) } override fun wifiConfigApplied() { return } override fun wifiConfigApplyFailed(e: Exception?) { promise?.reject(e) } override fun provisioningFailedFromDevice(failureReason: ESPConstants.ProvisionFailureReason?) { promise?.reject(Error(failureReason.toString())) } override fun deviceProvisioningSuccess() { val result = Arguments.createMap() result.putString("status", "success") promise?.resolve(result) } override fun onProvisioningFailed(e: Exception?) { promise?.reject(e) } }) } @ReactMethod override fun initializeSession(deviceName: String, sessionPath: String, promise: Promise?) { if (espDevices[deviceName] == null) { promise?.reject(Error("No ESP device found. Call createESPDevice first.")) return } espDevices[deviceName]?.initSession(object : ResponseListener { override fun onSuccess(returnData: ByteArray?) { val encodedData = Base64.getEncoder().encode(returnData) promise?.resolve(encodedData) } override fun onFailure(e: Exception?) { promise?.reject(e) } }) } }
0
Kotlin
0
0
eb50e13b6f5a31995e4e21a76bd349c24a6f3d78
21,044
react-native-esp-idf-provisioning
MIT License
ImagePickerLib/src/main/java/com/mx/imgpicker/app/MXImgShowActivity.kt
zhangmengxiong
386,508,261
false
null
package com.mx.imgpicker.app import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.PagerSnapHelper import androidx.recyclerview.widget.RecyclerView import com.mx.imgpicker.MXImagePicker import com.mx.imgpicker.R import com.mx.imgpicker.adapts.ImgShowAdapt import com.mx.imgpicker.models.MXItem import com.mx.imgpicker.models.MXPickerType import com.mx.imgpicker.utils.MXUtils class MXImgShowActivity : AppCompatActivity() { companion object { private const val EXTRAS_LIST = "EXTRAS_LIST" private const val EXTRAS_TITLE = "EXTRAS_TITLE" private const val EXTRAS_INDEX = "EXTRAS_INDEX" fun open(context: Context, list: List<String>, title: String? = null, index: Int = 0) { if (list.isEmpty()) return val list = list.map { MXItem(it, 0L, MXPickerType.Image) } context.startActivity( Intent(context, MXImgShowActivity::class.java) .putExtra(EXTRAS_LIST, ArrayList(list)) .putExtra(EXTRAS_TITLE, title) .putExtra(EXTRAS_INDEX, index) ) } } private val returnBtn by lazy { findViewById<View>(R.id.returnBtn) } private val recycleView by lazy { findViewById<RecyclerView>(R.id.recycleView) } private val titleTxv by lazy { findViewById<TextView>(R.id.titleTxv) } private val indexTxv by lazy { findViewById<TextView>(R.id.indexTxv) } private val imgList = ArrayList<MXItem>() private val adapt by lazy { ImgShowAdapt(imgList) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) MXImagePicker.init(application) setContentView(R.layout.mx_picker_activity_img_show) initView() initIntent() } private fun initView() { returnBtn.setOnClickListener { onBackPressed() } titleTxv.text = intent.getStringExtra(EXTRAS_TITLE) ?: getString(R.string.mx_picker_string_show_list) val layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) recycleView.layoutManager = layoutManager PagerSnapHelper().attachToRecyclerView(recycleView) recycleView.adapter = adapt recycleView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { if (newState == RecyclerView.SCROLL_STATE_IDLE) { val index = layoutManager.findFirstVisibleItemPosition() if (index >= 0) { indexTxv.text = "${index + 1} / ${imgList.size}" } } } }) } private fun initIntent() { try { val list = intent.getSerializableExtra(EXTRAS_LIST) as ArrayList<MXItem> imgList.addAll(list) } catch (e: Exception) { e.printStackTrace() finish() return } indexTxv.text = "1 / ${imgList.size}" MXUtils.log("显示图片:${imgList.joinToString(",") { it.path }}") adapt.notifyDataSetChanged() val index = intent.getIntExtra(EXTRAS_INDEX, 0) if (index < imgList.size && index >= 0) { recycleView.scrollToPosition(index) indexTxv.text = "${index + 1} / ${imgList.size}" } } }
0
null
0
5
1d8433244ca6a6c4a8d89903c8539771dd3764e1
3,613
MXImagePicker
Apache License 2.0
core/android/src/main/kotlin/com/walletconnect/android/sync/storage/AccountsStorageRepository.kt
WalletConnect
435,951,419
false
null
package com.walletconnect.android.sync.storage import com.walletconnect.android.internal.common.model.AccountId import com.walletconnect.android.sdk.storage.data.dao.sync.AccountsQueries import com.walletconnect.android.sync.common.model.Account import com.walletconnect.android.sync.common.model.Entropy internal class AccountsStorageRepository(private val accounts: AccountsQueries) { suspend fun createAccount(account: Account) = with(account) { // Only insert when account does not yet exists in db. Entropy will be the same so no need for multiple inserts/updates accounts.insertOrAbortAccount(accountId = accountId.value, entropy = entropy.value) } suspend fun getAccount(accountId: AccountId): Account = accounts.getAccountByAccountId(accountId.value, ::dbToAccount).executeAsOne() suspend fun doesAccountNotExists(accountId: AccountId) = accounts.doesAccountNotExists(accountId.value).executeAsOne() private fun dbToAccount(accountId: String, entropy: String): Account = Account(AccountId(accountId), Entropy(entropy)) }
147
Kotlin
59
157
e34c0e716ca68021602463773403d8d7fd558b34
1,088
WalletConnectKotlinV2
Apache License 2.0
feature-staking-api/src/main/java/io/novafoundation/nova/feature_staking_api/presentation/nominationPools/display/PoolDisplayModel.kt
novasamatech
415,834,480
false
{"Kotlin": 11112596, "Rust": 25308, "Java": 17664, "JavaScript": 425}
package io.novafoundation.nova.feature_staking_api.presentation.nominationPools.display import io.novafoundation.nova.common.utils.images.Icon import io.novafoundation.nova.common.view.TableCellView import io.novasama.substrate_sdk_android.runtime.AccountId class PoolDisplayModel( val icon: Icon, val title: String, val poolAccountId: AccountId, val address: String ) fun TableCellView.showPool(poolDisplayModel: PoolDisplayModel) { loadImage(poolDisplayModel.icon) showValue(poolDisplayModel.title) }
14
Kotlin
30
50
166755d1c3388a7afd9b592402489ea5ca26fdb8
530
nova-wallet-android
Apache License 2.0
src/test/kotlin/com/example/screenplay/question/OutcomesShown.kt
globalworming
364,037,743
false
null
package com.example.screenplay.question import net.serenitybdd.core.pages.WebElementFacade import net.serenitybdd.screenplay.Actor import net.serenitybdd.screenplay.targets.Target class OutcomesShown : QuestionWithDefaultSubject<List<WebElementFacade>>() { override fun answeredBy(actor: Actor): List<WebElementFacade> { return Target.the("outcomes that can be selected").locatedBy(".selectOutcome").resolveAllFor(actor) } }
1
Kotlin
0
3
19fb7833f48c4658a2a5cf8632f84003dd2ddb94
434
serenity-kotlin-junit-screenplay-starter
Apache License 2.0
app/src/main/kotlin/com/konifar/materialcat/domain/usecase/GetCatImagesUseCaseImpl.kt
konifar
40,127,425
false
null
package com.konifar.materialcat.domain.usecase import com.konifar.materialcat.domain.model.CatImage import com.konifar.materialcat.infra.data.SearchOrderType import com.konifar.materialcat.infra.repository.CatImageFlickrRepository import io.reactivex.Observable import io.reactivex.Single import io.reactivex.schedulers.Schedulers class GetCatImagesUseCaseImpl(private val catImageRepository: CatImageFlickrRepository) : GetCatImagesUseCase { companion object { private val SEARCH_TEXT = "cat" private val PER_PAGE = 36 } override fun requestGetPopular(page: Int, shouldRefresh: Boolean): Observable<List<CatImage>> { return requestGet(page, shouldRefresh, SearchOrderType.POPULAR) } override fun requestGetNew(page: Int, shouldRefresh: Boolean): Observable<List<CatImage>> { return requestGet(page, shouldRefresh, SearchOrderType.NEW) } private fun requestGet(page: Int, shouldRefresh: Boolean, searchOrderType: SearchOrderType): Observable<List<CatImage>> { val single: Single<Int> = if (shouldRefresh) catImageRepository.clearCache(searchOrderType, SEARCH_TEXT) else Single.just(1) return single.toObservable() .flatMap { catImageRepository.findByText(searchOrderType, SEARCH_TEXT, page, PER_PAGE) } .subscribeOn(Schedulers.io()) } }
12
Kotlin
82
397
6b47aef9fae8ad3de32a897b9dede729b28c1580
1,356
material-cat
Apache License 2.0
app/src/main/java/com/mw/beam/beamwallet/core/views/SnackBarsView.kt
BeamMW
156,687,787
false
{"Kotlin": 1454975, "Java": 16801, "Shell": 4651, "IDL": 1}
/* * // Copyright 2018 Beam Development * // * // 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.mw.beam.beamwallet.core.views import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.FrameLayout import android.widget.ProgressBar import android.widget.TextView import com.mw.beam.beamwallet.R import java.util.* import kotlin.concurrent.schedule import android.animation.ObjectAnimator import android.view.animation.AccelerateInterpolator import com.mw.beam.beamwallet.core.views.* import android.view.animation.AnimationUtils import android.view.animation.Animation import android.view.animation.ScaleAnimation class SnackBarsView: FrameLayout { private var snackbarLifeTime: Long = 5000 private val period: Long = 10 private var info: SnackBarInfo? = null private var currentView: View? = null private var timer: Timer? = null private var currentMillis: Long = 0 private var smoothAnimation:ObjectAnimator? = null constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context) : super(context) fun show(message: String, onDismiss: (() -> Unit)? = null, onUndo: (() -> Unit)? = null) { // dismiss() smoothAnimation?.cancel() smoothAnimation = null timer?.cancel() timer = null info = null removeAllViews() removeAllViewsInLayout() info = SnackBarInfo(message, onDismiss, onUndo) val animation = AnimationUtils.loadAnimation(context, R.anim.fade_in) val view = LayoutInflater.from(context).inflate(R.layout.snackbar_layout, this) view.startAnimation(animation) view?.setOnClickListener { } view.findViewById<TextView>(R.id.contentText).text = message if (onUndo != null) { snackbarLifeTime = 5000 view.findViewById<View>(R.id.timerView).visibility = View.VISIBLE val btnUndo = view.findViewById<View>(R.id.btnUndo) btnUndo.visibility = View.VISIBLE btnUndo.setOnClickListener { undo() } view.findViewById<TextView>(R.id.undoTime).text = millisToSecond(snackbarLifeTime) val progressBar = view.findViewById<ProgressBar>(R.id.progressTimer) progressBar.max = snackbarLifeTime.toInt() progressBar.progress = snackbarLifeTime.toInt() smoothAnimation = ObjectAnimator.ofInt(progressBar, "progress", progressBar!!.progress, progressBar.max) smoothAnimation?.duration = 100 smoothAnimation?.interpolator = AccelerateInterpolator() } else{ snackbarLifeTime = 3000 } startNewTimer() currentView = view } fun dismiss() { info?.onDismiss?.invoke() clear() } fun undo() { info?.onUndo?.invoke() clear() } private fun clear() { smoothAnimation?.cancel() smoothAnimation = null timer?.cancel() timer = null info = null val animation = AnimationUtils.loadAnimation(context, R.anim.fade_out) animation.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationStart(arg0: Animation) { } override fun onAnimationRepeat(arg0: Animation) { } override fun onAnimationEnd(arg0: Animation) { removeAllViews() } }) currentView?.startAnimation(animation) } private fun millisToSecond(millis: Long): String { return Math.ceil(millis.toDouble() / 1000).toInt().toString() } private fun startNewTimer() { currentMillis = snackbarLifeTime timer = Timer() timer?.schedule(0, period) { handler.post { currentMillis -= period if (currentMillis <= 0) { dismiss() } else if (info?.onUndo != null) { currentView?.findViewById<TextView>(R.id.undoTime)?.text = millisToSecond(currentMillis) currentView?.findViewById<ProgressBar>(R.id.progressTimer)?.progress = (snackbarLifeTime - currentMillis).toInt() } } } smoothAnimation?.start() } private data class SnackBarInfo(val message: String, val onDismiss: (() -> Unit)? = null, val onUndo: (() -> Unit)? = null) }
4
Kotlin
21
36
7e9d9c0df49f3cb35bb58152c285cc7b618a28ba
5,169
android-wallet
Apache License 2.0
src/main/kotlin/me/omico/genshinimpact/serverswitcher/preference/AppConfig.kt
Omico
375,150,844
false
null
package me.omico.genshinimpact.serverswitcher.preference import java.util.prefs.Preferences object AppConfig { private const val KEY_GAME_DIR = "gameDir" private const val KEY_LATEST_SELECTED_DIR = "latestSelectedDir" private val preferences = Preferences.userRoot().node(javaClass.packageName.replace(".", "/")) var gameRootDir: String get() = preferences.get(KEY_GAME_DIR, "") set(value) = preferences.put(KEY_GAME_DIR, value) var latestSelectedDir: String get() = preferences.get(KEY_LATEST_SELECTED_DIR, "") set(value) = preferences.put(KEY_LATEST_SELECTED_DIR, value) }
0
Kotlin
0
0
b12160ccbae7f6a69f987711cf726002b2252a78
633
genshin-impact-server-switcher
Apache License 2.0
LoadingLayout/src/main/java/com/xueqiya/loading/LoadingLayout.kt
xueqiya
372,415,339
false
null
package com.xueqiya.loading import android.app.Activity import android.content.Context import android.graphics.drawable.Drawable import android.util.AttributeSet import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.View.OnClickListener import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.annotation.DrawableRes import androidx.annotation.LayoutRes import androidx.constraintlayout.widget.ConstraintLayout import androidx.fragment.app.Fragment import com.xueqiya.loading.utils.DensityUtils import java.util.* class LoadingLayout @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.styleLoadingLayout ) : ConstraintLayout(context, attrs, defStyleAttr) { companion object { @JvmStatic fun wrap(activity: Activity?): LoadingLayout { if (activity == null) { throw RuntimeException("content activity can not be null") } val viewGroup = activity.findViewById<View>(android.R.id.content) as ViewGroup val view = viewGroup.getChildAt(0) return wrap(view) } @JvmStatic fun wrap(fragment: Fragment?): LoadingLayout { if (fragment == null) { throw RuntimeException("content fragment can not be null") } val view = fragment.view return wrap(view) } @JvmStatic fun wrap(view: View?): LoadingLayout { if (view == null) { throw RuntimeException("content view can not be null") } val parent = view.parent as ViewGroup val lp = view.layoutParams val index = parent.indexOfChild(view) parent.removeView(view) val layout = LoadingLayout(view.context) parent.addView(layout, index, lp) layout.addView(view) layout.setContentView(view) return layout } } private var mEmptyImageResId: Int private var mEmptyText: CharSequence private var mErrorImageResId: Int private var mRetryText: CharSequence private var mRetryListener: OnClickListener? = null private var mTextColor: Int private var mTextSize: Int private var mButtonTextColor: Int private var mButtonTextSize: Int private var mButtonBackground: Drawable private var mEmptyResId = View.NO_ID private var mLoadingResId = View.NO_ID private var mErrorResId = View.NO_ID private var mContentId = View.NO_ID private var pageState: State = State.CONTENT private var mLayouts: MutableMap<Int, View?> = HashMap() private var mInflater: LayoutInflater = LayoutInflater.from(context) init { val arrayType = context.obtainStyledAttributes(attrs, R.styleable.LoadingLayout, defStyleAttr, R.style.LoadingLayout_Style) mEmptyImageResId = arrayType.getResourceId(R.styleable.LoadingLayout_llEmptyImage, View.NO_ID) mEmptyText = arrayType.getString(R.styleable.LoadingLayout_llEmptyText).toString() mErrorImageResId = arrayType.getResourceId(R.styleable.LoadingLayout_llErrorImage, View.NO_ID) mRetryText = arrayType.getString(R.styleable.LoadingLayout_llRetryText).toString() mTextColor = arrayType.getColor(R.styleable.LoadingLayout_llTextColor, -0x666667) mTextSize = arrayType.getDimensionPixelSize(R.styleable.LoadingLayout_llTextSize, DensityUtils.dip2px(context, 16f)) mButtonTextColor = arrayType.getColor(R.styleable.LoadingLayout_llButtonTextColor, -0x666667) mButtonTextSize = arrayType.getDimensionPixelSize(R.styleable.LoadingLayout_llButtonTextSize, DensityUtils.dip2px(context, 16f)) mButtonBackground = arrayType.getDrawable(R.styleable.LoadingLayout_llButtonBackground)!! mEmptyResId = arrayType.getResourceId(R.styleable.LoadingLayout_llEmptyResId, R.layout.loading_layout_empty) mLoadingResId = arrayType.getResourceId(R.styleable.LoadingLayout_llLoadingResId, R.layout.loading_layout_loading) mErrorResId = arrayType.getResourceId(R.styleable.LoadingLayout_llErrorResId, R.layout.loading_layout_error) arrayType.recycle() } override fun onFinishInflate() { super.onFinishInflate() if (childCount == 0) { return } if (childCount > 1) { removeViews(1, childCount - 1) } val view = getChildAt(0) setContentView(view) pageState = State.CONTENT } private fun setContentView(view: View) { mContentId = view.id mLayouts[mContentId] = view } fun setLoading(@LayoutRes id: Int): LoadingLayout { if (mLoadingResId != id) { remove(mLoadingResId) mLoadingResId = id } return this } fun setEmpty(@LayoutRes id: Int): LoadingLayout { if (mEmptyResId != id) { remove(mEmptyResId) mEmptyResId = id } return this } fun setError(@LayoutRes id: Int): LoadingLayout { if (mErrorResId != id) { remove(mErrorResId) mErrorResId = id } return this } fun setEmptyImage(@DrawableRes resId: Int): LoadingLayout { mEmptyImageResId = resId image(mEmptyResId, R.id.empty_image, mEmptyImageResId) return this } fun setEmptyText(value: String): LoadingLayout { mEmptyText = value text(mEmptyResId, R.id.empty_text, mEmptyText) return this } fun setErrorImage(@DrawableRes resId: Int): LoadingLayout { mErrorImageResId = resId image(mErrorResId, R.id.error_image, mErrorImageResId) return this } fun setRetryText(text: String): LoadingLayout { mRetryText = text text(mErrorResId, R.id.retry_button, mRetryText) return this } fun showLoading() { pageState = State.LOADING show(mLoadingResId) } fun showEmpty() { pageState = State.EMPTY show(mEmptyResId) } fun showError() { pageState = State.ERROR show(mErrorResId) } fun showContent() { pageState = State.CONTENT show(mContentId) } fun getLoadingState(): State { return pageState } private fun show(layoutId: Int) { for (view in mLayouts.values) { view!!.visibility = View.GONE } layout(layoutId)!!.visibility = View.VISIBLE } private fun remove(layoutId: Int) { if (mLayouts.containsKey(layoutId)) { val vg = mLayouts.remove(layoutId) removeView(vg) } } private fun layout(layoutId: Int): View? { if (mLayouts.containsKey(layoutId)) { return mLayouts[layoutId] } val layout = mInflater.inflate(layoutId, this, false) layout.visibility = View.GONE addView(layout) mLayouts[layoutId] = layout if (layoutId == mEmptyResId) { val img = layout.findViewById<ImageView>(R.id.empty_image) if (img != null && mEmptyImageResId != View.NO_ID) { img.setImageResource(mEmptyImageResId) } val view = layout.findViewById<TextView>(R.id.empty_text) if (view != null) { view.text = mEmptyText view.setTextColor(mTextColor) view.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize.toFloat()) } } else if (layoutId == mErrorResId) { val img = layout.findViewById<ImageView>(R.id.error_image) if (img != null && mErrorImageResId != View.NO_ID) { img.setImageResource(mErrorImageResId) } val btn = layout.findViewById<TextView>(R.id.retry_button) if (btn != null) { btn.text = mRetryText btn.setTextColor(mButtonTextColor) btn.setTextSize(TypedValue.COMPLEX_UNIT_PX, mButtonTextSize.toFloat()) btn.background = mButtonBackground btn.setOnClickListener(mRetryButtonClickListener) } } return layout } private fun text(layoutId: Int, ctrlId: Int, value: CharSequence?) { if (mLayouts.containsKey(layoutId)) { val view = mLayouts[layoutId]!!.findViewById<TextView>(ctrlId) if (view != null) { view.text = value } } } private fun image(layoutId: Int, ctrlId: Int, resId: Int) { if (mLayouts.containsKey(layoutId)) { val view = mLayouts[layoutId]!!.findViewById<ImageView>(ctrlId) view?.setImageResource(resId) } } private var mRetryButtonClickListener = OnClickListener { v -> mRetryListener?.onClick(v) } fun setRetryListener(listener: OnClickListener?): LoadingLayout { mRetryListener = listener return this } }
0
Kotlin
0
2
7e822aebbac5767f8462a418a450e1ff4d87fc0d
9,089
LoadingLayout
Apache License 2.0
data/src/main/java/com/dev/data/mapper/ArticleResultDataMapper.kt
namdevlondhe
721,257,049
false
{"Kotlin": 33448}
package com.dev.data.mapper import com.dev.data.dto.ArticleData import com.dev.data.dto.ArticleResultData import com.dev.domain.model.ArticleResult import javax.inject.Inject class ArticleResultDataMapperclass @Inject constructor( private val characterMapper: EntityDataMapper ) { fun mapFromModel(model: ArticleResultData):ArticleResult { return with(model) { ArticleResult(count = count, next = next, previous = previous, results=results) } } }
0
Kotlin
0
0
193afcdf8c3353452bf0347be21435203b5d119f
521
Spaceflight-News
Apache License 2.0
retrogriod-network/src/main/java/com/app/retrogrid/annotation/RetrofitServiceConfiguration.kt
DeepuGeorgeJacob
612,718,565
false
null
package com.app.retrogrid.annotation import okhttp3.Interceptor import kotlin.reflect.KClass @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.CLASS) annotation class RetrofitServiceConfiguration( val baseUrl: String, val errorResponseClass: KClass<*> = Nothing::class, val interceptors:Array<KClass<out Interceptor>> = [], val enableRequestResponseDefaultLog:Boolean = false )
1
Kotlin
0
0
6bbe53a0e7e75ffdbd75ba214d6f8681e55e6bf3
411
retrogrid
MIT License
endlessRunnersGame/src/main/kotlin/cz/woitee/endlessRunners/game/objects/GameObject.kt
woitee
219,872,458
false
null
package cz.woitee.endlessRunners.game.objects import cz.woitee.endlessRunners.game.BlockHeight import cz.woitee.endlessRunners.game.BlockWidth import cz.woitee.endlessRunners.game.GameState import cz.woitee.endlessRunners.geom.Vector2Double import cz.woitee.endlessRunners.utils.MySerializable import cz.woitee.endlessRunners.utils.arrayList import cz.woitee.endlessRunners.utils.resizeTo import nl.pvdberg.hashkode.compareFields import java.io.* import java.util.* import kotlin.jvm.Transient /** * An object in a game. Provides access to its attributes and operations with its location. */ abstract class GameObject(var x: Double = 0.0, var y: Double = 0.0) : MySerializable, Serializable { abstract val gameObjectClass: GameObjectClass /** Whether the object should be notified in the update loop */ open var isUpdated: Boolean = false /** Whether the object can be passed through by a player */ open val isSolid: Boolean = false /** Basic width of the object */ open val defaultWidthBlocks: Int = 1 /** Basic height of the object */ open val defaultHeightBlocks: Int = 1 /** Current width of the object */ open var widthBlocks: Int = 1 /** Current height of the object */ open var heightBlocks: Int = 1 /** The char to show in a textdump of a GameState */ open val dumpChar = '?' /** Color of the object */ open var color = GameObjectColor.UNSPECIFIED val isCustomBlock get() = gameObjectClass.ord >= GameObjectClass.CUSTOM0.ord && gameObjectClass.ord <= GameObjectClass.CUSTOM3.ord var location: Vector2Double get() = Vector2Double(x, y) set(value) { x = value.x; y = value.y } @Transient lateinit var gameState: GameState val widthPx: Int get() = widthBlocks * BlockWidth val heightPx: Int get() = heightBlocks * BlockHeight /** * Updates the object, should be called every frame if isUpdate is true. */ open fun update(time: Double) {} /** * Locations of the 4 corners of this object. */ val corners: ArrayList<Vector2Double> = arrayList(4, { Vector2Double() }) get() { field[0].x = x field[0].y = y field[1].x = x + widthBlocks * BlockWidth field[1].y = y field[2].x = x field[2].y = y + heightBlocks * BlockHeight field[3].x = x + widthBlocks * BlockWidth field[3].y = y + heightBlocks * BlockHeight return field } /** Number of the collision points on this object */ val collPointsNumber get() = (widthBlocks + 1) * (heightBlocks + 1) /** * Locations of all the collision points of this object. * Small objects use their corners by default. */ val collPoints: ArrayList<Vector2Double> = arrayList(collPointsNumber, { Vector2Double() }) get() { if (field.count() != collPointsNumber) { field.resizeTo(collPointsNumber, { Vector2Double() }) } var i = 0 for (col in 0 .. widthBlocks) { for (row in 0 .. heightBlocks) { field[i].x = x + col * BlockWidth field[i].y = y + row * BlockHeight // Objects are slightly lower so they fit under stuff if (row == heightBlocks) field[i].y -= 1 ++i } } return field } abstract fun makeCopy(): GameObject override fun equals(other: Any?) = compareFields(other) { equal = one.gameObjectClass == two.gameObjectClass && one.x == two.x && one.y == two.y && one.isSolid == two.isSolid } override fun toString(): String { return "GameObject($dumpChar)" } override fun readObject(ois: ObjectInputStream): GameObject { x = ois.readDouble() y = ois.readDouble() heightBlocks = ois.readInt() widthBlocks = ois.readInt() return this } override fun writeObject(oos: ObjectOutputStream): GameObject { oos.writeDouble(x) oos.writeDouble(y) oos.writeInt(heightBlocks) oos.writeInt(widthBlocks) return this } }
0
Kotlin
0
1
5c980f44397f0b4f122e7b2cb51b82cf1c0419df
4,318
endlessRunners
Apache License 2.0
app/src/play/java/io/github/wulkanowy/utils/RemoteConfigHelper.kt
wezuwiusz
827,505,734
false
{"Kotlin": 1759089, "HTML": 1949, "Shell": 257}
package io.github.wulkanowy.utils import android.content.Context import com.google.firebase.FirebaseApp import com.google.firebase.ktx.Firebase import com.google.firebase.remoteconfig.ktx.remoteConfig import com.google.firebase.remoteconfig.ktx.remoteConfigSettings import dagger.hilt.android.qualifiers.ApplicationContext import javax.inject.Inject import javax.inject.Singleton @Singleton class RemoteConfigHelper @Inject constructor( @ApplicationContext private val context: Context, private val appInfo: AppInfo, ) : BaseRemoteConfigHelper() { override fun initialize() { FirebaseApp.initializeApp(context) Firebase.remoteConfig.setConfigSettingsAsync(remoteConfigSettings { fetchTimeoutInSeconds = 3 if (appInfo.isDebug) { minimumFetchIntervalInSeconds = 0 } }) Firebase.remoteConfig.setDefaultsAsync(RemoteConfigDefaults.values().associate { it.key to it.value }) Firebase.remoteConfig.fetchAndActivate() } override val userAgentTemplate: String get() = Firebase.remoteConfig.getString(RemoteConfigDefaults.USER_AGENT_TEMPLATE.key) }
1
Kotlin
6
28
82b4ea930e64d0d6e653fb9024201b372cdb5df2
1,185
neowulkanowy
Apache License 2.0
app/src/main/java/com/samkt/filmio/featureMovies/data/remote/dtos/MoviesResponseDto.kt
Sam-muigai
698,566,485
false
{"Kotlin": 257745}
package com.samkt.filmio.featureMovies.data.remote.dtos import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class MoviesResponseDto( @SerialName("page") val page: Int, @SerialName("results") val movies: List<Movie>, @SerialName("total_pages") val totalPages: Int, @SerialName("total_results") val totalResults: Int )
0
Kotlin
0
0
404350965297225420445e0ef47c9170ad720e0e
400
Filmio
Apache License 2.0