path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/html/compose/text/ui/theme/Color.kt
CHRehan
472,465,547
false
{"Kotlin": 23281}
package com.html.compose.text.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFFBB86FC) val Purple500 = Color(0xFF6200EE) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5) val VeryLightColor = Color(0x60DCDCDC) val LightGreen = Color(0x9932CD32) val Red = Color(0x99CD3270)
0
Kotlin
0
0
6beecb3b154c6553947d2f37013d4a20bdf5d421
318
HTMLComposeText
Apache License 2.0
android/src/main/java/io/github/droidkaigi/feeder/notification/LocaleChangeReceiver.kt
DroidKaigi
283,062,475
false
null
package io.github.droidkaigi.feeder.notification import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.Build class LocaleChangeReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && intent.action == Intent.ACTION_LOCALE_CHANGED ) { NotificationUtil.deleteNotificationChannel(context) NotificationUtil.createNotificationChannel(context) } } }
45
Kotlin
189
633
3fb47a7b7b245e5a7c7c66d6c18cb7d2a7b295f2
569
conference-app-2021
Apache License 2.0
src/main/kotlin/com/parmet/buf/gradle/Workspace.kt
andrewparmet
291,329,569
false
null
package com.parmet.buf.gradle import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.file.SourceDirectorySet import org.gradle.api.tasks.SourceSetContainer import org.gradle.kotlin.dsl.get import org.gradle.kotlin.dsl.the import java.io.File import java.nio.file.Files import java.nio.file.Path const val CREATE_SYM_LINKS_TO_MODULES_TASK_NAME = "createSymLinksToModules" const val WRITE_WORKSPACE_YAML_TASK_NAME = "writeWorkspaceYaml" private const val EXTRACT_INCLUDE_PROTO_TASK_NAME = "extractIncludeProto" private const val BUILD_EXTRACTED_INCLUDE_PROTOS_MAIN = "build/extracted-include-protos/main" private const val EXTRACT_PROTO_TASK_NAME = "extractProto" private const val BUILD_EXTRACTED_PROTOS_MAIN = "build/extracted-protos/main" internal fun Project.configureCreateSymLinksToModules() { tasks.register(CREATE_SYM_LINKS_TO_MODULES_TASK_NAME) { workspaceCommonConfig() doLast { protoDirs().forEach { createSymLink(it) } } } } private fun Project.createSymLink(protoDir: Path) { val symLinkFile = File(bufbuildDir, mangle(protoDir)) if (!symLinkFile.exists()) { logger.info("Creating symlink for $protoDir at $symLinkFile") Files.createSymbolicLink(symLinkFile.toPath(), Path.of(bufbuildDir).relativize(file(protoDir).toPath())) } } internal fun Project.configureWriteWorkspaceYaml() { tasks.register(WRITE_WORKSPACE_YAML_TASK_NAME) { workspaceCommonConfig() doLast { val bufWork = """ |version: v1 |directories: ${workspaceSymLinkEntries()} """.trimMargin() logger.info("Writing generated buf.work.yaml:\n$bufWork") File("$bufbuildDir/buf.work.yaml").writeText(bufWork) } } } private fun Task.workspaceCommonConfig() { dependsOn(EXTRACT_INCLUDE_PROTO_TASK_NAME) dependsOn(EXTRACT_PROTO_TASK_NAME) outputs.dir(project.bufbuildDir) doLast { File(project.bufbuildDir).mkdirs() } } private fun Project.workspaceSymLinkEntries() = protoDirs().joinToString("\n") { "| - ${mangle(it)}" } private fun Project.protoDirs(): List<Path> = (srcDirs() + extractDirs()).filter { anyProtos(it) } private fun Project.srcDirs() = the<SourceSetContainer>()["main"] .extensions .getByName("proto") .let { it as SourceDirectorySet } .srcDirs .map { projectDir.toPath().relativize(it.toPath()) } private fun extractDirs() = listOf( BUILD_EXTRACTED_INCLUDE_PROTOS_MAIN, BUILD_EXTRACTED_PROTOS_MAIN ).map(Path::of) private fun Project.anyProtos(path: Path) = file(path).walkTopDown().any { it.extension == "proto" } private fun mangle(name: Path) = name.toString().replace("-", "--").replace(File.separator, "-")
3
Kotlin
1
10
19ffb24e7538a920843a208689af0742ff058d73
2,852
buf-gradle-plugin
Apache License 2.0
src/commonMain/kotlin/com/bkahlert/kommons/kaomoji/categories/Depressed.kt
bkahlert
323,048,013
false
null
@file:Suppress( "KDocMissingDocumentation", "ObjectPropertyName", "RemoveRedundantBackticks", "unused", "NonAsciiCharacters", "SpellCheckingInspection", "DANGEROUS_CHARACTERS" ) package com.bkahlert.kommons.kaomoji.categories import com.bkahlert.kommons.kaomoji.Category import com.bkahlert.kommons.kaomoji.Kaomoji import kotlin.js.JsName public object Depressed : Category() { @JsName("depressed00") public val `(◞‸◟)`: Kaomoji by auto() @JsName("depressed01") public val `(´∵`)`: Kaomoji by auto() @JsName("depressed02") public val `|ω・`)`: Kaomoji by auto() @JsName("depressed03") public val `|ω・`)`: Kaomoji by auto("|ω・`)") @JsName("depressed04") public val `(-д-;)`: Kaomoji by auto() @JsName("depressed05") public val `从´_υ`从`: Kaomoji by auto() @JsName("depressed06") public val `(ノд`@)`: Kaomoji by auto() @JsName("depressed07") public val `(ノε`◎)`: Kaomoji by auto() @JsName("depressed08") public val `(ノω・`o)`: Kaomoji by auto() @JsName("depressed09") public val `(ー○ー)=3`: Kaomoji by auto() @JsName("depressed10") public val `(・´з`・)`: Kaomoji by auto("(・´з`・)") @JsName("depressed11") public val `(´・ω・`)`: Kaomoji by auto() @JsName("depressed12") public val `(´・ω・`)`: Kaomoji by auto() @JsName("depressed13") public val `(∥ ̄■ ̄∥)`: Kaomoji by auto() @JsName("depressed14") public val `(´-ω-`)`: Kaomoji by auto("(´-ω-`)") @JsName("depressed15") public val `(o´_`o)`: Kaomoji by auto() @JsName("depressed16") public val `(´・仝・`)`: Kaomoji by auto() @JsName("depressed17") public val `(*ノз`*)`: Kaomoji by auto("(*ノз`*)") @JsName("depressed18") public val `(っ´ω`c)`: Kaomoji by auto() @JsName("depressed19") public val `( ̄σ・・ ̄)`: Kaomoji by auto() @JsName("depressed20") public val `…φ(。。*)`: Kaomoji by auto() @JsName("depressed21") public val `(´・_・`)`: Kaomoji by auto("(´・_・`)") @JsName("depressed22") public val `(´゚ω゚`)`: Kaomoji by auto() @JsName("depressed23") public val `(lll-ω-)`: Kaomoji by auto() @JsName("depressed24") public val `(_ _|||)`: Kaomoji by auto() @JsName("depressed25") public val `(*´Д`)=з`: Kaomoji by auto() @JsName("depressed26") public val `(´‐ω‐)=з`: Kaomoji by auto() @JsName("depressed27") public val `( ◢д◣)`: Kaomoji by auto() @JsName("depressed28") public val `(* _ω_)…`: Kaomoji by auto() @JsName("depressed29") public val `…ρ(・ω`・、)`: Kaomoji by auto("…ρ(・ω`・、)") }
7
Kotlin
0
9
35e2ac1c4246decdf7e7a1160bfdd5c9e28fd066
2,470
kommons
MIT License
android_app/app/src/main/kotlin/dev/sergiobelda/iot/cloud/weather/firestoredatasource/FirestoreDataSource.kt
serbelga
179,172,949
false
{"Kotlin": 33151, "JavaScript": 2882}
/* * Copyright 2021 <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 dev.sergiobelda.iot.cloud.weather.firestoredatasource import com.google.firebase.firestore.ktx.firestore import com.google.firebase.firestore.ktx.toObject import com.google.firebase.ktx.Firebase import dev.sergiobelda.iot.cloud.weather.data.Result import dev.sergiobelda.iot.cloud.weather.firestoredatasource.FirestoreConstants.collectionPath import dev.sergiobelda.iot.cloud.weather.firestoredatasource.mapper.DeviceWeatherStateMapper.map import dev.sergiobelda.iot.cloud.weather.firestoredatasource.model.DeviceWeatherStateFirestore import dev.sergiobelda.iot.cloud.weather.model.Device import dev.sergiobelda.iot.cloud.weather.model.DeviceWeatherState import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow class FirestoreDataSource : IFirestoreDataSource { @OptIn(ExperimentalCoroutinesApi::class) override fun getDevices(): Flow<Result<List<Device>>> = callbackFlow { val collectionReference = Firebase.firestore.collection(collectionPath) val listenerRegistration = collectionReference.addSnapshotListener { value, error -> if (value != null) { val devices = mutableListOf<Device>() for (document in value.documents) { devices.add(Device(document.id)) } trySend(Result.Success(devices)).isSuccess } else { trySend(Result.Failure(exception = error)).isFailure } } awaitClose { listenerRegistration.remove() } } @OptIn(ExperimentalCoroutinesApi::class) override fun getDeviceWeatherState(deviceId: String): Flow<Result<DeviceWeatherState>> = callbackFlow { val documentReference = Firebase.firestore.collection(collectionPath).document(deviceId) val listenerRegistration = documentReference.addSnapshotListener { value, error -> if (value != null) { val deviceWeatherState = value.toObject<DeviceWeatherStateFirestore>()?.map() deviceWeatherState?.let { trySend(Result.Success(it)).isSuccess } ?: trySend(Result.Failure()).isFailure } else { trySend(Result.Failure(exception = error)).isFailure } } awaitClose { listenerRegistration.remove() } } }
20
Kotlin
1
15
8f63c6ab48dd8309a13e17fb6b9206bd4d788a59
3,107
IoTGoogleCloud-Weather
Apache License 2.0
Study/app/src/main/java/com/example/study/ui/UpdateTaskActivity.kt
nascimentoJulio
318,672,400
false
null
package com.example.study.ui import android.app.DatePickerDialog import android.content.Intent import android.os.Bundle import android.widget.* import androidx.appcompat.app.AppCompatActivity import com.example.study.R import com.example.study.constants.Constants import com.example.study.ui.viewmodel.UpdateViewModel import java.util.* class UpdateTaskActivity : AppCompatActivity(), DatePickerDialog.OnDateSetListener { lateinit var mDueDate: String lateinit var mDueDateSelector: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_update_task) val title = findViewById<EditText>(R.id.edit_update_title) val description = findViewById<EditText>(R.id.edit_update_description) val topic = findViewById<EditText>(R.id.edit_update_topic) this.mDueDateSelector = findViewById(R.id.button_update_show_date_picker) val buttonSave = findViewById<Button>(R.id.button_update_save) val checkCompleted = findViewById<CheckBox>(R.id.check_update_is_complete) val mViewModel = UpdateViewModel(this) val bundle = intent.extras val id = bundle?.getLong(Constants.BUNDLE) val taskModel = id?.let { mViewModel.getTaskById(it).value } this.mDueDate = taskModel?.dueDate.toString() title.setText(taskModel?.title) description.setText(taskModel?.description) topic.setText(taskModel?.topic) mDueDateSelector.text = this.mDueDate checkCompleted.isChecked = taskModel?.isCompleted!! mDueDateSelector.setOnClickListener { showDatePicker() } buttonSave.setOnClickListener { if (title.text.toString().isEmpty() || description.text.toString().isEmpty() || topic.text.toString().isEmpty() || this.mDueDate.isEmpty() ) { Toast.makeText(this, R.string.empty_fields, Toast.LENGTH_SHORT).show() } else { taskModel.title = title.text.toString() taskModel.description = description.text.toString() taskModel.topic = topic.text.toString() taskModel.dueDate = this.mDueDate taskModel.isCompleted = checkCompleted.isChecked taskModel.let { it1 -> mViewModel.update(it1) } startActivity( Intent(this, MainActivity::class.java) ) Toast.makeText(this, R.string.update_message, Toast.LENGTH_LONG).show() } } } fun showDatePicker() { val calendar = Calendar.getInstance() val year = calendar.get(Calendar.YEAR) val month = calendar.get(Calendar.MONTH) val day = calendar.get(Calendar.DAY_OF_MONTH) DatePickerDialog(this, this, year, month, day).show() } override fun onDateSet(p0: DatePicker?, year: Int, month: Int, day: Int) { if (month + 1 < 10) this.mDueDate = String.format("%d/0%d/%d", day, month + 1, year) else this.mDueDate = String.format("%d/%d/%d", day, month + 1, year) this.mDueDateSelector.text = this.mDueDate } }
0
Kotlin
0
0
a19e68b0364130c36cc49973a9b203779806a40c
3,262
Lab
MIT License
app/src/main/java/com/example/movie/di/Bindings.kt
eneskkoc
408,488,959
false
{"Kotlin": 14636}
package com.example.screen.di import com.example.screen.ui.main.MainActivity import dagger.Module import dagger.android.ContributesAndroidInjector @Module abstract class Bindings { @PerActivity @ContributesAndroidInjector abstract fun bindMainActivity(): MainActivity }
0
Kotlin
0
1
98989232c42843501a031fe6a765c699f458caf8
283
movie-app
MIT License
app/src/main/kotlin/com/skyline/msgbot/repository/JSEngineRepository.kt
SkyLineLab
451,012,446
false
null
package com.skyline.msgbot.repository import com.caoccao.javet.interop.V8Host import com.caoccao.javet.interop.V8Runtime import com.naijun.graaldalvik.AndroidClassLoaderFactory import com.skyline.msgbot.core.CoreHelper import com.skyline.msgbot.core.CoreHelper.baseNodePath import com.skyline.msgbot.reflow.script.javascript.JavaScriptConfig import io.adnopt.context.AdnoptContext import org.graalvm.polyglot.Context import org.graalvm.polyglot.HostAccess import org.graalvm.polyglot.PolyglotAccess object JSEngineRepository { /** * GraalJS + adnopt(develop) * * @return {org.graalvm.polyglot.Context} */ fun getGraalJSEngine(): Context { return Context.newBuilder("js") .allowHostAccess(HostAccess.ALL) .allowPolyglotAccess(PolyglotAccess.ALL) // .hostClassLoader(AndroidClassLoaderFactory.createClassLoader( // CoreHelper.contextGetter!!.invoke() // )) .allowExperimentalOptions(true) .allowIO(true) .options( JavaScriptConfig.getDefaultContextOption() ) .allowCreateThread(true) .allowCreateProcess(true) .allowNativeAccess(true) .allowHostClassLoading(true) .allowHostClassLookup { true }.build() } fun getGraalJSEngine(projectName: String): Context { return Context.newBuilder("js") .allowHostAccess(HostAccess.ALL) .allowPolyglotAccess(PolyglotAccess.ALL) // .hostClassLoader(AndroidClassLoaderFactory.createClassLoader(CoreHelper.contextGetter!!.invoke())) .allowExperimentalOptions(true) .allowIO(true) .options( JavaScriptConfig.getProjectContextOption(projectName) ) .allowCreateThread(true) .allowCreateProcess(true) .allowNativeAccess(true) .allowHostClassLoading(true) .allowHostClassLookup { true }.build() } /** * GraalJS + Adnopt (nodejs support) */ fun getAdnoptJSEngine(projectName: String): AdnoptContext { return getGraalJSEngine(projectName).let { AdnoptContext.create(it) } } /** * Javet */ fun getV8JSEngine(): V8Runtime { return V8Host.getV8Instance().createV8Runtime() } /** * Javet */ fun getNodeJSEngine(): V8Runtime { return V8Host.getNodeInstance().createV8Runtime() } }
4
Kotlin
1
9
9e9324e269c729f45f7c86f4939932fd72669355
2,517
SkyLine
MIT License
src/main/kotlin/de/kevcodez/metronom/model/delay/Departure.kt
kevcodez
63,542,748
false
null
package de.kevcodez.metronom.model.delay import de.kevcodez.metronom.model.station.Station import java.time.LocalTime /** * Contains the possible delay, target station, train number and time of a departure. * * @author <NAME> */ class Departure( val train: String, val targetStation: Station, val time: LocalTime, val delayInMinutes: Int, val track: String? = null, val isCancelled: Boolean = false )
0
Kotlin
1
2
7feddcaed80704604fd4664f8a7edce4ca09f635
431
Metronom-REST-API
MIT License
app/src/main/kotlin/org/kepocnhh/xfiles/provider/PathNames.kt
kepocnhh
616,000,116
false
{"Kotlin": 501352}
package org.kepocnhh.xfiles.provider internal data class PathNames( val symmetric: String, val asymmetric: String, val dataBase: String, val dataBaseSignature: String, val biometric: String, )
0
Kotlin
0
0
495157f0690ea01d0cbe37f6fd3f06a38dade8e4
214
xfiles
MIT License
demo/src/commonMain/kotlin/dev/alibagherifam/kavoshgar/demo/lobby/presenter/RandomLobbieGenerator.kt
alibagherifam
586,918,409
false
{"Kotlin": 9411}
package dev.alibagherifam.kavoshgar.demo.lobby.presenter import java.net.InetAddress import java.util.Random internal fun getRandomLobbies(): Lobby { val random = Random() return Lobby( name = "Server #" + random.nextInt(100), address = InetAddress.getByName("192.168.1." + random.nextInt(255)), latency = random.nextInt(300).toLong() ) }
0
Kotlin
2
15
2f388dd2566b7a7339c3c409fd0a00207c6bf5ff
377
kavoshgar
Apache License 2.0
walt-cli/src/main/kotlin/waltid/openbadgecredential/cli/utils/beautifier.kt
alegomes
733,176,233
false
{"Kotlin": 40105}
package waltid.openbadgecredential.cli.utils import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json val prettyJson = Json { prettyPrint = true } inline fun <reified T> toPrettyJson(content : T): String = prettyJson.encodeToString(content)
0
Kotlin
0
0
cdf4c806b8bb503457d0e597e6339f334f55cb61
269
waltid-openbadgecredential-cli
Apache License 2.0
sqlite-embedder-chicory/src/jvmMain/kotlin/host/module/emscripten/EmscriptenHostFunctionHandle.kt
illarionov
769,429,996
false
{"Kotlin": 1653596}
/* * Copyright 2024, the wasm-sqlite-open-helper project authors and contributors. Please see the AUTHORS file * for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. * SPDX-License-Identifier: Apache-2.0 */ package ru.pixnews.wasm.sqlite.open.helper.chicory.host.module.emscripten import com.dylibso.chicory.runtime.Instance import com.dylibso.chicory.wasm.types.Value internal fun interface EmscriptenHostFunctionHandle { fun apply(instance: Instance, vararg args: Value): Value? }
0
Kotlin
0
3
546dc6fce69d2d3704ddf34939ab498931b2d047
555
wasm-sqlite-open-helper
Apache License 2.0
app/src/main/java/org/plavelo/puppy/di/SingletonModule.kt
plavelo
342,108,138
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.plavelo.puppy.di import android.content.Context import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import org.plavelo.puppy.infrastructure.db.AppDatabase import org.plavelo.puppy.infrastructure.repository.PuppyRepositoryImpl import org.plavelo.puppy.usecase.repository.PuppyRepository import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object SingletonModule { @Provides @Singleton fun provideDatabase(@ApplicationContext context: Context): AppDatabase = AppDatabase.create(context) @Provides @Singleton fun providePuppyRepository(database: AppDatabase): PuppyRepository = PuppyRepositoryImpl(database.puppyDao()) }
0
Kotlin
0
0
2e5c123278c7c8bd26882b7cf1450c23c306ea96
1,441
compose-puppy
Apache License 2.0
src/main/kotlin/com/justai/jaicf/plugin/scenarios/psi/ReferencesSearcher.kt
just-ai
394,978,762
false
null
package com.justai.jaicf.plugin.scenarios.psi import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.SearchScope import com.intellij.psi.search.searches.ReferencesSearch import com.justai.jaicf.plugin.providers.ReferenceContributorsAvailabilityService import org.jetbrains.kotlin.idea.search.projectScope import org.jetbrains.kotlin.resolve.jvm.KotlinJavaPsiFacade fun PsiElement.search(scope: SearchScope = project.projectScope()): Collection<PsiReference> { if (DumbService.getInstance(project).isDumb) return emptyList() val referenceContributorService = ReferenceContributorsAvailabilityService.getInstance(this) return try { referenceContributorService?.disable() ReferencesSearch.search(this, scope, true).findAll() } finally { referenceContributorService?.enable() } } fun findClass(packageFq: String, className: String, project: Project): PsiClass? { if (DumbService.getInstance(project).isDumb) return null val kotlinPsiFacade = KotlinJavaPsiFacade.getInstance(project) val projectScope = GlobalSearchScope.allScope(project) return kotlinPsiFacade.findPackage(packageFq, projectScope)?.classes?.firstOrNull { it.name == className } } fun PsiClass.getMethods(vararg methods: String) = allMethods.filter { it.name in methods }
5
Kotlin
1
3
8868f5a6d2d02bd79ca526cf942d59df7d528d14
1,542
jaicf-plugin
Apache License 2.0
bot/src/main/kotlin/bot/bridges/TransactionsBridge.kt
a6dang
219,093,159
true
{"Kotlin": 59514, "SQLPL": 848}
package bot.bridges import io.reactivex.Observable import io.reactivex.Observer import io.reactivex.subjects.PublishSubject import org.jsoup.nodes.Document object TransactionsBridge : Bridge<Pair<Long, Document>> { private val dataBridge = PublishSubject.create<Pair<Long, Document>>() override val dataObserver: Observer<Pair<Long, Document>> get() = dataBridge override val dataObservable: Observable<Pair<Long, Document>> get() = dataBridge }
0
Kotlin
1
0
428bd3290ea36da3dbff258375d48bf972b03c1e
478
yahoo-fantasy-bot
MIT License
app/src/main/java/com/nicktra/moviesquare/data/source/remote/response/movie/MovieResponse.kt
nicktra
323,316,950
false
null
package com.nicktra.moviesquare.data.source.remote.response.movie import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class MovieResponse( var movieId: String, var title: String, var overview: String, var image: String, var release: String, var rating: String ) : Parcelable
0
Kotlin
0
0
95e8dab9cfb35810233a54e3359854c1e84bcac3
334
movie-square
MIT License
app/src/test/java/com/example/ethan/ui/speech/Text2SpeechTest.kt
inf20079
612,295,861
false
null
package com.example.ethan.ui.speech import org.junit.Assert.* import org.junit.Before import org.junit.Test class Text2SpeechTest{ private lateinit var text2speech: Text2Speech @Before fun setUp(){ text2speech = Text2Speech } @Test fun set_and_get_onFinished_initialized(){ text2speech.onFinished_initialized = true assertEquals(true, text2speech.onFinished_initialized) } @Test fun overritten_utteranceProgressListener(){ text2speech.utteranceProgressListener.onStart("Start") text2speech.utteranceProgressListener.onDone("Done") text2speech.utteranceProgressListener.onError("Error") //Test if methods can be called assertEquals(1,1) } @Test fun removeCallbackTest(){ text2speech.onFinished_initialized = true text2speech.removeCallback() assertEquals(false, text2speech.onFinished_initialized) } @Test fun setCallbackTest(){ text2speech.onFinished_initialized = false text2speech.setCallback { } assertEquals(true, text2speech.onFinished_initialized) } }
0
Kotlin
0
2
54863d4e8500c171ea23373e5d6761015a5dc104
1,140
e.t.h.a.n
MIT License
data/src/main/java/com/codeforcesvisualizer/data/model/ContestModel.kt
islamdidarmd
148,098,533
false
{"Kotlin": 185614}
package com.codeforcesvisualizer.data.model import com.codeforcesvisualizer.domain.entity.Contest import com.squareup.moshi.Json data class ContestModel( @field:Json(name = "id") val id: Int, @field:Json(name = "name") val name: String, @field:Json(name = "type") val type: Type, @field:Json(name = "phase") val phase: Phase, @field:Json(name = "frozen") val frozen: Boolean, @field:Json(name = "durationSeconds") val durationSeconds: Int, @field:Json(name = "startTimeSeconds") val startTimeSeconds: Int, @field:Json(name = "relativeTimeSeconds") val relativeTimeSeconds: Int, @field:Json(name = "preparedBy") val preparedBy: String?, @field:Json(name = "websiteUrl") val websiteUrl: String?, @field:Json(name = "description") val description: String?, @field:Json(name = "difficulty") val difficulty: Int?, @field:Json(name = "kind") val kind: String?, @field:Json(name = "icpcRegion") val icpcRegion: String?, @field:Json(name = "country") val country: String?, @field:Json(name = "season") val season: String?, ) { fun toEntity(): Contest { return Contest( id = id, name = name, type = type.name, phase = PhaseMapper.map(phase), frozen = frozen, durationSeconds = durationSeconds, startTimeSeconds = startTimeSeconds, relativeTimeSeconds = relativeTimeSeconds, scheduled = phase == Phase.BEFORE, preparedBy = preparedBy, websiteUrl = websiteUrl, description = description, difficulty = difficulty, kind = kind, icpcRegion = icpcRegion, country = country, season = season ) } } object PhaseMapper { fun map(phase: Phase): String { return when (phase) { Phase.BEFORE -> "Scheduled" Phase.CODING -> "Running" Phase.PENDING_SYSTEM_TEST -> "Pending System Test" Phase.SYSTEM_TEST -> "Running System Test" Phase.FINISHED -> "Finished" } } } enum class Phase { BEFORE, CODING, PENDING_SYSTEM_TEST, SYSTEM_TEST, FINISHED } enum class Type { CF, IOI, ICPC }
0
Kotlin
0
8
37123b15662c0353bedd487127a54c4be55b52f9
2,329
Codeforces-Companion
MIT License
select-lib/src/main/java/vip/qsos/lib/select/Operation.kt
hslooooooool
239,998,824
false
{"Kotlin": 23141}
package vip.qsos.lib.select import androidx.annotation.DrawableRes /** * @author 华清松 * * 选项实体 * @param key 选项名称 * @param value 选项值 * @param checked 是否选中 * @param checkable 是否可选 * @param iconId 选项图标 */ data class Operation( val key: String, val value: Any = key, var checked: Boolean = false, var checkable: Boolean = true, @DrawableRes var iconId: Int? = null )
0
Kotlin
0
2
d66207f709cfa4097abfff1aa1a16cc6a85d4d32
396
widgets-select
Apache License 2.0
core/src/jvmMain/kotlin/io/kinference/compiler/generation/operators/activations/SoftmaxGenerator.kt
JetBrains-Research
381,293,081
false
{"Kotlin": 122072, "PureBasic": 25827, "Python": 2231}
package io.kinference.compiler.generation.operators.activations import io.kinference.compiler.generation.operators.OperatorGenerationInfo import io.kinference.operators.activations.Softmax import kotlin.time.ExperimentalTime /** * Softmax generator. * * [ONNX documentation](https://github.com/onnx/onnx/blob/master/docs/Operators.md#Softmax) * * KInference class: [Softmax] */ @OptIn(ExperimentalTime::class) class SoftmaxGenerator( private val operator: Softmax, info: OperatorGenerationInfo ) : ActivationGenerator(operator, info)
5
Kotlin
0
2
7230b2e8024aba4b3b2257316367a902b116fc06
550
kinference-compiler
Apache License 2.0
core/ui/src/main/java/com/mldz/core/ui/preview/ThemePreviews.kt
MaximZubarev
729,033,741
false
{"Kotlin": 158696}
package com.mldz.core.ui.preview import android.content.res.Configuration import androidx.compose.ui.tooling.preview.Preview @Preview(uiMode = Configuration.UI_MODE_NIGHT_NO, name = "Light theme") @Preview(uiMode = Configuration.UI_MODE_NIGHT_YES, name = "Dark theme") annotation class ThemePreviews @Preview(showBackground = true, backgroundColor = 0xFFFFFFFF) @Preview(showBackground = true, backgroundColor = 0xFF000000) annotation class BlackWhiteBackgroundPreview
0
Kotlin
0
0
81fe998593361581c232e3d9d33661268f6bd25b
473
unsplash_app
The Unlicense
feature4/src/main/java/com/example/feature4/di/Feature4Module.kt
ChicK00o
194,475,938
false
null
package com.example.feature4.di import dagger.Module @Module(includes = [ ActivityModule::class ,ViewModelsModule::class ]) abstract class Feature4Module
0
Kotlin
0
1
83626707c0559443c90d60afb009d9dd5ba29b5f
163
android-multi-module-playground
MIT License
platform/runner/plugin/std/sys/src/main/kotlin/io/hamal/plugin/std/sys/func/FuncCreateFunction.kt
hamal-io
622,870,037
false
{"Kotlin": 2450833, "C": 1400046, "TypeScript": 323978, "Lua": 165691, "C++": 40651, "Makefile": 11728, "Java": 7564, "CMake": 2810, "JavaScript": 2640, "CSS": 1567, "Shell": 977, "HTML": 903}
package io.hamal.plugin.std.sys.func import io.hamal.lib.common.snowflake.SnowflakeId import io.hamal.lib.domain.vo.CodeValue import io.hamal.lib.domain.vo.FuncInputs import io.hamal.lib.domain.vo.FuncName import io.hamal.lib.domain.vo.NamespaceId import io.hamal.lib.kua.function.Function1In2Out import io.hamal.lib.kua.function.FunctionContext import io.hamal.lib.kua.function.FunctionInput1Schema import io.hamal.lib.kua.function.FunctionOutput2Schema import io.hamal.lib.kua.type.* import io.hamal.lib.sdk.ApiSdk import io.hamal.lib.sdk.api.ApiFuncCreateRequest class FuncCreateFunction( private val sdk: ApiSdk ) : Function1In2Out<KuaTable, KuaError, KuaTable>( FunctionInput1Schema(KuaTable::class), FunctionOutput2Schema(KuaError::class, KuaTable::class) ) { override fun invoke(ctx: FunctionContext, arg1: KuaTable): Pair<KuaError?, KuaTable?> { return try { val res = sdk.func.create( arg1.findString("namespace_id")?.let { NamespaceId(SnowflakeId(it.stringValue)) } ?: ctx[NamespaceId::class], ApiFuncCreateRequest( name = FuncName(arg1.getString("name").stringValue), inputs = FuncInputs(), code = CodeValue(arg1.getString("code").stringValue) ) ) null to ctx.tableCreate( "request_id" to KuaString(res.requestId.value.value.toString(16)), "request_status" to KuaString(res.requestStatus.name), "id" to KuaString(res.id.value.value.toString(16)), "workspace_id" to KuaString(res.workspaceId.value.value.toString(16)), "namespace_id" to KuaString(res.namespaceId.value.value.toString(16)) ) } catch (t: Throwable) { KuaError(t.message!!) to null } } }
39
Kotlin
0
0
7ead833ab99206c5a20bcb295103ee3642972423
1,878
hamal
Creative Commons Zero v1.0 Universal
modules-api/src/main/java/io/appmetrica/analytics/modulesapi/internal/client/ModuleClientEntryPoint.kt
appmetrica
650,662,094
false
{"Java": 5767508, "C++": 5729793, "Kotlin": 2677873, "Python": 229161, "Objective-C++": 152166, "C": 127185, "Assembly": 59003, "Emacs Lisp": 14657, "Objective-C": 10302, "Starlark": 7767, "Shell": 5746, "Go": 4930, "CMake": 3562, "CSS": 1454, "AppleScript": 1429, "AIDL": 504}
package io.appmetrica.analytics.modulesapi.internal.client abstract class ModuleClientEntryPoint<T : Any> { abstract val identifier: String open val serviceConfigExtensionConfiguration: ServiceConfigExtensionConfiguration<T>? = null open fun initClientSide(clientContext: ClientContext) {} open fun onActivated() {} }
2
Java
7
54
ae0626e12338a01ce0effad1e9e3706a85b9e752
339
appmetrica-sdk-android
MIT License
modules-api/src/main/java/io/appmetrica/analytics/modulesapi/internal/client/ModuleClientEntryPoint.kt
appmetrica
650,662,094
false
{"Java": 5767508, "C++": 5729793, "Kotlin": 2677873, "Python": 229161, "Objective-C++": 152166, "C": 127185, "Assembly": 59003, "Emacs Lisp": 14657, "Objective-C": 10302, "Starlark": 7767, "Shell": 5746, "Go": 4930, "CMake": 3562, "CSS": 1454, "AppleScript": 1429, "AIDL": 504}
package io.appmetrica.analytics.modulesapi.internal.client abstract class ModuleClientEntryPoint<T : Any> { abstract val identifier: String open val serviceConfigExtensionConfiguration: ServiceConfigExtensionConfiguration<T>? = null open fun initClientSide(clientContext: ClientContext) {} open fun onActivated() {} }
2
Java
7
54
ae0626e12338a01ce0effad1e9e3706a85b9e752
339
appmetrica-sdk-android
MIT License
app/src/main/java/com/duhan/satelliteinfo/features/base/data/Resource.kt
enesduhanbulut
667,576,346
false
null
package com.duhan.satelliteinfo.features.base.data import com.duhan.satelliteinfo.features.base.domain.ITimeLimitedResource import com.duhan.satelliteinfo.features.base.domain.RefreshControl import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow class Resource<in Input, out Output>( private val remoteFetch: suspend (Input) -> Output?, private val localFetch: suspend (Input) -> Output?, private val localStore: suspend (Output) -> Unit, private val localDelete: suspend () -> Unit, private val refreshControl: RefreshControl = RefreshControl() ) : RefreshControl.Listener, ITimeLimitedResource by refreshControl { init { refreshControl.addListener(this) } fun query(args: Input, force: Boolean = false): Flow<Output?> = flow { if (!force) { fetchFromLocal(args)?.run { emit(this) } } if (refreshControl.isExpired() || force) { fetchFromRemote(args).run { emit(this) } } } override suspend fun cleanup() { deleteLocal() } // Private API private suspend fun deleteLocal() = kotlin.runCatching { localDelete() }.getOrNull() private suspend fun fetchFromLocal(args: Input) = kotlin.runCatching { localFetch(args) }.getOrNull() private suspend fun fetchFromRemote(args: Input) = kotlin.run { remoteFetch(args) }?.also { kotlin.runCatching { localStore(it) refreshControl.refresh() } } }
0
Kotlin
0
0
5c5673706f3277e0a92a891842d4d7703e1069ce
1,522
3fa826302e266388d90bc2780706c998
MIT License
module-api/src/main/java/langchainkt/store/embedding/RelevanceScore.kt
c0x12c
655,095,005
false
{"Kotlin": 322914, "Java": 13181}
package langchainkt.store.embedding object RelevanceScore { /** * Converts cosine similarity into relevance score. * * @param cosineSimilarity Cosine similarity in the range [-1..1] where -1 is not relevant and 1 is relevant. * @return Relevance score in the range [0..1] where 0 is not relevant and 1 is relevant. */ @JvmStatic fun fromCosineSimilarity(cosineSimilarity: Double): Double { return (cosineSimilarity + 1) / 2 } }
0
Kotlin
0
0
1dc065a3aec804d53259171f6f95206eb2fdb0b6
456
langchainkt
Apache License 2.0
data/src/main/kotlin/repository/local/source/user/spock/classes/all/DataSourcePdfPropertiesSpock.kt
tardisjphon
647,261,331
false
null
package repository.local.source.user.spock.classes.all import repository.model.pdf.general.CvLanguage import repository.model.pdf.properties.IPdfProperties class DataSourcePdfPropertiesSpock : IPdfProperties { override var subject = "CV" override var author = "Spock" override var pathImages = "data/src/main/resources/image/" override var imageNamePhoto = "spock.jpg" override var imageNameWatermark = "cv_generator_watermark.png" override fun getLanguages() = arrayListOf( CvLanguage.ENGLISH, CvLanguage.POLISH ) }
0
Kotlin
0
0
95f14ec3ad35a5345ed4664ed985dd215a382190
565
CvGenerator
MIT License
backend/book/src/main/kotlin/com/zenika/kbooks/feature/book/IBookRepository.kt
Zenika
126,350,105
false
null
package com.zenika.kbooks.feature.book import org.springframework.data.repository.PagingAndSortingRepository import org.springframework.stereotype.Repository /** * Repository to access books. */ @Repository interface IBookRepository : PagingAndSortingRepository<Book, Long>
2
Kotlin
2
5
7e00728f5ad3909594a679bcca83d150d109126e
277
kbooks
MIT License
app/src/main/java/com/concordium/wallet/util/Extensions.kt
Concordium
358,250,608
false
null
package com.concordium.wallet.util import android.content.Intent import android.os.Build import android.os.Bundle import java.io.Serializable import java.math.BigInteger fun ByteArray.toHex() = joinToString("") { Integer.toUnsignedString(java.lang.Byte.toUnsignedInt(it), 16).padStart(2, '0') } fun String.toHex() = this.toByteArray().joinToString("") { Integer.toUnsignedString(java.lang.Byte.toUnsignedInt(it), 16).padStart(2, '0') } fun Float.roundUpToInt(): Int { return (this + 0.99).toInt() } fun <T : Serializable?> Intent.getSerializable(key: String, m_class: Class<T>): T { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) this.getSerializableExtra(key, m_class)!! else { @Suppress("DEPRECATION", "UNCHECKED_CAST") this.getSerializableExtra(key) as T } } fun <T : Serializable?> Bundle.getSerializableFromBundle(key: String, m_class: Class<T>): T { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) this.getSerializable(key, m_class)!! else { @Suppress("DEPRECATION", "UNCHECKED_CAST") this.getSerializable(key) as T } } /** * Allows to safely parse [BigInteger] from [String] with default value (0 by default) * @return parsed value or [defaultValue] if it can't be parsed */ fun String?.toBigInteger(defaultValue: BigInteger = BigInteger.ZERO): BigInteger = try { if (isNullOrBlank()) defaultValue else BigInteger(this) } catch (e: NumberFormatException) { defaultValue }
6
null
3
9
3e478e26e85ff36d148b7ac40b705971d2665775
1,569
concordium-reference-wallet-android
Apache License 2.0
app/src/main/java/com/mirea/jetpack3dviews/MainActivity.kt
TerrifyingAnt
708,086,285
false
{"Kotlin": 11244}
package com.mirea.jetpack3dviews import android.annotation.SuppressLint import android.opengl.GLSurfaceView import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar 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 androidx.compose.ui.viewinterop.AndroidView import com.mirea.jetpack3dviews.ui.theme.Jetpack3DViewsTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { var glSurfaceView = GLSurfaceView(this) super.onCreate(savedInstanceState) setContent { Jetpack3DViewsTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { ProductPage(glSurfaceView) } } } } } @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @OptIn(ExperimentalMaterial3Api::class) @Composable fun ProductPage(glSurfaceView: GLSurfaceView) { var rendererSet = false var quantity by remember { mutableStateOf(1) } Scaffold( topBar = { TopAppBar( title = { Text(text = "Product Name") }, ) } ) { Box(modifier = Modifier.fillMaxSize()){ AndroidView( factory = { glSurfaceView.apply { setEGLContextClientVersion(2) setRenderer(ObjectRenderer()) rendererSet = true } }, modifier = Modifier.fillMaxSize(), ) } // LazyColumn( // modifier = Modifier.fillMaxSize() // ) { // // item { // Spacer(modifier = Modifier.height(16.dp)) // Text( // text = "Product Name", // style = MaterialTheme.typography.labelLarge, // modifier = Modifier.padding(16.dp) // ) // Text( // text = "Product Description", // style = MaterialTheme.typography.labelMedium, // modifier = Modifier.padding(16.dp) // ) // Spacer(modifier = Modifier.height(16.dp)) // } // item { // var totalPrice = quantity * 29.99 // Row( // modifier = Modifier // .fillMaxWidth() // .padding(16.dp), // verticalAlignment = Alignment.CenterVertically // ) { // Text( // text = "Price: $$totalPrice", // style = MaterialTheme.typography.labelSmall, // modifier = Modifier.weight(1f) // ) // BasicTextField( // value = quantity.toString(), // onValueChange = { // quantity = it.toIntOrNull() ?: 0 // }, // keyboardOptions = KeyboardOptions.Default.copy( // imeAction = ImeAction.Done, // keyboardType = KeyboardType.Number // ), // keyboardActions = KeyboardActions( // onDone = { // Обработка нажатия клавиши "Готово" // // Дополнительная логика здесь, если необходимо // } // ), // singleLine = true, // modifier = Modifier // .width(50.dp) // .background(Color.White) // .clip(MaterialTheme.shapes.small) // .padding(8.dp) // .fillMaxHeight() // ) // Spacer(modifier = Modifier.width(8.dp)) // IconButton( // onClick = { // quantity++ // } // ) { // Icon(imageVector = Icons.Default.Add, contentDescription = null) // } // IconButton( // onClick = { // if (quantity > 1) { // quantity-- // } // } // ) { // Icon(imageVector = Icons.Default.Remove, contentDescription = null) // } // } // } // item { // Button( // onClick = { /* Действие по нажатию на кнопку "Добавить в корзину" */ }, // modifier = Modifier // .fillMaxWidth() // .padding(16.dp) // ) { // Text(text = "Добавить в корзину") // } // } // } } }
0
Kotlin
0
0
599fafffc1088425c6e09d1f0f38ffb539ade993
5,889
Jetpack3DViews
MIT License
android/app/src/main/kotlin/com/example/mvvm_skeleton/MainActivity.kt
fthdmirr
354,347,014
false
{"Dart": 31697, "HTML": 1515, "Swift": 404, "Kotlin": 130, "Objective-C": 38}
package com.example.mvvm_skeleton import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
93c8009816e7ea061eb06e046966c1c1d4be310a
130
mvvm_skeleton
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsresettlementpassportapi/data/cvlapi/LicenceDTO.kt
ministryofjustice
665,659,688
false
{"Kotlin": 1609755, "Dockerfile": 1994}
package uk.gov.justice.digital.hmpps.hmppsresettlementpassportapi.data.cvlapi data class Licence( val id: Long, val typeCode: String, val version: String? = null, val statusCode: String?, val nomsId: String? = null, val bookingNo: String? = null, val bookingId: Long? = null, val crn: String? = null, val pnc: String? = null, val cro: String? = null, val prisonCode: String? = null, val prisonDescription: String? = null, val prisonTelephone: String? = null, val forename: String? = null, val middleNames: String? = null, val surname: String? = null, val dateOfBirth: String? = null, val conditionalReleaseDate: String? = null, val actualReleaseDate: String? = null, val sentenceStartDate: String? = null, val sentenceEndDate: String? = null, val licenceStartDate: String? = null, val licenceExpiryDate: String? = null, val topupSupervisionStartDate: String? = null, val topupSupervisionExpiryDate: String? = null, val comUsername: String? = null, val comStaffId: Long? = null, val comEmail: String? = null, val probationAreaCode: String? = null, val probationAreaDescription: String? = null, val probationPduCode: String? = null, val probationPduDescription: String? = null, val probationLauCode: String? = null, val probationLauDescription: String? = null, val probationTeamCode: String? = null, val probationTeamDescription: String? = null, val appointmentPerson: String? = null, val appointmentTime: String? = null, val appointmentAddress: String? = null, val appointmentContact: String? = null, val spoDiscussion: String? = null, val vloDiscussion: String? = null, val approvedDate: String? = null, val approvedByUsername: String? = null, val approvedByName: String? = null, val supersededDate: String? = null, val dateCreated: String? = null, val createdByUsername: String? = null, val dateLastUpdated: String? = null, val updatedByUsername: String? = null, val standardLicenceConditions: List<StandardCondition>? = emptyList(), val standardPssConditions: List<StandardCondition>? = emptyList(), val additionalLicenceConditions: List<AdditionalCondition> = emptyList(), val additionalPssConditions: List<AdditionalCondition> = emptyList(), val bespokeConditions: List<BespokeCondition> = emptyList(), val isVariation: Boolean, val variationOf: Long? = null, val createdByFullName: String? = null, ) data class BespokeCondition( val id: Long? = null, val sequence: Int? = null, val text: String? = null, ) data class StandardCondition( val id: Long? = null, val code: String? = null, val sequence: Int? = null, val text: String? = null, ) data class AdditionalCondition( val id: Long? = null, val code: String? = null, val version: String? = null, val category: String? = null, val sequence: Int? = null, val text: String? = null, val expandedText: String? = null, // val data: List<AdditionalConditionData> = emptyList(), val uploadSummary: List<AdditionalConditionUploadSummary> = emptyList(), ) data class AdditionalConditionUploadSummary( val id: Long? = null, val filename: String? = null, val fileType: String? = null, val fileSize: Int = 0, val uploadedTime: String? = null, val description: String? = null, val thumbnailImage: String? = null, val uploadDetailId: Long? = null, )
0
Kotlin
2
1
78550deb9cf07550c94f144de6ca4fafbdcc1c74
3,361
hmpps-resettlement-passport-api
MIT License
app/src/main/java/com/aditya/to_do/di/DatabaseModule.kt
aditya-bhawsar
413,261,754
false
{"Kotlin": 73381}
package com.aditya.to_do.di import android.content.Context import androidx.room.Room import com.aditya.to_do.data.ToDoDao import com.aditya.to_do.data.ToDoDatabase import com.aditya.to_do.util.Constants import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object DatabaseModule { @Provides @Singleton internal fun getDatabase(@ApplicationContext ctx: Context): ToDoDatabase = Room.databaseBuilder( ctx, ToDoDatabase::class.java, Constants.DB_NAME ).build() @Provides @Singleton internal fun getTodoDao(database: ToDoDatabase): ToDoDao = database.getToDoDao() }
0
Kotlin
0
1
e2e4d58c9e6d3463ccafa93e427f27b30b008b12
819
to-do-compose
Apache License 2.0
app/src/test/kotlin/jp/co/yumemi/android/codecheck/data/GithubApiRepositoryTest.kt
mickie895
633,669,896
false
null
package jp.co.yumemi.android.codecheck.data import jp.co.yumemi.android.codecheck.restapi.mock.getMockService import jp.co.yumemi.android.codecheck.restapi.mock.getServerErrorMockService import kotlinx.coroutines.test.runTest import org.junit.Assert import org.junit.Test class GithubApiRepositoryTest { /** * GithubAPIが正常なときの動作チェック */ @Test fun normalQueryTest() = runTest { val apiService = getMockService(sampleApiResult) val repository = GithubApiRepository(apiService) val queryResult = repository.searchQuery("git") Assert.assertTrue("正常判定", queryResult is SearchApiResponse.Ok) apiService.nextApiResult = emptyApiResult val emptyResult = repository.searchQuery("git") Assert.assertTrue("空の結果も正常である", emptyResult is SearchApiResponse.Ok) apiService.nextApiResult = sampleErrorResult val errorResult = repository.searchQuery("git") Assert.assertTrue("失敗を受け取れていることの確認", errorResult is SearchApiResponse.Error) Assert.assertTrue("失敗時は対応する返答を返す", errorResult is SearchApiResponse.Error.ByQuery) } /** * エラーを吐いているときの確認 */ @Test fun errorQueryTest() = runTest { val repository = GithubApiRepository( getServerErrorMockService(sampleApiResult), ) val errorResult = repository.searchQuery("git") Assert.assertTrue("失敗を受け取れていることの確認", errorResult is SearchApiResponse.Error) Assert.assertTrue("失敗時は対応する返答を返す", errorResult is SearchApiResponse.Error.ByQuery) } }
9
Kotlin
0
0
c80c8de149a10c4e5a86b94a273b8234b5bda4c8
1,556
yumemi_codecheck
Apache License 2.0
deob-processor/src/main/kotlin/org/openrs2/deob/processor/LocalVariableScanner.kt
openrs2
315,027,372
false
null
package org.openrs2.deob.processor import com.sun.source.tree.VariableTree import com.sun.source.util.TreePathScanner import com.sun.source.util.Trees import org.openrs2.deob.annotation.Pc public class LocalVariableScanner(private val trees: Trees) : TreePathScanner<Void, MutableMap<Int, String>>() { override fun visitVariable(node: VariableTree, p: MutableMap<Int, String>): Void? { val element = trees.getElement(currentPath) val pc = element.getAnnotation(Pc::class.java) if (pc != null) { p[pc.value] = element.simpleName.toString() } return super.visitVariable(node, p) } }
0
Kotlin
2
8
12eba96055ba13e8a8e3ec0ad3be7d93b3dd5b1b
645
openrs2
ISC License
clients/intellij/src/main/kotlin/com/tabbyml/intellijtabby/agent/AgentService.kt
TabbyML
614,764,248
false
{"TypeScript": 220353, "Rust": 113845, "Kotlin": 57581, "Python": 50804, "HTML": 28032, "Vim Script": 22935, "JavaScript": 20947, "C++": 9113, "CMake": 4436, "CSS": 3448, "MDX": 3432, "Shell": 2961, "Dockerfile": 1449, "Makefile": 306}
package com.tabbyml.intellijtabby.agent import com.intellij.ide.BrowserUtil import com.intellij.ide.plugins.PluginManagerCore import com.intellij.lang.Language import com.intellij.notification.Notification import com.intellij.notification.NotificationType import com.intellij.notification.Notifications import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ReadAction import com.intellij.openapi.application.invokeLater import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.progress.ProgressIndicator import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.tabbyml.intellijtabby.settings.ApplicationSettingsState import com.tabbyml.intellijtabby.usage.AnonymousUsageLogger import io.ktor.util.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking @Service class AgentService : Disposable { private val logger = Logger.getInstance(AgentService::class.java) private var agent: Agent = Agent() val scope: CoroutineScope = CoroutineScope(Dispatchers.IO) private var initFailedNotification: Notification? = null var authNotification: Notification? = null private set var issueNotification: Notification? = null private set private var completionResponseWarningShown = false enum class Status { INITIALIZING, INITIALIZATION_FAILED, } private var initResultFlow: MutableStateFlow<Boolean?> = MutableStateFlow(null) val status = initResultFlow.combine(agent.status) { initResult, agentStatus -> if (initResult == null) { Status.INITIALIZING } else if (initResult) { agentStatus } else { Status.INITIALIZATION_FAILED } }.stateIn(scope, SharingStarted.Eagerly, Status.INITIALIZING) val currentIssue get() = agent.currentIssue init { val settings = service<ApplicationSettingsState>() val anonymousUsageLogger = service<AnonymousUsageLogger>() scope.launch { val config = createAgentConfig(settings.data) val clientProperties = createClientProperties(settings.data) try { agent.open() agent.initialize(config, clientProperties) initResultFlow.value = true logger.info("Agent init done.") } catch (e: Exception) { initResultFlow.value = false logger.warn("Agent init failed: $e") anonymousUsageLogger.event( "IntelliJInitFailed", mapOf( "client" to clientProperties.session["client"] as String, "error" to e.stackTraceToString() ) ) val notification = Notification( "com.tabbyml.intellijtabby.notification.warning", "Tabby initialization failed", "${e.message}", NotificationType.ERROR, ) // FIXME: Add action to open FAQ page to help user set up nodejs. invokeLater { initFailedNotification?.expire() initFailedNotification = notification Notifications.Bus.notify(notification) } } } scope.launch { settings.state.collect { if (it.serverEndpoint.isNotBlank()) { updateConfig("server.endpoint", it.serverEndpoint) } else { clearConfig("server.endpoint") } updateClientProperties("user", "intellij.triggerMode", it.completionTriggerMode) updateConfig("anonymousUsageTracking.disable", it.isAnonymousUsageTrackingDisabled) } } scope.launch { agent.authRequiredEvent.collect { logger.info("Will show auth required notification.") val notification = Notification( "com.tabbyml.intellijtabby.notification.warning", "Authorization required for Tabby server", NotificationType.WARNING, ) notification.addAction(ActionManager.getInstance().getAction("Tabby.OpenAuthPage")) invokeLater { authNotification?.expire() authNotification = notification Notifications.Bus.notify(notification) } } } scope.launch { agent.currentIssue.collect { issueName -> val content = when (issueName) { "slowCompletionResponseTime" -> "Completion requests appear to take too much time" "highCompletionTimeoutRate" -> "Most completion requests timed out" else -> return@collect } if (completionResponseWarningShown) { return@collect } completionResponseWarningShown = true val notification = Notification( "com.tabbyml.intellijtabby.notification.warning", content, NotificationType.WARNING, ) notification.addAction(ActionManager.getInstance().getAction("Tabby.CheckIssueDetail")) invokeLater { issueNotification?.expire() issueNotification = notification Notifications.Bus.notify(notification) } } } } private fun createAgentConfig(state: ApplicationSettingsState.State): Agent.Config { return Agent.Config( server = if (state.serverEndpoint.isNotBlank()) { Agent.Config.Server( endpoint = state.serverEndpoint, ) } else { null }, anonymousUsageTracking = if (state.isAnonymousUsageTrackingDisabled) { Agent.Config.AnonymousUsageTracking( disabled = true, ) } else { null }, ) } private fun createClientProperties(state: ApplicationSettingsState.State): Agent.ClientProperties { val appInfo = ApplicationInfo.getInstance() val appVersion = appInfo.fullVersion val appName = appInfo.fullApplicationName.replace(appVersion, "").trim() val pluginId = "com.tabbyml.intellij-tabby" val pluginVersion = PluginManagerCore.getPlugin(PluginId.getId(pluginId))?.version val client = "$appName $pluginId $pluginVersion" return Agent.ClientProperties( user = mapOf( "intellij" to mapOf( "triggerMode" to state.completionTriggerMode, ), ), session = mapOf( "client" to client, "ide" to mapOf("name" to appName, "version" to appVersion), "tabby_plugin" to mapOf("name" to pluginId, "version" to pluginVersion), ), ) } private suspend fun waitForInitialized() { agent.status.first { it != Agent.Status.NOT_INITIALIZED } } private suspend fun updateClientProperties(type: String, key: String, config: Any) { waitForInitialized() agent.updateClientProperties(type, key, config) } private suspend fun updateConfig(key: String, config: Any) { waitForInitialized() agent.updateConfig(key, config) } private suspend fun clearConfig(key: String) { waitForInitialized() agent.clearConfig(key) } suspend fun provideCompletion(editor: Editor, offset: Int, manually: Boolean = false): Agent.CompletionResponse? { waitForInitialized() return ReadAction.compute<PsiFile, Throwable> { editor.project?.let { project -> PsiDocumentManager.getInstance(project).getPsiFile(editor.document) } }?.let { file -> agent.provideCompletions( Agent.CompletionRequest( file.virtualFile.path, file.getLanguageId(), editor.document.text, offset, manually, ) ) } } suspend fun postEvent(event: Agent.LogEventRequest) { waitForInitialized() agent.postEvent(event) } suspend fun requestAuth(progress: ProgressIndicator) { waitForInitialized() progress.isIndeterminate = true progress.text = "Generating authorization url..." val authUrlResponse = agent.requestAuthUrl() val notification = if (authUrlResponse != null) { BrowserUtil.browse(authUrlResponse.authUrl) progress.text = "Waiting for authorization from browser..." agent.waitForAuthToken(authUrlResponse.code) if (agent.status.value == Agent.Status.READY) { Notification( "com.tabbyml.intellijtabby.notification.info", "Congrats, you're authorized, start to use Tabby now.", NotificationType.INFORMATION ) } else { Notification( "com.tabbyml.intellijtabby.notification.warning", "Connection error, please check settings and try again.", NotificationType.WARNING ) } } else { Notification( "com.tabbyml.intellijtabby.notification.info", "You are already authorized.", NotificationType.INFORMATION ) } invokeLater { authNotification?.expire() authNotification = notification Notifications.Bus.notify(notification) } } suspend fun getCurrentIssueDetail(): Map<String, Any>? { waitForInitialized() return agent.getIssueDetail(Agent.GetIssueDetailOptions(name = currentIssue.value)) } suspend fun getServerHealthState(): Map<String, Any>? { waitForInitialized() return agent.getServerHealthState() } override fun dispose() { runBlocking { runCatching { agent.finalize() } } agent.close() } companion object { // Language id: https://code.visualstudio.com/docs/languages/identifiers private fun PsiFile.getLanguageId(): String { if (this.language != Language.ANY && this.language.id.toLowerCasePreservingASCIIRules() !in arrayOf( "txt", "text", "textmate" ) ) { if (languageIdMap.containsKey(this.language.id)) { return languageIdMap[this.language.id]!! } return this.language.id.toLowerCasePreservingASCIIRules().replace("#", "sharp").replace("++", "pp") .replace(" ", "") } return if (filetypeMap.containsKey(this.fileType.defaultExtension)) { filetypeMap[this.fileType.defaultExtension]!! } else { this.fileType.defaultExtension.toLowerCasePreservingASCIIRules() } } private val languageIdMap = mapOf( "ObjectiveC" to "objective-c", "ObjectiveC++" to "objective-cpp", ) private val filetypeMap = mapOf( "py" to "python", "js" to "javascript", "cjs" to "javascript", "mjs" to "javascript", "jsx" to "javascriptreact", "ts" to "typescript", "tsx" to "typescriptreact", "kt" to "kotlin", "md" to "markdown", "cc" to "cpp", "cs" to "csharp", "m" to "objective-c", "mm" to "objective-cpp", "sh" to "shellscript", "zsh" to "shellscript", "bash" to "shellscript", "txt" to "plaintext", ) } }
27
TypeScript
367
10,822
dfdd0373a60a2ead0de939c2bb3b00b4729dd365
10,964
tabby
Apache License 2.0
kotlin/workflows/samples/sample-workflow-temporal/src/main/kotlin/com/github/frtu/sample/source/sync/RouterConfig.kt
frtu
338,595,537
false
{"Kotlin": 442294, "Java": 157399, "Shell": 10826, "Dockerfile": 248}
package com.github.frtu.sample.source.sync import com.github.frtu.logs.core.RpcLogger.* import com.github.frtu.sample.domain.EmailCrudHandler import com.github.frtu.sample.persistence.basic.EmailEntity import com.github.frtu.sample.temporal.staticwkf.SubscriptionEvent import com.github.frtu.sample.temporal.staticwkf.starter.SubscriptionHandler import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.web.reactive.function.server.* import java.net.URI @Configuration class RouterConfig( private val subscriptionHandler: SubscriptionHandler, private val emailCrudHandler: EmailCrudHandler, ) { @Bean fun route(): RouterFunction<*> = coRouter { // Workflow val uriPath = "/v1/workflows" POST(uriPath) { serverRequest -> val subscriptionEvent = serverRequest.awaitBody<SubscriptionEvent>() rpcLogger.info(uri(uriPath), requestBody(subscriptionEvent)) val createdId = subscriptionHandler.handle(subscriptionEvent) rpcLogger.info(uri(uriPath), requestBody(subscriptionEvent), responseBody(createdId)) created(URI.create("$uriPath/$createdId")).buildAndAwait() } // Simple CRUD val uriPathEmails = "/v1/emails" GET(uriPathEmails) { rpcLogger.info(uri(uriPathEmails), message("query all")) ok().json().bodyAndAwait(emailCrudHandler.queryMany()) } GET("/v1/emails/{id}") { serverRequest -> val id = serverRequest.pathVariable("id") val entity = emailCrudHandler.queryOne(id) when { entity != null -> ok().json().bodyValueAndAwait(entity) else -> notFound().buildAndAwait() } } POST(uriPathEmails) { serverRequest -> val emailEntity = serverRequest.awaitBody<EmailEntity>() val createdId = emailCrudHandler.insertOne(emailEntity) rpcLogger.info(uri(uriPathEmails), requestBody(emailEntity), responseBody(createdId)) created(URI.create("$uriPathEmails/$createdId")).buildAndAwait() } } internal val rpcLogger = create(this::class.java) }
0
Kotlin
0
1
b480fef80acb753bd6d824c556aa3e9c09ec4d14
2,247
lib-toolbox
Apache License 2.0
core/src/animations/Shrink.kt
PatriotCodes
114,823,813
false
null
package animations import com.badlogic.gdx.graphics.g2d.Batch import com.badlogic.gdx.graphics.g2d.TextureRegion import interfaces.Anim class Expand(override val texture: TextureRegion, override val speed: Float, override val isLoop: Boolean) : Anim { private var sizeModifier = 0f var waitFor1 = true private var increment = true var maxSize = 1f var isStopped = false override fun draw(batch: Batch, x: Float, y: Float, size: Float, delta: Float) { if (!isStopped) { if (sizeModifier > 1f) sizeModifier = 1f if (sizeModifier < 0f) sizeModifier = 0f batch.draw(texture, x + assertOffset(size), y + assertOffset(size), size * sizeModifier, size * sizeModifier) assertSizeModifier(delta) } } private fun assertSizeModifier(delta: Float) { if (waitFor1) { if (sizeModifier >= maxSize) { increment = false waitFor1 = false if (!isLoop) { isStopped = true } } } else { if (sizeModifier <= 0f) { increment = true waitFor1 = true } } if (increment) { sizeModifier += delta * speed } else { sizeModifier -= delta * speed } } private fun assertOffset(size : Float) : Float { val newSize = size * sizeModifier return (size - newSize) / 2 } }
13
Kotlin
0
5
3c654ce4744c1e0dab9c8727c25738baabfd304f
1,500
Diamond-Story
MIT License
codebase/android/feature/accounts/src/main/java/com/makeappssimple/abhimanyu/financemanager/android/feature/accounts/edit_account/screen/EditAccountScreenUIStateAndEvents.kt
Abhimanyu14
429,663,688
false
{"Kotlin": 1650951}
package com.makeappssimple.abhimanyu.financemanager.android.feature.accounts.edit_account.screen import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.focus.FocusRequester import com.makeappssimple.abhimanyu.financemanager.android.core.common.extensions.isNotNull import com.makeappssimple.abhimanyu.financemanager.android.core.common.extensions.isNull import com.makeappssimple.abhimanyu.financemanager.android.core.common.extensions.orFalse import com.makeappssimple.abhimanyu.financemanager.android.core.common.extensions.orZero import com.makeappssimple.abhimanyu.financemanager.android.core.common.result.MyResult import com.makeappssimple.abhimanyu.financemanager.android.core.model.AccountType import com.makeappssimple.abhimanyu.financemanager.android.core.ui.base.ScreenUIStateAndEvents import com.makeappssimple.abhimanyu.financemanager.android.core.ui.base.ScreenUIStateEvents import com.makeappssimple.abhimanyu.financemanager.android.core.ui.component.chip.ChipUIData import com.makeappssimple.abhimanyu.financemanager.android.core.ui.extensions.icon import com.makeappssimple.abhimanyu.financemanager.android.core.ui.extensions.orEmpty import com.makeappssimple.abhimanyu.financemanager.android.feature.accounts.R @Stable internal class EditAccountScreenUIStateAndEvents( val state: EditAccountScreenUIState, val events: EditAccountScreenUIStateEvents, ) : ScreenUIStateAndEvents @Stable internal class EditAccountScreenUIStateEvents( val resetScreenBottomSheetType: () -> Unit, ) : ScreenUIStateEvents @Composable internal fun rememberEditAccountScreenUIStateAndEvents( data: MyResult<EditAccountScreenUIData>?, ): EditAccountScreenUIStateAndEvents { val nameTextFieldFocusRequester = remember { FocusRequester() } val balanceAmountTextFieldFocusRequester = remember { FocusRequester() } var screenBottomSheetType: EditAccountScreenBottomSheetType by remember { mutableStateOf( value = EditAccountScreenBottomSheetType.None, ) } val setScreenBottomSheetType = { updatedEditAccountScreenBottomSheetType: EditAccountScreenBottomSheetType -> screenBottomSheetType = updatedEditAccountScreenBottomSheetType } return remember( data, screenBottomSheetType, nameTextFieldFocusRequester, balanceAmountTextFieldFocusRequester, ) { val unwrappedData: EditAccountScreenUIData? = when (data) { is MyResult.Success -> { data.data } else -> { null } } val selectedAccountTypeIndex = unwrappedData?.selectedAccountTypeIndex.orZero() val selectedAccount = unwrappedData?.accountTypes?.getOrNull( selectedAccountTypeIndex ) // TODO(Abhi): Can be reordered to match the class ordering EditAccountScreenUIStateAndEvents( state = EditAccountScreenUIState( screenBottomSheetType = screenBottomSheetType, nameTextFieldFocusRequester = nameTextFieldFocusRequester, balanceAmountTextFieldFocusRequester = balanceAmountTextFieldFocusRequester, isLoading = unwrappedData.isNull(), isCtaButtonEnabled = unwrappedData?.isValidAccountData.orFalse(), appBarTitleTextStringResourceId = R.string.screen_edit_account_appbar_title, ctaButtonLabelTextStringResourceId = R.string.screen_edit_account_floating_action_button_content_description, nameTextFieldErrorTextStringResourceId = unwrappedData?.errorData?.nameTextField?.textStringResourceId, selectedAccountTypeIndex = unwrappedData?.selectedAccountTypeIndex.orZero(), accountTypesChipUIDataList = unwrappedData?.accountTypes ?.map { accountType -> ChipUIData( text = accountType.title, icon = accountType.icon, ) } .orEmpty(), balanceAmountValue = unwrappedData?.balanceAmountValue.orEmpty(), minimumBalanceAmountValue = unwrappedData?.minimumBalanceAmountValue.orEmpty(), name = unwrappedData?.name.orEmpty(), visibilityData = EditAccountScreenUIVisibilityData( balanceAmountTextField = true, minimumBalanceAmountTextField = selectedAccount == AccountType.BANK, nameTextField = unwrappedData?.accountIsNotCash.orFalse(), nameTextFieldErrorText = unwrappedData?.errorData?.nameTextField.isNotNull(), accountTypesRadioGroup = unwrappedData?.accountIsNotCash.orFalse(), ), ), events = EditAccountScreenUIStateEvents( resetScreenBottomSheetType = { setScreenBottomSheetType(EditAccountScreenBottomSheetType.None) }, ), ) } }
11
Kotlin
0
2
f68666ee47f55616a6fc65f9c71621d0fc6ecb65
5,310
finance-manager
Apache License 2.0
brum-backend/src/main/kotlin/pl/przemyslawpitus/brum/infrastructure/InMemoryUserRepository.kt
MagicznyCzarodziej
502,406,042
false
null
package pl.przemyslawpitus.brum.infrastructure import org.springframework.stereotype.Repository import pl.przemyslawpitus.brum.domain.entity.RegisterUser import pl.przemyslawpitus.brum.domain.entity.User import pl.przemyslawpitus.brum.domain.entity.UserId import pl.przemyslawpitus.brum.domain.repository.UserRepository @Repository class InMemoryUserRepository : UserRepository { private var nextUserId: UserId = 1 private val users: MutableList<User> = mutableListOf() override fun createUser(user: RegisterUser) { val userWithId = User( id = nextUserId, username = user.username, passwordHash = user.passwordHash ) users.add(userWithId) nextUserId++ } override fun findByUsername(username: String): User? { return users.find { it.username == username } } }
0
Kotlin
0
0
640abc51bcd55260d57445804cee65c3aae22f2c
862
Brum
MIT License
api/src/main/kotlin/nebulosa/api/controllers/FocuserController.kt
tiagohm
568,578,345
false
null
package nebulosa.api.controllers import jakarta.validation.Valid import jakarta.validation.constraints.NotBlank import jakarta.validation.constraints.PositiveOrZero import nebulosa.api.data.responses.FocuserResponse import nebulosa.api.services.EquipmentService import nebulosa.api.services.FocuserService import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController @RestController class FocuserController( private val equipmentService: EquipmentService, private val focuserService: FocuserService, ) { @GetMapping("attachedFocusers") fun attachedFocusers(): List<FocuserResponse> { return equipmentService.focusers().map(::FocuserResponse) } @GetMapping("focuser") fun focuser(@RequestParam @Valid @NotBlank name: String): FocuserResponse { return FocuserResponse(requireNotNull(equipmentService.focuser(name))) } @PostMapping("focuserConnect") fun connect(@RequestParam @Valid @NotBlank name: String) { val focuser = requireNotNull(equipmentService.focuser(name)) focuserService.connect(focuser) } @PostMapping("focuserDisconnect") fun disconnect(@RequestParam @Valid @NotBlank name: String) { val focuser = requireNotNull(equipmentService.focuser(name)) focuserService.disconnect(focuser) } @PostMapping("focuserMoveIn") fun moveIn( @RequestParam @Valid @NotBlank name: String, @RequestParam @Valid @PositiveOrZero steps: Int, ) { val focuser = requireNotNull(equipmentService.focuser(name)) focuserService.moveIn(focuser, steps) } @PostMapping("focuserMoveOut") fun moveOut( @RequestParam @Valid @NotBlank name: String, @RequestParam @Valid @PositiveOrZero steps: Int, ) { val focuser = requireNotNull(equipmentService.focuser(name)) focuserService.moveOut(focuser, steps) } @PostMapping("focuserMoveTo") fun moveTo( @RequestParam @Valid @NotBlank name: String, @RequestParam @Valid @PositiveOrZero steps: Int, ) { val focuser = requireNotNull(equipmentService.focuser(name)) focuserService.moveTo(focuser, steps) } @PostMapping("focuserAbort") fun abort(@RequestParam @Valid @NotBlank name: String) { val focuser = requireNotNull(equipmentService.focuser(name)) focuserService.abort(focuser) } @PostMapping("focuserSyncTo") fun syncTo( @RequestParam @Valid @NotBlank name: String, @RequestParam @Valid @PositiveOrZero steps: Int, ) { val focuser = requireNotNull(equipmentService.focuser(name)) focuserService.syncTo(focuser, steps) } }
0
Kotlin
0
1
a8f8826ce5d470a77a73d41170f45bfe96ff235e
2,856
nebulosa
MIT License
lavaplayer/src/main/java/com/sedmelluq/discord/lavaplayer/container/ogg/OggTrackBlueprint.kt
mixtape-bot
397,835,411
true
{"Kotlin": 781109, "Java": 315803}
package com.sedmelluq.discord.lavaplayer.container.ogg interface OggTrackBlueprint { fun loadTrackHandler(stream: OggPacketInputStream): OggTrackHandler }
0
Kotlin
0
6
06b02d8e711930c52d8ca67ad6347a17ca352ba2
160
lavaplayer
Apache License 2.0
octicons/src/commonMain/kotlin/com/woowla/compose/icon/collections/octicons/octicons/Archive24.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.octicons.octicons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin 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.octicons.Octicons public val Octicons.Archive24: ImageVector get() { if (_archive24 != null) { return _archive24!! } _archive24 = Builder(name = "Archive24", 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(2.75f, 2.0f) horizontalLineToRelative(18.5f) curveToRelative(0.966f, 0.0f, 1.75f, 0.784f, 1.75f, 1.75f) verticalLineToRelative(3.5f) arcTo(1.75f, 1.75f, 0.0f, false, true, 21.25f, 9.0f) lineTo(2.75f, 9.0f) arcTo(1.75f, 1.75f, 0.0f, false, true, 1.0f, 7.25f) verticalLineToRelative(-3.5f) curveTo(1.0f, 2.784f, 1.784f, 2.0f, 2.75f, 2.0f) close() moveTo(21.25f, 3.5f) lineTo(2.75f, 3.5f) arcToRelative(0.25f, 0.25f, 0.0f, false, false, -0.25f, 0.25f) verticalLineToRelative(3.5f) curveToRelative(0.0f, 0.138f, 0.112f, 0.25f, 0.25f, 0.25f) horizontalLineToRelative(18.5f) arcToRelative(0.25f, 0.25f, 0.0f, false, false, 0.25f, -0.25f) verticalLineToRelative(-3.5f) arcToRelative(0.25f, 0.25f, 0.0f, false, false, -0.25f, -0.25f) close() moveTo(2.75f, 10.0f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.75f, 0.75f) verticalLineToRelative(9.5f) curveToRelative(0.0f, 0.138f, 0.112f, 0.25f, 0.25f, 0.25f) horizontalLineToRelative(16.5f) arcToRelative(0.25f, 0.25f, 0.0f, false, false, 0.25f, -0.25f) verticalLineToRelative(-9.5f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 1.5f, 0.0f) verticalLineToRelative(9.5f) arcTo(1.75f, 1.75f, 0.0f, false, true, 20.25f, 22.0f) lineTo(3.75f, 22.0f) arcTo(1.75f, 1.75f, 0.0f, false, true, 2.0f, 20.25f) verticalLineToRelative(-9.5f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.75f, -0.75f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(9.75f, 11.5f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.0f, 1.5f) horizontalLineToRelative(4.5f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.0f, -1.5f) horizontalLineToRelative(-4.5f) close() } } .build() return _archive24!! } private var _archive24: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
3,863
compose-icon-collections
MIT License
libs/virtual-node/cpi-upload-endpoints/src/main/kotlin/net/corda/libs/cpiupload/endpoints/v1/GetCPIsResponse.kt
corda
346,070,752
false
{"Kotlin": 20585393, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244}
package net.corda.libs.cpiupload.endpoints.v1 /** * Response from CPI list API * * @param cpis List of CPIs. */ data class GetCPIsResponse(val cpis: List<CpiMetadata>)
14
Kotlin
27
69
0766222eb6284c01ba321633e12b70f1a93ca04e
173
corda-runtime-os
Apache License 2.0
readme/src/main/kotlin/docusaurus/Docusaurus.kt
mfwgenerics
584,628,939
false
null
package docusaurus import io.koalaql.markout.Markout import io.koalaql.markout.docusaurus.docusaurus fun Markout.setupDocusaurus() = docusaurus { configure { url = "https://mfwgenerics.github.io/" baseUrl = "/markout/" title = "Markout" github = "https://github.com/mfwgenerics/markout" metadata = mapOf("google-site-verification" to "<KEY>") } docs { intro() } }
0
Kotlin
0
7
f633c572d27abf5f783e1324ebfdbab1b83abb8d
433
markout
MIT License
secret-santa-service/src/test/kotlin/com/ggranados/sercretsanta/api/SecretSantaServiceApplicationTest.kt
ggranados
418,981,357
false
{"Kotlin": 21003}
package com.ggranados.sercretsanta.api import com.fasterxml.jackson.databind.ObjectMapper import com.ggranados.sercretsanta.api.model.Person import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.http.MediaType import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders import org.springframework.test.web.servlet.result.MockMvcResultHandlers.print import org.springframework.test.web.servlet.result.MockMvcResultMatchers @SpringBootTest @AutoConfigureMockMvc internal class SecretSantaServiceApplicationTest{ @Autowired lateinit var mockMvc: MockMvc @Test @DisplayName("givenPersonWhenSavedThenPersonReturned") @Throws(Exception::class) fun givenPersonWhenSavedThenPersonReturned() { //TODO: assign relations //val eventTest = Event(1,"Secret Santa 2021", LocalDate.of(2021,11,24)) //var teamTest = Team(1, "team1") val personTest = Person(1,"","","","", Person.PersonaStatus.REGISTERED, null) mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/team/1/persons/") .contentType(MediaType.APPLICATION_JSON) .content(asJsonString(personTest))).andDo(print()) .andExpect(MockMvcResultMatchers.status().isOk) .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.jsonPath("$.id").exists()) } fun asJsonString(obj: Person): String { return try { ObjectMapper().writeValueAsString(obj) } catch (e: java.lang.Exception) { throw RuntimeException(e) } } }
0
Kotlin
0
0
9d1df03cd96e074a620e501cf7f72e5166940d7e
1,925
kotlin
MIT License
comet-core/src/test/kotlin/ren/natsuyuk1/comet/test/network/thirdparty/minecraft/TestMinecraftMotd.kt
StarWishsama
173,288,057
false
null
package ren.natsuyuk1.comet.test.network.thirdparty.minecraft import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.Test import ren.natsuyuk1.comet.network.thirdparty.minecraft.MinecraftServerType import ren.natsuyuk1.comet.network.thirdparty.minecraft.query import ren.natsuyuk1.comet.test.isCI class TestMinecraftMotd { @Test fun test() { if (isCI()) return runBlocking { val r = query("127.0.0.1", 25565, MinecraftServerType.JAVA) assert(r != null) println(r!!.toMessageWrapper()) } } }
19
Kotlin
20
193
19ed20ec4003a37be3bc2dfc6b55a9e2548f0542
578
Comet-Bot
MIT License
data/src/main/java/com/synrgyacademy/data/local/room/PassengerDao.kt
Synrgy-Academy-Final-Project
738,116,027
false
{"Kotlin": 429514, "Ruby": 1824}
package com.synrgyacademy.data.local.room import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Update import com.synrgyacademy.data.local.model.PassengerEntity import kotlinx.coroutines.flow.Flow @Dao interface PassengerDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertPassenger(passengerEntity: PassengerEntity) @Query("DELETE FROM passenger") suspend fun deleteAllPassenger() @Update suspend fun updatePassenger(passengerEntity: PassengerEntity) @Query("SELECT COUNT(*) FROM passenger") fun getCountPassenger() : Int @Query("SELECT * FROM passenger") fun getAllPassenger() : Flow<List<PassengerEntity>> @Query("SELECT * FROM passenger WHERE idUser = :id") fun getPassengerById(id: Int) : PassengerEntity @Query("SELECT * FROM passenger WHERE name = :name") fun getPassengerByName(name: String) : PassengerEntity @Query("SELECT * FROM passenger WHERE type = :type") fun getPassengerByType(type: String) : PassengerEntity }
0
Kotlin
0
0
d7fefca1200efd6eae4a33a34ef0511d90dfd54a
1,109
Android
MIT License
src/main/kotlin/no/nav/personbruker/minesaker/api/domain/Journalposttype.kt
joakibj
458,172,377
true
{"Kotlin": 170883, "Shell": 265, "Dockerfile": 250}
package no.nav.personbruker.minesaker.api.domain enum class Journalposttype { INNGAAENDE, UTGAAENDE, NOTAT }
0
null
0
0
51dd522799ecbd53207a55a44c8378ecdb819547
122
mine-saker-api
MIT License
js/js.translator/testData/incremental/invalidation/inlineFunctionAsParam/lib1/l1.9.kt
JetBrains
3,432,266
false
{"Markdown": 192, "Gradle": 401, "Gradle Kotlin DSL": 1182, "Java Properties": 29, "Shell": 45, "Ignore List": 20, "Batchfile": 21, "Git Attributes": 8, "JSON": 203, "XML": 833, "Kotlin": 56096, "INI": 200, "Java": 3899, "Text": 25219, "JavaScript": 316, "JAR Manifest": 2, "Roff": 256, "Roff Manpage": 56, "Protocol Buffer": 16, "Proguard": 15, "TOML": 1, "AsciiDoc": 1, "YAML": 8, "EditorConfig": 2, "OpenStep Property List": 24, "C": 216, "C++": 368, "Pascal": 1, "Python": 4, "CMake": 2, "Objective-C++": 19, "Objective-C": 237, "Groovy": 10, "Dockerfile": 5, "Diff": 4, "EJS": 1, "CSS": 6, "HTML": 11, "Swift": 161, "LLVM": 1, "Reason": 1, "JSON with Comments": 62, "TypeScript": 8, "CODEOWNERS": 1, "JFlex": 2, "Graphviz (DOT)": 102, "Ant Build System": 32, "Dotenv": 5, "Maven POM": 77, "FreeMarker": 1, "Fluent": 2, "Ruby": 19, "Scala": 1}
inline fun foo1(x: () -> Int = { 99 }) = x() inline fun foo2() = 88 inline fun foo3() = "foo3 update"
179
Kotlin
5640
48,055
e3542ec7d0ffb0a27b189cadc323e88e4cb8ba4f
102
kotlin
Apache License 2.0
app/src/main/java/hu/bme/aut/mobweb/edoxam/globetrotter/network/NetworkManager.kt
Iashiq
603,859,076
false
null
package hu.bme.aut.mobweb.edoxam.globetrotter.network import hu.bme.aut.mobweb.edoxam.globetrotter.data.CountryData import okhttp3.OkHttpClient import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.create object NetworkManager { val retrofit: Retrofit val countryApi: CountryApi private const val SERVICE_URL = "https://restcountries.com/" init { retrofit = Retrofit.Builder() .baseUrl(SERVICE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(OkHttpClient.Builder().build()) .build() countryApi = retrofit.create(CountryApi::class.java) } fun getCountryByName(name: String): Call<List<CountryData>?> { return countryApi.getCountryByName(name) } }
0
Kotlin
0
0
5e0d01759ee9edf9353dc013f6c5a0948987fe12
832
Globetrotter-MobileApp
MIT License
feature/favorites/src/main/java/com/redpine/favorites/di/FavoritesComponent.kt
maiow
600,207,272
false
{"Kotlin": 188157}
package com.redpine.favorites.di import androidx.lifecycle.ViewModelProvider import com.redpine.core.base.DiComponent import com.redpine.favorites.di.module.Binds import com.redpine.favorites.di.module.RepositoryModule import com.redpine.favorites.di.module.UseCaseModule import dagger.Component import javax.inject.Singleton @Component( dependencies = [ FavoritesDependencies::class ], modules = [ RepositoryModule::class, Binds::class, UseCaseModule::class ] ) @Singleton interface FavoritesComponent : DiComponent { override val viewModelFactory: ViewModelProvider.Factory @Component.Builder interface Builder { fun dependencies(dependencies: FavoritesDependencies): Builder fun build(): FavoritesComponent } }
6
Kotlin
1
5
a5a4344c45c22e20dec25d319201174ed0e6c158
794
dog-shelter
MIT License
app/src/main/java/dev/makuch/simplyTime/settings/WatchFaceConfigStateHolder.kt
tmakuch
634,219,242
false
null
package dev.makuch.simplyTime.settings import android.util.Log import androidx.activity.ComponentActivity import androidx.wear.watchface.editor.EditorSession import androidx.wear.watchface.style.UserStyle import androidx.wear.watchface.style.UserStyleSchema import androidx.wear.watchface.style.UserStyleSetting import dev.makuch.simplyTime.data.SettingsProps import dev.makuch.simplyTime.data.SettingsUIState import dev.makuch.simplyTime.utils.COMPLICATION_ID import dev.makuch.simplyTime.utils.SHOW_ON_AMBIENT_SETTING import dev.makuch.simplyTime.utils.SHOW_RING_SETTING import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.plus class WatchFaceConfigStateHolder( private val scope: CoroutineScope, private val activity: ComponentActivity ) { private lateinit var editorSession: EditorSession private lateinit var showRing: UserStyleSetting.BooleanUserStyleSetting private lateinit var showOnAmbient: UserStyleSetting.BooleanUserStyleSetting val uiState: StateFlow<SettingsUIState> = flow<SettingsUIState> { editorSession = EditorSession.createOnWatchEditorSession( activity = activity ) initSettingsPropsOnClass(editorSession.userStyleSchema) editorSession.userStyle.collect { userStyle -> emit( SettingsUIState.Success( getCurrentSettingsProps(userStyle) ) ) } } .stateIn( scope + Dispatchers.Main.immediate, SharingStarted.Eagerly, SettingsUIState.Loading("Initializing") ) private fun initSettingsPropsOnClass(userStyleSchema: UserStyleSchema) { for (setting in userStyleSchema.userStyleSettings) { when (setting.id.toString()) { SHOW_RING_SETTING -> { showRing = setting as UserStyleSetting.BooleanUserStyleSetting } SHOW_ON_AMBIENT_SETTING -> { showOnAmbient = setting as UserStyleSetting.BooleanUserStyleSetting } } } } private fun getCurrentSettingsProps( userStyle: UserStyle ): SettingsProps { Log.d(TAG, "updatesWatchFacePreview()") val showDivisionRingStyle = userStyle[showRing] as UserStyleSetting.BooleanUserStyleSetting.BooleanOption val showDivisionRingOnAmbientStyle = userStyle[showOnAmbient] as UserStyleSetting.BooleanUserStyleSetting.BooleanOption Log.d(TAG, "/new values: $showDivisionRingStyle") return SettingsProps( showRing = showDivisionRingStyle.value, showOnAmbient = showDivisionRingOnAmbientStyle.value ) } fun setComplication() { scope.launch(Dispatchers.Main.immediate) { editorSession.openComplicationDataSourceChooser(COMPLICATION_ID) } } fun setShowRing(enabled: Boolean) { setSettingsProp( showRing, UserStyleSetting.BooleanUserStyleSetting.BooleanOption.from(enabled) ) } fun setShowOnAmbient(enabled: Boolean) { setSettingsProp( showOnAmbient, UserStyleSetting.BooleanUserStyleSetting.BooleanOption.from(enabled) ) } private fun setSettingsProp( userStyleSetting: UserStyleSetting, userStyleOption: UserStyleSetting.Option ) { Log.d(TAG, "setUserStyleOption()") Log.d(TAG, "\tuserStyleSetting: $userStyleSetting") Log.d(TAG, "\tuserStyleOption: $userStyleOption") val mutableUserStyle = editorSession.userStyle.value.toMutableUserStyle() mutableUserStyle[userStyleSetting] = userStyleOption editorSession.userStyle.value = mutableUserStyle.toUserStyle() } companion object { private const val TAG = "WatchFaceConfigStateHolder" } }
0
Kotlin
0
0
df967356e5b03a5ab82f7e01e4a5dc9378fa1a5c
4,214
simply-time-wear
Apache License 2.0
app/android-tracker/src/main/java/it/torino/tracker/data_upload/dts_data/ActivityDataDTS.kt
fabcira
776,354,078
false
{"Kotlin": 376104}
/* * Copyright (c) Code Developed by Prof. Fabio Ciravegna * All rights Reserved */ package it.torino.tracker.data_upload.dts_data import it.torino.tracker.tracker.sensors.activity_recognition.ActivityData /** * the activity data type */ class ActivityDataDTS(activityData: ActivityData) { val id: Int = activityData.id val timeInMsecs: Long = activityData.timeInMsecs val type: Int = activityData.type val transitionType: Int = activityData.transitionType /** * it is necessary to define toString otherwise the obfuscator will remove the fields of the class * * @return */ override fun toString(): String { return "ActivityDataDTS(id=$id, timeInMsecs=$timeInMsecs, type=$type, transitionType=$transitionType)" } }
0
Kotlin
0
0
7639774b5ef546b478dc2a3b394e35437cb1cb42
783
healthTracker
MIT License
data/src/main/java/com/movingmaker/data/remote/model/request/EditDiaryRequest.kt
Comment-Diary
458,682,004
false
null
package com.movingmaker.data.remote.model.request import com.movingmaker.data.remote.model.RemoteModel import com.movingmaker.domain.model.request.EditDiaryModel import kotlinx.serialization.Serializable @Serializable data class EditDiaryRequest( val title: String, val content: String, val tempYn: Char, ) : RemoteModel { override fun toDomainModel() = EditDiaryModel( title, content, tempYn ) } fun EditDiaryModel.toDataModel() = EditDiaryRequest( title, content, tempYN )
7
Kotlin
1
2
cf9f329970d83181c41a6cfc0470cd2712301f6f
509
CommentDiary-AOS
MIT License
shared/src/commonMain/kotlin/io/ktlab/bshelper/model/bsmg/beatmapv3/LightColorRotationBox.kt
ktKongTong
694,984,299
false
{"Kotlin": 836333, "Shell": 71}
package io.ktlab.bshelper.model.bsmg.beatmapv3 import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class LightRotationBox( @SerialName("b") val beat: Double, @SerialName("g") val group: Int, @SerialName("e") val events: List<LightRotationEvent>, ) @Serializable data class LightRotationEvent( @SerialName("f") val filterObject: FilterObject, @SerialName("w") val beatDistribution: Double, @SerialName("d") val beatDistributionType: Int, @SerialName("s") val rotationDistribution: Double, @SerialName("t") val rotationDistributionType: Int, @SerialName("b") val rotationDistributionAffectsFirstEvent: Int, @SerialName("i") val rotationDistributionEasing: Int, @SerialName("a") val axis: Int, @SerialName("r") val reverseRotation: Int, @SerialName("l") val eventData: List<LightRotationEventData>, ) @Serializable data class LightRotationEventData( @SerialName("b") val beat: Double, @SerialName("p") val transitionFromPreviousEventRotationBehaviour: Int, @SerialName("e") val easeType: Int, @SerialName("l") val additionalLoops: Int, @SerialName("r") val rotationValue: Double, @SerialName("o") val rotationDirection: Int, )
3
Kotlin
0
0
5e5ea79e31bc6c4a2565c191cddb7769e8007b45
1,253
cm-bs-helper
MIT License
src/vulkan/api/VkFence.kt
pvmoore
166,660,032
false
null
package vulkan.api import org.lwjgl.system.MemoryStack import org.lwjgl.system.MemoryUtil.memAllocLong import org.lwjgl.system.MemoryUtil.memFree import org.lwjgl.vulkan.VK10.* import org.lwjgl.vulkan.VkDevice import org.lwjgl.vulkan.VkFenceCreateInfo import vulkan.misc.check import java.nio.LongBuffer class VkFence(private val device:VkDevice, val handle:Long) { fun reset() { val pFences = memAllocLong(1).put(handle).flip() vkResetFences(device, pFences) memFree(pFences) } fun isSignalled():Boolean { return VK_SUCCESS==vkGetFenceStatus(device, handle) } fun waitFor(timeoutNanos:Long = -1):Boolean { return device.waitFor(arrayOf(this), true, timeoutNanos) } fun destroy() { vkDestroyFence(device, handle, null) } } fun LongBuffer.put(a:Array<VkFence>): LongBuffer { a.forEach { put(it.handle) } return this } fun VkDevice.createFence(signalled:Boolean = false):VkFence { val info = VkFenceCreateInfo.calloc() .sType(VK_STRUCTURE_TYPE_FENCE_CREATE_INFO) .flags(if(signalled) VK_FENCE_CREATE_SIGNALED_BIT else 0) val pFence = memAllocLong(1) vkCreateFence(this, info, null, pFence).check() val fence = VkFence(this, pFence.get(0)) info.free() memFree(pFence) return fence } /** * @return true - all fences are signalled (or 1 was signalled if waitForAll is false) * false - timeout occurred */ fun VkDevice.waitFor(fences:Array<VkFence>, waitForAll:Boolean, timeoutNanos:Long):Boolean { MemoryStack.stackPush().use { stack -> val pFences = stack.mallocLong(fences.size).put(fences).flip() return VK_SUCCESS == vkWaitForFences(this, pFences, waitForAll, timeoutNanos) } }
0
Kotlin
0
1
eccc265d05f72d4dd1610cb8e47c753fafb8025d
1,756
vulkanlib
MIT License
Itchy/app/src/main/java/kr/ac/kaist/itchy/collisionCheck/BoundingSphere.kt
mikodham
609,734,889
false
null
package kr.ac.kaist.itchy.collisionCheck import kr.ac.kaist.itchy.gameEngine.Transform import kr.ac.kaist.itchy.util.Vector3 import kotlin.math.sqrt //Sphere Wrapper for Collision checking between objects, currently only used for the blood point target class BoundingSphere( ) : CollisionObject { var vertices: FloatArray? = null var radius: Float? = null var center: Vector3? = null val scale = 1f //var scaled: Boolean = false lateinit var transform: Transform constructor(verts: FloatArray, transform: Transform) : this() { this.transform = transform this.vertices = getGlobalVertices(verts, transform.modelMatrix, transform.scale) center = transform.pos radius = getRadius() * scale } private fun getRadius(): Float { var maxDistance = 0.0f for (i in 0 until vertices!!.size step 3) { val posVertex = Vector3(vertices!![i], vertices!![i + 1], vertices!![i + 2]) var distance = center!!.getDistance(posVertex) if (distance > maxDistance) { maxDistance = distance } } return maxDistance } override fun intersects(aabb: AABB): Boolean { val x = aabb.minX.coerceAtLeast(center!!.x.coerceAtMost(aabb.maxX)) val y = aabb.minY.coerceAtLeast(center!!.y.coerceAtMost(aabb.maxY)) val z = aabb.minZ.coerceAtLeast(center!!.z.coerceAtMost(aabb.maxZ)) var distance = sqrt( (x - center!!.x) * (x - center!!.x) + (y - center!!.y) * (y - center!!.y) + (z - center!!.z) * (z - center!!.z) ) if (distance < radius!!) { return true } return distance < radius!! } override fun intersects(obj: BoundingSphere): Boolean { if (center!!.getDistance(obj.center!!) <= radius!! + obj.radius!!) { return true } return false } override fun update(verts: FloatArray, transform: Transform) { this.transform = transform this.vertices = getGlobalVertices(verts, transform.modelMatrix, transform.scale) /*if(!scaled) { radius = radius!! * transform.scale.x scaled = true }*/ center = transform.pos radius = getRadius() * scale } }
0
Kotlin
0
0
4b71a2ebe8731439be703da77278c8eefb3b23b3
2,338
Itchy
MIT License
kmm_mvikotlin_sample/androidApp/src/main/java/com/mvikotlin/android/post/list/PostList.kt
vladlen2010
444,197,061
false
{"Kotlin": 144652, "Swift": 43044, "Ruby": 3488}
package com.mvikotlin.android.post.list import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material.Divider import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.google.accompanist.swiperefresh.SwipeRefresh import com.google.accompanist.swiperefresh.rememberSwipeRefreshState import com.mvikotlin.components.post_list.PostListItem @Composable fun PostList( items: List<PostListItem>, isRefreshing: Boolean, onRefresh: (Boolean) -> Unit, onItemClicked: (Long) -> Unit, ) { SwipeRefresh( state = rememberSwipeRefreshState(isRefreshing), onRefresh = { onRefresh(true) } ) { LazyColumn { itemsIndexed(items) { index, item -> Row( modifier = Modifier .fillMaxWidth() .clickable { onItemClicked(item.id) } ) { Text( text = item.title, modifier = Modifier .padding( horizontal = 16.dp, vertical = 8.dp ) ) } if (index < items.lastIndex) { Divider() } } } } }
0
Kotlin
0
0
c081daab714d85e73f639b46286e2b587d77aed8
1,748
kmm-samples
Apache License 2.0
kmm_mvikotlin_sample/androidApp/src/main/java/com/mvikotlin/android/post/list/PostList.kt
vladlen2010
444,197,061
false
{"Kotlin": 144652, "Swift": 43044, "Ruby": 3488}
package com.mvikotlin.android.post.list import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material.Divider import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.google.accompanist.swiperefresh.SwipeRefresh import com.google.accompanist.swiperefresh.rememberSwipeRefreshState import com.mvikotlin.components.post_list.PostListItem @Composable fun PostList( items: List<PostListItem>, isRefreshing: Boolean, onRefresh: (Boolean) -> Unit, onItemClicked: (Long) -> Unit, ) { SwipeRefresh( state = rememberSwipeRefreshState(isRefreshing), onRefresh = { onRefresh(true) } ) { LazyColumn { itemsIndexed(items) { index, item -> Row( modifier = Modifier .fillMaxWidth() .clickable { onItemClicked(item.id) } ) { Text( text = item.title, modifier = Modifier .padding( horizontal = 16.dp, vertical = 8.dp ) ) } if (index < items.lastIndex) { Divider() } } } } }
0
Kotlin
0
0
c081daab714d85e73f639b46286e2b587d77aed8
1,748
kmm-samples
Apache License 2.0
app/src/test/java/com/jyodroid/tvseries/com/jyodroid/tvseries/ui/series/SeriesViewModelTest.kt
jyodroid
492,378,338
false
null
package com.jyodroid.tvseries.com.jyodroid.tvseries.ui.series import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.Observer import com.jyodroid.tvseries.com.jyodroid.tvseries.testutils.TestCoroutineRule import com.jyodroid.tvseries.model.business.Series import com.jyodroid.tvseries.model.dto.Result import com.jyodroid.tvseries.repository.SeriesRepository import com.jyodroid.tvseries.ui.series.SeriesViewModel import io.mockk.MockKAnnotations import io.mockk.coEvery import io.mockk.coVerify import io.mockk.impl.annotations.InjectMockKs import io.mockk.impl.annotations.MockK import junit.framework.TestCase.assertEquals import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test class SeriesViewModelTest { @get:Rule val testInstantTaskExecutorRule = InstantTaskExecutorRule() @ExperimentalCoroutinesApi @get:Rule val testCoroutineRule = TestCoroutineRule() @MockK(relaxed = true) lateinit var seriesRepository: SeriesRepository @MockK(relaxed = true) lateinit var seriesSearchObserver: Observer<List<Series>?> @MockK(relaxed = true) lateinit var seriesSearchErrorObserver: Observer<String> @InjectMockKs lateinit var seriesViewModel: SeriesViewModel @Before fun prepare() { MockKAnnotations.init(this) } @After fun tearDown() { seriesViewModel.seriesResultLiveData.removeObserver(seriesSearchObserver) seriesViewModel.errorLiveData.removeObserver(seriesSearchErrorObserver) } @ExperimentalCoroutinesApi @Test fun `When search series by name and get results`() = runTest { seriesViewModel.seriesResultLiveData.observeForever(seriesSearchObserver) seriesViewModel.errorLiveData.observeForever(seriesSearchErrorObserver) val query = "query" val seriesResult = Series(1, "test", "testUrl") val seriesListResult = listOf(seriesResult) val result = Result.success(seriesListResult) coEvery { seriesRepository.searchShows(query) } returns result seriesViewModel.searchSeries(query) coVerify(exactly = 1) { seriesRepository.searchShows(query) seriesSearchObserver.onChanged(seriesListResult) } coVerify(exactly = 0, timeout = 1000) { seriesSearchErrorObserver.onChanged(any()) } assertEquals(seriesListResult, seriesViewModel.seriesResultLiveData.value) } @ExperimentalCoroutinesApi @Test fun `When search series by name and get exception`() = runTest { seriesViewModel.seriesResultLiveData.observeForever(seriesSearchObserver) seriesViewModel.errorLiveData.observeForever(seriesSearchErrorObserver) val query = "query" val errorMessage = "No Internet Connection" val result = Result.failure<List<Series>>(Error(errorMessage)) coEvery { seriesRepository.searchShows(query) } returns result seriesViewModel.searchSeries(query) coVerify(exactly = 1) { seriesRepository.searchShows(query) seriesSearchErrorObserver.onChanged(errorMessage) } coVerify(exactly = 0, timeout = 1000) { seriesSearchObserver.onChanged(any()) } assertEquals(errorMessage, seriesViewModel.errorLiveData.value) } }
0
Kotlin
0
0
5ca652b6917ada7e3aeb1aef59ce167c3ef15f30
3,512
TVSeries
MIT License
spesialist-selve/src/test/kotlin/no/nav/helse/e2e/AdressebeskyttelseEndretE2ETest.kt
navikt
244,907,980
false
null
package no.nav.helse.e2e import AbstractE2ETest import no.nav.helse.person.Adressebeskyttelse import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import java.util.* internal class AdressebeskyttelseEndretE2ETest : AbstractE2ETest() { @Test fun `oppdaterer adressebeskyttelse på en person vi kjenner til fra før`() { vedtaksperiode(utbetalingId = UUID.randomUUID()) val originaleBehov = testRapid.inspektør.behov().size val hendelseId = sendAdressebeskyttelseEndret() assertEquals(originaleBehov + 1, testRapid.inspektør.behov().size) assertEquals(Adressebeskyttelse.Ugradert, personDao.findPersoninfoAdressebeskyttelse(FØDSELSNUMMER)) sendHentPersoninfoLøsning(hendelseId, adressebeskyttelse = "Fortrolig") assertEquals(Adressebeskyttelse.Fortrolig, personDao.findPersoninfoAdressebeskyttelse(FØDSELSNUMMER)) } @Test fun `oppdaterer ikke adressebeskyttelse dersom vi ikke kjenner til fødselsnummer`() { sendAdressebeskyttelseEndret() assertEquals(emptyList<String>(), testRapid.inspektør.behov()) } }
2
Kotlin
0
0
e221266ef6c7edfd3335717925094aea11385c60
1,124
helse-spesialist
MIT License
snt-dao-starter/src/main/kotlin/org/github/snt/dao/api/repo/spring/AuthResourceSpringDataRepo.kt
kilel
29,419,998
false
null
/* * Copyright 2018 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.github.snt.dao.api.repo.spring import org.github.snt.dao.api.entity.AuthResource import org.springframework.data.repository.CrudRepository import org.springframework.stereotype.Repository /** * Node DAO repository. */ @Repository interface AuthResourceSpringDataRepo : CrudRepository<AuthResource, Long> { fun findByUserIdAndTypeId(userId: Long?, typeId: Long): AuthResource fun findByUserId(userId: Long?): AuthResource? }
1
Kotlin
0
0
84a04716d93b48159a71c64f52b179dc886961fe
1,038
snt
Apache License 2.0
app/src/main/java/com/mindorks/example/coroutines/github/data/api/ApiHelperImpl.kt
saisasanksunkavalli
365,737,742
true
{"Kotlin": 68004}
package com.mindorks.example.coroutines.github.data.api class ApiHelperImpl(private val apiService: ApiService) : ApiHelper { override suspend fun getRepos(username: String) = apiService.getRepos(username) }
0
Kotlin
0
0
b8e40989800e14ffdf31f34e067fd2d5b1157203
214
Kotlin-Coroutines-Android-Examples
Apache License 2.0
kotlin/2024/round-2/src/main/kotlin/c/Solution.kt
ShreckYe
868,011,028
false
{"Kotlin": 12010}
package c import kotlin.math.max fun main() { val tt = readln().toInt() repeat(tt, ::testCase) } fun testCase(tti: Int) { val (rr, cc, kk) = readln().splitToSequence(' ').map { it.toInt() }.toList() val bb = List(rr) { readln().splitToSequence(' ').map { it.toInt() }.toList() } println(bb) // let rr >= cc fun ans(rr: Int, cc: Int, rdBound: Int, transposed: Boolean) = run { //println("$rr $cc $rdBound") (0 until rdBound).asSequence().flatMap { rd -> //println("rd: $rd") // TODO treat 0 (0 until rr - rd).asSequence().flatMap { r1 -> //println("r1: $r1") val r2 = r1 + rd //println("r2: $r2") (0..rd).asSequence().flatMap { cd -> //println("cd: $cd") //(0 until cc - cd).asSequence().mapNotNull { c1 -> (0 until cc).asSequence().flatMap { c1 -> //println("c1: $c1") val burrow1 = Burrow(r1, c1) listOfNotNull( run { val c2 = c1 + cd if (c2 < cc) { //println("c2: $c2") val burrow2 = Burrow(r2, c2) if (transposed) Hop(burrow1.transposed(), burrow2.transposed(), rd) else Hop(burrow1, burrow2, rd) } else null }, run { val c2e = c1 - cd if (c2e >= 0) { val burrow2 = Burrow(r2, c2e) if (transposed) Hop(burrow1.transposed(), burrow2.transposed(), rd) else Hop(burrow1, burrow2, rd) } else null } ) } } } } .also { println(it.toList()) } .filter { bb[it.burrow1] != bb[it.burrow2] } .also { println(it.toList()) } .elementAt((kk - 1) / 2) .score } val y = if (rr >= cc) ans(rr, cc, rr, false) else ans(cc, rr, cc, true) println("Case #${tti + 1}: $y") } data class Burrow(val r: Int, val c: Int) { fun transposed() = Burrow(c, r) override fun toString() = "($r, $c)" } data class Hop(val burrow1: Burrow, val burrow2: Burrow, val score: Int) { override fun toString() = "$burrow1->$burrow2" } operator fun List<List<Int>>.get(burrow: Burrow) = this[burrow.r][burrow.c]
0
Kotlin
0
0
016bc5c5b2fc708fd9d6d36f9d510575cbac1df0
2,972
meta-hacker-cup
MIT License
kotlin-asyncapi-maven-plugin/src/main/kotlin/org/openfolder/kotlinasyncapi/mavenplugin/AsyncApiFileWriter.kt
asyncapi
509,940,588
false
{"Kotlin": 233237}
package org.openfolder.kotlinasyncapi.mavenplugin import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.databind.ObjectMapper import org.openfolder.kotlinasyncapi.model.AsyncApi import java.io.File import javax.inject.Named import javax.inject.Singleton internal interface AsyncApiFileWriter { fun write(asyncApi: AsyncApi, file: File) } @Singleton @Named internal class AsyncApiJsonWriter : AsyncApiFileWriter { private val objectMapper = ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL) override fun write(asyncApi: AsyncApi, file: File) { file.parentFile?.mkdirs() file.createNewFile() objectMapper.writeValue(file, asyncApi) } }
1
Kotlin
1
22
703c7f50e1b96fbb27a7e05f5a3cba741131bb75
728
kotlin-asyncapi
Apache License 2.0
app/src/main/java/com/rahul/kotlin/architecture/helper/MergePagingAdapter.kt
rahuljpZignuts
642,706,535
false
null
package com.rahul.compose.architecture.helper import androidx.lifecycle.Lifecycle import androidx.paging.PagingData import androidx.paging.PagingDataAdapter import androidx.paging.insertFooterItem import androidx.paging.insertHeaderItem import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView abstract class MergePagingAdapter<T : Any, VH : RecyclerView.ViewHolder>( diffCallback: DiffUtil.ItemCallback<T>, ) : MergeAdapter<T, VH>, PagingDataAdapter<Any, RecyclerView.ViewHolder>(MergeAdapter.MergeItemDiffCallback(diffCallback)) { override var header: MergeAdapter.MergeItemFixed? = null override var footer: MergeAdapter.MergeItemFixed? = null @Suppress("UNCHECKED_CAST") override fun getActualItem(position: Int): T { return super.getItem(position) as T } override fun getFakeItem(position: Int): Any? { return super.getItem(position) } override fun getItemViewType(position: Int): Int { return getMergeItemViewType(position) } suspend fun submitPagingData(pagingData: PagingData<Any>) { super.submitData(getSubmitDataInternal(pagingData)) } fun submitPagingData(lifecycle: Lifecycle, pagingData: PagingData<Any>) { super.submitData(lifecycle, getSubmitDataInternal(pagingData)) } private fun getSubmitDataInternal(pagingData: PagingData<Any>): PagingData<Any> { var newPagingData = pagingData header?.let { newPagingData = newPagingData.insertHeaderItem(item = it) } footer?.let { newPagingData = newPagingData.insertFooterItem(item = it) } return newPagingData } }
0
Kotlin
0
0
83ef7957d3e67e080c6ec22ef7ab176e5666c26c
1,656
AndroidArchitecture-Kotlin
Apache License 2.0
kool-physics/src/jsMain/kotlin/de/fabmax/kool/physics/joints/PrismaticJointImpl.kt
fabmax
81,503,047
false
{"Kotlin": 4803212, "HTML": 1451, "JavaScript": 597}
package de.fabmax.kool.physics.joints import de.fabmax.kool.math.Mat4f import de.fabmax.kool.physics.* import physx.PxJointLinearLimitPair import physx.PxPrismaticJoint import physx.PxPrismaticJointFlagEnum import physx.PxSpring class PrismaticJointImpl( override val bodyA: RigidActor, override val bodyB: RigidActor, frameA: Mat4f, frameB: Mat4f ) : JointImpl(frameA, frameB), PrismaticJoint { override val pxJoint: PxPrismaticJoint init { PhysicsImpl.checkIsLoaded() MemoryStack.stackPush().use { mem -> val frmA = frameA.toPxTransform(mem.createPxTransform()) val frmB = frameB.toPxTransform(mem.createPxTransform()) pxJoint = PxTopLevelFunctions.PrismaticJointCreate(PhysicsImpl.physics, bodyA.holder.px, frmA, bodyB.holder.px, frmB) } } override fun setLimit( lowerLimit: Float, upperLimit: Float, stiffness: Float, damping: Float ) { pxJoint.setLimit(PxJointLinearLimitPair(lowerLimit, upperLimit, PxSpring(stiffness, damping))) pxJoint.setPrismaticJointFlag(PxPrismaticJointFlagEnum.eLIMIT_ENABLED, true) } override fun removeLimit() { pxJoint.setPrismaticJointFlag(PxPrismaticJointFlagEnum.eLIMIT_ENABLED, false) } }
10
Kotlin
14
225
bf6bac3200d4a4844b81b54eb9fa4d6d24097128
1,260
kool
Apache License 2.0
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/InteropUtils.kt
ech0s7r
103,114,220
true
{"Kotlin": 3453319, "C++": 723301, "C": 158624, "Groovy": 43736, "Protocol Buffer": 11804, "JavaScript": 6561, "Batchfile": 6131, "Shell": 6111, "Objective-C++": 4076, "Pascal": 1698, "Objective-C": 1391, "Makefile": 1341, "Python": 1086, "Java": 782, "HTML": 185}
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.backend.konan import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.util.OperatorNameConventions private val cPointerName = "CPointer" private val nativePointedName = "NativePointed" internal class InteropBuiltIns(builtIns: KonanBuiltIns) { object FqNames { val packageName = FqName("kotlinx.cinterop") val cPointer = packageName.child(Name.identifier(cPointerName)).toUnsafe() val nativePointed = packageName.child(Name.identifier(nativePointedName)).toUnsafe() } private val packageScope = builtIns.builtInsModule.getPackage(FqNames.packageName).memberScope val getPointerSize = packageScope.getContributedFunctions("getPointerSize").single() val nullableInteropValueTypes = listOf(ValueType.C_POINTER, ValueType.NATIVE_POINTED) private val nativePointed = packageScope.getContributedClass(nativePointedName) val cPointer = this.packageScope.getContributedClass(cPointerName) val cPointerRawValue = cPointer.unsubstitutedMemberScope.getContributedVariables("rawValue").single() val cPointerGetRawValue = packageScope.getContributedFunctions("getRawValue").single { val extensionReceiverParameter = it.extensionReceiverParameter extensionReceiverParameter != null && TypeUtils.getClassDescriptor(extensionReceiverParameter.type) == cPointer } val nativePointedRawPtrGetter = nativePointed.unsubstitutedMemberScope.getContributedVariables("rawPtr").single().getter!! val nativePointedGetRawPointer = packageScope.getContributedFunctions("getRawPointer").single { val extensionReceiverParameter = it.extensionReceiverParameter extensionReceiverParameter != null && TypeUtils.getClassDescriptor(extensionReceiverParameter.type) == nativePointed } val interpretNullablePointed = packageScope.getContributedFunctions("interpretNullablePointed").single() val interpretCPointer = packageScope.getContributedFunctions("interpretCPointer").single() val typeOf = packageScope.getContributedFunctions("typeOf").single() val nativeMemUtils = packageScope.getContributedClass("nativeMemUtils") private val primitives = listOf( builtIns.byte, builtIns.short, builtIns.int, builtIns.long, builtIns.float, builtIns.double, builtIns.nativePtr ) val readPrimitive = primitives.map { nativeMemUtils.unsubstitutedMemberScope.getContributedFunctions("get" + it.name).single() }.toSet() val writePrimitive = primitives.map { nativeMemUtils.unsubstitutedMemberScope.getContributedFunctions("put" + it.name).single() }.toSet() val bitsToFloat = packageScope.getContributedFunctions("bitsToFloat").single() val bitsToDouble = packageScope.getContributedFunctions("bitsToDouble").single() val staticCFunction = packageScope.getContributedFunctions("staticCFunction").toSet() val workerPackageScope = builtIns.builtInsModule.getPackage(FqName("konan.worker")).memberScope val scheduleFunction = workerPackageScope.getContributedClass("Worker") .unsubstitutedMemberScope.getContributedFunctions("schedule").single() val scheduleImplFunction = workerPackageScope.getContributedFunctions("scheduleImpl").single() val signExtend = packageScope.getContributedFunctions("signExtend").single() val narrow = packageScope.getContributedFunctions("narrow").single() val readBits = packageScope.getContributedFunctions("readBits").single() val writeBits = packageScope.getContributedFunctions("writeBits").single() val cFunctionPointerInvokes = packageScope.getContributedFunctions(OperatorNameConventions.INVOKE.asString()) .filter { val extensionReceiverParameter = it.extensionReceiverParameter it.isOperator && extensionReceiverParameter != null && TypeUtils.getClassDescriptor(extensionReceiverParameter.type) == cPointer }.toSet() val invokeImpls = mapOf( builtIns.unit to "invokeImplUnitRet", builtIns.boolean to "invokeImplBooleanRet", builtIns.byte to "invokeImplByteRet", builtIns.short to "invokeImplShortRet", builtIns.int to "invokeImplIntRet", builtIns.long to "invokeImplLongRet", builtIns.float to "invokeImplFloatRet", builtIns.double to "invokeImplDoubleRet", cPointer to "invokeImplPointerRet" ).mapValues { (_, name) -> packageScope.getContributedFunctions(name).single() }.toMap() val objCObject = packageScope.getContributedClass("ObjCObject") val objCPointerHolder = packageScope.getContributedClass("ObjCPointerHolder") val objCPointerHolderValue = objCPointerHolder.unsubstitutedMemberScope .getContributedDescriptors().filterIsInstance<PropertyDescriptor>().single() val objCObjectInitFromPtr = packageScope.getContributedFunctions("initFromPtr").single() val allocObjCObject = packageScope.getContributedFunctions("allocObjCObject").single() val getObjCClass = packageScope.getContributedFunctions("getObjCClass").single() val objCObjectRawPtr = packageScope.getContributedVariables("rawPtr").single { val extensionReceiverType = it.extensionReceiverParameter?.type extensionReceiverType != null && !extensionReceiverType.isMarkedNullable && TypeUtils.getClassDescriptor(extensionReceiverType) == objCObject } val getObjCReceiverOrSuper = packageScope.getContributedFunctions("getReceiverOrSuper").single() val getObjCMessenger = packageScope.getContributedFunctions("getMessenger").single() val getObjCMessengerLU = packageScope.getContributedFunctions("getMessengerLU").single() val interpretObjCPointerOrNull = packageScope.getContributedFunctions("interpretObjCPointerOrNull").single() val interpretObjCPointer = packageScope.getContributedFunctions("interpretObjCPointer").single() val objCObjectSuperInitCheck = packageScope.getContributedFunctions("superInitCheck").single() val objCObjectInitBy = packageScope.getContributedFunctions("initBy").single() val objCAction = packageScope.getContributedClass("ObjCAction") val objCOutlet = packageScope.getContributedClass("ObjCOutlet") val objCMethodImp = packageScope.getContributedClass("ObjCMethodImp") val exportObjCClass = packageScope.getContributedClass("ExportObjCClass") } private fun MemberScope.getContributedVariables(name: String) = this.getContributedVariables(Name.identifier(name), NoLookupLocation.FROM_BUILTINS) private fun MemberScope.getContributedClass(name: String): ClassDescriptor = this.getContributedClassifier(Name.identifier(name), NoLookupLocation.FROM_BUILTINS) as ClassDescriptor private fun MemberScope.getContributedFunctions(name: String) = this.getContributedFunctions(Name.identifier(name), NoLookupLocation.FROM_BUILTINS)
0
Kotlin
0
0
1186bc22b442023f1a5c367438cda64e57e2a36c
7,992
kotlin-native
Apache License 2.0
failgood/test/failgood/internal/util/StringUtilsTest.kt
failgood
323,114,755
false
{"Kotlin": 377177, "Java": 130}
package failgood.internal.util import failgood.Test import failgood.describe @Test object StringUtilsTest { val tests = describe("StringUtils") { describe("pluralize") { it("pluralizes") { assert(pluralize(2, "item") == "2 items") } it("does not pluralize") { assert(pluralize(1, "item") == "1 item") } } } }
38
Kotlin
5
20
f67ffd1dfeb82bfc342fb5a666b76af2b39843b6
387
failgood
MIT License
kotlintest-runner/kotlintest-runner-junit5/src/main/kotlin/io/kotlintest/runner/junit5/TestDiscovery.kt
ninjayoto
127,456,667
true
{"Kotlin": 351710, "Java": 1380}
package io.kotlintest.runner.junit5 import io.kotlintest.Project import io.kotlintest.Spec import io.kotlintest.TestCase import io.kotlintest.TestContainer import org.junit.platform.engine.UniqueId import org.junit.platform.engine.support.descriptor.EngineDescriptor import org.reflections.Reflections import org.reflections.scanners.SubTypesScanner import org.reflections.util.ConfigurationBuilder import org.reflections.util.FilterBuilder import java.lang.reflect.Modifier import java.net.URI import kotlin.reflect.KClass import kotlin.reflect.full.createInstance object TestDiscovery { init { ReflectionsHelper.registerUrlTypes() } data class DiscoveryRequest(val uris: List<URI>, val classNames: List<String>) val isSpec: (Class<*>) -> Boolean = { Spec::class.java.isAssignableFrom(it) && !Modifier.isAbstract(it.modifiers) } private fun reflections(uris: List<URI>): Reflections { val classOnly = { name: String? -> name?.endsWith(".class") ?: false } val excludeJDKPackages = FilterBuilder.parsePackages("-java, -javax, -sun, -com.sun") return Reflections(ConfigurationBuilder() .addUrls(uris.map { it.toURL() }) .setExpandSuperTypes(true) .useParallelExecutor(2) .filterInputsBy(excludeJDKPackages.add(classOnly)) .setScanners(SubTypesScanner())) } // returns all the locatable specs for the given uris private fun scan(uris: List<URI>): List<KClass<out Spec>> = reflections(uris) .getSubTypesOf(Spec::class.java) .map(Class<out Spec>::kotlin) // must filter out abstract to avoid the spec parent classes themselves .filter { !it.isAbstract } private fun loadClasses(classes: List<String>): List<KClass<out Spec>> = classes.map { Class.forName(it).kotlin }.filterIsInstance<KClass<out Spec>>() operator fun invoke(request: DiscoveryRequest, uniqueId: UniqueId): EngineDescriptor { val specs = when { request.classNames.isNotEmpty() -> loadClasses(request.classNames) else -> scan(request.uris) } val instances = specs.map { it.createInstance() }.sortedBy { it.name() } val descriptions = instances.map { it.root().description() } val afterExtensions = Project.discoveryExtensions().fold(descriptions, { d, e -> e.afterDiscovery(d) }) Project.listeners().forEach { it.afterDiscovery(afterExtensions) } val root = EngineDescriptor(uniqueId.append("root", "kotlintest"), "KotlinTest") instances.forEach { val specDescriptor = SpecTestDescriptor.fromSpecScope(root.uniqueId, it.root()) it.root().scopes.forEach { val scopeDescriptor = when (it) { is TestContainer -> TestContainerDescriptor.fromTestContainer(specDescriptor.uniqueId, it) is TestCase -> TestCaseDescriptor.fromTestCase(specDescriptor.uniqueId, it) else -> throw IllegalArgumentException() } specDescriptor.addChild(scopeDescriptor) } root.addChild(specDescriptor) } return root } }
0
Kotlin
0
0
51428799c8f857d96608555feedabc9c89e627a6
3,025
kotlintest
Apache License 2.0
shared/src/iosMain/kotlin/data/repository/BillingRepository.ios.kt
vinceglb
628,619,356
false
{"Kotlin": 206592, "Swift": 954, "Shell": 228}
package data.repository import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import model.AppProduct actual class BillingRepository { actual val isSubToUnlimited: StateFlow<Boolean> = MutableStateFlow(false) actual val unlimitedSubProduct: StateFlow<AppProduct?> = MutableStateFlow(null) }
2
Kotlin
2
93
7240671bdd5e6b74ff247f7443f3e996e995f634
336
ComposeAI
Apache License 2.0
app/src/main/java/loodos/droid/bitcointicker/ui/auth/AuthViewModelFactory.kt
BatuhanGunes
360,654,341
false
null
package loodos.droid.bitcointicker.ui.auth import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import loodos.droid.bitcointicker.data.repositories.UserRepository @Suppress("UNCHECKED_CAST") class AuthViewModelFactory(private val repository: UserRepository) : ViewModelProvider.NewInstanceFactory() { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return AuthViewModel(repository) as T } }
0
Kotlin
1
0
40507e84762ef9a69c12de52d183119780401109
456
BitcoinTicker
Apache License 2.0
rest/src/main/kotlin/builder/channel/thread/StartThreadBuilder.kt
jombidev
507,000,315
false
{"Kotlin": 2022642, "Java": 87103}
package dev.jombi.kordsb.rest.builder.channel.thread import dev.jombi.kordsb.common.entity.ArchiveDuration import dev.jombi.kordsb.common.entity.ChannelType import dev.jombi.kordsb.common.entity.optional.OptionalBoolean import dev.jombi.kordsb.common.entity.optional.delegate.delegate import dev.jombi.kordsb.common.entity.optional.optional import dev.jombi.kordsb.rest.builder.AuditRequestBuilder import dev.jombi.kordsb.rest.json.request.StartThreadRequest public class StartThreadBuilder( public var name: String, public var autoArchiveDuration: ArchiveDuration, public val type: ChannelType, ) : AuditRequestBuilder<StartThreadRequest> { override var reason: String? = null private var _invitable: OptionalBoolean = OptionalBoolean.Missing public var invitable: Boolean? by ::_invitable.delegate() override fun toRequest(): StartThreadRequest { return StartThreadRequest( name = name, autoArchiveDuration = autoArchiveDuration, type = type.optional(), // Currently this is optional, but in API v10 it will be required according to Discord's docs. invitable = _invitable ) } }
0
Kotlin
0
4
7e4eba1e65e5454e5c9400da83bd2de883acf96d
1,180
kord-selfbot
MIT License
year2022/test/cz/veleto/aoc/year2022/Day10Test.kt
haluzpav
573,073,312
false
{"Kotlin": 98019}
package cz.veleto.aoc.year2022 import kotlin.test.Test import kotlin.test.assertEquals class Day10Test { private val task = Day10("Day10_test") @Test fun testPart1() { assertEquals(13140, task.part1()) } @Test fun testPart2() { assertEquals(""" ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ███ ███ ███ ███ ███ ███ ███ ████ ████ ████ ████ ████ █████ █████ █████ █████ ██████ ██████ ██████ ████ ███████ ███████ ███████ """.trimIndent(), task.part2()) } }
0
Kotlin
0
0
4f2d63eb9c4c842798dedb0bde0659d368429480
655
advent-of-pavel-2022
Apache License 2.0
logcatx/src/main/java/me/bytebeats/logcatx/FloatingEntryLifecycle.kt
bytebeats
412,080,247
false
{"Kotlin": 45062}
package me.bytebeats.logcatx import android.app.Activity import android.app.Application import android.os.Bundle import me.bytebeats.logcatx.ui.FloatingEntryWindow import me.bytebeats.logcatx.ui.LogcatXActivity /** * @Author bytebeats * @Email <<EMAIL>> * @Github https://github.com/bytebeats * @Created at 2021/10/9 14:37 * @Version 1.0 * @Description FloatingEntryLifecycle registered by user's Application and showed floating entry icon for every Activity when Activity was created */ internal class FloatingEntryLifecycle : Application.ActivityLifecycleCallbacks { companion object { fun with(application: Application) { application.registerActivityLifecycleCallbacks(FloatingEntryLifecycle()) } } override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { if (activity is LogcatXActivity) { return } FloatingEntryWindow.with(activity).show() } override fun onActivityStarted(activity: Activity) {} override fun onActivityResumed(activity: Activity) {} override fun onActivityPaused(activity: Activity) {} override fun onActivityStopped(activity: Activity) {} override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {} override fun onActivityDestroyed(activity: Activity) {} }
0
Kotlin
0
3
e7a34067d2e34768c1b3dbbea090f35637638041
1,348
LogcatX
MIT License
app/src/main/java/gh/cloneconf/apkpurer/ui/ResultsFragment.kt
MuntashirAkon
456,842,828
false
{"Kotlin": 35004}
package gh.cloneconf.apkpurer.ui import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.drawable.BitmapDrawable import android.os.Bundle import android.view.LayoutInflater import androidx.fragment.app.Fragment import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.google.gson.Gson import gh.cloneconf.apkpurer.api.Apkpurer import gh.cloneconf.apkpurer.MainActivity import gh.cloneconf.apkpurer.R import gh.cloneconf.apkpurer.databinding.FragmentResultsBinding import gh.cloneconf.apkpurer.databinding.ItemResultBinding import gh.cloneconf.apkpurer.model.App import kotlinx.coroutines.* import java.lang.Exception class ResultsFragment : Fragment(R.layout.fragment_results) { val jobs = ArrayList<Job>() val q by lazy { requireArguments().getString("q")!! } val settings by lazy { (requireActivity() as MainActivity).settings } private lateinit var binds : FragmentResultsBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binds = FragmentResultsBinding.inflate(inflater) return binds.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Ui update. (requireContext() as MainActivity).apply { title = q back(true) } binds.resultsRv.layoutManager = LinearLayoutManager(requireContext()) binds.resultsRv.adapter = adapter if (page == 1) { download() } binds.resultsRv.viewTreeObserver.addOnScrollChangedListener { if (more && !busy) try { if (!binds.resultsRv.canScrollVertically(1)) { download() } }catch (e:Exception){} } } /** * Results Adapter. */ inner class ResultAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>(){ val results = ArrayList<Any>() fun add(item : Any){ results.add(item) notifyDataSetChanged() } inner class ResultViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){ val binds = ItemResultBinding.bind(itemView) } inner class LoadingViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){} override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return when(viewType){ 100 -> ResultViewHolder(layoutInflater.inflate(R.layout.item_result, parent, false)) else -> LoadingViewHolder(layoutInflater.inflate(R.layout.item_loading, parent, false)) } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val item = results[position] when (holder){ is ResultViewHolder -> { jobs.add(lifecycleScope.launch { val result = item as App holder.itemView.setOnClickListener { showApp(result) } holder.binds.titleTv.text = result.name holder.binds.devTv.text = result.dev val bm = Bitmap.createBitmap(170, 170, Bitmap.Config.ARGB_8888) val canvas = Canvas(bm) canvas.drawColor(Color.argb(100, 221, 221, 221)) if (settings.liteMode) { holder.binds.logoIv.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.mipmap.ic_launcher)) }else{ val bm = Bitmap.createBitmap(170, 170, Bitmap.Config.ARGB_8888) val canvas = Canvas(bm) canvas.drawColor(Color.argb(100, 221, 221, 221)) Glide.with(this@ResultsFragment) .load(result.logo) .placeholder(BitmapDrawable(requireContext().resources, bm)) .into(holder.binds.logoIv) } }) } } } override fun getItemCount(): Int { return results.size } override fun getItemViewType(position: Int): Int { return if (results[position] is App) 100 else 0 } } /** * Send to app fragment. */ fun showApp(app : App){ val fragment = AppFragment() fragment.arguments = Bundle().apply { putString("app", Gson().toJson(app)) } requireActivity().supportFragmentManager .beginTransaction() .replace(R.id.fContainer, fragment) .addToBackStack(null) .commit() } val adapter by lazy { ResultAdapter() } /** * Cancel all jobs when it's inactive. */ override fun onPause() { super.onPause() jobs.forEach { it.cancel() } } var page = 1 var more = false var busy = false private fun download(){ busy = true if (page == 1) adapter.add(1) jobs.add(lifecycleScope.launch(Dispatchers.IO) { val results = Apkpurer.search(q, page) more = results.more withContext(Dispatchers.Main){ if (adapter.results.isNotEmpty()) adapter.results.removeLast() adapter.results.addAll(results.apps) if (more) adapter.add(1) adapter.notifyDataSetChanged() } page++ busy = false }) } }
0
null
0
5
3ce467f7d18e7e6d75067d69646bed5d5821027b
6,209
Apkpurer
MIT License
app/src/main/java/com/example/fooddelivery/common/extensions/StringExtensions.kt
spencer2k19
720,201,452
false
{"Kotlin": 305089}
package com.example.fooddelivery.common.extensions import com.example.fooddelivery.common.HHmmFormat import com.example.fooddelivery.common.dayDateMonthFormat import com.example.fooddelivery.common.ddMMyyyyFormat import com.example.fooddelivery.common.ddMMyyyyHHmmssFormat import com.example.fooddelivery.common.humanDateFormat import com.example.fooddelivery.common.humanDateFormatWithoutDate import com.example.fooddelivery.common.yyyyMMddFormat import com.example.fooddelivery.common.yyyyMMddHHmmssFormat import java.text.SimpleDateFormat import java.util.* fun String.toHumanMonthFromDate(): String { //current date is for example 02/07/2022 and we want as result -> 02 Aout 2022 val data = this.split('/') val month = data[1].toInt() val cal: Calendar = Calendar.getInstance() val monthDate = SimpleDateFormat("MMMM") cal.set(Calendar.MONTH, month) return "${data[0]} ${monthDate.format(cal.time)} ${data[2]}" } fun String.toHumanDateFromTZ(): String? { val date = this.split('T')[0] return humanDateFormatWithoutDate.format(yyyyMMddFormat.parse(date)) } fun String.toDisplayDateFromTZ(): String? { val date = this.split('T')[0] return ddMMyyyyFormat.format(yyyyMMddFormat.parse(date)) } fun String.toDisplayDateTimeFromTZ(): String? { val dates = this.split('T') val date = dates[0] val time = dates[1].split("+")[0] val oldDate = yyyyMMddHHmmssFormat.parse("$date $time") return ddMMyyyyHHmmssFormat.format(oldDate) } fun String.toDisplayTimeFromTZ(): String? { val dates = this.split('T') val date = dates[0] val time = dates[1].split("+")[0] val oldDate = yyyyMMddHHmmssFormat.parse("$date $time") return HHmmFormat.format(oldDate) } fun String.toHumanDate(): String? { return humanDateFormat.format(yyyyMMddFormat.parse(this)) } fun String.toHumanWithoutDate(): String? { return humanDateFormatWithoutDate.format(yyyyMMddFormat.parse(this)) } fun String.toHumanDateFromDate(): String? { return humanDateFormat.format(ddMMyyyyFormat.parse(this)) } fun String.toDateFromHumanDate(): String? { return ddMMyyyyFormat.format(humanDateFormatWithoutDate.parse(this)) } fun String.toDayDateTimeFromTZ(): String? { val dates = this.split('T') val date = dates[0] val time = dates[1].split("+")[0] val oldDate = yyyyMMddHHmmssFormat.parse("$date $time") return dayDateMonthFormat.format(oldDate) } fun String.toDayDateTime(): String? { val dates = this.split(' ') val date = dates[0] val time = dates[1] val oldDate = yyyyMMddHHmmssFormat.parse("$date $time") return dayDateMonthFormat.format(oldDate) }
0
Kotlin
0
2
7be246eba97aa90740952a8bd85dbeb3229c826b
2,660
Food-Delivery-Android
MIT License
code/app/src/main/java/com/ravi/movies/domain/contract/RecyclerViewClickListener.kt
Ravi879
171,529,497
false
null
package com.ravi.movies.domain.contract import android.view.View interface RecyclerViewClickListener { fun onItemClick(view: View, position: Int) }
0
Kotlin
0
1
699f90370c9e0a7ffdcb3ec904f538ce1447208b
160
Upcoming-Movies
MIT License
auth/src/main/kotlin/com/tidal/sdk/auth/model/ErrorResponse.kt
tidal-music
806,866,286
false
{"Kotlin": 1775374, "Shell": 9881, "Python": 7380, "Mustache": 911}
package com.tidal.sdk.auth.model import kotlinx.serialization.Serializable import kotlinx.serialization.json.JsonNames @Serializable internal data class ErrorResponse( val status: Int, val error: String, @JsonNames("sub_status") val subStatus: Int, @JsonNames("error_description") val errorDescription: String, )
27
Kotlin
0
23
1f654552133ef7794fe9bb7677bc7fc94c713aa3
331
tidal-sdk-android
Apache License 2.0
src/main/kotlin/com/mvp/hackathon/application/v1/PunchTheClockController.kt
lfneves
774,082,718
false
{"Kotlin": 76596, "Gherkin": 203, "Dockerfile": 155}
package com.mvp.hackathon.application.v1 import com.mvp.hackathon.domain.model.exception.Exceptions import com.mvp.hackathon.domain.model.punch.PunchTheClockDTO import com.mvp.hackathon.domain.service.auth.ISecurityService import com.mvp.hackathon.domain.service.encryption.IEncryptionService import com.mvp.hackathon.domain.service.punch.IPunchTheClockService import com.mvp.hackathon.infrastructure.entity.time.PunchTheClockEntity import io.swagger.v3.oas.annotations.Operation import org.springframework.http.HttpStatus import org.springframework.security.access.prepost.PreAuthorize import org.springframework.web.bind.annotation.* import java.time.LocalDateTime @RestController @RequestMapping("/api/v1/punch-the-clock") class PunchTheClockController( private val service: IPunchTheClockService, private val securityService: ISecurityService, private val encryptionService: IEncryptionService ) { @PostMapping("/start") @PreAuthorize("isAuthenticated()") fun startWork(@RequestParam username: String): PunchTheClockEntity { if (!securityService.isCurrentUser(encryptionService.encrypt(username))) { throw Exceptions.AccessDeniedException("You do not have permission to access this resource.") } return service.recordStartTime(username, LocalDateTime.now()) } @PostMapping("/end") @PreAuthorize("isAuthenticated()") fun endWork(@RequestParam username: String): PunchTheClockEntity { if (!securityService.isCurrentUser(encryptionService.encrypt(username))) { throw Exceptions.AccessDeniedException("You do not have permission to access this resource.") } return service.recordEndTime(username, LocalDateTime.now()) } @PostMapping("/break-start") @PreAuthorize("isAuthenticated()") fun addBreakStart(@RequestParam username: String): PunchTheClockEntity { if (!securityService.isCurrentUser(encryptionService.encrypt(username))) { throw Exceptions.AccessDeniedException("You do not have permission to access this resource.") } return service.startBreak(username, LocalDateTime.now()) } @PostMapping("/break-end") @PreAuthorize("isAuthenticated()") fun addBreakEnd(@RequestParam username: String): PunchTheClockEntity { if (!securityService.isCurrentUser(encryptionService.encrypt(username))) { throw Exceptions.AccessDeniedException("You do not have permission to access this resource.") } return service.endBreak(username, LocalDateTime.now()) } @Operation(summary = "View-punch-in-today") @ResponseStatus(HttpStatus.FORBIDDEN) @GetMapping("/view-punch-in-today") @PreAuthorize("isAuthenticated()") fun viewEntries(@RequestParam username: String): MutableList<PunchTheClockDTO> { if (!securityService.isCurrentUser(encryptionService.encrypt(username))) { throw Exceptions.AccessDeniedException("You do not have permission to access this resource.") } return service.calculateTotalHours(username) } }
0
Kotlin
0
0
1beff4e2b9d16bc4db036d8619def509ae5751b7
3,090
tech-challenge-hackathon
MIT License
domain/src/commonMain/kotlin/mehiz/abdallah/progres/domain/ExamGradeUseCase.kt
abdallahmehiz
830,308,163
false
{"Kotlin": 449026, "Swift": 621}
package mehiz.abdallah.progres.domain import mehiz.abdallah.progres.api.ProgresApi import mehiz.abdallah.progres.data.daos.ExamGradeDao import mehiz.abdallah.progres.data.db.ExamGradeTable import mehiz.abdallah.progres.domain.models.ExamGradeModel import mehiz.abdallah.progres.domain.models.toModel import mehiz.abdallah.progres.domain.models.toTable class ExamGradeUseCase( private val api: ProgresApi, private val examGradeDao: ExamGradeDao, private val academicPeriodUseCase: AcademicPeriodUseCase, private val studentCardUseCase: StudentCardUseCase, private val userAuthUseCase: UserAuthUseCase ) { // returns ALL of the student's exams available from their student cards suspend fun getExamGrades(refresh: Boolean, propagateRefresh: Boolean): List<ExamGradeModel> { val academicPeriods = academicPeriodUseCase.getAcademicPeriods(refresh, propagateRefresh) examGradeDao.getAllExamGrades().let { grades -> if (grades.isNotEmpty() && !refresh) { return grades.map { grade -> grade.toModel(academicPeriods.first { it.yearPeriodCode == grade.yearPeriodCode }) } } } val studentCards = studentCardUseCase.getAllStudentCards(refresh) val token = userAuthUseCase.getToken() val examGrades = mutableListOf<ExamGradeTable>() studentCards.forEach { card -> examGrades.addAll( api.getExamGrades(card.id, token).map { grade -> grade.toTable( academicPeriods.first { card.openingTrainingOfferId == it.oofId && grade.idPeriode == it.id } .yearPeriodCode, ) }, ) } if (refresh) examGradeDao.deleteAllExamGrades() examGrades.forEach { examGradeDao.insert(it) } return examGrades.map { grade -> grade.toModel( academicPeriods.first { it.yearPeriodCode == grade.yearPeriodCode }, ) } } }
1
Kotlin
0
8
331d3c6c8caa126fdc7df033f2574cd3aa8f8e80
1,874
progres
MIT License
src/main/kotlin/cn/disy920/okapi/annotation/Undefined.kt
disymayufei
779,888,694
false
{"Kotlin": 129606}
package cn.disy920.okapi.annotation /** * 用于标记一个类或方法的调用行为是未定义的 * 这意味着在使用该类或方法时,可能会出现不可预知的行为 * 这通常是由于LLOneBot未实现,或未按预期实现某一接口导致的 * 除非你知道你在做什么,否则不要使用携带有该注解的类或方法 */ @Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS) @Retention(AnnotationRetention.RUNTIME) annotation class Undefined(val reason: String)
0
Kotlin
0
2
f541ce8ff5eb5420e3321abe84a721a4d6d62126
313
OneBot-Kotlin-SDK
Apache License 2.0
app/src/main/java/cn/arsenals/osarsenals/root/ArsenalsRoot.kt
Y-D-Lu
606,605,998
false
null
package cn.arsenals.osarsenals.root import cn.arsenals.osarsenals.utils.Alog import java.io.InputStream import java.io.OutputStream class ArsenalsRoot { companion object { private const val TAG = "ArsenalsRoot" fun getInstance() = Instance.instance } object Instance { val instance = ArsenalsRoot() } private var rootProcess: Process? = null private var rootOutPutStream: OutputStream? = null private var rootInputStream: InputStream? = null fun init() { Alog.info(TAG, "ArsenalsRoot init") if (!isRootAvailable()) { Alog.warn(TAG, "ArsenalsRoot !isRootAvailable!") } } fun uninit() { Alog.info(TAG, "ArsenalsRoot uninit") rootOutPutStream?.close() rootInputStream?.close() rootProcess?.destroy() } fun isRootAvailable(): Boolean { if (rootProcess != null) { return true } try { val rootProcess = Runtime.getRuntime().exec("su") rootOutPutStream = rootProcess.outputStream rootInputStream = rootProcess.inputStream this.rootProcess = rootProcess return true } catch (ex: Exception) { ex.printStackTrace() } return false } fun execAsRoot(cmd: String): Boolean { if (!isRootAvailable()) { Alog.warn(TAG, "execAsRoot !isRootAvailable!") return false } rootOutPutStream?.let { it.write(cmd.toByteArray()) it.flush() return true } ?: let { Alog.warn(TAG, "execAsRoot mRootOutPutStream is null!") return false } } }
0
Kotlin
0
0
305e4e2d9dcf355bd29e4c4bce4a47ca011b1d78
1,727
OsArsenals
Apache License 2.0
app/src/main/java/tool/xfy9326/milink/nfc/datastore/base/key/SuspendDefaultLazyKey.kt
XFY9326
724,531,401
false
{"Kotlin": 300068}
@file:Suppress("unused") package tool.xfy9326.milink.nfc.datastore.base.key import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.doublePreferencesKey import androidx.datastore.preferences.core.floatPreferencesKey import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.longPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.core.stringSetPreferencesKey import tool.xfy9326.milink.nfc.datastore.base.ExtendedDataStore import kotlin.properties.ReadOnlyProperty private fun <D : ExtendedDataStore, T> defaultSuspendLazyKeyDelegate( defaultBlock: suspend () -> T, block: (String) -> Preferences.Key<T> ) = ReadOnlyProperty<D, ReadWriteSuspendDefaultKey<D, T>> { obj, property -> SuspendDefaultLazyKey( obj, block(property.name), defaultBlock ) } fun <D : ExtendedDataStore> booleanSuspendDefaultLazyKey( name: String? = null, defaultBlock: suspend () -> Boolean ) = defaultSuspendLazyKeyDelegate<D, Boolean>(defaultBlock) { booleanPreferencesKey(name ?: it) } fun <D : ExtendedDataStore> stringSuspendDefaultLazyKey( name: String? = null, defaultBlock: suspend () -> String ) = defaultSuspendLazyKeyDelegate<D, String>(defaultBlock) { stringPreferencesKey(name ?: it) } fun <D : ExtendedDataStore> intSuspendDefaultLazyKey( name: String? = null, defaultBlock: suspend () -> Int ) = defaultSuspendLazyKeyDelegate<D, Int>(defaultBlock) { intPreferencesKey(name ?: it) } fun <D : ExtendedDataStore> longSuspendDefaultLazyKey( name: String? = null, defaultBlock: suspend () -> Long ) = defaultSuspendLazyKeyDelegate<D, Long>(defaultBlock) { longPreferencesKey(name ?: it) } fun <D : ExtendedDataStore> floatSuspendDefaultLazyKey( name: String? = null, defaultBlock: suspend () -> Float ) = defaultSuspendLazyKeyDelegate<D, Float>(defaultBlock) { floatPreferencesKey(name ?: it) } fun <D : ExtendedDataStore> doubleSuspendDefaultLazyKey( name: String? = null, defaultBlock: suspend () -> Double ) = defaultSuspendLazyKeyDelegate<D, Double>(defaultBlock) { doublePreferencesKey(name ?: it) } fun <D : ExtendedDataStore> stringSetSuspendDefaultLazyKey( name: String? = null, defaultBlock: suspend () -> Set<String> ) = defaultSuspendLazyKeyDelegate<D, Set<String>>(defaultBlock) { stringSetPreferencesKey( name ?: it ) } fun <D : ExtendedDataStore, T : Enum<T>> enumSuspendDefaultLazyKey( name: String? = null, defaultBlock: suspend () -> T, parser: (String) -> T ) = ReadOnlyProperty<D, ReadWriteSuspendDefaultEnumKey<D, T>> { obj, property -> SuspendDefaultEnumLazyKey( obj, stringPreferencesKey(name ?: property.name), defaultBlock, parser ) } fun <D : ExtendedDataStore, T : Enum<T>> enumSetSuspendDefaultLazyKey( name: String? = null, defaultBlock: suspend () -> Set<T>, parser: (String) -> T ) = ReadOnlyProperty<D, ReadWriteSuspendDefaultEnumSetKey<D, T>> { obj, property -> SuspendDefaultEnumSetLazyKey( obj, stringSetPreferencesKey(name ?: property.name), defaultBlock, parser ) } class SuspendDefaultLazyKey<D : ExtendedDataStore, T>( dataStore: D, preferencesKey: Preferences.Key<T>, private val defaultBlock: suspend () -> T ) : ReadWriteSuspendDefaultKey<D, T>(dataStore, preferencesKey) { override suspend fun defaultValue(): T = defaultBlock() } class SuspendDefaultEnumLazyKey<D : ExtendedDataStore, T : Enum<T>>( dataStore: D, preferencesKey: Preferences.Key<String>, private val defaultBlock: suspend () -> T, private val parser: (String) -> T ) : ReadWriteSuspendDefaultEnumKey<D, T>(dataStore, preferencesKey) { override suspend fun defaultEnumValue(): T = defaultBlock() override suspend fun parseEnum(value: String): T = parser(value) } class SuspendDefaultEnumSetLazyKey<D : ExtendedDataStore, T : Enum<T>>( dataStore: D, preferencesKey: Preferences.Key<Set<String>>, private val defaultBlock: suspend () -> Set<T>, private val parser: (String) -> T ) : ReadWriteSuspendDefaultEnumSetKey<D, T>(dataStore, preferencesKey) { override suspend fun defaultEnumSetValue(): Set<T> = defaultBlock() override suspend fun parseEnum(value: String): T = parser(value) }
1
Kotlin
4
91
85489b59c617f3ee8d006c47b73f53bbc4e08bc3
4,563
MiLinkNFC
MIT License
src/main/kotlin/hr/fer/infsus/handymanrepairs/service/IScheduleService.kt
Theanko1412
783,054,275
false
{"Kotlin": 222286, "Dockerfile": 106}
package hr.fer.infsus.handymanrepairs.service import hr.fer.infsus.handymanrepairs.model.dao.Schedule import hr.fer.infsus.handymanrepairs.model.dto.ScheduleDTO interface IScheduleService { fun getAllSchedules(): List<Schedule> fun getScheduleById(id: String): Schedule? fun getAllScheduleDTOs(): List<ScheduleDTO> fun getScheduleDTOById(id: String): ScheduleDTO? }
0
Kotlin
0
0
9f278da33e4fc15cf5ce48839e07d31bcdf31e45
387
handyman-repairs
MIT License
core/data/src/main/java/com/nyinyihtunlwin/data/model/response/SurveyResponse.kt
nyinyihtunlwin-codigo
802,104,160
false
{"Kotlin": 146145}
package com.nyinyihtunlwin.data.model.response import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class SurveyResponse( val data: List<SurveyResponseData>? = null, val meta: Meta? = null ) { @Serializable data class Meta( val page: Int, @SerialName("page_size") val pageSize: Int, val pages: Int, val records: Int ) } @Serializable data class SurveyResponseData( @SerialName("id") val id: String?, @SerialName("type") val type: String?, @SerialName("attributes") val attributes: AttributesResponseData? ) { @Serializable data class AttributesResponseData( @SerialName("title") val title: String?, @SerialName("survey_type") val surveyType: String?, @SerialName("description") val description: String?, @SerialName("cover_image_url") val coverImageUrl: String?, @SerialName("created_at") val createdAt: String?, @SerialName("inactive_at") val inactiveAt: String?, @SerialName("is_active") val isActive: Boolean?, @SerialName("active_at") val activeAt: String?, @SerialName("thank_email_above_threshold") val thankEmailAboveThreshold: String?, @SerialName("thank_email_below_threshold") val thankEmailBelowThreshold: String? ) }
7
Kotlin
0
0
3a42ba4f267e0221fbfd3ec0d381c9887c4054e7
1,436
nimble-survey
Apache License 2.0
app/src/main/java/com/example/productmanagment/MainActivity.kt
Priyaverma0596
269,779,065
false
null
package com.example.productmanagment import com.example.productmanagment.MyApplication.Companion.globalVar import com.example.productmanagment.MyApplication.Companion.products import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { var strGlobalVar = globalVar products.add(Product("water",30,4)) products.add(Product("rice",54,3)) products.add(Product("wheat",44,2)) products.add(Product("beans",60,10)) products.add(Product("refined oil",100,30)) products.add(Product("Cumin powder",22,0)) super.onCreate(savedInstanceState) setContentView(R.layout.activity_main); val viewbutton = findViewById<Button>(R.id.viewproduct) viewbutton.setOnClickListener{ val intent = Intent(this, ViewProducts::class.java) startActivity(intent) } val addbutton = findViewById<Button>(R.id.addproduct) addbutton.setOnClickListener{ val intent = Intent(this, AddProduct::class.java) startActivity(intent) } } }
0
Kotlin
1
2
058656ce20dff15f15de9e027b0d5d46f7412135
1,253
ProductManagment
The Unlicense
app/src/main/java/com/app/rapidnumberconverter/ui/theme/Shapes.kt
Potsane
711,613,161
false
{"Kotlin": 73128, "Java": 495}
package com.app.rapidnumberconverter.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(0.dp), medium = RoundedCornerShape(8.dp) )
9
Kotlin
0
0
e159f913dba123cef98082400a06171f1b9affc7
283
numbers_converter
Apache License 2.0
src/test/kotlin/ar/edu/unq/helpers/PropertyHelperTest.kt
CristianGonzalez1980
320,041,280
false
null
package ar.edu.unq.helpers import org.junit.Test import kotlin.test.assertEquals class PropertyHelperTest { private class MultiVisibilityPropertiesClass{ val property1: String = "" val property2: String = "" private val property3: String = "" private val property4: String = "" } @Test fun testObtenerPropiedadesPublicas() { assertEquals(setOf("property1", "property2"), PropertyHelper.publicProperties<MultiVisibilityPropertiesClass>().map { it.name }.toSet()) } }
1
Kotlin
0
0
28553d578b6c6ec24c32759d604731bfbc40627a
528
exposicion-virtual
The Unlicense
example/module-account/src/main/java/com/p2m/example/account/module_init/AccountModuleInit.kt
wangdaqi77
367,279,479
false
null
package com.p2m.example.account.module_init import android.content.Context import com.p2m.annotation.module.ModuleInitializer import com.p2m.core.P2M import com.p2m.core.module.* import com.p2m.example.account.p2m.api.Account import com.p2m.core.module.task.TaskOutputProvider import com.p2m.core.module.task.TaskRegister import com.p2m.core.module.task.TaskUnit import com.p2m.example.account.UserDiskCache import com.p2m.example.account.p2m.impl.mutable @ModuleInitializer class AccountModuleInit : ModuleInit { // 运行在子线程,用于注册该模块内的任务、组织任务的依赖关系,所有的任务在单独的子线程运行。 override fun onEvaluate(context: Context, taskRegister: TaskRegister) { val userDiskCache = UserDiskCache(context) // 用户本地缓存 // 注册读取登录状态的任务 taskRegister.register(LoadLoginStateTask::class.java, userDiskCache) // 注册读取登录用户信息的任务 taskRegister .register(LoadLastUserTask::class.java, userDiskCache) .dependOn(LoadLoginStateTask::class.java) // 执行顺序一定为LoadLoginStateTask.onExecute() > LoadLastUserTask.onExecute() } // 运行在主线程,当所有的依赖项完成模块初始化且本模块的任务执行完毕时调用 override fun onExecuted(context: Context, taskOutputProvider: TaskOutputProvider) { val loginState = taskOutputProvider.outputOf(LoadLoginStateTask::class.java) // 获取任务输出-登录状态 val loginInfo = taskOutputProvider.outputOf(LoadLastUserTask::class.java) // 在该模块初始化完成时务必对其Api区输入正确的数据,只有这样才能保证其他模块安全的使用该模块。 val account = P2M.apiOf(Account::class.java) // 找到自身的Api区 account.event.mutable().loginState.setValue(loginState ?: false) // 保存到事件持有者 account.event.mutable().loginInfo.setValue(loginInfo) // 保存到事件持有者 } }
0
Kotlin
1
26
ee8b5ac009b99f28c624f325c77511db6dd77e8f
1,699
P2M
Apache License 2.0
src/main/kotlin/objects/block/StandardBlockBehavior.kt
2xsaiko
123,460,493
false
null
package therealfarfetchd.quacklib.objects.block import net.minecraft.block.SoundType import net.minecraft.block.state.BlockFaceShape import net.minecraft.entity.Entity import net.minecraft.entity.player.EntityPlayer import net.minecraft.util.EnumFacing import net.minecraft.util.EnumHand import net.minecraft.util.math.AxisAlignedBB import net.minecraft.util.math.RayTraceResult import therealfarfetchd.math.Vec3 import therealfarfetchd.math.Vec3i import therealfarfetchd.math.getDistance import therealfarfetchd.quacklib.api.block.component.* import therealfarfetchd.quacklib.api.block.data.BlockDataPart import therealfarfetchd.quacklib.api.block.data.PartAccessToken import therealfarfetchd.quacklib.api.core.extensions.toMCVec3d import therealfarfetchd.quacklib.api.core.extensions.toMCVec3i import therealfarfetchd.quacklib.api.core.extensions.toVec3 import therealfarfetchd.quacklib.api.core.unsafe import therealfarfetchd.quacklib.api.objects.block.Block import therealfarfetchd.quacklib.api.objects.block.BlockBehavior import therealfarfetchd.quacklib.api.objects.block.BlockType import therealfarfetchd.quacklib.api.objects.block.MCBlockType import therealfarfetchd.quacklib.api.objects.getComponentsOfType import therealfarfetchd.quacklib.api.objects.item.Item import therealfarfetchd.quacklib.api.objects.item.orEmpty import therealfarfetchd.quacklib.api.objects.world.World import therealfarfetchd.quacklib.api.tools.Facing import therealfarfetchd.quacklib.api.tools.PositionGrid import therealfarfetchd.quacklib.block.data.PartAccessTokenImpl import therealfarfetchd.quacklib.block.impl.TileQuackLib class StandardBlockBehavior(val type: BlockType) : BlockBehavior { val cActivate = getComponentsOfType<BlockComponentActivation>() val cDrops = getComponentsOfType<BlockComponentDrops>() val cPickBlock = getComponentsOfType<BlockComponentPickBlock>() val cCollision = getComponentsOfType<BlockComponentCollision>() val cMouseOver = getComponentsOfType<BlockComponentMouseOver>() val cCustomMouseOver = getComponentsOfType<BlockComponentCustomMouseOver>() val cNeighborListener = getComponentsOfType<BlockComponentNeighborListener>() val cPlacementCheck = getComponentsOfType<BlockComponentPlacementCheck>() val cRedstone = getComponentsOfType<BlockComponentRedstone>() val cInit = getComponentsOfType<BlockComponentDataInit>() val cPlacement = getComponentsOfType<BlockComponentPlacement>() val cRemoved = getComponentsOfType<BlockComponentRemoved>() val cSelectionBox = getComponentsOfType<BlockComponentSelection>() private fun getContainer(block: Block) = unsafe { (block.getMCTile() as? TileQuackLib)?.c } override fun <T : BlockDataPart> getPart(block: Block, token: PartAccessToken<T>): T { if (token !is PartAccessTokenImpl<T>) error("Invalid token: $token") // TODO implement blocktype equality check, don't rely just on equal resourcelocation return getContainer(block)?.parts?.get(token.rl) as? T ?: error("Could not access part ${token.rl} for block ${block.type}") } override fun <T> getImported(block: Block, value: ImportedValue<T>): T { return value.retrieve(block) } override fun onActivated(block: Block, player: EntityPlayer, hand: EnumHand, facing: Facing, hitVec: Vec3): Boolean { return cActivate.any { it.onActivated(block, player, hand, facing, hitVec) } } override fun onNeighborChanged(block: Block, side: EnumFacing) { cNeighborListener.forEach { it.onNeighborChanged(block, side) } } override fun onPlaced(block: Block, player: EntityPlayer, item: Item) { cPlacement.forEach { it.onPlaced(block, player, item) } } override fun onRemoved(block: Block) { cRemoved.forEach { it.onRemoved(block) } } override fun getFaceShape(self: Block, side: Facing): BlockFaceShape { return BlockFaceShape.UNDEFINED } override fun getSoundType(block: Block, entity: Entity?): SoundType { return type.soundType } override fun getCollisionBoundingBox(block: Block): AxisAlignedBB? { return getCollisionBoundingBoxes(block) .takeIf { it.isNotEmpty() } ?.reduce(AxisAlignedBB::union) } override fun getCollisionBoundingBoxes(block: Block): List<AxisAlignedBB> { return if (cCollision.isNotEmpty()) cCollision.flatMap { it.getCollisionBoundingBoxes(block) } else listOf(MCBlockType.FULL_BLOCK_AABB) } override fun getRaytraceBoundingBox(block: Block): AxisAlignedBB? { return getRaytraceBoundingBoxes(block) .takeIf { it.isNotEmpty() } ?.reduce(AxisAlignedBB::union) } override fun getRaytraceBoundingBoxes(block: Block): List<AxisAlignedBB> { return if (cMouseOver.isNotEmpty()) cMouseOver.flatMap { it.getRaytraceBoundingBoxes(block) } else listOf(MCBlockType.FULL_BLOCK_AABB) } override fun getSelectedBoundingBox(block: Block, result: RayTraceResult): AxisAlignedBB? { return cSelectionBox.asSequence().mapNotNull { it.getSelectionBoundingBox(block, result) }.firstOrNull() ?: getRaytraceBoundingBox(block) } override fun getDrops(block: Block, fortune: Int): List<Item> { return cDrops.flatMap { it.getDrops(block) } } override fun getPickBlock(block: Block, target: RayTraceResult, player: EntityPlayer): Item { return cPickBlock.firstOrNull()?.getPickBlock(block).orEmpty() } override fun isReplacable(block: Block): Boolean { return false } override fun raytrace(block: Block, from: Vec3, to: Vec3): RayTraceResult? { val boxes = getRaytraceBoundingBoxes(block) return (boxes.map { raytraceDo(block.pos, from, to, it) } + cCustomMouseOver.map { it.raytrace(block, from, to) }) .asSequence() .filterNotNull() .sortedBy { getDistance(from, it.hitVec.toVec3()) } .firstOrNull() } private fun raytraceDo(pos: Vec3i, from: Vec3, to: Vec3, bb: AxisAlignedBB): RayTraceResult? { val vec3d = from - pos val vec3d1 = to - pos val raytraceresult = bb.calculateIntercept(vec3d.toMCVec3d(), vec3d1.toMCVec3d()) return if (raytraceresult == null) null else RayTraceResult((raytraceresult.hitVec.toVec3() + pos).toMCVec3d(), raytraceresult.sideHit, pos.toMCVec3i()) } override fun getStrongPower(block: Block, side: Facing): Int { return cRedstone.map { it.strongPowerLevel(block, side) }.max() ?: 0 } override fun getWeakPower(block: Block, side: Facing): Int { return cRedstone.map { it.weakPowerLevel(block, side) }.max() ?: 0 } override fun canConnectRedstone(block: Block, side: Facing): Boolean { return cRedstone.any { it.canConnectRedstone(block, side) } } override fun canPlaceBlockAt(world: World, pos: PositionGrid, side: Facing?): Boolean { return cPlacementCheck.all { it.canPlaceBlockAt(world, pos, side) } } override fun isNormalBlock(): Boolean { return cCollision.isEmpty() } override fun initialize(block: Block, player: EntityPlayer, hand: EnumHand, hitSide: Facing, hitVec: Vec3) { cInit.forEach { it.initialize(block, player, hand, hitSide, hitVec) } } private inline fun <reified T : BlockComponent> getComponentsOfType() = type.getComponentsOfType<T>() }
6
Kotlin
2
4
76c9a55f186c699fb4458f2a4a40a483ab3e3ef2
7,152
QuackLib
MIT License
core/src/main/kotlin/com/dvinc/core/di/component/DatabaseComponent.kt
DEcSENT
126,995,107
false
null
/* * Copyright (c) 2020 by <NAME> (<EMAIL>) * All rights reserved. */ package com.dvinc.core.di.component import com.dvinc.core.di.module.DatabaseModule import com.dvinc.core.di.provider.AppToolsProvider import com.dvinc.core.di.provider.DatabaseProvider import dagger.Component import javax.inject.Singleton @Singleton @Component( dependencies = [ AppToolsProvider::class ], modules = [ DatabaseModule::class ] ) interface DatabaseComponent : DatabaseProvider
11
Kotlin
3
8
1ffd25d40ba463be38d4cace16602d74d0369576
499
Notepad
MIT License
Exercicio/src/main/kotlin/Ex04.kt
Gabits13
856,065,773
false
{"Kotlin": 11861}
// Classe Pessoa representa um indivíduo com altura e sexo class individuo(val altura: Double, val sexo: String) fun main() { // lista chamada "pessoas" com 10 objetos do tipo "Pessoa". // Cada objeto representa uma pessoa com altura e sexo. val pessoas = mutableListOf<individuo>() // Solicitamos os dados de 10 pessoas for (i in 1..10) { println("Digite a altura da pessoa $i (em metros):") val altura = readLine()?.toDoubleOrNull() ?: 0.0 // lerá a entrada do usuário para a altura e convertemos para Double. // Se a entrada não for válida, aí vai o valor padrão 0.0. println("Digite o sexo da pessoa $i (feminino/masculino):") val sexo = readLine()?.toLowerCase() ?: "" // lerá a entrada do usuário para o sexo , convertendo para minúsculas. // Se a entrada for nula, vai ser uma string vazia. pessoas.add(individuo(altura, sexo)) // um objeto individuo com os valores lidos e adicionei à lista. } // a) Encontrando a maior e a menor altura do grupo val maiorAltura = pessoas.maxByOrNull { it.altura }?.altura //pega o valor maximo val menorAltura = pessoas.minByOrNull { it.altura }?.altura //pega o valor mininmo println("Maior altura: ${maiorAltura ?: "N/A"}") println("Menor altura: ${menorAltura ?: "N/A"}") // b) Calculando a média de altura dos homens val alturasHomens = pessoas.filter { it.sexo == "masculino" }.map { it.altura }// aqui filtra aqueles que o it se direciona ao objeto todo aquele que o sexo for masculino //A função map transforma cada elemento de uma coleção de acordo com uma função fornecida. val mediaAlturaHomens = alturasHomens.average() //A função average() é usada para calcular a média dos valores em uma coleção numérica. println("Média de altura dos homens: ${mediaAlturaHomens}") // c) Contando o número de mulheres val numMulheres = pessoas.count { it.sexo == "feminino" } //A função count conta o número de elementos que atendem a uma determinada condição. println("Número de mulheres: $numMulheres") } //Lembretes do biel //It representa cada elemento da coleção (lista) sobre a qual a função está sendo aplicada. e nesse caso, quando uso pessoas.filter { it.sexo == "masculino" }, o it se refere a cada objeto do tipo Pessoa na lista pessoas.
0
Kotlin
0
0
179e0732e4bf83ba75ac6197774ee376df6697d7
2,353
ExerciciosLogicaKotlin
MIT License
src/main/kotlin/org/sampl/parser/ExprBuilder.kt
SamChou19815
134,309,719
false
{"Kotlin": 282544, "ANTLR": 7823}
package org.sampl.parser import org.antlr.v4.runtime.tree.TerminalNode import org.apache.commons.text.StringEscapeUtils import org.sampl.antlr.PLBaseVisitor import org.sampl.antlr.PLParser.BitExprContext import org.sampl.antlr.PLParser.ComparisonExprContext import org.sampl.antlr.PLParser.ConjunctionExprContext import org.sampl.antlr.PLParser.ConstructorExprContext import org.sampl.antlr.PLParser.DisjunctionExprContext import org.sampl.antlr.PLParser.FactorExprContext import org.sampl.antlr.PLParser.FunExprContext import org.sampl.antlr.PLParser.FunctionApplicationExprContext import org.sampl.antlr.PLParser.IdentifierExprContext import org.sampl.antlr.PLParser.IfElseExprContext import org.sampl.antlr.PLParser.LetExprContext import org.sampl.antlr.PLParser.LiteralContext import org.sampl.antlr.PLParser.LiteralExprContext import org.sampl.antlr.PLParser.MatchExprContext import org.sampl.antlr.PLParser.NestedExprContext import org.sampl.antlr.PLParser.NotExprContext import org.sampl.antlr.PLParser.StructMemberAccessExprContext import org.sampl.antlr.PLParser.TermExprContext import org.sampl.antlr.PLParser.ThrowExprContext import org.sampl.antlr.PLParser.TryCatchExprContext import org.sampl.ast.common.BinaryOperator import org.sampl.ast.common.Literal import org.sampl.ast.raw.BinaryExpr import org.sampl.ast.raw.Expression import org.sampl.ast.raw.FunctionApplicationExpr import org.sampl.ast.raw.FunctionExpr import org.sampl.ast.raw.IfElseExpr import org.sampl.ast.raw.LetExpr import org.sampl.ast.raw.LiteralExpr import org.sampl.ast.raw.MatchExpr import org.sampl.ast.raw.NotExpr import org.sampl.ast.raw.StructMemberAccessExpr import org.sampl.ast.raw.ThrowExpr import org.sampl.ast.raw.TryCatchExpr import org.sampl.ast.raw.VariableIdentifierExpr import org.sampl.exceptions.InvalidLiteralError /** * [ExprBuilder] builds expression AST from parse tree. */ internal object ExprBuilder : PLBaseVisitor<Expression>() { override fun visitNestedExpr(ctx: NestedExprContext): Expression = ctx.expression().accept(this) override fun visitLiteralExpr(ctx: LiteralExprContext): Expression { val literalObj: LiteralContext = ctx.literal() // Case UNIT literalObj.UNIT()?.let { node -> return LiteralExpr(lineNo = node.symbol.line, literal = Literal.Unit) } // Case INT literalObj.IntegerLiteral()?.let { node -> val lineNo = node.symbol.line val text = node.text val intValue = text.toLongOrNull() ?: throw InvalidLiteralError(lineNo = lineNo, invalidLiteral = text) return LiteralExpr(lineNo = lineNo, literal = Literal.Int(value = intValue)) } // Case FLOAT literalObj.FloatingPointLiteral()?.let { node -> val lineNo = node.symbol.line val text = node.text val floatValue = text.toDoubleOrNull() ?: throw InvalidLiteralError(lineNo = lineNo, invalidLiteral = text) return LiteralExpr(lineNo = lineNo, literal = Literal.Float(value = floatValue)) } // Case BOOL literalObj.BooleanLiteral()?.let { node -> val lineNo = node.symbol.line val text = node.text return when (text) { "true" -> LiteralExpr(lineNo = lineNo, literal = Literal.Bool(value = true)) "false" -> LiteralExpr(lineNo = lineNo, literal = Literal.Bool(value = false)) else -> throw InvalidLiteralError(lineNo = lineNo, invalidLiteral = text) } } // Case CHAR literalObj.CharacterLiteral()?.let { node -> val lineNo = node.symbol.line val text = node.text val unescaped: kotlin.String = StringEscapeUtils.unescapeJava(text) val len = unescaped.length if (len < 2) { throw InvalidLiteralError(lineNo = lineNo, invalidLiteral = text) } val first = unescaped[0] val last = unescaped[len - 1] return if (first == '\'' && last == '\'') { val betweenQuotes = unescaped.substring(startIndex = 1, endIndex = len - 1) LiteralExpr(lineNo = lineNo, literal = Literal.Char(value = betweenQuotes[0])) } else { throw InvalidLiteralError(lineNo = lineNo, invalidLiteral = text) } } // Case STRING literalObj.StringLiteral()?.let { node -> val lineNo = node.symbol.line val text = node.text val unescaped: kotlin.String = StringEscapeUtils.unescapeJava(text) val len = unescaped.length if (len < 2) { throw InvalidLiteralError(lineNo = lineNo, invalidLiteral = text) } val first = unescaped[0] val last = unescaped[len - 1] return if (first == '"' && last == '"') { val betweenQuotes = unescaped.substring(startIndex = 1, endIndex = len - 1) LiteralExpr(lineNo = lineNo, literal = Literal.String(value = betweenQuotes)) } else { throw InvalidLiteralError(lineNo = lineNo, invalidLiteral = text) } } throw InvalidLiteralError(lineNo = ctx.literal().start.line, invalidLiteral = ctx.text) } override fun visitIdentifierExpr(ctx: IdentifierExprContext): Expression { val lineNo = ctx.start.line val upperIds = ctx.UpperIdentifier() val lower = ctx.LowerIdentifier().text val variable = if (upperIds.isEmpty()) lower else { upperIds.joinToString( separator = ".", postfix = ".", transform = TerminalNode::getText ) + lower } val genericInfo = ctx.genericsSpecialization() ?.typeExprInAnnotation() ?.map { it.accept(TypeExprInAnnotationBuilder) } ?: emptyList() return VariableIdentifierExpr( lineNo = lineNo, variable = variable, genericInfo = genericInfo ) } override fun visitConstructorExpr(ctx: ConstructorExprContext): Expression = ctx.accept(ConstructorExprBuilder) override fun visitStructMemberAccessExpr(ctx: StructMemberAccessExprContext): Expression = StructMemberAccessExpr( lineNo = ctx.start.line, structExpr = ctx.expression().accept(this), memberName = ctx.LowerIdentifier().text ) override fun visitNotExpr(ctx: NotExprContext): Expression = NotExpr(lineNo = ctx.start.line, expr = ctx.expression().accept(this)) override fun visitBitExpr(ctx: BitExprContext): Expression = BinaryExpr( lineNo = ctx.start.line, left = ctx.expression(0).accept(this), op = BinaryOperator.fromRaw(text = ctx.bitOperator().text), right = ctx.expression(1).accept(this) ) override fun visitFactorExpr(ctx: FactorExprContext): Expression = BinaryExpr( lineNo = ctx.start.line, left = ctx.expression(0).accept(this), op = BinaryOperator.fromRaw(text = ctx.factorOperator().text), right = ctx.expression(1).accept(this) ) override fun visitTermExpr(ctx: TermExprContext): Expression = BinaryExpr( lineNo = ctx.start.line, left = ctx.expression(0).accept(this), op = BinaryOperator.fromRaw(text = ctx.termOperator().text), right = ctx.expression(1).accept(this) ) override fun visitComparisonExpr(ctx: ComparisonExprContext): Expression = BinaryExpr( lineNo = ctx.start.line, left = ctx.expression(0).accept(this), op = BinaryOperator.fromRaw(text = ctx.comparisonOperator().text), right = ctx.expression(1).accept(this) ) override fun visitConjunctionExpr(ctx: ConjunctionExprContext): Expression = BinaryExpr( lineNo = ctx.start.line, left = ctx.expression(0).accept(this), op = BinaryOperator.AND, right = ctx.expression(1).accept(this) ) override fun visitDisjunctionExpr(ctx: DisjunctionExprContext): Expression = BinaryExpr( lineNo = ctx.start.line, left = ctx.expression(0).accept(this), op = BinaryOperator.OR, right = ctx.expression(1).accept(this) ) override fun visitThrowExpr(ctx: ThrowExprContext): Expression = ThrowExpr( lineNo = ctx.start.line, type = ctx.typeExprInAnnotation().accept(TypeExprInAnnotationBuilder), expr = ctx.expression().accept(this) ) override fun visitIfElseExpr(ctx: IfElseExprContext): Expression = IfElseExpr( lineNo = ctx.start.line, condition = ctx.expression(0).accept(this), e1 = ctx.expression(1).accept(this), e2 = ctx.expression(2).accept(this) ) override fun visitMatchExpr(ctx: MatchExprContext): Expression = MatchExpr( lineNo = ctx.start.line, exprToMatch = ctx.expression().accept(this), matchingList = ctx.patternToExpr().map { c -> val pattern = c.pattern().accept(PatternBuilder) val expr = c.expression().accept(this) pattern to expr } ) override fun visitFunExpr(ctx: FunExprContext): Expression = FunctionExpr( lineNo = ctx.start.line, arguments = ctx.argumentDeclarations().accept(ArgumentDeclarationsBuilder), body = ctx.expression().accept(this) ) override fun visitFunctionApplicationExpr(ctx: FunctionApplicationExprContext): Expression { val exprContextList = ctx.expression() val functionExpr = exprContextList[0].accept(this) val arguments = arrayListOf<Expression>() for (i in 1 until exprContextList.size) { arguments.add(exprContextList[i].accept(this)) } return FunctionApplicationExpr( lineNo = ctx.start.line, functionExpr = functionExpr, arguments = arguments ) } override fun visitTryCatchExpr(ctx: TryCatchExprContext): Expression = TryCatchExpr( lineNo = ctx.start.line, tryExpr = ctx.expression(0).accept(this), exception = ctx.LowerIdentifier().text, catchHandler = ctx.expression(1).accept(this) ) override fun visitLetExpr(ctx: LetExprContext): Expression = LetExpr( lineNo = ctx.start.line, identifier = ctx.LowerIdentifier()?.text, e1 = ctx.expression(0).accept(this), e2 = ctx.expression(1).accept(this) ) }
0
Kotlin
0
1
766f7b8e5c35eb788b75c636c443eca07a0051a1
11,407
sampl
MIT License
src/main/kotlin/usecase/repository/SurgeryReportRepository.kt
SmartOperatingBlock
638,493,553
false
null
/* * Copyright (c) 2023. Smart Operating Block * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ package usecase.repository import entity.process.SurgicalProcessID import entity.report.SurgeryReport /** * Interface that models the repository to manage surgery reports. */ interface SurgeryReportRepository { /** * Creates a [SurgeryReport]. * Return false if the surgery report already exists, true otherwise. */ fun createSurgeryReport(surgeryReport: SurgeryReport): Boolean /** * Integrate a Surgery report with additional information. * The surgery report to integrate with the [informationToAdd] is identified by the described [surgeryProcessID]. */ fun integrateSurgeryReport(surgeryProcessID: SurgicalProcessID, informationToAdd: String): Boolean /** * Get a surgery report that describe a surgical process identified by its [surgeryProcessID]. * The method return the surgery report if available, otherwise null. */ fun findBy(surgeryProcessID: SurgicalProcessID): SurgeryReport? /** * Get all the surgery reports that have been stored. */ fun getSurgeryReports(): List<SurgeryReport> }
1
Kotlin
0
1
04dc85a98213839d28426f4e71ab506458d00fc6
1,297
surgery-report-microservice
MIT License
inject/src/main/kotlin/com/github/niuhf0452/exile/inject/binder/StaticBinder.kt
niuhf0452
240,633,641
false
null
package com.github.niuhf0452.exile.inject.binder import com.github.niuhf0452.exile.inject.Injector import com.github.niuhf0452.exile.inject.InjectorBuilder import com.github.niuhf0452.exile.inject.TypeKey import kotlin.reflect.KClass import kotlin.reflect.KType import kotlin.reflect.full.starProjectedType class StaticBinder(config: (InjectorBuilder.Configurator) -> Unit) : Injector.Binder { private val binderCallMap = ConfiguratorImpl().run(config) override fun bind(key: TypeKey, context: Injector.BindingContext) { binderCallMap[key]?.forEach { c -> c(context) } } private class ConfiguratorImpl : InjectorBuilder.Configurator { private val binderCalls = mutableMapOf<TypeKey, MutableList<(Injector.BindingContext) -> Unit>>() override fun bind(type: KType): InjectorBuilder.BindingBuilder { val key = TypeKey(type) val calls = binderCalls.computeIfAbsent(key) { mutableListOf() } return BindingBuilderImpl(key, calls) } override fun bind(cls: KClass<*>): InjectorBuilder.BindingBuilder { if (cls.typeParameters.isNotEmpty()) { throw IllegalArgumentException("Can't bind generic class: $cls") } return bind(cls.starProjectedType) } fun run(configure: (InjectorBuilder.Configurator) -> Unit): Map<TypeKey, List<(Injector.BindingContext) -> Unit>> { configure(this) return binderCalls } } private class BindingBuilderImpl( private val key: TypeKey, private val calls: MutableList<(Injector.BindingContext) -> Unit> ) : InjectorBuilder.BindingBuilder { override fun toType(type: TypeKey, qualifiers: List<Annotation>) { if (type.classifier == key.classifier) { throw IllegalArgumentException("Don't bind class to itself: $type") } if (!key.isAssignableFrom(type)) { throw IllegalArgumentException("The implementation type doesn't comply to the bind type: " + "bind type = $key, implementation type = $type") } calls.add { c -> c.bindToType(qualifiers, type) } } override fun toInstance(instance: Any, qualifiers: List<Annotation>) { if (!key.classifier.isInstance(instance)) { throw IllegalArgumentException("The type of instance doesn't comply to the bind type: " + "bind type = $key, instance type = ${instance::class}") } calls.add { c -> c.bindToInstance(qualifiers, instance) } } override fun toProvider(qualifiers: List<Annotation>, provider: () -> Any) { toProvider(qualifiers, ProviderAdapter(provider)) } override fun toProvider(qualifiers: List<Annotation>, provider: Injector.Provider) { calls.add { c -> c.bindToProvider(qualifiers, provider) } } } private class ProviderAdapter( private val provider: () -> Any ) : Injector.Provider { override fun getInstance(): Any { return provider() } override fun toString(): String { return "ProviderAdapter($provider)" } } }
0
Kotlin
1
2
8020cb1ab799f7b1e75c73f762a9ee1ed493a003
3,285
exile
Apache License 2.0
app/src/main/java/com/kai/ui/login/LoginActivity.kt
pressureKai
326,004,502
false
null
package com.kai.ui.login import android.content.Context import androidx.annotation.NonNull import androidx.appcompat.app.AppCompatDelegate import androidx.appcompat.app.SkinAppCompatDelegateImpl import com.alibaba.android.arouter.facade.annotation.Route import com.alibaba.android.arouter.launcher.ARouter import com.kai.base.R import com.kai.base.activity.BaseMvpActivity import com.kai.base.application.BaseInit import com.kai.common.eventBusEntity.BaseEntity import com.kai.common.extension.* import com.kai.common.keyboard.KeyboardHeightObserver import com.kai.common.keyboard.KeyboardHeightProvider import com.kai.common.listener.CustomTextWatcher import com.kai.common.utils.StringUtils import com.kai.entity.User import com.kai.ui.forgetpassword.ForgetPasswordActivity import io.github.inflationx.viewpump.ViewPumpContextWrapper import kotlinx.android.synthetic.main.activity_login.* import kotlinx.android.synthetic.main.activity_login.account import kotlinx.android.synthetic.main.activity_login.account_layout import kotlinx.android.synthetic.main.activity_login.register import kotlinx.android.synthetic.main.activity_login.root import org.greenrobot.eventbus.EventBus import java.lang.Exception /** * * @ProjectName: app-page * @Description: 登陆页面 * @Author: pressureKai * @UpdateDate: 2021/4/7 15:45 */ @Route(path = BaseInit.LOGIN) class LoginActivity : BaseMvpActivity<LoginContract.View, LoginPresenter>(), KeyboardHeightObserver, LoginContract.View { companion object { const val REGISTER_CALLBACK = 0 const val LOGIN_FAIL_NO_ACCOUNT = 1 const val LOGIN_FAIL_ERROR_PASSWORD = 2 const val LOGIN_SUCCESS = 3 } private lateinit var keyboardHeightProvider: KeyboardHeightProvider private var loginCardOriginBottom = 0 override fun initView() { keyboardHeightProvider = KeyboardHeightProvider(this) keyboardHeightProvider.setKeyboardHeightObserver(this) initImmersionBar(fitSystem = false) login_lottie.layoutParams.height = getScreenWidth() login_content.post { keyboardHeightProvider.start() } forget_password.setOnClickListener { val number = StringUtils.trim(account.text.toString()) if (number.isEmpty()) { account_layout.error = resources.getString(R.string.phone_not_empty) } else { if(StringUtils.verifyPhone(number)){ account_layout.error = null } else { account_layout.error = resources.getString(R.string.phone_format_error) } } if (account_layout.error == null) { postStickyEvent(number, ForgetPasswordActivity.FORGET_PASSWORD_CODE, ForgetPasswordActivity::class.java.name) ARouter.getInstance().build(BaseInit.FORGETPASSWORD).navigation() } } register.setOnClickListener { ARouter.getInstance().build(BaseInit.REGISTER).navigation() } account.addTextChangedListener(object : CustomTextWatcher() { override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { account.formatPhone(start, count > 0) if (account_layout.error != null || account.text.toString().replace(" ", "").length >= 11) { if (StringUtils.verifyPhone(account.text.toString())) { val userByAccount = mPresenter?.getUserByAccount(StringUtils.trim(account.text.toString())) userByAccount?.let { observable -> observable.subscribe { if (it.isEmpty()) { account_layout.error = resources.getString(R.string.login_no_account) } else { account_layout.error = null } } } ?: kotlin.run { account_layout.error = null } } else { account_layout.error = resources.getString(R.string.phone_format_error) } } } }) password.addTextChangedListener(object : CustomTextWatcher() { override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { if (password_layout.error != null || password.text.toString().replace(" ", "").length >= 6) { if (password.text.toString().length >= 6) { password_layout.error = null } else { password_layout.error = resources.getString(R.string.password_length_no_enough) } } } }) login.setOnClickListener { if (verifyAll()) { mPresenter?.login(account.text.toString(), password.text.toString()) } } } override fun setLayoutId(): Int { return R.layout.activity_login } override fun attachBaseContext(newBase: Context) { super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase)) } @NonNull override fun getDelegate(): AppCompatDelegate { return SkinAppCompatDelegateImpl.get(this, this) } override fun onKeyboardHeightChanged(height: Int, orientation: Int) { login_card.post { if (loginCardOriginBottom == 0) { loginCardOriginBottom = login_card.bottom } val rootHeight = getScreenHeight() val changeHeight = if (height < 0) { 0 } else { if (rootHeight - loginCardOriginBottom < height) { height - (rootHeight - loginCardOriginBottom) } else { height } } beginAnimation(login_card, -changeHeight.toFloat()) } } override fun onPause() { super.onPause() keyboardHeightProvider.setKeyboardHeightObserver(null) } override fun onResume() { super.onResume() if (::keyboardHeightProvider.isInitialized) { keyboardHeightProvider.setKeyboardHeightObserver(this) } } override fun onDestroy() { super.onDestroy() keyboardHeightProvider.close() } override fun <T> onMessageReceiver(baseEntity: BaseEntity<T>) { super.onMessageReceiver(baseEntity) if (baseEntity.code == REGISTER_CALLBACK) { runOnUiThread { try { val user = baseEntity.data as User account.setText(user.account) } catch (e: Exception) { } } EventBus.getDefault().removeStickyEvent(baseEntity) } } override fun onLogin(entity: BaseEntity<User>) { when (entity.code) { LOGIN_FAIL_ERROR_PASSWORD -> { } LOGIN_SUCCESS -> { customToast(resources.getString(R.string.login_success)) val stringExtra = intent.getStringExtra(BaseInit.REBACK) if(!stringExtra.isNullOrEmpty()){ ARouter.getInstance().build(stringExtra).with(intent.extras).navigation() finish() } else { finish() } } LOGIN_FAIL_NO_ACCOUNT -> { } } } override fun createPresenter(): LoginPresenter { return LoginPresenter() } private fun verifyAll(): Boolean { if (password.text.toString().length < 6) { password_layout.error = resources.getString(R.string.password_length_no_enough) } return account_layout.error == null && password_layout.error == null } }
0
Kotlin
1
1
73edc5e8b838f9ba89e5ac717051c15871120673
8,070
FreeRead
Apache License 2.0