path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/windowsMain/kotlin/ca/gosyer/appdirs/impl/WindowsFolderResolver.kt
Syer10
578,459,054
false
{"Kotlin": 44823, "Shell": 1639}
package ca.gosyer.appdirs.impl interface WindowsFolderResolver { operator fun get(folderId: WindowsAppDirs.FolderId): String }
0
Kotlin
2
26
63290dea066fb5d3d7d46740a0335b918b6355f5
131
Kotlin-Multiplatform-AppDirs
Apache License 2.0
src/main/kotlin/lightnovelApi/model/response/Response.kt
CubeSugarCheese
545,268,622
false
null
package lightnovelApi.model.response import kotlinx.serialization.Serializable @Serializable data class Response<T> (val code: Int = 0, val data: T, val t: Long)
0
Kotlin
0
0
6dbaab8771efcfa7692a83606c2087e85a95f82d
163
LK-wap
MIT License
imageviewer/src/main/java/com/github/iielse/imageviewer/widgets/video/ExoVideoView2.kt
iielse
79,318,521
false
{"Kotlin": 136079}
package com.github.iielse.imageviewer.widgets.video import android.content.Context import android.util.AttributeSet import android.view.GestureDetector import android.view.MotionEvent import android.view.View import android.view.ViewConfiguration import androidx.viewpager2.widget.ViewPager2 import com.github.iielse.imageviewer.utils.Config import kotlin.math.abs import kotlin.math.max import kotlin.math.min class ExoVideoView2 @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : ExoVideoView(context, attrs, defStyleAttr), View.OnTouchListener { interface Listener { fun onDrag(view: ExoVideoView2, fraction: Float) fun onRestore(view: ExoVideoView2, fraction: Float) fun onRelease(view: ExoVideoView2) } private val scaledTouchSlop by lazy { ViewConfiguration.get(context).scaledTouchSlop * Config.SWIPE_TOUCH_SLOP } private val dismissEdge by lazy { height * Config.DISMISS_FRACTION } private var singleTouch = true private var fakeDragOffset = 0f private var lastX = 0f private var lastY = 0f private val listeners = mutableListOf<Listener>() private var clickListener: OnClickListener? = null private var longClickListener: OnLongClickListener? = null init { setOnTouchListener(this) } fun addListener(listener: Listener) { if (!listeners.contains(listener)) { listeners.add(listener) } } override fun setOnClickListener(listener: OnClickListener?) { clickListener = listener } override fun setOnLongClickListener(listener: OnLongClickListener?) { longClickListener = listener } override fun dispatchTouchEvent(event: MotionEvent?): Boolean { if (Config.SWIPE_DISMISS && Config.VIEWER_ORIENTATION == ViewPager2.ORIENTATION_HORIZONTAL) { handleDispatchTouchEvent(event) } return super.dispatchTouchEvent(event) } override fun onTouch(v: View?, event: MotionEvent?): Boolean { gestureDetector.onTouchEvent(event) return true } private fun handleDispatchTouchEvent(event: MotionEvent?) { if (!prepared) return when (event?.actionMasked) { MotionEvent.ACTION_POINTER_DOWN -> { singleTouch = false animate() .translationX(0f).translationY(0f).scaleX(1f).scaleY(1f) .setDuration(200).start() } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> up() MotionEvent.ACTION_MOVE -> { if (singleTouch) { if (lastX == 0f) lastX = event.rawX if (lastY == 0f) lastY = event.rawY val offsetX = event.rawX - lastX val offsetY = event.rawY - lastY fakeDrag(offsetX, offsetY) } } } } private fun fakeDrag(offsetX: Float, offsetY: Float) { if (fakeDragOffset == 0f) { if (offsetY > scaledTouchSlop) fakeDragOffset = scaledTouchSlop else if (offsetY < -scaledTouchSlop) fakeDragOffset = -scaledTouchSlop } if (fakeDragOffset != 0f) { val fixedOffsetY = offsetY - fakeDragOffset parent?.requestDisallowInterceptTouchEvent(true) val fraction = abs(max(-1f, min(1f, fixedOffsetY / height))) val fakeScale = 1 - min(0.4f, fraction) scaleX = fakeScale scaleY = fakeScale translationY = fixedOffsetY translationX = offsetX / 2 listeners.toList().forEach { it.onDrag(this, fraction) } } } private fun up() { parent?.requestDisallowInterceptTouchEvent(false) singleTouch = true fakeDragOffset = 0f lastX = 0f lastY = 0f if (abs(translationY) > dismissEdge) { listeners.toList().forEach { it.onRelease(this) } } else { val offsetY = translationY val fraction = min(1f, offsetY / height) listeners.toList().forEach { it.onRestore(this, fraction) } animate() .translationX(0f).translationY(0f).scaleX(1f).scaleY(1f) .setDuration(200).start() } } override fun onDetachedFromWindow() { super.onDetachedFromWindow() animate().cancel() } private val gestureDetector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() { // forward long click listener override fun onLongPress(e: MotionEvent) { longClickListener?.onLongClick(this@ExoVideoView2) } }).apply { setOnDoubleTapListener(object : GestureDetector.OnDoubleTapListener { override fun onSingleTapConfirmed(e: MotionEvent?): Boolean { clickListener?.onClick(this@ExoVideoView2) return true } override fun onDoubleTapEvent(e: MotionEvent?) = false override fun onDoubleTap(e: MotionEvent?): Boolean = true }) } }
1
Kotlin
309
2,185
2711ea6d67cf0a39ed4a128be11262a0bae712f1
5,170
imageviewer
MIT License
kairo-config/src/test/kotlin/kairo/config/CommandConfigLoaderStringNullableDeserializerTest.kt
hudson155
836,940,978
false
{"Kotlin": 486567, "HCL": 1700}
package kairo.config import com.fasterxml.jackson.module.kotlin.readValue import io.kotest.matchers.shouldBe import kotlinx.coroutines.test.runTest import org.junit.jupiter.api.Test /** * This test is intended to test behaviour strictly related to [ConfigLoaderSource.Command]. */ internal class CommandConfigLoaderStringNullableDeserializerTest : ConfigLoaderDeserializerTest() { /** * This test is specifically for nullable [String] properties. */ internal data class MyClass( val message: String?, ) private val nonNullString: String = """ { "message": { "source": "Command", "command": "echo \"Hello, World!\"" } } """.trimIndent() private val nullString: String = """ { "message": { "source": "Command", "command": ";" } } """.trimIndent() @Test fun `non-null (allowInsecureConfigSources = false)`(): Unit = runTest { allowInsecureConfigSources(false) val mapper = createMapper() shouldBeInsecure("Config loader source Command is considered insecure.") { mapper.readValue<MyClass>(nonNullString) } } @Test fun `non-null (allowInsecureConfigSources = true)`(): Unit = runTest { allowInsecureConfigSources(true) val mapper = createMapper() mapper.readValue<MyClass>(nonNullString).shouldBe(MyClass("Hello, World!")) } @Test fun `null (allowInsecureConfigSources = false)`(): Unit = runTest { allowInsecureConfigSources(false) val mapper = createMapper() shouldBeInsecure("Config loader source Command is considered insecure.") { mapper.readValue<MyClass>(nullString) } } @Test fun `null (allowInsecureConfigSources = true)`(): Unit = runTest { allowInsecureConfigSources(true) val mapper = createMapper() mapper.readValue<MyClass>(nullString).shouldBe(MyClass(null)) } }
0
Kotlin
1
9
da21d969005c51aa6d30ac20b1e682452494c50c
1,872
kairo
Apache License 2.0
shared/src/commonMain/kotlin/com.sbga.sdgbapp/DB/OptionTrackskipID.kt
NickJi2019
717,286,554
false
{"Kotlin": 134744, "Ruby": 2257, "Swift": 1595, "JavaScript": 485, "HTML": 323}
package com.sbga.sdgbapp.DB enum class OptionTrackskipID(val value: Int) { Off(0), Push(1), AutoS(2), AutoSS(3), AutoSSS(4), AutoBest(5), Begin(0), End(6), Invalid(-1) }
0
Kotlin
1
4
4358ab163f560a9e28255b789e42b8054e4cd8f9
208
SDGBApp
MIT License
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/TestResultObject.kt
Danilo-Araujo-Silva
271,904,885
false
null
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction /** *```` * * Name: TestResultObject * * Full name: System`TestResultObject * * Usage: TestResultObject[…] gives an object that represents the results of a VerificationTest. * * Options: None * * Attributes: ReadProtected * * local: paclet:ref/TestResultObject * Documentation: web: http://reference.wolfram.com/language/ref/TestResultObject.html * * Definitions: None * * Own values: None * * Down values: None * * Up values: None * * Sub values: None * * Default value: None * * Numeric values: None */ fun testResultObject(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction { return MathematicaFunction("TestResultObject", arguments.toMutableList(), options) }
2
Kotlin
0
3
4fcf68af14f55b8634132d34f61dae8bb2ee2942
1,009
mathemagika
Apache License 2.0
app/src/main/java/soy/gabimoreno/audioclean/di/AppModule.kt
soygabimoreno
266,280,006
false
{"Kotlin": 63351, "CMake": 1598}
package soy.gabimoreno.audioclean.di import android.content.Context import org.koin.android.ext.koin.androidContext import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.core.qualifier.named import org.koin.dsl.module import soy.gabimoreno.audioclean.data.DefaultUserSession import soy.gabimoreno.audioclean.data.equalization.VoiceManEqualization import soy.gabimoreno.audioclean.data.preferences.EqualizationDatasource import soy.gabimoreno.audioclean.domain.Equalization import soy.gabimoreno.audioclean.domain.UserSession import soy.gabimoreno.audioclean.domain.usecase.GetAudioSessionIdUseCase import soy.gabimoreno.audioclean.domain.usecase.GetEqualizationUseCase import soy.gabimoreno.audioclean.framework.AudioProcessor import soy.gabimoreno.audioclean.framework.GetActiveRecordingConfigurations import soy.gabimoreno.audioclean.presentation.MainActivity import soy.gabimoreno.audioclean.presentation.MainViewModel val appModule = module { single<UserSession> { DefaultUserSession() } single { GetActiveRecordingConfigurations( context = androidContext(), errorTrackerComponent = get() ) } single { GetAudioSessionIdUseCase(getActiveRecordingConfigurations = get()) } single { GetEqualizationUseCase() } single<Equalization> { VoiceManEqualization().get() } single { EqualizationDatasource( sharedPreferences = androidContext() .getSharedPreferences("AUDIO_CLEAN_PREFS", Context.MODE_PRIVATE) ) } single { AudioProcessor( getAudioSessionIdUseCase = get(), equalization = get() ) } scope(named<MainActivity>()) { viewModel { MainViewModel( audioProcessor = get(), equalizationDatasource = get(), getEqualizationUseCase = get(), analyticsTrackerComponent = get(), errorTrackerComponent = get() ) } } }
0
Kotlin
0
9
624e2a5622e9da3bf46ecbf980db5a6621ce99f4
2,012
AudioClean
Apache License 2.0
site/src/jsMain/kotlin/org/example/newportfolio/components/sections/nav_header/components/NavBar.kt
MohamedElgohary88
836,458,650
false
{"Kotlin": 113326, "HTML": 83476, "CSS": 356}
@file:Suppress("DEPRECATION") package org.example.newportfolio.components.sections.nav_header.components import androidx.compose.runtime.Composable import org.example.newportfolio.models.Section import org.example.newportfolio.theme.brand import org.example.newportfolio.theme.fonts.LabelLargeTextStyle import org.example.newportfolio.theme.fonts.TextStyle import org.example.newportfolio.theme.text import com.varabyte.kobweb.compose.css.CSSTransition import com.varabyte.kobweb.compose.css.ListStyleType import com.varabyte.kobweb.compose.css.TextDecorationLine import com.varabyte.kobweb.compose.css.autoLength import com.varabyte.kobweb.compose.foundation.layout.Box import com.varabyte.kobweb.compose.ui.Alignment import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.modifiers.* import com.varabyte.kobweb.silk.components.navigation.Link import com.varabyte.kobweb.silk.components.navigation.LinkStyle import com.varabyte.kobweb.silk.components.style.* import com.varabyte.kobweb.silk.components.style.breakpoint.Breakpoint import com.varabyte.kobweb.silk.style.thenIf import com.varabyte.kobweb.silk.theme.colors.palette.overlay import com.varabyte.kobweb.silk.theme.colors.palette.toPalette import com.varabyte.kobweb.silk.theme.colors.shifted import org.jetbrains.compose.web.css.* import org.jetbrains.compose.web.dom.Nav import org.jetbrains.compose.web.dom.Text val NavBarStyle by ComponentStyle { val colorPalette = colorMode.toPalette() base { Modifier .size(autoLength) .background(colorPalette.overlay) .borderRadius(30.px) .listStyle(ListStyleType.None) .display(DisplayStyle.Flex) .justifyContent(JustifyContent.Center) .flex(1) } } @Composable fun NavBar( selectedSectionId: String ) { Nav( attrs = NavBarStyle.toAttrs() ) { Section.entries.forEach { section -> NavBarLink( href = section.href, text = section.text, selected = section.id == selectedSectionId ) } } } val NavBarLinkVariant = LinkStyle.addVariant(extraModifiers = { TextStyle.toModifier(LabelLargeTextStyle) }) { val colorPalette = colorMode.toPalette() base { Modifier .alignContent(AlignContent.Center) .color(colorPalette.text.primary) .background(colorPalette.overlay) .borderRadius(r = 30.px) .textDecorationLine(TextDecorationLine.None) .transition(CSSTransition("0.2s")) } hover { Modifier.background(colorPalette.overlay.shifted(colorMode, 0.1f)) } active { Modifier.background(colorPalette.overlay.shifted(colorMode, 0.15f)) } Breakpoint.LG { Modifier.size(width = 13.5.em, height = 3.8.em) } Breakpoint.XL { Modifier.size(width = 13.8.em, height = 3.9.em) } } val ActiveNavBarLinkVariant = LinkStyle.addVariant { val colorPalette = colorMode.toPalette() base { Modifier .color(colorPalette.brand.onPrimary) .background(colorPalette.brand.primary) .backgroundColor(colorPalette.brand.primary) .transition(CSSTransition("0.1s")) } hover { Modifier.background(colorPalette.brand.primary) } } @Composable private fun NavBarLink( href: String, text: String, selected: Boolean, ) { Link( path = href, variant = NavBarLinkVariant.thenIf(selected, ActiveNavBarLinkVariant), ) { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { Text(text) } } }
0
Kotlin
0
0
712f9de08c957fe2d1d83b0060d6265c989d111a
3,758
My-Portfolio
MIT License
src/main/kotlin/org/kamiblue/botkt/command/commands/system/PluginCommand.kt
l1ving
288,019,910
false
null
package org.kamiblue.botkt.command.commands.system import io.ktor.client.request.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import org.kamiblue.botkt.Main import org.kamiblue.botkt.PermissionTypes import org.kamiblue.botkt.command.BotCommand import org.kamiblue.botkt.command.Category import org.kamiblue.botkt.command.MessageExecuteEvent import org.kamiblue.botkt.command.options.HasPermission import org.kamiblue.botkt.plugin.Plugin import org.kamiblue.botkt.plugin.PluginLoader import org.kamiblue.botkt.plugin.PluginManager import org.kamiblue.botkt.utils.* import java.io.File object PluginCommand : BotCommand( name = "plugin", category = Category.SYSTEM, description = "Manage plugins" ) { init { literal("load") { greedy("jar name") { nameArg -> execute(HasPermission.get(PermissionTypes.MANAGE_PLUGINS)) { val name = nameArg.value val file = File("${PluginManager.pluginPath}$name") if (!file.exists() || !file.extension.equals("jar", true)) { channel.error("$name is not a valid jar file name!") } val time = System.currentTimeMillis() val message = channel.normal("Loading plugin $name...") val loader = PluginLoader(file) val plugin = loader.load() if (PluginManager.loadedPlugins.contains(plugin)) { message.edit("Plugin $name already loaded!") return@execute } PluginManager.load(loader) val stopTime = System.currentTimeMillis() - time message.edit { description = "Loaded plugin $name, took $stopTime ms!" color = Colors.SUCCESS.color } } } } literal("reload") { greedy("plugin name") { nameArg -> execute(HasPermission.get(PermissionTypes.MANAGE_PLUGINS)) { val name = nameArg.value val plugin = PluginManager.loadedPlugins[name] if (plugin == null) { channel.error("No plugin found for name $name") return@execute } val time = System.currentTimeMillis() val message = channel.normal("Reloading plugin $name...") val file = PluginManager.pluginLoaderMap[plugin]!!.file PluginManager.unload(plugin) PluginManager.load(PluginLoader(file)) val stopTime = System.currentTimeMillis() - time message.edit { description = "Reloaded plugin $name, took $stopTime ms!" color = Colors.SUCCESS.color } } } execute(HasPermission.get(PermissionTypes.MANAGE_PLUGINS)) { val time = System.currentTimeMillis() val message = channel.normal("Reloading all plugins...") PluginManager.unloadAll() PluginManager.loadAll(PluginManager.getLoaders()) val stopTime = System.currentTimeMillis() - time message.edit { description = "Reloaded plugins, took $stopTime ms!" color = Colors.SUCCESS.color } } } literal("unload") { greedy("plugin name") { nameArg -> execute(HasPermission.get(PermissionTypes.MANAGE_PLUGINS)) { val name = nameArg.value val plugin = PluginManager.loadedPlugins[name] if (plugin == null) { channel.error("No plugin found for name $name") return@execute } val time = System.currentTimeMillis() val message = channel.normal("Unloading plugin $name...") PluginManager.unload(plugin) val stopTime = System.currentTimeMillis() - time message.edit { description = "Unloaded plugin $name, took $stopTime ms!" color = Colors.SUCCESS.color } } } execute(HasPermission.get(PermissionTypes.MANAGE_PLUGINS)) { val time = System.currentTimeMillis() val message = channel.normal("Unloading plugins...") PluginManager.unloadAll() val stopTime = System.currentTimeMillis() - time message.edit { description = "Unloaded plugins, took $stopTime ms!" color = Colors.SUCCESS.color } } } literal("download") { string("file name") { fileNameArg -> greedy("url") { urlArg -> execute("Download a plugin", HasPermission.get(PermissionTypes.MANAGE_PLUGINS)) { val time = System.currentTimeMillis() val name = fileNameArg.value.removeSuffix(".jar") + ".jar" val deferred = coroutineScope { async(Dispatchers.IO) { val bytes = Main.httpClient.get<ByteArray> { header("User-Agent", "") url(urlArg.value) } File(PluginManager.pluginPath + name).writeBytes(bytes) } } val message = channel.normal("Downloading plugin `$name` from URL <${urlArg.value}>...") deferred.join() val stopTime = System.currentTimeMillis() - time message.edit { description = "Downloaded plugin `$name`, took $stopTime ms!" color = Colors.SUCCESS.color } } } } } literal("delete") { greedy("file name") { fileNameArg -> execute("Delete a plugin", HasPermission.get(PermissionTypes.MANAGE_PLUGINS)) { val name = fileNameArg.value.removeSuffix(".jar") + ".jar" val file = File(PluginManager.pluginPath + name) if (!file.exists()) { channel.error("Could not find a plugin file with the name `$name`") return@execute } file.delete() channel.success("Deleted plugin with file name `$name`") } } } literal("list") { execute(HasPermission.get(PermissionTypes.MANAGE_PLUGINS)) { if (PluginManager.loadedPlugins.isEmpty()) { channel.warn("No plugins loaded") } else { channel.send { embed { title = "Loaded plugins: `${PluginManager.loadedPlugins.size}`" description = PluginManager.loadedPlugins.withIndex() .joinToString("\n") { (index, plugin) -> "`$index`. ${plugin.name}" } } } } } } literal("info") { int("index") { indexArg -> execute(HasPermission.get(PermissionTypes.MANAGE_PLUGINS)) { val index = indexArg.value val plugin = PluginManager.loadedPlugins.toList().getOrNull(index) ?: run { channel.error("No plugin found for index: `$index`") return@execute } val loader = PluginManager.pluginLoaderMap[plugin]!! sendPluginInfo(plugin, loader) } } string("plugin name") { nameArg -> execute { val name = nameArg.value val plugin = PluginManager.loadedPlugins[name] ?: run { channel.error("No plugin found for name: `$name`") return@execute } val loader = PluginManager.pluginLoaderMap[plugin]!! sendPluginInfo(plugin, loader) } } } } private suspend fun MessageExecuteEvent.sendPluginInfo(plugin: Plugin, loader: PluginLoader) { channel.send { embed { title = "Info for plugin: $loader" description = plugin.toString() color = Colors.PRIMARY.color } } } }
8
Kotlin
4
14
b6f49dc530ded6ef3daa0959e62234ed86098a19
9,315
bot-kt
ISC License
react-table-kotlin/src/jsMain/kotlin/tanstack/table/core/TableOptions.kt
karakum-team
393,199,102
false
{"Kotlin": 6272741}
// Automatically generated - do not modify! package tanstack.table.core external interface TableOptions<TData : RowData> : TableOptionsResolved<TData>
0
Kotlin
8
36
95b065622a9445caf058ad2581f4c91f9e2b0d91
153
types-kotlin
Apache License 2.0
src/jsMain/kotlin/reactredux/reducers/CliContext.kt
AD1306
336,248,126
true
{"Kotlin": 181746, "Dockerfile": 1138}
package reactredux.reducers import model.CliContext import reactredux.actions.UpdateContext import redux.RAction fun cliContext(state: CliContext = CliContext(), action: RAction): CliContext = when (action) { is UpdateContext -> { action.context } else -> state }
0
null
0
0
99051472819d0de6ee660120efd5a2fdcf1d99ed
309
org.hl7.fhir.validator-wrapper
Apache License 2.0
app_pemantau/src/main/java/app/trian/pemantau/ui/pages/form_odp/FormOdpViewModel.kt
triandamai
510,087,041
false
{"Kotlin": 499465}
package app.trian.pemantau.ui.pages.form_odp import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.trian.data.repository.design.OdpRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class FormOdpViewModel @Inject constructor( private val odpRepository: OdpRepository ) : ViewModel() { fun submitOdp( name:String, religion:String, nik:String, dateOfBirth:String, placeOfBirth:String, address:String, rt:String, rw:String, bloodType:String, profession:String, phoneNUmber:String, tripHistory:String, placeOfTrip:String, isolation:Boolean, safetyNet:Boolean, behavior:Boolean, condition:String, gender:String, cb:(Boolean,String)->Unit )=viewModelScope.launch { odpRepository .saveOdp( name, religion, nik, dateOfBirth, placeOfBirth, address, rt, rw, bloodType, profession, phoneNUmber, tripHistory, placeOfTrip, isolation, safetyNet, behavior, condition, gender ) .catch { cb(false,"${it.message}") } .onEach { cb(it.first,it.second) } .collect() } }
0
Kotlin
0
0
608d28a7800a39ee9ded14c6d85b7e7db770d01a
1,765
pantau-odp-v2
Apache License 2.0
src/test/kotlin/br/com/jiratorio/service/impl/DueDateServiceImplTest.kt
andrelugomes
230,294,644
true
{"Kotlin": 541514, "PLSQL": 366, "Dockerfile": 315, "TSQL": 269}
package br.com.jiratorio.service.impl import br.com.jiratorio.assert.assertThat import br.com.jiratorio.context.UnitTestContext import br.com.jiratorio.domain.entity.embedded.DueDateHistory import br.com.jiratorio.domain.jira.changelog.JiraChangelogItem import br.com.jiratorio.extension.toLocalDate import br.com.jiratorio.factory.domain.JiraChangelogItemFactory import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.test.context.ContextConfiguration import org.springframework.test.context.junit.jupiter.SpringExtension import java.time.LocalDateTime import java.util.Comparator @Tag("unit") @ExtendWith(SpringExtension::class) @ContextConfiguration(classes = [UnitTestContext::class]) internal class DueDateServiceImplTest( private val jiraChangelogItemFactory: JiraChangelogItemFactory ) { private val dueDateService = DueDateServiceImpl() @Test fun `extract due date history with one item`() { val jiraChangelogItem = jiraChangelogItemFactory.create() val dueDateHistories = dueDateService.extractDueDateHistory("duedate", listOf(jiraChangelogItem)) assertThat(dueDateHistories).hasSize(1) dueDateHistories.first().assertThat { hasDueDate(jiraChangelogItem.to?.toLocalDate("yyyy-MM-dd")) hasCreated(jiraChangelogItem.created) } } @Test fun `extract due date history with many items`() { jiraChangelogItemFactory.create( quantity = 5, modifyingFields = mapOf( JiraChangelogItem::field to "other_field" ) ) val jiraChangelogItems = jiraChangelogItemFactory.create(5) val dueDateHistories = dueDateService.extractDueDateHistory("duedate", jiraChangelogItems) assertThat(dueDateHistories) .hasSize(5) .isSortedAccordingTo(Comparator.comparing<DueDateHistory, LocalDateTime> { it.created }) } }
0
null
0
1
168de10e5e53f31734937816811ac9dae6940202
2,085
jirareport
MIT License
platform/android/goldengate/GoldenGateBindings/src/main/kotlin/com/fitbit/goldengate/bindings/coap/data/BaseOutgoingMessageBuilder.kt
Fitbit
252,750,226
false
{"C": 2519513, "Kotlin": 897890, "Swift": 806092, "C++": 805305, "CMake": 121256, "Python": 115131, "Objective-C": 88567, "JavaScript": 20929, "HTML": 13841, "Shell": 2041, "Dockerfile": 1379, "Ruby": 252}
// Copyright 2017-2020 Fitbit, Inc // SPDX-License-Identifier: Apache-2.0 package com.fitbit.goldengate.bindings.coap.data import io.reactivex.Observer import io.reactivex.internal.util.EmptyComponent import java.io.InputStream /** * Base class for [MessageBuilder] providing common implementation */ abstract class BaseOutgoingMessageBuilder<T : Message> : OutgoingMessageBuilder<T> { internal val options = Options() internal var body: OutgoingBody = EmptyOutgoingBody() internal var progressObserver: Observer<Int> = EmptyComponent.asObserver<Int>() override fun option(option: Option): OutgoingMessageBuilder<T> { options.add(option) return this } override fun body(data: Data): OutgoingMessageBuilder<T> { body = BytesArrayOutgoingBody(data) return this } override fun body(stream: InputStream): OutgoingMessageBuilder<T> { body = InputStreamOutgoingBody(stream) return this } override fun progressObserver(progressObserver: Observer<Int>): OutgoingMessageBuilder<T> { this.progressObserver = progressObserver return this } internal fun addAll(options: Options): OutgoingMessageBuilder<T> { this.options.addAll(options) return this } }
14
C
32
290
417aad0080bdc8b20c27cf8fff2455c20e6f3adb
1,285
golden-gate
Apache License 2.0
Sheet #4 (Strings)/Good or Bad/src/Main.kt
yasserahmed10
722,709,626
false
{"Kotlin": 14251}
fun main() { val t = readln().toInt() repeat(t) { val s = readln() if (s.contains("010") || s.contains("101")) { println("Good") } else { println("Bad") } } }
0
Kotlin
0
1
0ed2428e4421a49833fce5ae758e283f87f196af
229
Assiut-University-Training---Newcomers-Kotlin-
MIT License
src/main/kotlin/ink/ptms/adyeshach/api/AdyeshachAPI.kt
Glom-c
393,003,109
true
{"Kotlin": 477394}
package ink.ptms.adyeshach.api import com.google.gson.JsonParser import ink.ptms.adyeshach.Adyeshach import ink.ptms.adyeshach.api.event.CustomDatabaseEvent import ink.ptms.adyeshach.common.entity.EntityInstance import ink.ptms.adyeshach.common.entity.EntityTypes import ink.ptms.adyeshach.common.entity.manager.* import ink.ptms.adyeshach.common.script.KnownController import ink.ptms.adyeshach.common.script.ScriptHandler import ink.ptms.adyeshach.common.util.serializer.Converter import ink.ptms.adyeshach.common.util.serializer.Serializer import ink.ptms.adyeshach.common.util.serializer.UnknownWorldException import ink.ptms.adyeshach.internal.database.DatabaseLocal import ink.ptms.adyeshach.internal.database.DatabaseMongodb import org.bukkit.Location import org.bukkit.entity.Player import org.bukkit.event.player.PlayerQuitEvent import taboolib.common.LifeCycle import taboolib.common.platform.* import taboolib.common.util.each import taboolib.library.configuration.ConfigurationSection import taboolib.module.configuration.SecuredFile import java.io.File import java.io.InputStream import java.nio.charset.StandardCharsets import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.CopyOnWriteArrayList import kotlin.collections.ArrayList object AdyeshachAPI { val onlinePlayers = CopyOnWriteArrayList<String>() private val managerPrivate = ConcurrentHashMap<String, ManagerPrivate>() private val managerPrivateTemp = ConcurrentHashMap<String, ManagerPrivateTemp>() private val managerPublic = ManagerPublic() private val managerPublicTemp = ManagerPublicTemp() private val database by lazy { when (val db = Adyeshach.conf.getString("Database.method")!!.uppercase(Locale.getDefault())) { "LOCAL" -> DatabaseLocal() "MONGODB" -> DatabaseMongodb() else -> { val event = CustomDatabaseEvent(db) event.call() event.database ?: error("Storage method \"${Adyeshach.conf.getString("Database.method")}\" not supported.") } } } fun getEntityManagerPublic(): Manager { return managerPublic } fun getEntityManagerPublicTemporary(): Manager { return managerPublicTemp } fun getEntityManagerPrivate(player: Player): Manager { return managerPrivate.computeIfAbsent(player.name) { ManagerPrivate(player.name, database) } } fun getEntityManagerPrivateTemporary(player: Player): Manager { return managerPrivateTemp.computeIfAbsent(player.name) { ManagerPrivateTemp(player.name) } } @Throws(UnknownWorldException::class) fun fromYaml(section: ConfigurationSection): EntityInstance? { return fromJson(Converter.yamlToJson(section).toString()) } @Throws(UnknownWorldException::class) fun fromYaml(source: String): EntityInstance? { return fromJson(Converter.yamlToJson(SecuredFile.loadConfiguration(source)).toString()) } @Throws(UnknownWorldException::class) fun fromJson(inputStream: InputStream): EntityInstance? { return fromJson(inputStream.readBytes().toString(StandardCharsets.UTF_8)) } @Throws(UnknownWorldException::class) fun fromJson(file: File): EntityInstance? { return fromJson(file.readText(StandardCharsets.UTF_8)) } @Throws(UnknownWorldException::class) fun fromJson(source: String): EntityInstance? { val entityType = try { EntityTypes.valueOf(JsonParser().parse(source).asJsonObject.get("entityType").asString) } catch (ex: UnknownWorldException) { throw ex } catch (t: Throwable) { t.printStackTrace() return null } return Serializer.gson.fromJson(source, entityType.entityBase) } fun getEntityNearly(player: Player): EntityInstance? { return getEntity(player) { true } } fun getEntityFromEntityId(id: Int, player: Player? = null): EntityInstance? { return getEntity(player) { it.index == id } } fun getEntityFromId(id: String, player: Player? = null): EntityInstance? { return getEntity(player) { it.id == id } } fun getEntityFromUniqueId(id: String, player: Player? = null): EntityInstance? { return getEntity(player) { it.uniqueId == id } } fun getEntityFromUniqueIdOrId(id: String, player: Player? = null): EntityInstance? { return getEntity(player) { it.id == id || it.uniqueId == id } } fun getEntity(player: Player? = null, filter: (EntityInstance) -> Boolean): EntityInstance? { val entity = getEntities(player, filter) return if (player != null) entity.minByOrNull { it.position.toLocation().toDistance(player.location) } else entity.firstOrNull() } fun getEntities(player: Player? = null, filter: (EntityInstance) -> Boolean): List<EntityInstance> { val entity = ArrayList<EntityInstance>() entity.addAll(getEntityManagerPublic().getEntities().filter { filter(it) }) entity.addAll(getEntityManagerPublicTemporary().getEntities().filter { filter(it) }) if (player != null) { entity.addAll(getEntityManagerPrivate(player).getEntities().filter { filter(it) }) entity.addAll(getEntityManagerPrivateTemporary(player).getEntities().filter { filter(it) }) } return entity } fun registerKnownController(name: String, event: KnownController) { ScriptHandler.controllers[name] = event } fun getKnownController(name: String): KnownController? { return ScriptHandler.getKnownController(name) } fun getKnownController(): Map<String, KnownController> { return ScriptHandler.controllers } fun Location.toDistance(loc: Location): Double { return if (this.world!!.name == loc.world!!.name) { this.distance(loc) } else { Double.MAX_VALUE } } @Awake(LifeCycle.DISABLE) private fun e() { onlinePlayers().forEach { database.push(it.cast()) } } @SubscribeEvent private fun e(e: PlayerQuitEvent) { onlinePlayers.remove(e.player.name) managerPrivate.remove(e.player.name) managerPrivateTemp.remove(e.player.name) submit(async = true) { database.push(e.player) database.release(e.player) } } }
0
null
0
0
ea654b73b9a3a126833219c9baeddf8fb185c43d
6,417
Adyeshach
MIT License
kindex/src/main/kotlin/Kindex.kt
Monkopedia
305,151,965
false
{"Kotlin": 381076, "JavaScript": 1289, "HTML": 912}
/* * Copyright 2020 <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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.monkopedia.kindex import MdFileTable import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.parameters.options.default import com.github.ajalt.clikt.parameters.options.option import com.monkopedia.FileLogger import com.monkopedia.Log import com.monkopedia.StdoutLogger import com.monkopedia.imdex.Korpus import com.monkopedia.imdex.KorpusManager.DataType.ARTIFACT import com.monkopedia.imdex.KorpusManager.DataType.STRING import com.monkopedia.imdex.KorpusManager.KorpusDataType import com.monkopedia.imdex.KorpusManager.KorpusKeyInfo import com.monkopedia.imdex.KorpusManager.KorpusType import com.monkopedia.imdex.Scriptorium import com.monkopedia.imdex.Scriptorium.KorpusInfo import com.monkopedia.imdex.ensureConfig import com.monkopedia.ksrpc.connect import com.monkopedia.ksrpc.deserialized import com.monkopedia.ksrpc.toKsrpcUri import com.zaxxer.hikari.HikariConfig import com.zaxxer.hikari.HikariDataSource import java.io.File import java.sql.Connection import kotlinx.coroutines.runBlocking import org.jetbrains.exposed.sql.Database import org.jetbrains.exposed.sql.SchemaUtils import org.jetbrains.exposed.sql.transactions.TransactionManager import org.jetbrains.exposed.sql.transactions.transaction fun main(args: Array<String>) = KindexApp().main(args) class KindexApp : CliktCommand() { private val log by option("-l", "--log", help = "Path to log to, or stdout") .default("/tmp/kindex_indexer.txt") private val imdexPath by option("-i", "--imdex", help = "Ksrpc uri to imdex server") .default("ksrpc://localhost:14038") override fun run() { if (log == "stdout") { Log.init(StdoutLogger) } else { Log.init(FileLogger(File(log))) } runBlocking { val imdex = Scriptorium.wrap(imdexPath.toKsrpcUri().connect().deserialized()) imdex.korpusManager(Unit).ensureConfig(kindexerType) val configs = imdex.getKorpii(Unit).filter { it.type == "imdex.korpus.kindex" } for (c in configs) { println("Running indexing on ${c.id}") val korpus = imdex.korpus(c.id) val db = dbFor(config = c) val kindexer = ArtifactIndexWorker(c, db) kindexer.launchIndexing(korpus) } } } private fun dbFor(config: KorpusInfo): Database { val db = File(File(config.config[Korpus.DATA_PATH_KEY]), "state.db") if (!db.exists()) { db.parentFile.mkdirs() } val config = HikariConfig().apply { jdbcUrl = "jdbc:sqlite:${db.absolutePath}" driverClassName = "org.sqlite.JDBC" maximumPoolSize = 1 } val dataSource = HikariDataSource(config) return Database.connect(dataSource).also { TransactionManager.managerFor(it)?.defaultIsolationLevel = Connection.TRANSACTION_SERIALIZABLE transaction(db = it) { SchemaUtils.createMissingTablesAndColumns(MdFileTable, ArtifactStateTable) } } } companion object { const val MAVEN_URL_KEYS = "korpus.kindex.urls" const val ARTIFACTS_URL_KEYS = "korpus.kindex.artifacts" val kindexerType = KorpusType( "Kindex", "imdex.korpus.kindex", listOf( KorpusKeyInfo.LABEL, KorpusKeyInfo( "Maven URLs", KorpusDataType(listOf = STRING.type), MAVEN_URL_KEYS ), KorpusKeyInfo( "Artifacts", KorpusDataType(listOf = ARTIFACT.type), ARTIFACTS_URL_KEYS ), ), ) } }
0
Kotlin
0
0
c6f6a460e00af6b8ffc98b8e39cbad509549bc9f
4,431
imdex
Apache License 2.0
code/app/src/main/java/com/tanfra/shopmob/smob/data/repo/utils/Resource.kt
fwornle
440,434,944
false
{"Kotlin": 997071, "JavaScript": 29417, "HTML": 180, "Batchfile": 177}
package com.tanfra.shopmob.smob.data.repo.utils sealed class Resource<out T> { data class Success<out T>(val data: T) : Resource<T>() data class Failure(val exception: Exception) : Resource<Nothing>() data object Empty : Resource<Nothing>() }
0
Kotlin
0
0
beb57c22e9b9618a592817990309ea6d415ffe3e
256
ShopMob
MIT License
app/src/main/java/com/anshdeep/kotlinmessenger/Fragment/MainActivity.kt
Stivenmore
262,952,473
false
null
package com.anshdeep.kotlinmessenger.Fragment import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.anshdeep.kotlinmessenger.R import com.anshdeep.kotlinmessenger.Fragment.CursosFragment import com.anshdeep.kotlinmessenger.messages.LatestMessagesActivity import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.fragment_cursos.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) CambiarFragment() Mensajes() } private fun Mensajes() { new_message_chat.setOnClickListener { val intent = Intent(this, LatestMessagesActivity::class.java) startActivity(intent) } } private fun CambiarFragment() { loadFragment(BecasFragment()) nav_botton.setOnNavigationItemReselectedListener { menuItem -> when (menuItem.itemId) { R.id.Inicio -> { loadFragment(InicioFragment()) return@setOnNavigationItemReselectedListener } R.id.Becas -> { loadFragment(BecasFragment()) return@setOnNavigationItemReselectedListener } R.id.Cursos -> { loadFragment(CursosFragment()) return@setOnNavigationItemReselectedListener } } } } private fun loadFragment(fragment: Fragment) { supportFragmentManager.beginTransaction().also { fragmentTransaction -> fragmentTransaction.replace(R.id.nav_fragment, fragment) fragmentTransaction.commit() } } }
0
Kotlin
0
1
27e5f06bb7ecc6f37c3733f9b34327028198bf56
1,989
AppUniversidad
Apache License 2.0
src/test/kotlin/net/jp/vss/sample/usecase/users/CreateUserUseCaseParameterFixtures.kt
nemuzuka
184,200,566
false
null
package net.jp.vss.sample.usecase.users /** * CreateUserUseCaseParameter の Fixture. */ class CreateUserUseCaseParameterFixtures { companion object { fun create() = CreateUserUseCaseParameter("USER_0001", "名前1", "google", "PRINCIPAL_0001") } }
18
Kotlin
0
0
ef8ed4626d2cd1dbbd3455534fedf67940a32361
274
spring-kotlin-sample
Apache License 2.0
app/src/main/java/com/github/psm/moviedb/db/model/shared/credit/Cast.kt
Pidsamhai
371,868,606
false
{"Kotlin": 243787, "CMake": 1715}
package com.github.psm.moviedb.db.model.shared.credit import android.os.Parcelable import androidx.annotation.Keep import kotlinx.parcelize.Parcelize import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Keep @Serializable @Parcelize data class Cast( @SerialName("adult") val adult: Boolean? = null, @SerialName("cast_id") val castId: Int? = null, @SerialName("character") val character: String? = null, @SerialName("credit_id") val creditId: String? = null, @SerialName("gender") val gender: Int? = null, @SerialName("id") val id: Long? = null, @SerialName("known_for_department") val knownForDepartment: String? = null, @SerialName("name") val name: String? = null, @SerialName("order") val order: Int? = null, @SerialName("original_name") val originalName: String? = null, @SerialName("popularity") val popularity: Double? = null, @SerialName("profile_path") val profilePath: String? = null ) : Parcelable
1
Kotlin
1
3
6f4e67ee83349604b3396902469f4c3a83a68c3c
1,037
movie_db
Apache License 2.0
crystal-map-processor/src/main/java/com/schwarz/crystalprocessor/processing/WorkSet.kt
SchwarzIT
92,849,438
false
{"Kotlin": 267497, "Java": 22478}
package com.schwarz.crystalprocessor.processing import com.schwarz.crystalprocessor.Logger import javax.annotation.processing.ProcessingEnvironment interface WorkSet { fun preValidate(logger: Logger) fun loadModels(logger: Logger, env: ProcessingEnvironment) }
1
Kotlin
3
14
6737df3ffdde97826152d8239f403a01fa6db7af
273
crystal-map
MIT License
library/igdb/src/main/kotlin/ru/pixnews/library/igdb/dsl/RetryPolicy.kt
illarionov
305,333,284
false
null
/* * Copyright 2023 <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 ru.pixnews.igdbclient.dsl import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.minutes @IgdbClientDsl @Suppress("FLOAT_IN_ACCURATE_CALCULATIONS") public class RetryPolicy { /** * Enabled automatic retry on HTTP 429 "Too Many Requests" error. * * Set to `false` to handle this error manually. */ public var enabled: Boolean = true /** * Specifies the maximum number of attempts to retry a request. * * If set to `null` the request will be retried indefinitely. */ public var maxRequestRetries: Int? = 5 set(value) { check(value == null || value > 0) { "maxRequestRetries should be > 0" } field = value } /** * Initial retry interval. Applied before the first retry. * Also used to calculate intervals for next repetitions. * * When set to 0, all requests will be retried without delay. */ public var initialDelay: Duration = 25.milliseconds set(value) { check(value >= Duration.ZERO) { "initialDelay should be >= 0" } field = value } /** * Exponential delay scaling factor. * * If set to 1, the interval between retries will be [initialDelay]. */ public var factor: Float = 2f set(value) { check(value >= 1f) { "factor should be >= 1" } field = value } /** * Minimum and maximum value of the delay between retries. */ public var delayRange: ClosedRange<Duration> = Duration.ZERO..2.minutes /** * The relative jitter factor applied to the interval. * * * 0.0f: without a jitter. * * 1.0f: the final delay will be a random value from 0 to 2 * the current interval without jitter. */ public var jitterFactor: Float = 0.1f }
0
null
0
2
8912bf1116dd9fe94d110162ff9a302e93af1509
2,477
Pixnews
Apache License 2.0
src/main/kotlin/no/nav/familie/ef/sak/blankett/BlankettSteg.kt
navikt
206,805,010
false
null
package no.nav.familie.ef.sak.blankett import no.nav.familie.ef.sak.arbeidsfordeling.ArbeidsfordelingService import no.nav.familie.ef.sak.behandling.BehandlingRepository import no.nav.familie.ef.sak.behandling.BehandlingService import no.nav.familie.ef.sak.behandling.Saksbehandling import no.nav.familie.ef.sak.behandlingsflyt.steg.BehandlingSteg import no.nav.familie.ef.sak.behandlingsflyt.steg.StegType import no.nav.familie.ef.sak.behandlingsflyt.task.FerdigstillBehandlingTask import no.nav.familie.ef.sak.infrastruktur.exception.Feil import no.nav.familie.ef.sak.journalføring.JournalpostClient import no.nav.familie.ef.sak.repository.findByIdOrThrow import no.nav.familie.ef.sak.vedtak.TotrinnskontrollService import no.nav.familie.kontrakter.felles.journalpost.Journalposttype import no.nav.familie.prosessering.domene.TaskRepository import org.slf4j.LoggerFactory import org.springframework.stereotype.Service @Service class BlankettSteg( private val behandlingService: BehandlingService, private val behandlingRepository: BehandlingRepository, private val journalpostClient: JournalpostClient, private val arbeidsfordelingService: ArbeidsfordelingService, private val blankettRepository: BlankettRepository, private val totrinnskontrollService: TotrinnskontrollService, private val taskRepository: TaskRepository) : BehandlingSteg<Void?> { private val logger = LoggerFactory.getLogger(javaClass) override fun validerSteg(saksbehandling: Saksbehandling) { if (saksbehandling.steg != stegType()) { throw Feil("Behandling er i feil steg=${saksbehandling.steg}") } } override fun utførSteg(saksbehandling: Saksbehandling, data: Void?) { val journalposter = behandlingService.hentBehandlingsjournalposter(saksbehandling.id) val journalpostForBehandling = journalpostClient.hentJournalpost(journalposter.first().journalpostId) val personIdent = behandlingRepository.finnAktivIdent(saksbehandling.id) val enhet = arbeidsfordelingService.hentNavEnhetIdEllerBrukMaskinellEnhetHvisNull(personIdent) val blankettPdf = blankettRepository.findByIdOrThrow(saksbehandling.id).pdf.bytes val beslutter = totrinnskontrollService.hentBeslutter(saksbehandling.id) if (beslutter == null) { logger.info("steg=${stegType()} fant ikke beslutter på behandling=$saksbehandling") } val arkiverDokumentRequest = BlankettHelper.lagArkiverBlankettRequestMotInfotrygd(personIdent, blankettPdf, enhet, journalpostForBehandling.sak?.fagsakId, saksbehandling.id) val journalpostRespons = journalpostClient.arkiverDokument(arkiverDokumentRequest, beslutter) behandlingService.leggTilBehandlingsjournalpost(journalpostRespons.journalpostId, Journalposttype.N, saksbehandling.id) ferdigstillBehandling(saksbehandling) } private fun ferdigstillBehandling(saksbehandling: Saksbehandling) { taskRepository.save(FerdigstillBehandlingTask.opprettTask(saksbehandling)) } override fun stegType(): StegType = StegType.JOURNALFØR_BLANKETT }
7
Kotlin
2
0
79833410b98739f78b0c6019445e6502249cb0b2
3,509
familie-ef-sak
MIT License
feature/video-thumbnail-grid/src/main/java/io/filmtime/feature/video/thumbnail/grid/VideoThumbnailGridUiState.kt
moallemi
633,160,161
false
{"Kotlin": 522936, "Shell": 3102}
package io.filmtime.feature.video.thumbnail.grid data class VideoThumbnailGridUiState( val title: String, )
21
Kotlin
14
87
ad3eeed30bed20216a9fa12e34f06e43b70a74cc
111
Film-Time
MIT License
app/src/test/java/com/emrekose/videogames/ui/detail/GameDetailViewModelTest.kt
emrekose26
329,276,392
false
null
package com.emrekose.videogames.ui.detail import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.Observer import com.emrekose.videogames.common.Resource import com.emrekose.videogames.ui.model.GameDetailItem import com.emrekose.videogames.utils.MainCoroutineRule import com.google.common.truth.Truth import io.mockk.MockKAnnotations import io.mockk.coJustRun import io.mockk.coVerify import io.mockk.every import io.mockk.impl.annotations.InjectMockKs import io.mockk.impl.annotations.MockK import io.mockk.slot import io.mockk.spyk import io.mockk.verify import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.flow import kotlinx.coroutines.test.runBlockingTest import org.junit.Before import org.junit.Rule import org.junit.Test @ExperimentalCoroutinesApi class GameDetailViewModelTest { // Executes tasks in the Architecture Components in the same thread @get:Rule val instantTaskExecutorRule = InstantTaskExecutorRule() // Set the main coroutines dispatcher for unit testing. @get:Rule var mainCoroutineRule = MainCoroutineRule() @MockK private lateinit var useCase: GameDetailUseCase @InjectMockKs private lateinit var viewModel: GameDetailViewModel @Before fun setUp() { MockKAnnotations.init(this) } @Test fun `given loading state, when get game details, then verify loading state`() { // Given val mockedObserver = createMockedObserver() viewModel.gameDetailsLiveData.observeForever(mockedObserver) every { useCase.getGameDetails(1) } returns flow { emit(Resource.Loading) } // When viewModel.getGameDetails(1) // Then val slot = slot<Resource<GameDetailItem>>() verify { mockedObserver.onChanged(capture(slot)) } Truth.assertThat(slot.captured).isSameInstanceAs(Resource.Loading) verify { useCase.getGameDetails(1) } } @Test fun `given success state, when get game details, then verify data`() { // Given val mockedObserver = createMockedObserver() viewModel.gameDetailsLiveData.observeForever(mockedObserver) every { useCase.getGameDetails(1) } returns flow { emit(Resource.Success(createFakeGameItem())) } // When viewModel.getGameDetails(1) // Then val slot = slot<Resource<GameDetailItem>>() verify { mockedObserver.onChanged(capture(slot)) } Truth.assertThat(Resource.Success(createFakeGameItem()).data.name).isEqualTo("EsEs") verify { useCase.getGameDetails(1) } } @Test fun `given error state, when get game details, then verify error state`() { // given val mockedObserver = createMockedObserver() viewModel.gameDetailsLiveData.observeForever(mockedObserver) val exception = createException() every { useCase.getGameDetails(1) } returns flow { emit(Resource.Error(exception)) } // when viewModel.getGameDetails(1) // then val slot = slot<Resource<GameDetailItem>>() verify { mockedObserver.onChanged(capture(slot)) } Truth.assertThat(slot.captured).isEqualTo(Resource.Error(exception)) verify { useCase.getGameDetails(1) } } @Test fun `given game, when add to favorites, then verify added game`() { mainCoroutineRule.testDispatcher.runBlockingTest { // Given val game = GameDetailItem(26, "Test Game", 56, "19-09-2019", "bg.png", 12.6, "desc") coJustRun { useCase.addFavGameToDb(game) } // When viewModel.addGameToDb(game) // Then coVerify { useCase.addFavGameToDb(game) } } } @Test fun `given game, when delete game, then verify deleted game`() { // Given val game = GameDetailItem(54, "Test Game 2", 99, "01-02-2020", "bg.png", 19.7, "desc 2") coJustRun { useCase.deleteFavGameFromDb(game.gameId) } // When viewModel.deleteGameFromDb(game.gameId) // Then coVerify { useCase.deleteFavGameFromDb(game.gameId) } } private fun createMockedObserver(): Observer<Resource<GameDetailItem>> = spyk(Observer { }) private fun createException() = spyk(Exception("This is my error message")) private fun createFakeGameItem() = GameDetailItem( gameId = 26, name = "EsEs", backgroundImage = "eses.png", metacritic = 100, released = "19.06.1965", description = "Lorem ipsum dolor sit amet", rating = 99.9 ) }
0
Kotlin
0
2
9ff281a07df645bf8477f91f6350fed8bc6e8bb9
4,642
video-games-app
Apache License 2.0
src/main/kotlin/ch/rjenni/examscheduler/domain/collections/DestinationToSessionsMap.kt
RaphaelJenni
378,999,325
false
null
package ch.rjenni.examscheduler.domain.collections import java.util.concurrent.ConcurrentHashMap internal class DestinationToSessionsMap { private val destinationToSessionsMap: ConcurrentHashMap<String, MutableSet<String>> = ConcurrentHashMap() fun isEmpty() = destinationToSessionsMap.isEmpty() fun allSessionsForDestinationAreClosed(destination: String): Boolean = getDestinationSessionsCount(destination) == 0 fun isNewDestination(destination: String): Boolean { return !destinationToSessionsMap.containsKey(destination) } fun mapSessionToDestination(sessionId: String, destination: String) { destinationToSessionsMap.computeIfAbsent(destination) { HashSet() }.add(sessionId) } fun unmapSessionFromDestination(sessionId: String, destination: String) { val sessions = destinationToSessionsMap[destination] if (sessions != null) { sessions.remove(sessionId) if (sessions.isEmpty()) { destinationToSessionsMap.remove(destination) } } } private fun getDestinationSessionsCount(destination: String): Int = destinationToSessionsMap[destination]?.size ?: 0 override fun toString(): String { return destinationToSessionsMap.toString() } }
0
Kotlin
0
1
6ca24f7ce39a1a90d70e9660c3ba678022d31d99
1,294
springboot-websocket-connection-handler
Apache License 2.0
src/main/java/parser/SHTechParser2024.kt
YZune
232,583,513
false
{"Kotlin": 426459, "Java": 45879}
package main.java.parser import bean.Course import main.java.bean.TimeDetail import main.java.bean.TimeTable import org.jsoup.Jsoup import org.jsoup.nodes.Element import parser.Parser import java.lang.Integer.max import kotlin.math.min /** * @author trace1729 * @date 20240915 * @email [email protected] * 上海科技大学研究生教务导入-2024 **/ // 课程表网页链接 `https://graduate.shanghaitech.edu.cn/gsapp/sys/wdkbappshtech/*default/index.do` /** 2024年学校的教务系统更新, 之前的 parser 不能使用,于是就在 @auther mhk 的基础上做了些修改。 使用方式: 1. fork 本项目,git clone 到本地,用 IDEA 导入。 2. 需要配置 jdk17 环境。 3. 访问网页课表 (参加18行),使用 `CTRL+S` 将网页保存到本地 4. 在 `src/test/SHTechTest.kt` 中替换 File 中的文件路径为你保存在本地的网页路径 5. 运行后, 按照指示将终端的内容复制到 [name].wakeup_schedule 文件 6. 使用qq 将文件发送给手机 7. 手机上选择 「其他应用打开」,点击 「导入 wakeup」 8. 在 wakeup 程序界面,点击右上角的 菜单 键选择导入的课程表 Notice: 1. 为了正确设置作息,你需要手动修改 src/main/java/Generator 下的timePreference变量 2. colorScheme 变量中的值也需要做相应修改 Node -> 13, startDate -> 2024.9.16 1. 缺少单双周的检测 2. 缺少不连续周的识别 **/ class SHTechParser2024(source: String) : Parser(source) { override fun getNodes(): Int = 13 override fun getTableName(): String = "上科大导入" override fun generateTimeTable(): TimeTable { val timeList: ArrayList<TimeDetail> = SHTechParser2024.timeList return TimeTable("上科大作息", timeList) } override fun generateCourseList(): List<Course> { val contents = source.split("<head>", "</head>") val body = contents.last() val course = getCourse(body) // 合并相邻的两门课程 merge(course) return course } fun getCourse(html: String): ArrayList<Course> { val toReturn = ArrayList<Course>() val document = Jsoup.parse(html) // 获取课程表 val table = document.getElementById("jsTbl_01") // 课程表有14行,8列 val trs = table?.select("tr") ?: return arrayListOf() for ((row, tr) in trs.withIndex()) { val tds = tr.select("td") for ((col, td) in tds.withIndex()) { val rowspan = td.attr("rowspan").toIntOrNull() // rowspan == 1 说明当前单元格没有课程,跳过 if (rowspan != null && rowspan == 1) { continue } // 从单元格中提取课程信息 if (row in 1..13 && col in 2..8) { toReturn.addAll(extractCourseItem(td, row, col)) } } } return toReturn } private fun extractCourseItem(td: Element, row: Int, col: Int) : ArrayList<Course> { val courseItems = td.children() val courseList = ArrayList<Course>() courseItems.forEach { it -> val metadataDivs = it.children() val timeScale = metadataDivs[0].text() val courseName = metadataDivs[1].text() val teacher = metadataDivs[2].text() val location = metadataDivs[3].text() // 单双周处理 var typeOfCourse = 0 if (timeScale.contains("单")) { typeOfCourse = 1 } else if (timeScale.contains("双")) { typeOfCourse = 2 } val newTimeScale = timeScale.replace("双", "").replace("单", "") // println("$timeScale, $courseName, $teacher, $location") // 获取一节课的周次情况 val weekRange = getWeek(newTimeScale) weekRange.forEach { courseList.add( Course( name=courseName, day=col - 1, // need passing row room=location, teacher=teacher, startNode=row, endNode=row, startWeek=it.first, endWeek=it.second, type=typeOfCourse, startTime=timeList[row - 1].startTime, endTime=timeList[row - 1].endTime, ) ) } } return courseList } private fun getWeek( weekStr: String ): List<Pair<Int, Int>> { // 匹配 1-3, 4-10, 14周 val weekPattern = Regex("""\d+-\d+|\d+""") if (weekPattern.containsMatchIn(weekStr)) { // Extracting matched groups val matchResult = weekPattern.findAll(weekStr) val weekRanges = ArrayList<Pair<Int, Int>>() matchResult.forEach { val match = it.groupValues.first() if (match.contains("-")) weekRanges.add(Pair(match.split("-").first().toInt(), match.split("-").last().toInt())) else weekRanges.add(Pair(match.toInt(), match.toInt())) } return weekRanges } else { return ArrayList() } } private fun merge(data: ArrayList<Course>) { var i = 0 while (i < data.size) { val a = data[i] var j = i + 1 while (j < data.size) { val b = data[j] if ( a.name == b.name && a.startWeek == b.startWeek && a.endWeek == b.endWeek && a.room == b.room && a.teacher == b.teacher && a.day == b.day ) { a.startNode = min(a.startNode, b.startNode) a.endNode = max(a.endNode, b.endNode) data.remove(b) } else { j++ } } i++ } } companion object { val timeList: ArrayList<TimeDetail> = arrayListOf( TimeDetail(1, "08:15", "09:00"), TimeDetail(2, "09:10", "09:55"), TimeDetail(3, "10:15", "11:00"), TimeDetail(4, "11:10", "11:55"), TimeDetail(5, "13:00", "13:45"), TimeDetail(6, "13:55", "14:40"), TimeDetail(7, "15:00", "15:45"), TimeDetail(8, "15:55", "16:40"), TimeDetail(9, "16:50", "17:35"), TimeDetail(10, "18:00", "18:45"), TimeDetail(11, "18:55", "19:40"), TimeDetail(12, "19:50", "20:35"), TimeDetail(13, "20:45", "21:30") ) // Using this the override the timePreference in `Generator.kt` fun timePreference():String { var result = "[" timeList.forEach { result += "{" + "\"endTime\": \"${it.endTime}\"," + "\"node\": \"${it.node}\"," + "\"startTime\": \"${it.startTime}\"," + "\"tableTime\": \"${1}\"" + "}," } result += "]" return result.replace("},]","}]") } // Using this the override the colorScheme in `Generator.kt` val colorScheme = "{\"background\":\"\",\"courseTextColor\":-1,\"id\":1,\"itemAlpha\":60,\"itemHeight\":64,\"itemTextSize\":12,\"maxWeek\":20,\"nodes\":14,\"showOtherWeekCourse\":true,\"showSat\":true,\"showSun\":true,\"showTime\":false,\"startDate\":\"2024-9-18\",\"strokeColor\":-2130706433,\"sundayFirst\":false,\"tableName\":\"SHTech\",\"textColor\":-16777216,\"timeTable\":1,\"type\":0,\"widgetCourseTextColor\":-1,\"widgetItemAlpha\":60,\"widgetItemHeight\":64,\"widgetItemTextSize\":12,\"widgetStrokeColor\":-2130706433,\"widgetTextColor\":-16777216}" } }
1
Kotlin
135
146
2029c2688d2080e91b1a21c745889fa75e8fa539
7,520
CourseAdapter
MIT License
data/api/src/main/java/com/kazakago/blueprint/data/api/di/ApiModule.kt
KazaKago
60,256,062
false
null
package com.kazakago.blueprint.data.api.di import com.kazakago.blueprint.data.api.global.ApiRequester import com.kazakago.blueprint.data.api.hierarchy.GithubService import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) internal object ApiModule { @Singleton @Provides fun provideGithubService(apiRequester: ApiRequester): GithubService { return apiRequester.create(GithubService::class) } }
0
Kotlin
1
3
d5b752351bedf3aecca375251843e405c68f5151
562
blueprint_android
Apache License 2.0
app-main/src/test/kotlin/testcase/service/post/CreatePostServiceTest.kt
oen142
449,552,568
true
{"Kotlin": 584930, "Groovy": 179252, "Java": 88552, "Dart": 11943, "HTML": 1113, "Batchfile": 488, "Shell": 479, "Swift": 404, "Vim Snippet": 314, "Objective-C": 38}
/* * spring-message-board-demo * Refer to LICENCE.txt for licence details. */ package testcase.service.post import com.github.fj.board.exception.client.board.BoardNotFoundException import com.github.fj.board.exception.client.post.CannotCreatePostException import com.github.fj.board.exception.client.user.UserNotFoundException import com.github.fj.board.persistence.entity.board.Board import com.github.fj.board.persistence.entity.post.Attachment import com.github.fj.board.persistence.entity.post.Post import com.github.fj.board.persistence.model.board.BoardMode import com.github.fj.board.persistence.model.board.BoardStatus import com.github.fj.board.service.post.CreatePostService import com.github.fj.board.service.post.impl.CreatePostServiceImpl import com.nhaarman.mockitokotlin2.KArgumentCaptor import com.nhaarman.mockitokotlin2.argumentCaptor import com.nhaarman.mockitokotlin2.times import com.nhaarman.mockitokotlin2.verify import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.`is` import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource import org.mockito.Mockito.`when` import test.com.github.fj.board.endpoint.v1.post.dto.CreatePostRequestBuilder import test.com.github.fj.board.persistence.entity.board.BoardBuilder import test.com.github.fj.board.vo.auth.ClientAuthInfoBuilder import java.util.* import java.util.stream.Stream import kotlin.reflect.KClass /** * @author <NAME>(<EMAIL>) * @since 26 - Jul - 2020 */ class CreatePostServiceTest : AbstractPostServiceTestTemplate() { private lateinit var sut: CreatePostService @BeforeEach override fun setup() { super.setup() this.sut = CreatePostServiceImpl(userRepo, boardRepo, replyRepo, postRepo, attachmentRepo) } @Test fun `fail is user is not authenticated`() { // given: val clientInfo = ClientAuthInfoBuilder.createRandom() val req = CreatePostRequestBuilder.createRandom() // when: `when`(userRepo.findByLoginName(clientInfo.loginName)).thenReturn(null) // then: assertThrows<UserNotFoundException> { sut.create(UUID.randomUUID(), req, clientInfo) } } @Test fun `fail if board for given boardId is not present`() { // given: val (clientInfo, _, post) = postPreconditions() val req = CreatePostRequestBuilder.createRandom() val board = post.board // when: `when`(boardRepo.findByAccessId(board.accessId)).thenReturn(null) // then: assertThrows<BoardNotFoundException> { sut.create(board.accessId, req, clientInfo) } } @ParameterizedTest(name = "Cannot write post({1}) for \"{0}\" board") @MethodSource("testCannotCreatePost") fun `fail if board has some constraints`( constraint: String, expectedException: KClass<out Exception>, board: Board ) { // given: val (clientInfo, _) = prepareSelf() val targetBoardId = board.accessId val req = CreatePostRequestBuilder.createRandom() // when: `when`(boardRepo.findByAccessId(targetBoardId)).thenReturn(board) // then: Assertions.assertThrows(expectedException.java) { sut.create(targetBoardId, req, clientInfo) } } @Test fun `post is created if request is valid`() { // given: val (clientInfo, _, post) = postPreconditions() val req = CreatePostRequestBuilder.createRandom() val board = post.board // when: `when`(boardRepo.findByAccessId(board.accessId)).thenReturn(board) // then: sut.create(board.accessId, req, clientInfo) // and: val postCaptor: KArgumentCaptor<Post> = argumentCaptor() verify(postRepo, times(1)).save(postCaptor.capture()) val savedPost = postCaptor.firstValue // expect: "Post" assertThat(savedPost.title, `is`(req.title)) assertThat(savedPost.contents, `is`(req.contents)) assertThat(savedPost.mode, `is`(req.mode)) // and: val attachmentCaptor: KArgumentCaptor<List<Attachment>> = argumentCaptor() verify(attachmentRepo, times(1)).saveAll(attachmentCaptor.capture()) val savedAttachments = attachmentCaptor.firstValue // expect: "Attachments" assertThat(savedAttachments.size, `is`(req.attachments.size)) req.attachments.forEachIndexed { i, r -> assertThat("#$i attachment name is different", savedAttachments[i].name, `is`(r.name)) assertThat("#$i attachment mimeType is different", savedAttachments[i].mimeType, `is`(r.mimeType)) assertThat("#$i attachment uri is different", savedAttachments[i].uri, `is`(r.uri)) } } companion object { @JvmStatic @Suppress("unused") fun testCannotCreatePost(): Stream<Arguments> { return Stream.of( Arguments.of( "Status:CLOSED", BoardNotFoundException::class, BoardBuilder(BoardBuilder.createRandom()) .status(BoardStatus.CLOSED) .mode(BoardMode.FREE_STYLE) .build() ), Arguments.of( "Mode:READ_ONLY", CannotCreatePostException::class, BoardBuilder(BoardBuilder.createRandom()) .status(BoardStatus.NORMAL) .mode(BoardMode.READ_ONLY) .build() ) ) } } }
0
null
0
0
9a3860f780a1c994fcc7f2bed1525a0d73a3fa64
5,832
spring-board-demo
Beerware License
deck-common/src/main/kotlin/util/Constants.kt
SrGaabriel
444,842,991
false
null
package io.github.srgaabriel.deck.common.util public object Constants { public const val GuildedDomain: String = "www.guilded.gg" public const val GuildedGatewayPath: String = "/websocket/v1" public const val GuildedRestApiRoute: String = "/api/v1" public const val GuildedRestApi: String = "https://$GuildedDomain$GuildedRestApiRoute" public const val GuildedMedia: String = "https://media.guilded.gg" }
0
Kotlin
1
14
11b89730c01c3e620271c104dd745696c46be392
427
deck
MIT License
app/src/main/java/com/brandoncano/resistancecalculator/ui/screens/smd/SmdComponents.kt
bmcano
501,427,754
false
{"Kotlin": 215877}
package com.brandoncano.resistancecalculator.ui.screens.smd import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.brandoncano.resistancecalculator.R import com.brandoncano.resistancecalculator.model.smd.SmdResistor import com.brandoncano.resistancecalculator.ui.theme.ResistorCalculatorTheme import com.brandoncano.resistancecalculator.ui.theme.white import com.brandoncano.resistancecalculator.util.formatResistance import com.brandoncano.sharedcomponents.composables.AppCard import com.brandoncano.sharedcomponents.composables.AppComponentPreviews import com.brandoncano.sharedcomponents.text.textStyleLargeTitle import com.brandoncano.sharedcomponents.text.textStyleTitle @Composable fun SmdResistorLayout( resistor: SmdResistor, isError: Boolean, ) { Column( modifier = Modifier.padding(top = 24.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { Box( modifier = Modifier.clip(RoundedCornerShape(4.dp)), contentAlignment = Alignment.Center, ) { Image( painter = painterResource(id = R.drawable.img_smd_resistor), contentDescription = stringResource(id = R.string.content_description_app_icon), ) val text = if (isError) { stringResource(id = R.string.error_na) } else { resistor.code } Text( text = text, style = textStyleLargeTitle().white() ) } val text = when { resistor.isEmpty() -> stringResource(id = R.string.default_smd_value) isError -> stringResource(id = R.string.error_na) else -> resistor.formatResistance() } AppCard(modifier = Modifier.padding(top = 12.dp)) { Text( text = text, modifier = Modifier .align(Alignment.CenterHorizontally) .padding(top = 6.dp, bottom = 6.dp, start = 12.dp, end = 12.dp), style = textStyleTitle(), ) } } } @AppComponentPreviews @Composable private fun SmdResistorLayoutPreview() { ResistorCalculatorTheme { val resistor = SmdResistor(code = "1R4") SmdResistorLayout(resistor, false) } }
4
Kotlin
0
1
32bf41f079990b700059a1ce7adef146c91e525c
2,841
ResistanceCalculatorApp
MIT License
buildSrc/src/main/kotlin/Versions.kt
tobyzulka
681,164,997
false
null
// Version Depedencies object Versions { object Androidx { const val APP_COMPAT = "1.6.1" const val LIFECYCLE = "2.6.1" const val CORE_KTX = "1.10.1" const val WORK_MANAGER = "2.3.0" const val BROWSER = "1.2.0" const val ROOM = "2.2.3" } object Test { const val JUNIT = "4.13.2" const val JUNIT_EXT = "1.1.5" const val ESPRESSO_CORE = "3.5.1" } object Compose { const val COMPOSE_ACTIVITY_VERSION = "1.7.2" const val COMPOSE_MATERIAL_3_VERSION = "1.1.1" const val COMPOSE_MATERIAL_VERSION = "1.5.0" const val COMPOSE_UI_VERSION = "1.4.3" const val COMPOSE_BOMB = "2023.08.00" const val COMPOSE_VIEWMODEL_VERSION = "2.6.1" const val COMPOSE_PAGING_VERSION = "3.2.0" } object Koin { const val KOIN_ANDROID_VERSION = "3.4.3" const val KOIN_ANDROIDX_COMPOSE_VERSION = "3.4.6" } object NavigationCompose { const val NAVIGATION_COMPOSE_VERSION = "2.6.0" } const val COIL_COMPOSE_VERSION = "2.3.0" const val MATERIAL_ANDROID = "1.9.0" const val COROUTINES_ANDROID = "1.7.1" const val KOTLIN_COROUTINE_CORE = "1.7.1" const val TIMBER = "5.0.1" const val LOGGER = "2.2.0" const val LANDSCAPIST_COIL = "1.4.1" const val RETROFIT = "2.9.0" const val MOSHI = "1.14.0" const val OKHTTP3 = "4.9.3" }
0
Kotlin
0
0
112d744c317277729f7c87bdd42569c32aac1af4
1,427
OniNews
MIT License
T0D0/app/src/main/java/com/codingtho/t0d0/ui/screen/viewModel/MainScreenViewModel.kt
codingtho
852,589,581
false
{"Kotlin": 32228}
package com.codingtho.t0d0.ui.screen.viewModel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.codingtho.t0d0.data.repository.TaskRepository import com.codingtho.t0d0.data.repository.model.Task import com.codingtho.t0d0.data.repository.model.toEntity import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class MainScreenViewModel @Inject constructor( private val taskRepository: TaskRepository ) : ViewModel() { private val _isLoading: MutableStateFlow<Boolean> = MutableStateFlow(true) val isLoading: StateFlow<Boolean> get() = _isLoading.asStateFlow() private val _title: MutableStateFlow<String> = MutableStateFlow("") val title: StateFlow<String> = _title.asStateFlow() private val _showInputError: MutableStateFlow<Boolean> = MutableStateFlow(false) val showInputError: StateFlow<Boolean> get() = _showInputError.asStateFlow() private val _isAddTaskDialogOpen: MutableStateFlow<Boolean> = MutableStateFlow(false) val isAddTaskDialogOpen: StateFlow<Boolean> get() = _isAddTaskDialogOpen.asStateFlow() private val _isEditDialogOpen: MutableStateFlow<Boolean> = MutableStateFlow(false) val isEditDialogOpen: StateFlow<Boolean> get() = _isEditDialogOpen.asStateFlow() private val _isDeleteTaskDialogOpen: MutableStateFlow<Boolean> = MutableStateFlow(false) val isDeleteTaskDialogOpen: StateFlow<Boolean> get() = _isDeleteTaskDialogOpen.asStateFlow() private val _selectedTask: MutableStateFlow<Task?> = MutableStateFlow(null) val selectedTask: StateFlow<Task?> get() = _selectedTask.asStateFlow() private val _notDoneTasks: MutableStateFlow<List<Task>> = MutableStateFlow(emptyList()) val notDoneTasks: StateFlow<List<Task>> get() = _notDoneTasks.asStateFlow() private val _doneTasks: MutableStateFlow<List<Task>> = MutableStateFlow(emptyList()) val doneTasks: StateFlow<List<Task>> get() = _doneTasks.asStateFlow() private val _progressPercentage: MutableStateFlow<Int> = MutableStateFlow(0) val progressPercentage: StateFlow<Int> get() = _progressPercentage.asStateFlow() init { refreshTasks() } fun onTitleChange(newTitle: String) { _title.value = newTitle } fun validateInput(): Boolean { _showInputError.value = _title.value.isEmpty().or(_title.value.isBlank()) return _showInputError.value } private fun clearInput() { _title.value = "" _showInputError.value = false } fun initInput(task: Task) { _title.value = task.title } fun openAddTaskDialog() { _isAddTaskDialogOpen.value = true } fun closeAddTaskDialog() { _isAddTaskDialogOpen.value = false clearInput() } fun openEditDialog(task: Task) { _selectedTask.value = task _isEditDialogOpen.value = true } fun closeEditDialog() { _selectedTask.value = null _isEditDialogOpen.value = false clearInput() } fun openDeleteTaskDialog(task: Task) { _selectedTask.value = task _isDeleteTaskDialogOpen.value = true } fun closeDeleteTaskDialog() { _selectedTask.value = null _isDeleteTaskDialogOpen.value = false } fun addTask() { val task = Task(title = title.value) viewModelScope.launch { taskRepository.insertTask(task) refreshTasks() } } fun editTask() { viewModelScope.launch { _selectedTask.value.let { task -> taskRepository.insertTask(task!!.copy(title = title.value)) refreshTasks() } } } fun deleteTask() { viewModelScope.launch { _selectedTask.value.let { task -> taskRepository.deleteTask(task!!.toEntity()) refreshTasks() } } } private fun refreshTasks() { viewModelScope.launch { _notDoneTasks.value = taskRepository.getNotDoneTasks() _doneTasks.value = taskRepository.getDoneTasks() updateProgressPercentage() delay(700) _isLoading.value = false } } fun markAsDone(task: Task) { viewModelScope.launch { taskRepository.insertTask(task.copy(done = true)) refreshTasks() } } fun unmarkAsDone(task: Task) { viewModelScope.launch { taskRepository.insertTask(task.copy(done = false)) refreshTasks() } } private fun updateProgressPercentage() { val totalTasks = _notDoneTasks.value.size + _doneTasks.value.size val completedTasks = _doneTasks.value.size _progressPercentage.value = if (totalTasks == 0) 0 else (completedTasks * 100) / totalTasks } }
0
Kotlin
0
0
235fbc0ffb9b3f11f1d1bd68acc741e6544444d1
5,068
T0D0
MIT License
app/src/main/java/com/example/android/guesstheword/screens/game/GameFragment.kt
A7MeDG0L0L
814,106,007
false
{"Kotlin": 21746}
/* * Copyright 2018, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.guesstheword.screens.game import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import androidx.lifecycle.observe import androidx.navigation.fragment.NavHostFragment.findNavController import com.example.android.guesstheword.R import com.example.android.guesstheword.databinding.GameFragmentBinding /** * Fragment where the game is played */ class GameFragment : Fragment() { private lateinit var binding: GameFragmentBinding lateinit var viewModel: GameViewModel override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate view and obtain an instance of the binding class binding = DataBindingUtil.inflate( inflater, R.layout.game_fragment, container, false ) Log.i("GameViewModel","OnCreated ViewModel Providers") viewModel = ViewModelProviders.of(this).get(GameViewModel::class.java) binding.correctButton.setOnClickListener { viewModel.onCorrect() } binding.timerText.text = viewModel.countDown.toString() binding.skipButton.setOnClickListener { viewModel.onSkip() } viewModel.score.observe(viewLifecycleOwner, Observer {newScore -> binding.scoreText.text = newScore.toString() }) viewModel.word.observe(viewLifecycleOwner, Observer { newWord -> binding.wordText.text = newWord.toString() }) viewModel.eventGameFinished.observe(viewLifecycleOwner, Observer { gameFinish -> gameFinished() viewModel.onGameFinished() }) return binding.root } /** * Called when the game is finished */ private fun gameFinished() { val action = GameFragmentDirections.actionGameToScore() findNavController(this).navigate(action) } // /** Methods for updating the UI **/ // // private fun updateWordText() { // binding.wordText.text = viewModel.word.value // // } // // private fun updateScoreText() { // binding.scoreText.text = viewModel.score.toString() // } }
0
Kotlin
0
0
5eafe50d26e5ab2431ac0425c382c8542d0676fb
3,154
andfun-kotlin-guess-it
Apache License 2.0
src/main/kotlin/com/stepanov/bbf/bugfinder/mutator/transformations/ChangeVarToNull.kt
mandelshtamd
249,374,670
true
{"Kotlin": 7965847}
package com.stepanov.bbf.bugfinder.mutator.transformations import org.jetbrains.kotlin.psi.KtExpression import com.stepanov.bbf.bugfinder.util.getAllPSIChildrenOfType import com.stepanov.bbf.bugfinder.util.getRandomBoolean class ChangeVarToNull : Transformation() { override fun transform() { file.getAllPSIChildrenOfType<KtExpression>() .filter { getRandomBoolean(16) } .forEach { checker.replacePSINodeIfPossible(file, it, psiFactory.createExpression("null")) } } }
0
Kotlin
0
1
da010bdc91c159492ae74456ad14d93bdb5fdd0a
520
bbfgradle
Apache License 2.0
src/main/kotlin/com/github/cnrture/quickprojectwizard/cmparch/CMPImageLibrary.kt
cnrture
849,704,826
false
{"Kotlin": 138780}
package com.github.cnrture.quickprojectwizard.cmparch enum class CMPImageLibrary { None, Coil, Kamel }
2
Kotlin
2
32
f52310e5738c0974bf5e6b3e5c51c5b0070d2316
104
QuickProjectWizard
Apache License 2.0
app/src/main/java/me/wsj/fengyun/db/dao/CacheDao.kt
wsjAliYun
283,814,909
false
null
package me.wsj.fengyun.db.dao import androidx.room.* import me.wsj.fengyun.db.entity.CacheEntity @Dao interface CacheDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun saveCache(cache: CacheEntity): Long @Query("select *from cache where `key`=:key") fun getCache(key: String): CacheEntity? @Delete fun deleteCache(cache: CacheEntity): Int }
3
Java
74
514
da4cba77a13cf10878c388bc67d96f9bc8a4230d
378
kms
Apache License 2.0
src/main/kotlin/com/finnhub/api/models/Estimate.kt
njsoly
362,377,870
true
{"Kotlin": 237238, "Shell": 59}
/** * Finnhub API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.finnhub.api.models import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable /** * * @param revenueAvg Average revenue estimates. * @param revenueHigh Highest estimate. * @param revenueLow Lowest estimate. * @param numberAnalysts Number of Analysts. * @param period Period. */ @Serializable data class Estimate ( /* Average revenue estimates. */ @SerialName("revenueAvg") val revenueAvg: Long? = null, /* Highest estimate. */ @SerialName("revenueHigh") val revenueHigh: Long? = null, /* Lowest estimate. */ @SerialName("revenueLow") val revenueLow: Long? = null, /* Number of Analysts. */ @SerialName("numberAnalysts") val numberAnalysts: Long? = null, /* Period. */ @SerialName("period") val period: String? = null ) { companion object { private const val serialVersionUID: Long = 123 } }
0
Kotlin
0
0
606005fb8f2d1255298a370ea84f2685c37c7cd1
1,245
finnhub-kotlin
Apache License 2.0
RetenoSdkCore/src/main/java/com/reteno/core/data/remote/model/user/AddressRemote.kt
reteno-com
545,381,514
false
{"Kotlin": 1251795, "Java": 165207, "HTML": 17807, "Shell": 379}
package com.reteno.core.data.remote.model.user import com.google.gson.annotations.SerializedName internal data class AddressRemote( @SerializedName("region") val region: String? = null, @SerializedName("town") val town: String? = null, @SerializedName("address") val address: String? = null, @SerializedName("postcode") val postcode: String? = null )
1
Kotlin
1
1
f52fc040ae94f5830e874f0f41e36fba35e3a276
384
reteno-mobile-android-sdk
MIT License
kommons-core/src/commonMain/kotlin/com/bkahlert/kommons/lists.kt
bkahlert
323,048,013
false
null
package com.bkahlert.kommons /** Shortcut for `subList(range.first, range.last+1)` */ @Suppress("NOTHING_TO_INLINE") public inline fun <T> List<T>.subList(range: IntRange): List<T> = subList(range.first, range.end) /** * Returns a new list wrapping this list with the following differences: * 1) Negative indices are supported and start from the end of this list. * For example `this[-1]` returns the last element, `this[-2]` returns the second, ... * 2) Modulus operation is applied, that is, * `listOf("a","b","c").withNegativeIndices(4)` returns `a`. `this[-4]` would return `c`. */ public fun <T> List<T>.withNegativeIndices(): List<T> = object : List<T> by this { override fun get(index: Int): T = this@withNegativeIndices[index.mod(size)] }
0
Kotlin
0
13
35002a02e0702157c5fa906a0e087ff0576a53ca
777
kommons
MIT License
core/kmpp/libJs/src/jsMain/kotlin/utils/Logging.kt
kanawish
480,934,685
false
null
package com.kanastruk.utils import kotlin.js.Console fun debug(key:String, block: Console.()->Unit) { if(SearchParamHelper.isDebug(key)) console.block() } fun debug(block: Console.()->Unit) { if(SearchParamHelper.isDebug()) console.block() } fun verbose(block: Console.()->Unit) { if(SearchParamHelper.isVerbose()) console.block() } // See https://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid fun uuidv4():String { val jsUUID = js("'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n" + " var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);\n" + " return v.toString(16);\n" + " })") return jsUUID }
3
Kotlin
1
1
24da293e6511f80d1678963bfbfe8fe4a4ad49e0
718
ks-community
MIT License
template-mpp/template-mpp-lib/src/linuxX64Main/kotlin/hello/Hello.linux64.kt
langara
124,675,080
false
null
@file:Suppress("PackageDirectoryMismatch") package pl.mareklangiewicz.templatefull actual fun helloPlatform(): String = "Hello Native Linux 64 World!".also { println(it) }
0
null
2
5
c2d18dc565cf986246b8a6a5d6b6f296f7fa000b
174
DepsKt
Apache License 2.0
app/src/main/java/com/example/moviedb/data/constants/MovieListType.kt
RezaKoerniawan
477,964,911
false
{"Kotlin": 234004}
package com.example.moviedb.data.constants enum class MovieListType(val type: Int) { POPULAR(0), TOP_RATED(1), FAVORITE(2) }
0
Kotlin
0
0
afc3cdbea0dce671a60fd869aef265daf83909db
137
MovieDB-app
Apache License 2.0
app/src/main/java/xyz/sachil/essence/vm/TypeViewModel.kt
sachil
52,771,681
false
null
package xyz.sachil.essence.vm import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import androidx.lifecycle.viewModelScope import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.koin.core.component.KoinApiExtension import org.koin.core.component.inject import xyz.sachil.essence.model.net.bean.Type import xyz.sachil.essence.repository.TypeRepository import xyz.sachil.essence.util.Utils @KoinApiExtension class TypeViewModel : BaseViewModel() { private val typeRepository: TypeRepository by inject() private val internalTypes = MutableLiveData<List<Type>>() val types: LiveData<List<Type>> = Transformations.map(internalTypes) { it } fun getTypes(category: Utils.Category) = viewModelScope.launch(Dispatchers.IO + exceptionHandler.getHandler()) { val result = typeRepository.getTypes(category) internalTypes.postValue(result) } override fun onExceptionHandled() { } }
0
Kotlin
0
0
ae80cdd14529844cbb539ffe01edddd3e6c696a7
1,085
Essence
Apache License 2.0
app/src/main/java/net/schwiz/marvel/domain/DomainError.kt
nschwermann
219,101,983
false
null
package net.schwiz.marvel.domain sealed class DomainError(val cause : Throwable? = null, val message : String? = null) { class UnknownError(cause: Throwable? = null, message: String? = null) : DomainError(cause = cause, message = message) }
0
Kotlin
0
0
714d83244b3a60bde0eb0b810d4a2fd23ff07dac
246
marvel
Apache License 2.0
designer/src/main/kotlin/com/griffithindustries/samples/designer/MarkdownWorkspace.kt
paul-griffith
310,073,618
false
null
package com.griffithindustries.samples.designer import com.griffithindustries.samples.common.* import com.inductiveautomation.ignition.client.icons.* import com.inductiveautomation.ignition.common.project.resource.* import com.inductiveautomation.ignition.designer.model.* import com.inductiveautomation.ignition.designer.tabbedworkspace.* import com.inductiveautomation.ignition.designer.workspacewelcome.* import java.util.* import javax.swing.* class MarkdownWorkspace(context: DesignerContext) : TabbedResourceWorkspace(context, ResourceDescriptor.builder() .resourceType(MarkdownResource.RESOURCE_TYPE) .nounKey("markdown.resource.noun") .rootFolderText("Markdown Notes") .rootIcon(VectorIcons.get("resource-note")) .navTreeLocation(999) .build()) { override fun getKey() = "markdownEditor" override fun newResourceEditor(resourcePath: ResourcePath): ResourceEditor<MarkdownResource> { return MarkdownEditor(this, resourcePath) } private val newMarkdownNote: (ProjectResourceBuilder) -> Unit = { builder -> builder.putData(MarkdownResource.DATA_KEY, "Enter a note".toByteArray()) } override fun addNewResourceActions(folderNode: ResourceFolderNode, menu: JPopupMenu) { menu.add(object : NewResourceAction(this, folderNode, newMarkdownNote) { override fun newResourceName() = "note" init { putValue(Action.NAME, "New Note") putValue(Action.SMALL_ICON, VectorIcons.get("resource-note")) } }) } override fun createWorkspaceHomeTab(): Optional<JComponent> { return object : WorkspaceWelcomePanel("Markdown Notes Workspace Title", null, null) { override fun createPanels(): List<JComponent> { return listOf( ResourceBuilderPanel( context, "markdown note", MarkdownResource.RESOURCE_TYPE.rootPath(), listOf( ResourceBuilderDelegate.build( "markdown note", VectorIcons.get("resource-note"), newMarkdownNote ) ), this@MarkdownWorkspace::open ), RecentlyModifiedTablePanel( context, MarkdownResource.RESOURCE_TYPE, "markdown notes", this@MarkdownWorkspace::open ) ) } }.toOptional() } }
0
Kotlin
0
2
1c088ad2e984d9a749977d4552d0da91f41b9692
2,723
markdown-resources
Apache License 2.0
mediator_old/src/main/kotlin/no/nav/dagpenger/behandling/serder/JsonNodeExt.kt
navikt
571,475,339
false
{"Kotlin": 199091, "Mustache": 4238, "HTML": 687, "Dockerfile": 77}
package no.nav.dagpenger.behandling.serder import com.fasterxml.jackson.databind.JsonNode import java.util.UUID fun JsonNode.asUUID(): UUID = this.asText().let { UUID.fromString(it) }
1
Kotlin
0
0
ada9fc0e965dde27c358c036a78814b3d8071afd
186
dp-behandling
MIT License
domain/src/main/java/org/oppia/domain/classify/rules/ratioinput/RatioInputIsEquivalentRuleClassifierProvider.kt
The-Fuse
290,502,917
true
{"Kotlin": 3041512, "Starlark": 85090, "Java": 27484, "Shell": 1855}
package org.oppia.domain.classify.rules.ratioinput import org.oppia.app.model.InteractionObject import org.oppia.app.model.RatioExpression import org.oppia.domain.classify.RuleClassifier import org.oppia.domain.classify.rules.GenericRuleClassifier import org.oppia.domain.classify.rules.RuleClassifierProvider import org.oppia.domain.util.toSimplestForm import javax.inject.Inject /** * Provider for a classifier that determines whether two object are equal by converting them into * their lowest form as per the ratio input interaction. */ internal class RatioInputIsEquivalentRuleClassifierProvider @Inject constructor( private val classifierFactory: GenericRuleClassifier.Factory ) : RuleClassifierProvider, GenericRuleClassifier.SingleInputMatcher<RatioExpression> { override fun createRuleClassifier(): RuleClassifier { return classifierFactory.createSingleInputClassifier( InteractionObject.ObjectTypeCase.RATIO_EXPRESSION, "x", this ) } override fun matches(answer: RatioExpression, input: RatioExpression): Boolean { return answer.toSimplestForm() == input.toSimplestForm() } }
0
null
0
0
6ee99027a169c501855271b80c0a86ab2cf84420
1,133
oppia-android
Apache License 2.0
SearchCountryNames/app/src/main/java/com/example/searchcountrynames/model/CountryModel.kt
fairoozp
356,848,633
false
null
package com.example.searchcountrynames.model data class CountryModel (val name : String)
0
Kotlin
0
1
09bfb87ce91f6ccb6f8b08534b127f77116a5179
90
Android_Kotlin_projects
MIT License
1935.Maximum Number of Words You Can Type.kt
sarvex
842,260,390
false
{"Kotlin": 1775678, "PowerShell": 418}
internal class Solution { fun canBeTypedWords(text: String, brokenLetters: String): Int { val s = BooleanArray(26) for (c in brokenLetters.toCharArray()) { s[c.code - 'a'.code] = true } var ans = 0 for (w in text.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) { for (c in w.toCharArray()) { if (s[c.code - 'a'.code]) { --ans break } } ++ans } return ans } }
0
Kotlin
0
0
71f5d03abd6ae1cd397ec4f1d5ba04f792dd1b48
471
kotlin-leetcode
MIT License
browser-kotlin/src/jsMain/kotlin/web/svg/SVGTransform.kt
karakum-team
393,199,102
false
null
// Automatically generated - do not modify! package web.svg import web.geometry.DOMMatrix import web.geometry.DOMMatrix2DInit import web.geometry.DOMMatrixReadOnly sealed external class SVGTransform { val angle: Double val matrix: DOMMatrix val type: Short fun setMatrix(matrix: DOMMatrix2DInit = definedExternally) fun setMatrix(matrix: DOMMatrixReadOnly /* DOMMatrix2DInit */) fun setRotate( angle: Number, cx: Number, cy: Number, ) fun setScale( sx: Number, sy: Number, ) fun setSkewX(angle: Number) fun setSkewY(angle: Number) fun setTranslate( tx: Number, ty: Number, ) val SVG_TRANSFORM_UNKNOWN: Short val SVG_TRANSFORM_MATRIX: Short val SVG_TRANSFORM_TRANSLATE: Short val SVG_TRANSFORM_SCALE: Short val SVG_TRANSFORM_ROTATE: Short val SVG_TRANSFORM_SKEWX: Short val SVG_TRANSFORM_SKEWY: Short companion object { val SVG_TRANSFORM_UNKNOWN: Short val SVG_TRANSFORM_MATRIX: Short val SVG_TRANSFORM_TRANSLATE: Short val SVG_TRANSFORM_SCALE: Short val SVG_TRANSFORM_ROTATE: Short val SVG_TRANSFORM_SKEWX: Short val SVG_TRANSFORM_SKEWY: Short } }
0
Kotlin
6
22
340fa5d93f874ebf14810ab797a9808af574e058
1,255
types-kotlin
Apache License 2.0
app/src/main/kotlin/org/libsql/app/App.kt
CodingDoug
629,809,959
false
null
package org.libsql.app import kotlinx.coroutines.runBlocking import org.libsql.client.Client fun main() { val envUrl = System.getenv("LIBSQL_DB_URL") val envAuthToken = System.getenv("LIBSQL_AUTH_TOKEN") val client = Client.build { url = envUrl authToken = envAuthToken } // val client = Client.BuilderJ() // .url("https://asdf") // .authToken("adf") // .build() client.use { client -> runBlocking { val rss = client.batch(arrayOf("select * from users")) println(rss) } } println("Done") }
0
Kotlin
0
0
8ff89a51b1449900c29ffeffa6bacf01f5521624
603
libsql-client-kotlin
MIT License
libhulk/src/main/java/com/madreain/libhulk/components/base/IPage.kt
madreain
221,871,750
false
null
package com.madreain.libhulk.components.base /** * 页面接口 * 一个与NetHelper交互的页面应该包括IPageContext(获取context)、IPageInit(加载交互)等功能 * 可以通过activity、fragment、view等来实现 */ interface IPage : IPageContext, IPageInit
5
Kotlin
16
114
43a7297b146d5edb71366a7f21b9d1b211fbbe6d
205
AACHulk
Apache License 2.0
src/main/kotlin/fr/alasdiablo/spring/database/api/TableDefinitions.kt
AlasDiablo
571,129,307
false
{"Kotlin": 11008}
package fr.alasdiablo.spring.database.api interface TableDefinitions { fun getDefinitions(): Map<String, Type> fun getType(name: String): Type? fun setType(name: String, type: Type) enum class Type { STRING, INTEGER } }
0
Kotlin
0
0
78b5252cc2b82c03a181b65cc0f1e05ac26efc01
248
Spring-DataBase
MIT License
src/main/kotlin/io/realworld/app/config/DbConfig.kt
Rudge
177,908,216
false
null
package io.realworld.app.config import com.zaxxer.hikari.HikariConfig import com.zaxxer.hikari.HikariDataSource import org.h2.tools.Server import org.jetbrains.exposed.sql.Database object DbConfig { fun setup(jdbcUrl: String, username: String, password: String) { Server.createPgServer().start() val config = HikariConfig().also { config -> config.jdbcUrl = jdbcUrl config.username = username config.password = password } Database.connect(HikariDataSource(config)) } }
1
Kotlin
18
98
60a2c4fdb2f04f47d1085a6c49f699a3d50fa949
547
kotlin-ktor-realworld-example-app
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/evidently/CfnFeaturePropsDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.evidently import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.evidently.CfnFeatureProps @Generated public fun buildCfnFeatureProps(initializer: @AwsCdkDsl CfnFeatureProps.Builder.() -> Unit): CfnFeatureProps = CfnFeatureProps.Builder().apply(initializer).build()
1
Kotlin
0
0
e9a0ff020b0db2b99e176059efdb124bf822d754
397
aws-cdk-kt
Apache License 2.0
android/app/src/main/java/com/cyrillrx/library/ui/gamedetail/GameDetailActivity.kt
cyrillrx
476,088,931
false
{"Kotlin": 35812}
package com.cyrillrx.library.ui.gamedetail import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import coil.annotation.ExperimentalCoilApi @ExperimentalCoilApi class GameDetailActivity : ComponentActivity() { private val viewModel by viewModels<GameDetailViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { GameDetailScreen(viewModel) } val gameId = intent.getStringExtra(ARG_GAME_ID)!! viewModel.refresh(gameId) } companion object { const val ARG_GAME_ID = "game_id" } }
0
Kotlin
0
0
1ea90c1ca871768e6216ea28baf4c18fc4415298
716
game-library
MIT License
src/test/sampleAssignments/testKotlinProj2/src/main/kotlin/org/dropproject/samples/samplekotlinassignment/Main.kt
drop-project-edu
173,646,045
false
{"Kotlin": 950084, "JavaScript": 219974, "HTML": 135757, "Java": 62901, "CSS": 17181, "Dockerfile": 443, "Procfile": 88}
package org.dropproject.samples.samplekotlinassignment fun findMax(numbers: Array<Int>): Int { var max = Int.MIN_VALUE for (number in numbers) { if (number > max) { max = number } } return max } fun main(args: Array<String>) { val numbers = arrayOf( 1, 3, 7, 4, 2) println("max = ${findMax(numbers)}") }
6
Kotlin
13
21
84c798ddacef829c4472e2a37e162c03f1a14d8c
358
drop-project
Apache License 2.0
src/test/sampleAssignments/testKotlinProj2/src/main/kotlin/org/dropproject/samples/samplekotlinassignment/Main.kt
drop-project-edu
173,646,045
false
{"Kotlin": 950084, "JavaScript": 219974, "HTML": 135757, "Java": 62901, "CSS": 17181, "Dockerfile": 443, "Procfile": 88}
package org.dropproject.samples.samplekotlinassignment fun findMax(numbers: Array<Int>): Int { var max = Int.MIN_VALUE for (number in numbers) { if (number > max) { max = number } } return max } fun main(args: Array<String>) { val numbers = arrayOf( 1, 3, 7, 4, 2) println("max = ${findMax(numbers)}") }
6
Kotlin
13
21
84c798ddacef829c4472e2a37e162c03f1a14d8c
358
drop-project
Apache License 2.0
src/test/kotlin/io/vlang/lang/typing/TypingTestBase.kt
vlang
754,996,747
false
null
package io.vlang.lang.typing import com.intellij.openapi.actionSystem.IdeActions import com.intellij.testFramework.fixtures.BasePlatformTestCase abstract class TypingTestBase : BasePlatformTestCase() { override fun getTestDataPath() = "src/test/resources/typing" fun type(text: String, stringToType: String, after: String) { myFixture.configureByText("a.v", text) myFixture.type(stringToType) myFixture.checkResult(after) } fun delete(text: String, after: String) { myFixture.configureByText("a.v", text) myFixture.performEditorAction(IdeActions.ACTION_EDITOR_BACKSPACE) myFixture.checkResult(after) } }
5
null
5
33
a0d2cbfa63b995d93aaca3c80676f0c2f9bef117
676
intellij-v
MIT License
data/src/main/java/com/example/data/cache/models/BookCache.kt
yusuf0405
484,801,816
false
{"Kotlin": 1421124}
package com.example.data.cache.models import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey import java.util.* @Entity( tableName = "books", indices = [ Index("id"), Index("title", "id"), Index("author", "id"), Index("public_year", "id"), Index("poster", "id"), Index("saved_status", "id"), ] ) data class BookCache( @PrimaryKey var id: String, @ColumnInfo(name = "author") var author: String, @ColumnInfo(name = "description") val description: String, @ColumnInfo(name = "created_at") var createdAt: Date, @ColumnInfo(name = "page") var page: Int, @ColumnInfo(name = "is_exclusive") var isExclusive: Boolean, @ColumnInfo(name = "public_year") var publicYear: String, @ColumnInfo(name = "book") var book: BookPdfCache, @ColumnInfo(name = "genres") var genres: List<String>, @ColumnInfo(name = "title") var title: String, @ColumnInfo(name = "chapter_count") var chapterCount: Int, @ColumnInfo(name = "poster") var poster: BookPosterCache, @ColumnInfo(name = "updated_at") var updatedAt: Date, @ColumnInfo(name = "saved_status") var savedStatus: SavedStatusCache, ) enum class SavedStatusCache { SAVED, NOT_SAVED, SAVING } data class BookPdfCache( var name: String, var type: String, var url: String, ) data class BookPosterCache( var name: String, var url: String, )
1
Kotlin
1
3
e1ecdb14efbf7a25643ded1319841712f5e12a3b
1,484
BookLoverFinalApp
Apache License 1.1
ui/src/main/java/de/markusressel/kutepreferences/ui/views/KuteStyleManager.kt
markusressel
129,962,741
false
null
package de.markusressel.kutepreferences.ui.views import android.util.Log import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import de.markusressel.kutepreferences.core.KuteNavigator import de.markusressel.kutepreferences.core.preference.KutePreferenceListItem import de.markusressel.kutepreferences.core.preference.action.ActionPreferenceBehavior import de.markusressel.kutepreferences.core.preference.action.KuteAction import de.markusressel.kutepreferences.core.preference.bool.BooleanPreferenceBehavior import de.markusressel.kutepreferences.core.preference.bool.KuteBooleanPreference import de.markusressel.kutepreferences.core.preference.category.KuteCategory import de.markusressel.kutepreferences.core.preference.category.KuteCategoryBehavior import de.markusressel.kutepreferences.core.preference.color.ColorPreferenceBehavior import de.markusressel.kutepreferences.core.preference.color.KuteColorPreference import de.markusressel.kutepreferences.core.preference.date.DatePreferenceBehavior import de.markusressel.kutepreferences.core.preference.date.KuteDatePreference import de.markusressel.kutepreferences.core.preference.number.KuteNumberPreference import de.markusressel.kutepreferences.core.preference.number.NumberPreferenceBehavior import de.markusressel.kutepreferences.core.preference.number.range.FloatRangeSliderPreferenceBehavior import de.markusressel.kutepreferences.core.preference.number.range.KuteFloatRangePreference import de.markusressel.kutepreferences.core.preference.number.slider.KuteSliderPreference import de.markusressel.kutepreferences.core.preference.number.slider.NumberSliderPreferenceBehavior import de.markusressel.kutepreferences.core.preference.section.KuteSection import de.markusressel.kutepreferences.core.preference.section.KuteSectionBehavior import de.markusressel.kutepreferences.core.preference.select.KuteMultiSelectStringPreference import de.markusressel.kutepreferences.core.preference.select.KuteSingleSelectStringPreference import de.markusressel.kutepreferences.core.preference.select.MultiSelectionPreferenceBehavior import de.markusressel.kutepreferences.core.preference.select.SingleSelectionPreferenceBehavior import de.markusressel.kutepreferences.core.preference.text.* import de.markusressel.kutepreferences.core.preference.time.KuteTimePreference import de.markusressel.kutepreferences.core.preference.time.TimePreferenceBehavior import de.markusressel.kutepreferences.ui.views.listitems.* /** * Global place for the associations between [KutePreferenceListItem] implementations * and their UI. */ object KuteStyleManager { private val hooks = mutableListOf<@Composable (item: KutePreferenceListItem) -> Boolean>() /** * Registers the built-in components * * @param navigator a [KuteNavigator] used f.ex. for navigation between categories */ fun registerDefaultStyles(navigator: KuteNavigator) = registerTypeHook { when (it) { is KuteAction -> { val kuteActionBehavior = ActionPreferenceBehavior(it) ActionPreference( behavior = kuteActionBehavior ) true } is KuteSection -> { KuteSectionView( KuteSectionBehavior(preferenceItem = it) ) true } is KuteCategory -> { val behavior = KuteCategoryBehavior( preferenceItem = it, navigator = navigator, ) KuteCategoryView(behavior) true } is KuteBooleanPreference -> { val behavior = BooleanPreferenceBehavior(it) BooleanPreference( behavior = behavior ) true } is KuteColorPreference -> { val behavior = ColorPreferenceBehavior(it) ColorPreferenceView( behavior = behavior ) true } // NOTE: must be checked before KuteTextPreference is KuteUrlPreference -> { val behavior = UrlPreferenceBehavior(it) UrlPreference( behavior = behavior ) true } // NOTE: must be checked before KuteTextPreference is KutePasswordPreference -> { val behavior = PasswordPreferenceBehavior(it) PasswordPreference( behavior = behavior ) true } is KuteTextPreference -> { val behavior = TextPreferenceBehavior(it) TextPreference( behavior = behavior ) true } is KuteNumberPreference -> { val behavior = NumberPreferenceBehavior(it) NumberPreference( behavior = behavior ) true } is KuteFloatRangePreference -> { val behavior = FloatRangeSliderPreferenceBehavior(it) NumberRangeSliderPreference( behavior = behavior ) true } is KuteSliderPreference -> { val behavior = NumberSliderPreferenceBehavior(it) NumberSliderPreference( behavior = behavior, ) true } is KuteDatePreference -> { val behavior = DatePreferenceBehavior(it) DatePreference( behavior = behavior, ) true } is KuteTimePreference -> { val behavior = TimePreferenceBehavior(it) TimePreference( behavior = behavior, ) true } is KuteSingleSelectStringPreference -> { val behavior = SingleSelectionPreferenceBehavior(it) SingleSelectionPreference( behavior = behavior, ) true } is KuteMultiSelectStringPreference -> { val behavior = MultiSelectionPreferenceBehavior(it) MultiSelectionPreference( behavior = behavior, ) true } else -> { Column( modifier = Modifier.padding(8.dp) ) { Text(text = "Unsupported list item type: ${it.javaClass.simpleName}") Text(text = "Did you forget to register it on KuteStyleManager?") } true } } } /** * Register a type hook function, which will be used to instantiate the UI for * a given [KutePreferenceListItem] type. * * Type hooks are called in reverse order of registration, which lets you override existing * hooks (like the built-in one). * * To make custom preference types show your custom UI, you have to register them with the * [KuteStyleManager] using this method. You can also use this to manipulate the UI of existing * types by using the above mentioned override mechanism. * * @param hook function which (optionally) renders the UI for a given preference item. * returns true if it handled the given item, false otherwise. */ fun registerTypeHook( hook: @Composable (item: KutePreferenceListItem) -> Boolean, ) { hooks.add(hook) } @Composable fun renderComposable( item: KutePreferenceListItem, ) { for (hook in hooks.reversed()) { val result = hook(item) if (result) { return } } Log.w( "KuteStyleManager", "No hook with positive return value while trying " + "to render: ${item::class.java}" ) } }
5
Kotlin
0
9
6d8d2e86f46808a376355f54f82c2f4878834e24
8,412
KutePreferences
The Unlicense
app/src/main/java/com/app/examexchange/utils/EventManager.kt
VaruzhSargsyan
591,386,776
false
null
package com.app.examexchange.utils import java.util.concurrent.ScheduledThreadPoolExecutor import java.util.concurrent.TimeUnit /* * The event generator which is able to call the block after about 5 seconds * Used Scheduled Thread Pool which is more comfortable to control the time delays * and tasks in in pool. */ class EventManager { private val threadPool = ScheduledThreadPoolExecutor(1) private var delayInSeconds: Long = 5 private lateinit var block: () -> Unit fun setup(delayInSeconds: Long = 5, block: () -> Unit) { this.block = block this.delayInSeconds = delayInSeconds } fun prepareNextCall() { threadPool.schedule(Runnable(block), delayInSeconds, TimeUnit.SECONDS) } fun stop() { threadPool.shutdownNow() } }
0
Kotlin
0
0
1b347024290a247cec6ddcf1c69604c8d6978edf
812
ExamExchange
Apache License 2.0
library/src/main/java/com/mctech/architecture/generator/path/ModuleFilePath.kt
MayconCardoso
224,556,754
false
null
package com.mctech.architecture.generator.path import com.mctech.architecture.generator.class_contract.Package import com.mctech.architecture.generator.settings.GlobalSettings import com.mctech.architecture.generator.settings.featurePackage import com.mctech.architecture.generator.settings.featureSegment /** * @author <NAME> on 2019-11-27. */ class ModuleFilePath( val packageValue: Package, val gradleModuleName : String, val moduleLocation: String ) : FilePath { val type: ModuleFilePathType = ModuleFilePathType.Java override fun getPath(): String { return "$moduleLocation/${type.folderName}/${packageValue.getSegmentedPackage()}/" } } sealed class ModuleFilePathType(val folderName: String) { fun getResFolder() = "src/main/res/" fun getMainFolder() = "src/main/" fun getSourceFolder() = "" /** * This is a JAVA module, so our path is 'src/main/java/....' */ object Java : ModuleFilePathType("src/main/java/") /** * This is a KOTLIN module, so our path is 'src/main/java/....' */ object Kotlin : ModuleFilePathType("src/main/kotlin/") } // This is the base package of the architecture. val projectPackage = GlobalSettings.projectSettings.basePackageName.value /** * These are the defaults layers implementation of the project. * You can change it when generating your feature by changing the layers variables. */ sealed class ModuleDefaultLayers(val moduleFile: ModuleFilePath) { object Data : ModuleDefaultLayers( ModuleFilePath( moduleLocation = "data", gradleModuleName = ":data", packageValue = Package("$projectPackage.data") ) ) object Domain : ModuleDefaultLayers( ModuleFilePath( moduleLocation = "domain", gradleModuleName = ":domain", packageValue = Package("$projectPackage.domain") ) ) object BaseArchitecture : ModuleDefaultLayers( ModuleFilePath( moduleLocation = "", gradleModuleName = "", packageValue = Package("com.mctech.architecture.mvvm.x.core") ) ) object GeneratedFeature : ModuleDefaultLayers( ModuleFilePath( moduleLocation = "feature-${featureSegment()}", gradleModuleName = ":features:feature-${featureSegment()}", packageValue = Package("$projectPackage.feature.${featurePackage()}") ) ) }
1
Kotlin
2
16
3f66618aec512b3fac5386d2adad8c5c99d4443b
2,474
ArchitectureBoilerplateGenerator
Apache License 2.0
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/AlarmOn.kt
karakum-team
387,062,541
false
{"Kotlin": 3037818, "TypeScript": 2249, "HTML": 724, "CSS": 86}
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/AlarmOn") package mui.icons.material @JsName("default") external val AlarmOn: SvgIconComponent
1
Kotlin
5
35
7c4376ba64ea84a5c40255d83c8c046978c3843d
178
mui-kotlin
Apache License 2.0
src/main/kotlin/dev/adirelle/adicrate/block/entity/internal/UpgradeInventory.kt
Adirelle
454,710,946
false
{"Kotlin": 74806}
package dev.adirelle.adicrate.block.entity.internal import dev.adirelle.adicrate.block.entity.CrateBlockEntity import net.minecraft.inventory.SimpleInventory import net.minecraft.item.ItemStack class UpgradeInventory : SimpleInventory(CrateBlockEntity.UPGRADE_COUNT) { override fun getMaxCountPerStack() = 1 override fun isValid(slot: Int, stack: ItemStack) = Upgrade.isValid(stack) }
0
Kotlin
0
1
3d34c36e0c649c8e394a03c4a67c141fba16cb07
413
AdiCrate
MIT License
demo/plot-common/src/commonMain/kotlin/demo/plot/common/model/plotConfig/LineTypes.kt
JetBrains
176,771,727
false
{"Kotlin": 7616680, "Python": 1299756, "Shell": 3453, "C": 3039, "JavaScript": 931, "Dockerfile": 94}
/* * Copyright (c) 2024. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package demo.plot.common.model.plotConfig import demoAndTestShared.parsePlotSpec class LineTypes { fun plotSpecList(): List<MutableMap<String, Any>> { return listOf( namedLineTypes(), arrayLineTypes(), hexLineTypes() ) } private fun namedLineTypes(): MutableMap<String, Any> { val linetypes = listOf( "solid", "dashed", "dotted", "dotdash", "longdash", "twodash" ) return plotSpec(linetypes) } private fun arrayLineTypes(): MutableMap<String, Any> { val linetypes = listOf( listOf(1, 1), listOf(5, 5), listOf(10, 5), listOf(5, listOf(10, 5)), listOf(5, 10, 1, 10), listOf(10, 5, 1, 5, 1, 5) ) return plotSpec(linetypes) } private fun hexLineTypes(): MutableMap<String, Any> { val linetypes = listOf( "11", "55", "A5", "5A1A" ) return plotSpec(linetypes) } companion object { private fun plotSpec(linetypes: List<Any>): MutableMap<String, Any> { val n = linetypes.size val data = mapOf( "x" to List(n) { 0 }, "xend" to List(n) { 1 }, "y" to linetypes, "yend" to linetypes, "linetype" to linetypes ) val spec = """{ "kind": "plot", "scales": [ { "aesthetic": "linetype", "guide": "none", "scale_mapper_kind": "identity", "discrete": true } ], "layers": [ { "geom": "segment", "size":6, "mapping": { "x": "x", "y": "y", "xend": "xend", "yend": "yend", "linetype": "linetype" }, "tooltips": "none" } ] }""".trimIndent() val plotSpec = HashMap(parsePlotSpec(spec)) plotSpec["data"] = data return plotSpec } } }
150
Kotlin
51
1,561
c8db300544974ddd35a82a90072772b788600ac6
2,484
lets-plot
MIT License
demo/plot-common/src/commonMain/kotlin/demo/plot/common/model/plotConfig/LineTypes.kt
JetBrains
176,771,727
false
{"Kotlin": 7616680, "Python": 1299756, "Shell": 3453, "C": 3039, "JavaScript": 931, "Dockerfile": 94}
/* * Copyright (c) 2024. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package demo.plot.common.model.plotConfig import demoAndTestShared.parsePlotSpec class LineTypes { fun plotSpecList(): List<MutableMap<String, Any>> { return listOf( namedLineTypes(), arrayLineTypes(), hexLineTypes() ) } private fun namedLineTypes(): MutableMap<String, Any> { val linetypes = listOf( "solid", "dashed", "dotted", "dotdash", "longdash", "twodash" ) return plotSpec(linetypes) } private fun arrayLineTypes(): MutableMap<String, Any> { val linetypes = listOf( listOf(1, 1), listOf(5, 5), listOf(10, 5), listOf(5, listOf(10, 5)), listOf(5, 10, 1, 10), listOf(10, 5, 1, 5, 1, 5) ) return plotSpec(linetypes) } private fun hexLineTypes(): MutableMap<String, Any> { val linetypes = listOf( "11", "55", "A5", "5A1A" ) return plotSpec(linetypes) } companion object { private fun plotSpec(linetypes: List<Any>): MutableMap<String, Any> { val n = linetypes.size val data = mapOf( "x" to List(n) { 0 }, "xend" to List(n) { 1 }, "y" to linetypes, "yend" to linetypes, "linetype" to linetypes ) val spec = """{ "kind": "plot", "scales": [ { "aesthetic": "linetype", "guide": "none", "scale_mapper_kind": "identity", "discrete": true } ], "layers": [ { "geom": "segment", "size":6, "mapping": { "x": "x", "y": "y", "xend": "xend", "yend": "yend", "linetype": "linetype" }, "tooltips": "none" } ] }""".trimIndent() val plotSpec = HashMap(parsePlotSpec(spec)) plotSpec["data"] = data return plotSpec } } }
150
Kotlin
51
1,561
c8db300544974ddd35a82a90072772b788600ac6
2,484
lets-plot
MIT License
app/src/main/java/com/example/newsapp/ui/NewsViewModel.kt
CodeHunterDev
473,493,112
true
{"Kotlin": 37723}
package com.example.newsapp.ui import android.app.Application import android.content.Context import android.net.ConnectivityManager import android.net.ConnectivityManager.* import android.net.NetworkCapabilities.* import android.os.Build import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.newsapp.NewsApplication import com.example.newsapp.models.Article import com.example.newsapp.models.NewsResponse import com.example.newsapp.repository.NewsRepository import com.example.newsapp.util.Resources import kotlinx.coroutines.launch import retrofit2.Response import java.io.IOException class NewsViewModel( app: Application, val newsRepository: NewsRepository ) : AndroidViewModel(app) { val breakingNews: MutableLiveData<Resources<NewsResponse>> = MutableLiveData() var breakingNewsPage = 1 var breakingNewsResponse: NewsResponse? = null val searchNews: MutableLiveData<Resources<NewsResponse>> = MutableLiveData() var pageSearchNews = 1 var searchNewsResponse: NewsResponse? = null var newSearchQuery:String? = null var oldSearchQuery:String? = null init { getBreakingNews("us") } fun getBreakingNews(countryCode: String) = viewModelScope.launch { safeBreakingNewsCall(countryCode) } fun searchNews(searchQuery: String) = viewModelScope.launch { safeSearchNewsCall(searchQuery) } private fun handlingNewsResponse(response: Response<NewsResponse>): Resources<NewsResponse> { if (response.isSuccessful) { response.body()?.let { resultResponse -> breakingNewsPage++ if (breakingNewsResponse == null) { breakingNewsResponse = resultResponse } else { val oldArticles = breakingNewsResponse?.articles val newArticles = resultResponse.articles oldArticles?.addAll(newArticles) } return Resources.Success(breakingNewsResponse ?: resultResponse) } } return Resources.Error(response.message()) } private fun handlingSearchResponse(response: Response<NewsResponse>): Resources<NewsResponse> { if (response.isSuccessful) { response.body()?.let { resultResponse -> pageSearchNews++ if(searchNewsResponse == null || newSearchQuery != oldSearchQuery) { pageSearchNews = 1 oldSearchQuery = newSearchQuery searchNewsResponse = resultResponse } else { val oldArticles = searchNewsResponse?.articles val newArticles = resultResponse.articles oldArticles?.addAll(newArticles) } return Resources.Success(searchNewsResponse ?: resultResponse) } } return Resources.Error(response.message()) } //Save Article in room database fun saveArticle(article: Article) = viewModelScope.launch { newsRepository.upsert(article) } fun getSavedNews() = newsRepository.getSavedNews() fun deleteSavedNews(article: Article) = viewModelScope.launch { newsRepository.deleteArticle(article) } private suspend fun safeBreakingNewsCall(countryCode: String) { breakingNews.postValue(Resources.Loading()) try { if(hasInternetConnection()) { val response = newsRepository.getBreakingNews(countryCode, breakingNewsPage) breakingNews.postValue(handlingNewsResponse(response)) } else { breakingNews.postValue(Resources.Error("No internet connection")) } } catch(t: Throwable) { when(t) { is IOException -> breakingNews.postValue(Resources.Error("Network Failure")) else -> breakingNews.postValue(Resources.Error("Conversion Error")) } } } private suspend fun safeSearchNewsCall(searchQuery: String) { newSearchQuery = searchQuery searchNews.postValue(Resources.Loading()) try { if(hasInternetConnection()) { val response = newsRepository.searchNews(searchQuery, pageSearchNews) searchNews.postValue(handlingSearchResponse(response)) } else { searchNews.postValue(Resources.Error("No internet connection")) } } catch(t: Throwable) { when(t) { is IOException -> searchNews.postValue(Resources.Error("Network Failure")) else -> searchNews.postValue(Resources.Error("Conversion Error")) } } } private fun hasInternetConnection(): Boolean { val connectivityManager = getApplication<NewsApplication>().getSystemService( Context.CONNECTIVITY_SERVICE ) as ConnectivityManager if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val activeNetwork = connectivityManager.activeNetwork ?: return false val capabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false return when { capabilities.hasTransport(TRANSPORT_WIFI) -> true capabilities.hasTransport(TRANSPORT_CELLULAR) -> true capabilities.hasTransport(TRANSPORT_ETHERNET) -> true else -> false } } else { connectivityManager.activeNetworkInfo?.run { return when(type) { TYPE_WIFI -> true TYPE_MOBILE -> true TYPE_ETHERNET -> true else -> false } } } return false } }
0
null
0
0
f403c980c25d383bce2e18c9943a2990fe1b71eb
5,920
NewsApp-2
MIT License
ktlint-rule-engine/src/main/kotlin/com/pinterest/ktlint/rule/engine/internal/FormatterTags.kt
pinterest
64,293,719
false
{"Kotlin": 3159822, "Shell": 4162, "Batchfile": 518, "Python": 103}
package com.pinterest.ktlint.rule.engine.internal import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfigProperty import org.ec4j.core.model.PropertyType internal data class FormatterTags( val formatterTagOff: String?, val formatterTagOn: String?, ) { companion object { private val DISABLED_FORMATTER_TAGS = FormatterTags(null, null) fun from(editorConfig: EditorConfig): FormatterTags = if (editorConfig[FORMATTER_TAGS_ENABLED_PROPERTY]) { FormatterTags( formatterTagOff = editorConfig[FORMATTER_TAG_OFF_ENABLED_PROPERTY], formatterTagOn = editorConfig[FORMATTER_TAG_ON_ENABLED_PROPERTY], ) } else { DISABLED_FORMATTER_TAGS } val FORMATTER_TAGS_ENABLED_PROPERTY: EditorConfigProperty<Boolean> = EditorConfigProperty( type = PropertyType.LowerCasingPropertyType( "ij_formatter_tags_enabled", "When enabled, IntelliJ IDEA Formatter tags will be respected (e.g. disable and enable all ktlint rules for the " + "code enclosed between the formatter tags.", PropertyType.PropertyValueParser.BOOLEAN_VALUE_PARSER, setOf(true.toString(), false.toString()), ), defaultValue = false, ) val FORMATTER_TAG_OFF_ENABLED_PROPERTY: EditorConfigProperty<String> = EditorConfigProperty( type = PropertyType.LowerCasingPropertyType( "ij_formatter_off_tag", "The IntelliJ IDEA formatter tag to disable formatting. This also disables the ktlint rules.", PropertyType.PropertyValueParser.IDENTITY_VALUE_PARSER, ), defaultValue = "@formatter:off", ) val FORMATTER_TAG_ON_ENABLED_PROPERTY: EditorConfigProperty<String> = EditorConfigProperty( type = PropertyType.LowerCasingPropertyType( "ij_formatter_on_tag", "The IntelliJ IDEA formatter tag to enable formatting. This also enables the ktlint rules.", PropertyType.PropertyValueParser.IDENTITY_VALUE_PARSER, ), defaultValue = "@formatter:on", ) } }
14
Kotlin
509
6,205
80c4d5d822d47bb7077a874ebb9105097f2eb1c2
2,615
ktlint
MIT License
app/src/main/java/de/adschmidt/sunrisesunset/calc/TimeCalculator.kt
schmidti159
361,402,739
false
null
package de.adschmidt.sunrisesunset.calc import android.location.Location import de.adschmidt.sunrisesunset.model.Times import net.time4j.PlainDate import net.time4j.calendar.astro.SolarTime import net.time4j.calendar.astro.StdSolarCalculator import net.time4j.calendar.astro.Twilight import kotlin.math.abs import kotlin.math.floor class TimeCalculator { fun solarTimeForLocation(location: Location): SolarTime { val solarTimeBuilder = SolarTime.ofLocation() .atAltitude(location.altitude.toInt()) .usingCalculator(StdSolarCalculator.TIME4J) if (location.latitude >= 0) { solarTimeBuilder.northernLatitude( getDegrees(location.latitude), getMinutes(location.latitude), getSeconds(location.latitude) ) } else { solarTimeBuilder.southernLatitude( getDegrees(location.latitude), getMinutes(location.latitude), getSeconds(location.latitude) ) } if (location.longitude >= 0) { solarTimeBuilder.easternLongitude( getDegrees(location.longitude), getMinutes(location.longitude), getSeconds(location.longitude) ) } else { solarTimeBuilder.westernLongitude( getDegrees(location.longitude), getMinutes(location.longitude), getSeconds(location.longitude) ) } return solarTimeBuilder.build() } fun getTimesForDate(solarTime: SolarTime, date: PlainDate): Times { return Times( date.get(solarTime.sunrise(Twilight.CIVIL)), date.get(solarTime.sunrise()), date.get(solarTime.sunset()), date.get(solarTime.sunset(Twilight.CIVIL)) ) } private fun getDegrees(degrees: Double): Int { return floor(abs(degrees)).toInt() } private fun getMinutes(degrees: Double): Int { val minutesInDegrees = abs(degrees) - getDegrees(degrees) return floor(minutesInDegrees * 60).toInt() } private fun getSeconds(degrees: Double): Double { val secondsInDegrees = abs(degrees) - getDegrees(degrees) - getMinutes(degrees) / 60.0 return floor(secondsInDegrees * 60 * 60) } }
0
Kotlin
0
0
163a772b874ea2b196bf7c90ed48d4c2cd28f88d
2,360
android-sunrise-sunset-widgets
Apache License 2.0
feature/collection/src/main/java/com/example/collection/CollectionScreen.kt
KanuKim97
428,755,782
false
{"Kotlin": 139829}
package com.example.collection import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.lazy.items import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.example.designsystem.component.EatCenterAlignedAppBar import com.example.designsystem.component.EatCircularProgressIndicator import com.example.designsystem.component.EatLazyColumn import com.example.designsystem.icons.EatIcons import com.example.designsystem.theme.EatTypography import com.example.ui.CollectionCard @Composable internal fun CollectionRoute(navigationIconOnClick: () -> Unit) { val collectionViewModel = hiltViewModel<CollectionViewModel>() val readAllContentUiState by collectionViewModel.readAllCollectionUiState.collectAsStateWithLifecycle() CollectionScreen( navigationIconOnClick = navigationIconOnClick, readAllContentUiState = readAllContentUiState ) } @Composable internal fun CollectionScreen( navigationIconOnClick: () -> Unit, readAllContentUiState: ReadAllCollectionUiState, modifier: Modifier = Modifier ) { Scaffold( modifier = modifier.fillMaxSize(), topBar = { EatCenterAlignedAppBar( navigationIcon = EatIcons.arrowBackOutlined, navigationIconOnClick = navigationIconOnClick ) } ) { paddingValues -> when (readAllContentUiState) { is ReadAllCollectionUiState.IsLoading -> { EatCircularProgressIndicator() } is ReadAllCollectionUiState.IsSuccess -> { val content = readAllContentUiState.data EatLazyColumn( modifier = modifier.fillMaxSize(), contentPadding = paddingValues ) { items(items = content) { collection -> CollectionCard( placeName = collection.name, placeImgUrl = collection.imgUrl ) } } } is ReadAllCollectionUiState.IsFailed -> { Box( modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center, content = { Text(text = "로딩에 실패하였습니다.", style = EatTypography.labelLarge) } ) } } } }
0
Kotlin
0
2
be17650e8e05db2ee02914068f953df536037319
2,738
whats_eat
Apache License 2.0
lib/src/main/kotlin/org/hravemzdy/legalios/providers/period2022/ProviderSalary2022.kt
infohravemzdy
425,931,709
false
{"Kotlin": 1039271}
package org.hravemzdy.legalios.providers.period2022 import org.hravemzdy.legalios.providers.ProviderBase import org.hravemzdy.legalios.providers.IProviderSalary import org.hravemzdy.legalios.interfaces.IPropsSalary import org.hravemzdy.legalios.interfaces.IPeriod import org.hravemzdy.legalios.props.PropsSalary class ProviderSalary2022 : ProviderBase(HistoryConstSalary2022.VERSION_CODE), IProviderSalary { override fun getProps(period: IPeriod): IPropsSalary { return PropsSalary( version, workingShiftWeek(period), workingShiftTime(period), minMonthlyWage(period), minHourlyWage(period) ) } override fun workingShiftWeek(period: IPeriod): Int { return HistoryConstSalary2022.WORKING_SHIFT_WEEK } override fun workingShiftTime(period: IPeriod): Int { return HistoryConstSalary2022.WORKING_SHIFT_TIME } override fun minMonthlyWage(period: IPeriod): Int { return HistoryConstSalary2022.MIN_MONTHLY_WAGE } override fun minHourlyWage(period: IPeriod): Int { return HistoryConstSalary2022.MIN_HOURLY_WAGE } }
0
Kotlin
0
0
3393f208546e8b369222dffb91e01bb9515045b8
1,159
legalioskotlin
The Unlicense
lib/src/main/kotlin/org/hravemzdy/legalios/providers/period2022/ProviderSalary2022.kt
infohravemzdy
425,931,709
false
{"Kotlin": 1039271}
package org.hravemzdy.legalios.providers.period2022 import org.hravemzdy.legalios.providers.ProviderBase import org.hravemzdy.legalios.providers.IProviderSalary import org.hravemzdy.legalios.interfaces.IPropsSalary import org.hravemzdy.legalios.interfaces.IPeriod import org.hravemzdy.legalios.props.PropsSalary class ProviderSalary2022 : ProviderBase(HistoryConstSalary2022.VERSION_CODE), IProviderSalary { override fun getProps(period: IPeriod): IPropsSalary { return PropsSalary( version, workingShiftWeek(period), workingShiftTime(period), minMonthlyWage(period), minHourlyWage(period) ) } override fun workingShiftWeek(period: IPeriod): Int { return HistoryConstSalary2022.WORKING_SHIFT_WEEK } override fun workingShiftTime(period: IPeriod): Int { return HistoryConstSalary2022.WORKING_SHIFT_TIME } override fun minMonthlyWage(period: IPeriod): Int { return HistoryConstSalary2022.MIN_MONTHLY_WAGE } override fun minHourlyWage(period: IPeriod): Int { return HistoryConstSalary2022.MIN_HOURLY_WAGE } }
0
Kotlin
0
0
3393f208546e8b369222dffb91e01bb9515045b8
1,159
legalioskotlin
The Unlicense
src/main/kotlin/com/kneelawk/wiredredstone/part/WRParts.kt
Kneelawk
443,064,933
false
null
package com.kneelawk.wiredredstone.part import alexiil.mc.lib.multipart.api.PartDefinition import com.kneelawk.wiredredstone.WRConstants object WRParts { // Wires val RED_ALLOY_WIRE by lazy { definition("red_alloy_wire", ::RedAlloyWirePart, ::RedAlloyWirePart) } val INSULATED_WIRE by lazy { definition("insulated_wire", ::InsulatedWirePart, ::InsulatedWirePart) } val BUNDLED_CABLE by lazy { definition("bundled_cable", ::BundledCablePart, ::BundledCablePart) } val POWERLINE_CONNECTOR by lazy { definition("powerline_connector", ::PowerlineConnectorPart, ::PowerlineConnectorPart) } // Gates val GATE_AND by lazy { definition("gate_and", ::GateAndPart, ::GateAndPart) } val GATE_DIODE by lazy { definition("gate_diode", ::GateDiodePart, ::GateDiodePart) } val GATE_NAND by lazy { definition("gate_nand", ::GateNandPart, ::GateNandPart) } val GATE_NOR by lazy { definition("gate_nor", ::GateNorPart, ::GateNorPart) } val GATE_NOT by lazy { definition("gate_not", ::GateNotPart, ::GateNotPart) } val GATE_OR by lazy { definition("gate_or", ::GateOrPart, ::GateOrPart) } val GATE_PROJECTOR_SIMPLE by lazy { definition("gate_projector_simple", ::GateProjectorSimplePart, ::GateProjectorSimplePart) } val GATE_REPEATER by lazy { definition("gate_repeater", ::GateRepeaterPart, ::GateRepeaterPart) } val GATE_RS_LATCH by lazy { definition("gate_rs_latch", ::GateRSLatchPart, ::GateRSLatchPart) } private fun definition( path: String, reader: PartDefinition.IPartNbtReader, loader: PartDefinition.IPartNetLoader ): PartDefinition { return PartDefinition(WRConstants.id(path), reader, loader) } fun init() { PartDefinition.PARTS[RED_ALLOY_WIRE.identifier] = RED_ALLOY_WIRE PartDefinition.PARTS[INSULATED_WIRE.identifier] = INSULATED_WIRE PartDefinition.PARTS[BUNDLED_CABLE.identifier] = BUNDLED_CABLE PartDefinition.PARTS[POWERLINE_CONNECTOR.identifier] = POWERLINE_CONNECTOR PartDefinition.PARTS[GATE_AND.identifier] = GATE_AND PartDefinition.PARTS[GATE_DIODE.identifier] = GATE_DIODE PartDefinition.PARTS[GATE_NAND.identifier] = GATE_NAND PartDefinition.PARTS[GATE_NOR.identifier] = GATE_NOR PartDefinition.PARTS[GATE_NOT.identifier] = GATE_NOT PartDefinition.PARTS[GATE_OR.identifier] = GATE_OR PartDefinition.PARTS[GATE_PROJECTOR_SIMPLE.identifier] = GATE_PROJECTOR_SIMPLE PartDefinition.PARTS[GATE_REPEATER.identifier] = GATE_REPEATER PartDefinition.PARTS[GATE_RS_LATCH.identifier] = GATE_RS_LATCH } }
5
Kotlin
3
9
d9c2571b3e0d14911c29d12de24eba9a41ce36f6
2,633
WiredRedstone
MIT License
cryptokmplib/src/commonMain/kotlin/encoding/Base58Encoder.kt
globalid
805,347,679
false
{"Kotlin": 15720, "Swift": 408}
package encoding private const val ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" private val BASE58 = ALPHABET.toCharArray() private val INDEXES = IntArray(128) { -1 }.apply { for (i in BASE58.indices) { this[BASE58[i].code] = i } } fun ByteArray.encodeToBase58(): String { if (isEmpty()) return "" var zeros = 0 while (zeros < size && this[zeros] == 0.toByte()) { ++zeros } val input = this.copyOf(size) // since we modify it in-place val encoded = CharArray(size * 2) // upper bound var outputStart = encoded.size var inputStart = zeros while (inputStart < input.size) { encoded[--outputStart] = BASE58[divmod(input, inputStart, 256, 58).toInt()] if (input[inputStart] == 0.toByte()) { ++inputStart // optimization - skip leading zeros } } // Preserve exactly as many leading encoded zeros in output as there were leading zeros in input. while (outputStart < encoded.size && encoded[outputStart] == BASE58[0]) { ++outputStart } while (--zeros >= 0) { encoded[--outputStart] = BASE58[0] } return constructString(encoded, outputStart, encoded.size - outputStart) } fun String.decodeFromBase58(): ByteArray { if (isEmpty()) return ByteArray(0) // Convert the base58-encoded ASCII chars to a base58 byte sequence (base58 digits). val input58 = ByteArray(length) for (i in indices) { val c = this[i] val digit = if (c.code < 128) INDEXES[c.code] else -1 require(digit >= 0) { "Invalid Base58 character: $c" } input58[i] = digit.toByte() } // Count leading zeros. var zeros = 0 while (zeros < input58.size && input58[zeros] == 0.toByte()) { ++zeros } // Convert base-58 digits to base-256 digits. val decoded = ByteArray(length) var outputStart = decoded.size var inputStart = zeros while (inputStart < input58.size) { decoded[--outputStart] = divmod(input58, inputStart, 58, 256) if (input58[inputStart] == 0.toByte()) { ++inputStart // optimization - skip leading zeros } } // Ignore extra leading zeros that were added during the calculation. while (outputStart < decoded.size && decoded[outputStart] == 0.toByte()) { ++outputStart } return decoded.copyOfRange(outputStart - zeros, decoded.size) } private fun divmod(number: ByteArray, firstDigit: Int, base: Int, divisor: Int): Byte { var remainder = 0 for (i in firstDigit until number.size) { val digit = number[i].toInt() and 0xFF val temp = remainder * base + digit number[i] = (temp / divisor).toByte() remainder = temp % divisor } return remainder.toByte() }
2
Kotlin
0
0
26678577c49733b2c04d3ad071a187eeacc72aac
2,801
crypto-kmp
Apache License 2.0
app/src/main/java/com/dluvian/voyage/ui/components/row/post/FeedRootRow.kt
dluvian
766,355,809
false
{"Kotlin": 898366}
package com.dluvian.voyage.ui.components.row.post import androidx.compose.runtime.Composable import com.dluvian.voyage.core.OnUpdate import com.dluvian.voyage.core.model.RootPostUI @Composable fun FeedRootRow(post: RootPostUI, showAuthorName: Boolean, onUpdate: OnUpdate) { BaseRootRow( post = post, isOp = false, isThread = false, showAuthorName = showAuthorName, onUpdate = onUpdate ) }
36
Kotlin
4
36
9cf78d9ca55469a9c157ad713426d77fd051e0a8
439
voyage
MIT License
component-acgcomic/src/main/java/com/rabtman/acgcomic/mvp/ui/fragment/QiMiaoComicFragment.kt
Rabtman
129,618,096
false
{"Gradle": 19, "Text": 2, "Java Properties": 2, "Shell": 1, "Ignore List": 13, "Batchfile": 1, "Markdown": 2, "Proguard": 12, "XML": 163, "Kotlin": 225, "Java": 59, "Gradle Kotlin DSL": 1, "AIDL": 3}
package com.rabtman.acgcomic.mvp.ui.fragment import android.text.Editable import android.text.TextWatcher import android.view.View import androidx.appcompat.widget.AppCompatEditText import androidx.appcompat.widget.AppCompatImageButton import androidx.core.content.ContextCompat import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import butterknife.BindView import com.alibaba.android.arouter.facade.annotation.Route import com.rabtman.acgcomic.R import com.rabtman.acgcomic.R2 import com.rabtman.acgcomic.base.constant.IntentConstant import com.rabtman.acgcomic.di.DaggerQiMiaoComicComponent import com.rabtman.acgcomic.di.QiMiaoComicModule import com.rabtman.acgcomic.mvp.QiMiaoComicContract import com.rabtman.acgcomic.mvp.model.entity.jsoup.QiMiaoComicItem import com.rabtman.acgcomic.mvp.presenter.QiMiaoComicPresenter import com.rabtman.acgcomic.mvp.ui.adapter.ComicMenuAdapter import com.rabtman.acgcomic.mvp.ui.adapter.QiMiaoComicItemAdpater import com.rabtman.common.base.BaseFragment import com.rabtman.common.base.widget.DropDownMenu import com.rabtman.common.di.component.AppComponent import com.rabtman.common.utils.ToastUtil import com.rabtman.router.RouterConstants import com.rabtman.router.RouterUtils /** * @author Rabtman */ @Route(path = RouterConstants.PATH_COMIC_QIMIAO) class QiMiaoComicFragment : BaseFragment<QiMiaoComicPresenter>(), QiMiaoComicContract.View { @BindView(R2.id.ddm_comic_menu) lateinit var mMenuComicMain: DropDownMenu private var mSwipeRefresh: SwipeRefreshLayout? = null private var mRcvComicMain: RecyclerView? = null private var mLayoutManager: LinearLayoutManager? = null private lateinit var mQiMiaoComicItemAdapter: QiMiaoComicItemAdpater private val headers = listOf("分类") //菜单选项 private val type = arrayListOf( "全部", "热血", "恋爱", "青春", "彩虹", "冒险", "后宫", "悬疑", "玄幻", "穿越", "都士", "腹黑", "爆笑", "少年", "奇幻", "古风", "妖恋", "元气", "治愈", "励志", "日常", "百合") //菜单选项适配器 private lateinit var typeAdapter: ComicMenuAdapter //弹出菜单视图集 private lateinit var popupViews: List<View> //头部搜索框 private lateinit var headerSearchView: View override fun getLayoutId(): Int { return R.layout.acgcomic_view_comic_menu } override fun setupFragmentComponent(appComponent: AppComponent) { DaggerQiMiaoComicComponent.builder() .appComponent(appComponent) .qiMiaoComicModule(QiMiaoComicModule(this)) .build() .inject(this) } override fun initData() { initDropDownMenu() initHeaderView() mMenuComicMain.setDropDownMenu(headers, popupViews, initContentView()) mPresenter.getComicInfos() } override fun useLoadSir(): Boolean { return true } override fun onPageRetry(v: View?) { mPresenter.getComicInfos() } override fun hideLoading() { mSwipeRefresh?.let { it -> if (it.isRefreshing) { it.isRefreshing = false } } super.hideLoading() } //初始化菜单布局 private fun initDropDownMenu() { //分类 val typeView = RecyclerView(mContext) typeView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.grey200)) typeAdapter = ComicMenuAdapter(type).apply { this.setOnItemClickListener { adapter, _, position -> if (adapter is ComicMenuAdapter) { adapter.setCheckItem(position) mMenuComicMain.setTabText(if (position == 0) headers[0] else type[position]) mMenuComicMain.closeMenu() mPresenter.getComicInfosByMenuSelected(if (position == 0) "" else (position + 6).toString()) } } } typeView.layoutManager = GridLayoutManager(mContext, 4) typeView.adapter = typeAdapter popupViews = listOf<View>(typeView) } //初始化内容布局 private fun initContentView(): View { val contentView = layoutInflater.inflate(R.layout.acgcomic_view_qimiao_comic_content, null) mSwipeRefresh = contentView.findViewById(R.id.swipe_refresh_qimiao_comic) mRcvComicMain = contentView.findViewById(R.id.rcv_qimiao_comic) mQiMiaoComicItemAdapter = QiMiaoComicItemAdpater(mAppComponent.imageLoader()).apply { this.setOnItemClickListener { adpater, _, pos -> val comicItem: QiMiaoComicItem = adpater.getItem(pos) as QiMiaoComicItem if (comicItem.comicLink.isNotEmpty()) { RouterUtils.getInstance() .build(RouterConstants.PATH_COMIC_QIMIAO_DETAIL) .withParcelable(IntentConstant.QIMIAO_COMIC_ITEM, comicItem) .navigation() } else { showMsg("找不到该漫画/(ㄒoㄒ)/~~") } } } mQiMiaoComicItemAdapter.setHeaderView(headerSearchView) //加载更多 mQiMiaoComicItemAdapter.loadMoreModule.setOnLoadMoreListener { mPresenter.getMoreComicInfos() } mLayoutManager = LinearLayoutManager(mContext) mRcvComicMain?.layoutManager = mLayoutManager mRcvComicMain?.adapter = mQiMiaoComicItemAdapter //下拉刷新 mSwipeRefresh?.setOnRefreshListener { mPresenter.getComicInfos() } return contentView } private fun initHeaderView(): View { headerSearchView = layoutInflater.inflate(R.layout.acgcomic_view_qimiao_comic_search, null) val etKeyword: AppCompatEditText = headerSearchView.findViewById(R.id.et_qimiao_comic_keyword) val btnClear: AppCompatImageButton = headerSearchView.findViewById(R.id.btn_qimiao_comic_close) val btnSearch: AppCompatImageButton = headerSearchView.findViewById(R.id.btn_qimiao_comic_search) //监听搜索框输入情况 etKeyword.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { //控制清除按钮的状态 if (s.toString().isEmpty()) { btnClear.visibility = View.INVISIBLE } else { btnClear.visibility = View.VISIBLE } } override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } }) //清除事件 btnClear.setOnClickListener { etKeyword.setText("") } //搜索事件 btnSearch.setOnClickListener { val keyword = etKeyword.text.toString() if (keyword.isEmpty()) { ToastUtil.show(context, getString(R.string.acgcomic_msg_empty_comic_search)) } else { etKeyword.setText("") mPresenter.searchComicInfos(keyword) } } return headerSearchView } override fun resetComicMenu() { typeAdapter.setCheckItem(0) mMenuComicMain.setTabPosition(0) mMenuComicMain.setTabText(headers[0]) mMenuComicMain.setTabPosition(-1) } override fun showSearchComicInfo(comicInfos: List<QiMiaoComicItem>?, canLoadMore: Boolean) { mRcvComicMain?.scrollToPosition(0) mQiMiaoComicItemAdapter.setList(comicInfos) mRcvComicMain?.scrollBy(0, 0) if (!canLoadMore) { mQiMiaoComicItemAdapter.loadMoreModule.loadMoreEnd() } } override fun showComicInfo(comicInfos: List<QiMiaoComicItem>?) { mRcvComicMain?.scrollToPosition(0) mQiMiaoComicItemAdapter.setList(comicInfos) mRcvComicMain?.scrollBy(0, 0) } override fun showMoreComicInfo(comicInfos: List<QiMiaoComicItem>?, canLoadMore: Boolean) { comicInfos?.let { mQiMiaoComicItemAdapter.addData(it) } mQiMiaoComicItemAdapter.loadMoreModule.loadMoreComplete() if (!canLoadMore) { mQiMiaoComicItemAdapter.loadMoreModule.loadMoreEnd() } } override fun onLoadMoreFail() { mQiMiaoComicItemAdapter.loadMoreModule.loadMoreFail() } }
2
Kotlin
120
840
9150f3abe50e046afd83cc97cb4415a39b1f1bd1
8,361
AcgClub
Apache License 2.0
app/src/main/java/io/github/takusan23/akaridroid/manager/VideoEditProjectManager.kt
takusan23
584,131,815
false
null
package io.github.takusan23.akaridroid.manager import android.content.Context import android.net.Uri import io.github.takusan23.akaridroid.data.AkariProjectData import io.github.takusan23.akaridroid.tool.JsonTool import io.github.takusan23.akaridroid.tool.MediaStoreTool import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.File /** * プロジェクトを管理する * * @param context [Context] */ class VideoEditProjectManager(private val context: Context) { /** 保存先 */ private val videoEditFolder by lazy { File(context.getExternalFilesDir(null), "project").apply { if (!exists()) { mkdir() } } } /** * プロジェクトを保存する * * @param akariProjectData */ suspend fun saveProjectData(akariProjectData: AkariProjectData) = withContext(Dispatchers.IO) { val projectFolder = getProjectFolder(akariProjectData.projectId) // JSON で保存 val jsonText = JsonTool.encode(akariProjectData) File(projectFolder, PROJECT_JSON_FILE_NAME).writeText(jsonText) } /** * プロジェクトを読み込む * * @return [AkariProjectData] */ suspend fun loadProjectData(projectId: String): AkariProjectData = withContext(Dispatchers.IO) { val projectFolder = getProjectFolder(projectId) // JSON から データクラスへ val jsonText = File(projectFolder, PROJECT_JSON_FILE_NAME).readText() return@withContext JsonTool.parse<AkariProjectData>(jsonText) } /** * プロジェクトにファイルを追加する * * @param projectId プロジェクトID * @param uri Uri * @return [File] */ suspend fun addFileToProject(projectId: String, uri: Uri, fileName: String) = withContext(Dispatchers.IO) { val projectFolder = getProjectFolder(projectId) val addFile = File(projectFolder, fileName).apply { createNewFile() } MediaStoreTool.fileCopy(context, uri, addFile) return@withContext addFile } /** * プロジェクトのファイルを削除する * * @param filePath ファイルパス */ suspend fun deleteFile(filePath: String) = withContext(Dispatchers.IO) { File(filePath).delete() } /** * プロジェクトのフォルダの[File]を取得する * * @param projectId プロジェクトID * @return [File] */ private suspend fun getProjectFolder(projectId: String): File = withContext(Dispatchers.IO) { return@withContext File(videoEditFolder, projectId).apply { if (!exists()) { mkdir() } } } companion object { /** プロジェクトJSONファイルの名前 */ private const val PROJECT_JSON_FILE_NAME = "project.json" } }
0
Kotlin
0
0
89101bdfd260280f16c7e9f9c180ec92558f96f2
2,681
AkariDroid
Apache License 2.0
app/src/main/java/com/ishant/bikerush/ui/BikeRushActivity.kt
ishantchauhan710
409,959,130
false
{"Kotlin": 46630}
package com.ishant.bikerush.ui import android.content.Intent import android.content.res.Resources import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.Layout import android.util.TypedValue import android.view.LayoutInflater import android.view.View import androidx.navigation.findNavController import androidx.navigation.ui.setupWithNavController import com.ishant.bikerush.R import com.ishant.bikerush.databinding.ActivityBikerushBinding import com.ishant.bikerush.other.Constants import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class BikeRushActivity : AppCompatActivity() { // View Binding Variable lateinit var binding: ActivityBikerushBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityBikerushBinding.inflate(LayoutInflater.from(this)) setContentView(binding.root) // This is the function we created at bottom startTrackingActivityIfNeeded(intent) // Bottom Navigation Setup binding.bottomNavigationView.background = null binding.bottomNavigationView.menu.getItem(1).isEnabled = false // Connecting bottom navigation view with navController val navController = findNavController(R.id.fragment) binding.bottomNavigationView.setupWithNavController(navController) // When fab button is clicked, start Tracking Activity binding.btnNewJourney.setOnClickListener { val intent = Intent(this,TrackingActivity::class.java) startActivity(intent) } } // In case our service is running and user closes app and clicks on notification, we want the tracking activity to be started. We can do it using this function private fun startTrackingActivityIfNeeded(intent: Intent?) { if(intent?.action== Constants.ACTION_SHOW_TRACKING_ACTIVITY) { val trackingActivityIntent = Intent(this,TrackingActivity::class.java) startActivity(trackingActivityIntent) } } }
0
Kotlin
3
25
6fa1c7159f67164a9c9c668af600be46d0751d72
2,079
BikeRush
Apache License 2.0
src/main/kotlin/common.kt
josianne
160,246,173
false
{"Kotlin": 3478}
package xyz fun loadData(filename: String) = DayOne::class.java.getResource(filename) .readText() .lines() .filter(String::isNotBlank)
0
Kotlin
0
0
03aba19c41e196fc0c4da6a91ae79914aea4bb63
163
advent_of_code_2018
MIT License
data/src/main/kotlin/com/rantolin/cleanarchitecture/data/entity/BaseEntity.kt
ricardoAntolin
86,933,107
false
null
package com.rantolin.cleanarchitecture.data.entity class BaseEntity { }
0
Kotlin
7
49
98b076b044017c4c68917b02bfff704dfba4a39c
74
androidKotlinCleanArchitecture
Apache License 2.0
Shared/validation/src/commonMain/kotlin/shared/validation/companion/String.kt
SingularityIndonesia
776,620,771
false
{"Kotlin": 125451, "Shell": 7143, "Swift": 585}
/* * Copyright (c) 2024 Singularity Indonesia (<EMAIL>) * You are not allowed to remove the copyright. Unless you have a "free software" licence. */ package shared.validation.companion import shared.validation.ValidationError import shared.validation.Validator fun String.validateWith(validator: Validator): ValidationError? { return validator.asIterable() .firstOrNull { this.matches(it.key.toRegex()) } ?.value }
0
Kotlin
3
0
7052a619d90cba81d670c0dd3ddc90416f79ae76
459
SingularityBaseMobile
Creative Commons Zero v1.0 Universal
paysafe-core/src/main/java/com/paysafe/android/paymentmethods/data/entity/GooglePaySerializable.kt
paysafegroup
768,755,663
false
{"Kotlin": 913640, "Shell": 912}
/* * Copyright (c) 2024 Paysafe Group */ package com.paysafe.android.paymentmethods.data.entity import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable internal data class GooglePaySerializable( @SerialName("merchantId") val merchantId: String? = null, @SerialName("merchantName") val merchantName: String? = null, @SerialName("paymentMethods") val paymentMethods: List<GooglePaymentMethodSerializable>? = null )
0
Kotlin
0
0
ed2ed1de90636bd495fdb2e85ba667bac55adecf
484
paysafe_sdk_android_payments_api
MIT License
bubbles/src/main/java/com/txusballesteros/bubbles/BubbleBaseLayout.kt
jhelsinmijael
324,592,586
true
{"Kotlin": 39860}
/* * Copyright <NAME> 2015 (@txusballesteros) * * This file is part of some open source application. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * * Contact: <NAME> <<EMAIL>> */ package com.txusballesteros.bubbles import android.content.Context import android.util.AttributeSet import android.view.WindowManager import android.widget.FrameLayout open class BubbleBaseLayout @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr) { var windowManager: WindowManager? = null var viewParams: WindowManager.LayoutParams? = null internal var layoutCoordinator: BubblesLayoutCoordinator? = null }
0
Kotlin
0
0
b8e6afecc96497221ca055c75a6dd0c090644488
1,465
bubble-Android-
Apache License 2.0
data/src/main/kotlin/io/petros/github/data/network/rest/mapper/search/SearchMapper.kt
ParaskP7
140,927,471
false
{"Kotlin": 118109}
package io.petros.github.data.network.rest.mapper.search import io.petros.github.data.network.rest.response.repository.Repo import io.petros.github.data.network.rest.response.repository.RepositoryResultsResponse import io.petros.github.domain.model.repository.Repository import io.petros.github.domain.model.repository.RepositoryResults class SearchMapper { // MIT companion object { internal fun transform(repositoryResultsResponse: RepositoryResultsResponse): RepositoryResults { val repositories = arrayListOf<Repository>() for (repo in repositoryResultsResponse.items) { repositories.add(repo.toRepository()) } return RepositoryResults(repositories) } } } fun Repo.toRepository(): Repository { return Repository( id = id, ownerAvatar = owner.avatar_url, login = owner.login, name = name, description = description, numberOfForks = forks_count, subscribersUrl = subscribers_url ) }
0
Kotlin
1
9
ad9c53165db32af9ca08e4ae3ca4ea9b30e24d2e
1,044
sample-code-github
Apache License 2.0
play-handler-classes/src/main/kotlin/org/example/hc/demos/MethodAnnoTakeEffectKotlinDemo.kt
dowenliu-xyz
808,693,582
false
{"Gradle Kotlin DSL": 13, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 2, "Java": 399, "YAML": 4, "INI": 6, "Kotlin": 354, "Java Properties": 1}
package org.example.hc.demos import com.alibaba.csp.sentinel.annotation.SentinelResource import org.example.hc.biz.Greeting import org.springframework.stereotype.Component @Suppress("unused") @Component class MethodAnnoTakeEffectKotlinDemo { @SentinelResource(blockHandlerClass = [BlockHandlerClass::class], fallbackClass = [FallbackClass::class]) fun greeting1(name: String?): String { return Greeting.doGreeting(name) } @SentinelResource(blockHandlerClass = [BlockHandlerClass::class], fallbackClass = [FallbackClass::class]) fun greeting2(name: String?): String { return Greeting.doGreeting(name) } @SentinelResource( blockHandlerClass = [BlockHandlerClass::class, BlockHandlerClass2::class], fallbackClass = [FallbackClass::class, FallbackClass2::class] ) fun greeting3(name: String?): String { return Greeting.doGreeting(name) } }
0
Java
0
1
8b6df6f693a0c7efa25c3a7d634823d7b8ec4915
920
sentinel-plays
Apache License 2.0
app/src/main/java/pt/dbmg/mobiletaiga/view/UsersListFragment.kt
worm69
166,021,572
false
{"Gradle": 7, "YAML": 12, "Java Properties": 2, "Markdown": 6, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Proguard": 3, "Kotlin": 464, "XML": 78, "Java": 55, "JSON": 2, "GraphQL": 1, "Dockerfile": 1}
package pt.dbmg.mobiletaiga.view import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.Toast import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.users_fragment.usersList import pt.dbmg.mobiletaiga.App import pt.dbmg.mobiletaiga.R import pt.dbmg.mobiletaiga.viewmodel.data.UsersList import timber.log.Timber import java.net.ConnectException import java.net.UnknownHostException class UsersListFragment : MvvmFragment() { val userListViewModel = App.injectUserListViewModel() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.users_fragment, container, false) } override fun onStart() { super.onStart() subscribe(userListViewModel.getUsers() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ Timber.d("Received UIModel $it users.") showUsers(it) }, { Timber.w(it) showError() })) } fun showUsers(data: UsersList) { if (data.error == null) { usersList.adapter = context?.let { ArrayAdapter(it, android.R.layout.simple_list_item_1, data.users) } } else if (data.error is ConnectException || data.error is UnknownHostException) { Timber.d("No connection, maybe inform user that data loaded from DB.") } else { showError() } } fun showError() { Toast.makeText(context, "An error occurred :(", Toast.LENGTH_SHORT).show() } }
0
Kotlin
0
4
8ec09bed018d57225b85e042865608952633c622
1,856
mobiletaiga
Apache License 2.0
skellig-test-step-processing/src/test/kotlin/org/skellig/teststep/processing/value/extractor/collection/FindFunctionExecutorTest.kt
skellig-framework
263,021,995
false
{"Kotlin": 819078, "CSS": 525608, "Java": 181384, "HTML": 11313, "FreeMarker": 9740, "ANTLR": 2041}
package org.skellig.teststep.processing.value.extractor.collection import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Test class FindFunctionExecutorTest { private val findFunctionExecutor = FindFunctionExecutor() private val findLastFunctionExecutor = FindLastFunctionExecutor() private val findAllFunctionExecutor = FindAllFunctionExecutor() private val values = listOf( mapOf(Pair("name", "Alex"), Pair("balance", 700)), mapOf(Pair("name", "Bob"), Pair("balance", 12)), mapOf(Pair("name", "Chuck"), Pair("balance", 45)) ) @Test fun testFindExpression() { assertEquals(values[1], findFunctionExecutor.extractFrom("find", values, arrayOf({ v: Any? -> (v as Map<*, *>)["name"] == "Bob" }))) assertNull(findFunctionExecutor.extractFrom("find", values, arrayOf({ v: Any? -> (v as Map<*, *>)["name"] == "MyName" }))) } @Test fun testFindLastExpression() { assertEquals(values[2], findLastFunctionExecutor.extractFrom("findLast", values, arrayOf({ v: Any? -> ((v as Map<*, *>)["balance"] as Int) < 100 }))) assertNull(findLastFunctionExecutor.extractFrom("findLast", values, arrayOf({ v: Any? -> ((v as Map<*, *>)["balance"] as Int) > 1000 }))) } @Test fun testFindAllExpression() { assertEquals( listOf(values[1], values[2]), findAllFunctionExecutor.extractFrom("findLast", values, arrayOf({ v: Any? -> ((v as Map<*, *>)["balance"] as Int) < 100 })) ) assertEquals(emptyList<Map<*, *>>(), findAllFunctionExecutor.extractFrom("findLast", values, arrayOf({ v: Any? -> ((v as Map<*, *>)["balance"] as Int) > 1000 }))) } }
17
Kotlin
0
2
64238035cbec9c73268da3e5997fd485f86906fe
1,759
skellig-core
Apache License 2.0
app/src/main/java/com/liyulive/timeer/ui/settings/SettingsFragment.kt
Liyulive
321,229,647
false
null
package com.liyulive.timeer.ui.settings import android.app.AlertDialog import android.content.DialogInterface import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.hjq.permissions.OnPermissionCallback import com.hjq.permissions.Permission import com.hjq.permissions.XXPermissions import com.liyulive.timeer.MainActivity import com.liyulive.timeer.R import com.liyulive.timeer.TimeErApplication import com.liyulive.timeer.ui.settings.diyType.DiyTypeActivity import kotlinx.android.synthetic.main.fragment_settings.* class SettingsFragment : Fragment() { private lateinit var settingsViewModel: SettingsViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { settingsViewModel = ViewModelProvider(this).get(SettingsViewModel::class.java) val root = inflater.inflate(R.layout.fragment_settings, container, false) return root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) setting_diy_type.setOnClickListener { val intent = Intent(this.activity, DiyTypeActivity::class.java) startActivity(intent) } setting_ImportAndExport.setOnClickListener { val intent = Intent(this.activity, ImportAndExportActivity::class.java) XXPermissions.with(this).permission(Permission.MANAGE_EXTERNAL_STORAGE).request(object : OnPermissionCallback { override fun onGranted(permissions: MutableList<String>?, all: Boolean) { if (all) { startActivity(intent) } } override fun onDenied(permissions: MutableList<String>?, never: Boolean) { if (never) { Toast.makeText( TimeErApplication.context, "授权被拒绝,请手动授予存储权限", Toast.LENGTH_SHORT ).show() XXPermissions.startPermissionActivity(this@SettingsFragment, permissions) } else { Toast.makeText(TimeErApplication.context, "获取权限失败", Toast.LENGTH_SHORT) .show() } } }) } setting_about.setOnClickListener { val intent = Intent(this.activity, AboutActivity::class.java) startActivity(intent) } setting_general.setOnClickListener { val intent = Intent(this.activity, GeneralSettingActivity::class.java) startActivity(intent) } } }
0
Kotlin
0
0
701837fd229aa9c9a6319c1d169092fea226f43a
2,989
TimeEr
Apache License 2.0
app/src/main/java/com/wkk/compose/catalog/ui/App.kt
knight-kk
344,404,991
false
null
/* * Copyright 2021 wkk-knight * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wkk.compose.catalog.ui import androidx.compose.animation.Crossfade import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.runtime.Composable import com.wkk.compose.catalog.data.ComposableDemo import com.wkk.compose.catalog.data.DemoCategory import com.wkk.compose.catalog.data.HomeDemoModule import com.wkk.compose.catalog.ui.demopages.DemoContent import com.wkk.compose.catalog.ui.demopages.DemoList import com.wkk.compose.catalog.ui.demopages.Home @ExperimentalFoundationApi @Composable fun App(navigationViewModel: NavigationViewModel) { Surface(color = MaterialTheme.colors.background) { Crossfade(navigationViewModel.currentDemo) { demo -> when (demo) { is HomeDemoModule -> Home(navigationViewModel, demo) is DemoCategory -> DemoList(navigationViewModel, demo) is ComposableDemo -> DemoContent(navigationViewModel, demo) } } } }
0
Kotlin
0
0
1267a695439d4a684418194ef70e0f035e7919ad
1,658
ComposeCatalog
Apache License 2.0
app/src/main/java/ru/object/epsoncamera/extension/Int.kt
MrApple100
505,842,270
false
null
package ru.`object`.epsoncamera.extension fun Int?.orZero(): Int { return this ?: 0 }
0
Kotlin
1
2
f3652040f970fea2c60050631d1eef3bba86bd8c
90
EpsonPlata
Apache License 2.0
src/fungsi.kt
feetbo90
134,932,600
false
null
import java.util.Scanner fun main(args: Array<String>) { var input = Scanner(System.`in`) /* tanpaPengembalianNilai() println(denganPengembalianNilai()) var pengembalianNilai = denganPengembalianNilai() println(pengembalianNilai) var input2 = input.next() var next = denganParameter(input2) println("Hasil Input adalah $next") */ println("masukkan bilangan pertama") var nilai = input.nextInt() println("masukkan bilangan kedua") var nilai2 = input.nextInt() var hasil = pengurangan( nilai2 = nilai) println("maka pengurannya adalah $hasil") println(tambah(nilai, nilai2)) println("${nilai dikali nilai2}") } // ada 2 tipe // tipe pengembalian nilai dan tanpa pengembalian nilai fun tanpaPengembalianNilai() { println("fungsi tanpa pengembalian nilai") } fun denganPengembalianNilai():String { var nilai:String = "Ok" return nilai } fun denganParameter(nilai : String):String{ return nilai } // fungsi named parameter fun pengurangan(nilai: Int= 11, nilai2:Int = 10):Int{ var hasil = nilai - nilai2 return hasil } // fungsi expression // pengembalian nilai //fun perbandingan(bil1 : Int, bil2: Int) :Unit= if(bil1 > bil2)println("${bil1}") else println("${bil2}") fun tambah(a : Int = 1, b : Int = 0) = if(a>b) println(a) else println("ini b $b") // infix function infix fun Int.dikali(bil2 : Int):Int { var hasil = this * bil2 return hasil }
0
Kotlin
0
0
529b95e3b065db86556b7c5cbe8ddfa78742ba22
1,455
Introduction-to-Kotlin
Apache License 2.0
app/src/main/java/com/sample/githubconnect/view/fragments/UserDetailsFragment.kt
chetan-AD
315,594,185
false
null
package com.sample.githubconnect.view.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.navigation.NavOptions import androidx.navigation.fragment.NavHostFragment import com.google.android.material.tabs.TabLayout import com.sample.githubconnect.R import com.sample.githubconnect.databinding.FragmentUserDetailsBinding import com.sample.githubconnect.models.response.Status import com.sample.githubconnect.util.loadUrl import com.sample.githubconnect.viewmodel.UserDetailViewModel import com.sample.githubconnect.viewmodel.UserListViewModel import org.koin.androidx.viewmodel.ext.android.sharedViewModel import org.koin.androidx.viewmodel.ext.android.viewModel class UserDetailsFragment : Fragment() { private val userListViewModel by sharedViewModel<UserListViewModel>() private val userDetailViewModel by viewModel<UserDetailViewModel>() private lateinit var binding: FragmentUserDetailsBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_user_details, container, false) initViewModel() initTabLayout() return binding.root } private fun initViewModel() { binding.lifecycleOwner = this binding.userDetailViewModel = userDetailViewModel initSelectedUserDetails() } private fun initSelectedUserDetails() { val selectedUser = userListViewModel.selectedUser userDetailViewModel.loadUserDetails(selectedUser?.login) binding.imageView.loadUrl(selectedUser?.imageUrl ?: "") binding.loginId.text = selectedUser?.login userDetailViewModel.user.observe(viewLifecycleOwner, { when(it.status){ Status.ERROR -> Toast.makeText(context, it.message, Toast.LENGTH_LONG).show() else -> { } } }) } private fun initTabLayout() { val localNavHost = childFragmentManager.findFragmentById(R.id.base_container) as NavHostFragment val localController = localNavHost.navController val navOptions = NavOptions.Builder() .setLaunchSingleTop(true) .setPopUpTo(localController.graph.startDestination, false) .build() binding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener { override fun onTabSelected(tab: TabLayout.Tab?) { when (tab?.position) { 0 -> localController.navigate( R.id.action_followingListFragment_to_followerListFragment, null, navOptions ) 1 -> localController.navigate( R.id.action_followerListFragment_to_followingListFragment, null, navOptions ) } } override fun onTabUnselected(tab: TabLayout.Tab?) { } override fun onTabReselected(tab: TabLayout.Tab?) { } }) } }
0
Kotlin
0
1
8c3c08e2c803717c9a0d6e7e88b86bc1c0d1d708
3,376
GithubConnect
Apache License 2.0
utbot-framework/src/main/kotlin/org/utbot/framework/codegen/renderer/UtilMethodRenderer.kt
UnitTestBot
480,810,501
false
null
package org.utbot.framework.codegen.renderer import org.utbot.framework.codegen.domain.StaticImport import org.utbot.framework.codegen.domain.builtin.TestClassUtilMethodProvider import org.utbot.framework.codegen.domain.builtin.UtilMethodProvider import org.utbot.framework.codegen.domain.context.CgContextOwner import org.utbot.framework.codegen.tree.importIfNeeded import org.utbot.framework.plugin.api.ClassId import org.utbot.framework.plugin.api.CodegenLanguage import org.utbot.framework.plugin.api.MethodId import org.utbot.framework.plugin.api.MockFramework import org.utbot.framework.plugin.api.util.fieldClassId import org.utbot.framework.plugin.api.util.id import java.lang.invoke.CallSite import java.lang.invoke.LambdaMetafactory import java.lang.invoke.MethodHandle import java.lang.invoke.MethodHandles import java.lang.invoke.MethodType import java.lang.reflect.Field import java.lang.reflect.Method import java.lang.reflect.Modifier import java.util.Arrays import java.util.Objects import java.util.stream.Collectors private enum class Visibility(val text: String) { PRIVATE("private"), @Suppress("unused") PROTECTED("protected"), PUBLIC("public"); infix fun by(language: CodegenLanguage): String { if (this == PUBLIC && language == CodegenLanguage.KOTLIN) { // public is default in Kotlin return "" } return "$text " } } // TODO: This method may throw an exception that will crash rendering. // TODO: Add isolation on rendering: https://github.com/UnitTestBot/UTBotJava/issues/853 internal fun UtilMethodProvider.utilMethodTextById( id: MethodId, mockFrameworkUsed: Boolean, mockFramework: MockFramework, codegenLanguage: CodegenLanguage ): String { // If util methods are declared in the test class, then they are private. Otherwise, they are public. val visibility = if (this is TestClassUtilMethodProvider) Visibility.PRIVATE else Visibility.PUBLIC return with(this) { when (id) { getUnsafeInstanceMethodId -> getUnsafeInstance(visibility, codegenLanguage) createInstanceMethodId -> createInstance(visibility, codegenLanguage) createArrayMethodId -> createArray(visibility, codegenLanguage) setFieldMethodId -> setField(visibility, codegenLanguage) setStaticFieldMethodId -> setStaticField(visibility, codegenLanguage) getFieldValueMethodId -> getFieldValue(visibility, codegenLanguage) getStaticFieldValueMethodId -> getStaticFieldValue(visibility, codegenLanguage) getEnumConstantByNameMethodId -> getEnumConstantByName(visibility, codegenLanguage) deepEqualsMethodId -> deepEquals(visibility, codegenLanguage, mockFrameworkUsed, mockFramework) arraysDeepEqualsMethodId -> arraysDeepEquals(visibility, codegenLanguage) iterablesDeepEqualsMethodId -> iterablesDeepEquals(visibility, codegenLanguage) streamsDeepEqualsMethodId -> streamsDeepEquals(visibility, codegenLanguage) mapsDeepEqualsMethodId -> mapsDeepEquals(visibility, codegenLanguage) hasCustomEqualsMethodId -> hasCustomEquals(visibility, codegenLanguage) getArrayLengthMethodId -> getArrayLength(visibility, codegenLanguage) consumeBaseStreamMethodId -> consumeBaseStream(visibility, codegenLanguage) buildStaticLambdaMethodId -> buildStaticLambda(visibility, codegenLanguage) buildLambdaMethodId -> buildLambda(visibility, codegenLanguage) // the following methods are used only by other util methods, so they can always be private getLookupInMethodId -> getLookupIn(codegenLanguage) getLambdaCapturedArgumentTypesMethodId -> getLambdaCapturedArgumentTypes(codegenLanguage) getLambdaCapturedArgumentValuesMethodId -> getLambdaCapturedArgumentValues(codegenLanguage) getInstantiatedMethodTypeMethodId -> getInstantiatedMethodType(codegenLanguage) getLambdaMethodMethodId -> getLambdaMethod(codegenLanguage) getSingleAbstractMethodMethodId -> getSingleAbstractMethod(codegenLanguage) else -> error("Unknown util method for class $this: $id") } } } // TODO: This method may throw an exception that will crash rendering. // TODO: Add isolation on rendering: https://github.com/UnitTestBot/UTBotJava/issues/853 internal fun UtilMethodProvider.auxiliaryClassTextById(id: ClassId, codegenLanguage: CodegenLanguage): String = with(this) { when (id) { capturedArgumentClassId -> capturedArgumentClass(codegenLanguage) else -> error("Unknown auxiliary class: $id") } } private fun getEnumConstantByName(visibility: Visibility, language: CodegenLanguage): String = when (language) { CodegenLanguage.JAVA -> { """ ${visibility by language}static Object getEnumConstantByName(Class<?> enumClass, String name) throws IllegalAccessException { java.lang.reflect.Field[] fields = enumClass.getDeclaredFields(); for (java.lang.reflect.Field field : fields) { String fieldName = field.getName(); if (field.isEnumConstant() && fieldName.equals(name)) { field.setAccessible(true); return field.get(null); } } return null; } """ } CodegenLanguage.KOTLIN -> { """ ${visibility by language}fun getEnumConstantByName(enumClass: Class<*>, name: String): kotlin.Any? { val fields: kotlin.Array<java.lang.reflect.Field> = enumClass.declaredFields for (field in fields) { val fieldName = field.name if (field.isEnumConstant && fieldName == name) { field.isAccessible = true return field.get(null) } } return null } """ } }.trimIndent() private fun getFieldRetrievingBlock(language : CodegenLanguage, fullClassName : String, fieldName : String, resultName : String): String { val methodName = "methodForGetDeclaredFields${System.nanoTime()}" val fieldsName = "allFieldsFromFieldClass${System.nanoTime()}" return when (language) { CodegenLanguage.JAVA -> """ java.lang.reflect.Method $methodName = java.lang.Class.class.getDeclaredMethod("getDeclaredFields0", boolean.class); $methodName.setAccessible(true); java.lang.reflect.Field[] $fieldsName = (java.lang.reflect.Field[]) $methodName.invoke($fullClassName.class, false); $resultName = java.util.Arrays.stream($fieldsName).filter(field1 -> field1.getName().equals("$fieldName")).findFirst().get(); """ CodegenLanguage.KOTLIN -> """ val $methodName = Class::class.java.getDeclaredMethod("getDeclaredFields0", Boolean::class.java) $methodName.isAccessible = true val $fieldsName = $methodName.invoke($fullClassName::class.java, false) as kotlin.Array<java.lang.reflect.Field> $resultName = $fieldsName.filter { field1: java.lang.reflect.Field -> field1.name == "$fieldName" }.first() """ } } private fun getStaticFieldValue(visibility: Visibility, language: CodegenLanguage): String = when (language) { CodegenLanguage.JAVA -> { """ ${visibility by language}static Object getStaticFieldValue(Class<?> clazz, String fieldName) throws IllegalAccessException, NoSuchFieldException { java.lang.reflect.Field field; Class<?> originClass = clazz; do { try { field = clazz.getDeclaredField(fieldName); field.setAccessible(true); java.lang.reflect.Field modifiersField; ${getFieldRetrievingBlock(language, "java.lang.reflect.Field", "modifiers", "modifiersField")} modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~java.lang.reflect.Modifier.FINAL); return field.get(null); } catch (NoSuchFieldException e) { clazz = clazz.getSuperclass(); } catch (NoSuchMethodException e2) { e2.printStackTrace(); } catch (java.lang.reflect.InvocationTargetException e3) { e3.printStackTrace(); } } while (clazz != null); throw new NoSuchFieldException("Field '" + fieldName + "' not found on class " + originClass); } """ } CodegenLanguage.KOTLIN -> { """ ${visibility by language}fun getStaticFieldValue(clazz: Class<*>, fieldName: String): kotlin.Any? { var currentClass: Class<*>? = clazz var field: java.lang.reflect.Field do { try { field = currentClass!!.getDeclaredField(fieldName) field.isAccessible = true val modifiersField: java.lang.reflect.Field ${getFieldRetrievingBlock(language, "java.lang.reflect.Field", "modifiers", "modifiersField")} modifiersField.isAccessible = true modifiersField.setInt(field, field.modifiers and java.lang.reflect.Modifier.FINAL.inv()) return field.get(null) } catch (e: NoSuchFieldException) { currentClass = currentClass!!.superclass } } while (currentClass != null) throw NoSuchFieldException("Field '" + fieldName + "' not found on class " + clazz) } """ } }.trimIndent() private fun getFieldValue(visibility: Visibility, language: CodegenLanguage): String = when (language) { CodegenLanguage.JAVA -> { """ ${visibility by language}static Object getFieldValue(Object obj, String fieldClassName, String fieldName) throws ClassNotFoundException, NoSuchMethodException, java.lang.reflect.InvocationTargetException, IllegalAccessException, NoSuchFieldException { Class<?> clazz = Class.forName(fieldClassName); java.lang.reflect.Field field = clazz.getDeclaredField(fieldName); field.setAccessible(true); java.lang.reflect.Field modifiersField; ${getFieldRetrievingBlock(language, "java.lang.reflect.Field", "modifiers", "modifiersField")} modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~java.lang.reflect.Modifier.FINAL); return field.get(obj); } """ } CodegenLanguage.KOTLIN -> { """ ${visibility by language}fun getFieldValue(any: kotlin.Any, fieldClassName: String, fieldName: String): kotlin.Any? { val clazz: Class<*> = Class.forName(fieldClassName) val field: java.lang.reflect.Field = clazz.getDeclaredField(fieldName) field.isAccessible = true val modifiersField: java.lang.reflect.Field ${getFieldRetrievingBlock(language, "java.lang.reflect.Field", "modifiers", "modifiersField")} modifiersField.isAccessible = true modifiersField.setInt(field, field.modifiers and java.lang.reflect.Modifier.FINAL.inv()) return field.get(any) } """ } }.trimIndent() private fun setStaticField(visibility: Visibility, language: CodegenLanguage): String = when (language) { CodegenLanguage.JAVA -> { """ ${visibility by language}static void setStaticField(Class<?> clazz, String fieldName, Object fieldValue) throws NoSuchFieldException, IllegalAccessException { java.lang.reflect.Field field; try { do { try { field = clazz.getDeclaredField(fieldName); } catch (Exception e) { clazz = clazz.getSuperclass(); field = null; } } while (field == null); java.lang.reflect.Field modifiersField; ${getFieldRetrievingBlock(language, "java.lang.reflect.Field", "modifiers", "modifiersField")} modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~java.lang.reflect.Modifier.FINAL); field.setAccessible(true); field.set(null, fieldValue); } catch(java.lang.reflect.InvocationTargetException e){ e.printStackTrace(); } catch(NoSuchMethodException e2) { e2.printStackTrace(); } } """ } CodegenLanguage.KOTLIN -> { """ ${visibility by language}fun setStaticField(defaultClass: Class<*>, fieldName: String, fieldValue: kotlin.Any?) { var field: java.lang.reflect.Field? var clazz = defaultClass do { try { field = clazz.getDeclaredField(fieldName) } catch (e: Exception) { clazz = clazz.superclass field = null } } while (field == null) val modifiersField: java.lang.reflect.Field ${getFieldRetrievingBlock(language, "java.lang.reflect.Field", "modifiers", "modifiersField")} modifiersField.isAccessible = true modifiersField.setInt(field, field.modifiers and java.lang.reflect.Modifier.FINAL.inv()) field.isAccessible = true field.set(null, fieldValue) } """ } }.trimIndent() private fun setField(visibility: Visibility, language: CodegenLanguage): String = when (language) { CodegenLanguage.JAVA -> { """ ${visibility by language}static void setField(Object object, String fieldClassName, String fieldName, Object fieldValue) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, java.lang.reflect.InvocationTargetException { Class<?> clazz = Class.forName(fieldClassName); java.lang.reflect.Field field = clazz.getDeclaredField(fieldName); java.lang.reflect.Field modifiersField; ${getFieldRetrievingBlock(language, "java.lang.reflect.Field", "modifiers", "modifiersField")} modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~java.lang.reflect.Modifier.FINAL); field.setAccessible(true); field.set(object, fieldValue); } """ } CodegenLanguage.KOTLIN -> { """ ${visibility by language}fun setField(any: kotlin.Any, fieldClassName: String, fieldName: String, fieldValue: kotlin.Any?) { val clazz: Class<*> = Class.forName(fieldClassName) val field: java.lang.reflect.Field = clazz.getDeclaredField(fieldName) val modifiersField: java.lang.reflect.Field ${getFieldRetrievingBlock(language, "java.lang.reflect.Field", "modifiers", "modifiersField")} modifiersField.isAccessible = true modifiersField.setInt(field, field.modifiers and java.lang.reflect.Modifier.FINAL.inv()) field.isAccessible = true field.set(any, fieldValue) } """ } }.trimIndent() private fun createArray(visibility: Visibility, language: CodegenLanguage): String = when (language) { CodegenLanguage.JAVA -> { """ ${visibility by language}static Object[] createArray(String className, int length, Object... values) throws ClassNotFoundException { Object array = java.lang.reflect.Array.newInstance(Class.forName(className), length); for (int i = 0; i < values.length; i++) { java.lang.reflect.Array.set(array, i, values[i]); } return (Object[]) array; } """ } CodegenLanguage.KOTLIN -> { """ ${visibility by language}fun createArray( className: String, length: Int, vararg values: kotlin.Any ): kotlin.Array<kotlin.Any?> { val array: kotlin.Any = java.lang.reflect.Array.newInstance(Class.forName(className), length) for (i in values.indices) { java.lang.reflect.Array.set(array, i, values[i]) } return array as kotlin.Array<kotlin.Any?> } """ } }.trimIndent() private fun createInstance(visibility: Visibility, language: CodegenLanguage): String = when (language) { CodegenLanguage.JAVA -> { """ ${visibility by language}static Object createInstance(String className) throws Exception { Class<?> clazz = Class.forName(className); return Class.forName("sun.misc.Unsafe").getDeclaredMethod("allocateInstance", Class.class) .invoke(getUnsafeInstance(), clazz); } """ } CodegenLanguage.KOTLIN -> { """ ${visibility by language}fun createInstance(className: String): kotlin.Any { val clazz: Class<*> = Class.forName(className) return Class.forName("sun.misc.Unsafe").getDeclaredMethod("allocateInstance", Class::class.java) .invoke(getUnsafeInstance(), clazz) } """ } }.trimIndent() private fun getUnsafeInstance(visibility: Visibility, language: CodegenLanguage): String = when (language) { CodegenLanguage.JAVA -> { """ ${visibility by language}static Object getUnsafeInstance() throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException { java.lang.reflect.Field f = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); f.setAccessible(true); return f.get(null); } """ } CodegenLanguage.KOTLIN -> { """ ${visibility by language}fun getUnsafeInstance(): kotlin.Any? { val f: java.lang.reflect.Field = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe") f.isAccessible = true return f[null] } """ } }.trimIndent() /** * Mockito mock uses its own equals which we cannot rely on */ private fun isMockCondition(mockFrameworkUsed: Boolean, mockFramework: MockFramework): String { if (!mockFrameworkUsed) return "" return when (mockFramework) { MockFramework.MOCKITO -> " && !org.mockito.Mockito.mockingDetails(o1).isMock()" // in case we will add any other mock frameworks, newer Kotlin compiler versions // will report a non-exhaustive 'when', so we will not forget to support them here as well } } private fun deepEquals( visibility: Visibility, language: CodegenLanguage, mockFrameworkUsed: Boolean, mockFramework: MockFramework ): String = when (language) { CodegenLanguage.JAVA -> { """ static class FieldsPair { final Object o1; final Object o2; public FieldsPair(Object o1, Object o2) { this.o1 = o1; this.o2 = o2; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FieldsPair that = (FieldsPair) o; return java.util.Objects.equals(o1, that.o1) && java.util.Objects.equals(o2, that.o2); } @Override public int hashCode() { return java.util.Objects.hash(o1, o2); } } ${visibility by language}static boolean deepEquals(Object o1, Object o2) { return deepEquals(o1, o2, new java.util.HashSet<>()); } private static boolean deepEquals(Object o1, Object o2, java.util.Set<FieldsPair> visited) { visited.add(new FieldsPair(o1, o2)); if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } if (o1 instanceof Iterable) { if (!(o2 instanceof Iterable)) { return false; } return iterablesDeepEquals((Iterable<?>) o1, (Iterable<?>) o2, visited); } if (o2 instanceof Iterable) { return false; } if (o1 instanceof java.util.stream.BaseStream) { if (!(o2 instanceof java.util.stream.BaseStream)) { return false; } return streamsDeepEquals((java.util.stream.BaseStream<?, ?>) o1, (java.util.stream.BaseStream<?, ?>) o2, visited); } if (o2 instanceof java.util.stream.BaseStream) { return false; } if (o1 instanceof java.util.Map) { if (!(o2 instanceof java.util.Map)) { return false; } return mapsDeepEquals((java.util.Map<?, ?>) o1, (java.util.Map<?, ?>) o2, visited); } if (o2 instanceof java.util.Map) { return false; } Class<?> firstClass = o1.getClass(); if (firstClass.isArray()) { if (!o2.getClass().isArray()) { return false; } // Primitive arrays should not appear here return arraysDeepEquals(o1, o2, visited); } // common classes // check if class has custom equals method (including wrappers and strings) // It is very important to check it here but not earlier because iterables and maps also have custom equals // based on elements equals if (hasCustomEquals(firstClass)${isMockCondition(mockFrameworkUsed, mockFramework)}) { return o1.equals(o2); } // common classes without custom equals, use comparison by fields final java.util.List<java.lang.reflect.Field> fields = new java.util.ArrayList<>(); while (firstClass != Object.class) { fields.addAll(java.util.Arrays.asList(firstClass.getDeclaredFields())); // Interface should not appear here firstClass = firstClass.getSuperclass(); } for (java.lang.reflect.Field field : fields) { field.setAccessible(true); try { final Object field1 = field.get(o1); final Object field2 = field.get(o2); if (!visited.contains(new FieldsPair(field1, field2)) && !deepEquals(field1, field2, visited)) { return false; } } catch (IllegalArgumentException e) { return false; } catch (IllegalAccessException e) { // should never occur because field was set accessible return false; } } return true; } """.trimIndent() } CodegenLanguage.KOTLIN -> { """ ${visibility by language}fun deepEquals(o1: kotlin.Any?, o2: kotlin.Any?): Boolean = deepEquals(o1, o2, hashSetOf()) private fun deepEquals( o1: kotlin.Any?, o2: kotlin.Any?, visited: kotlin.collections.MutableSet<kotlin.Pair<kotlin.Any?, kotlin.Any?>> ): Boolean { visited += o1 to o2 if (o1 === o2) return true if (o1 == null || o2 == null) return false if (o1 is kotlin.collections.Iterable<*>) { return if (o2 !is kotlin.collections.Iterable<*>) false else iterablesDeepEquals(o1, o2, visited) } if (o2 is kotlin.collections.Iterable<*>) return false if (o1 is java.util.stream.BaseStream<*, *>) { return if (o2 !is java.util.stream.BaseStream<*, *>) false else streamsDeepEquals(o1, o2, visited) } if (o2 is java.util.stream.BaseStream<*, *>) return false if (o1 is kotlin.collections.Map<*, *>) { return if (o2 !is kotlin.collections.Map<*, *>) false else mapsDeepEquals(o1, o2, visited) } if (o2 is kotlin.collections.Map<*, *>) return false var firstClass: Class<*> = o1.javaClass if (firstClass.isArray) { return if (!o2.javaClass.isArray) { false } else { arraysDeepEquals(o1, o2, visited) } } // check if class has custom equals method (including wrappers and strings) // It is very important to check it here but not earlier because iterables and maps also have custom equals // based on elements equals if (hasCustomEquals(firstClass)${isMockCondition(mockFrameworkUsed, mockFramework)}) { return o1 == o2 } // common classes without custom equals, use comparison by fields val fields: kotlin.collections.MutableList<java.lang.reflect.Field> = mutableListOf() while (firstClass != kotlin.Any::class.java) { fields += listOf(*firstClass.declaredFields) // Interface should not appear here firstClass = firstClass.superclass } for (field in fields) { field.isAccessible = true try { val field1 = field[o1] val field2 = field[o2] if ((field1 to field2) !in visited && !deepEquals(field1, field2, visited)) return false } catch (e: IllegalArgumentException) { return false } catch (e: IllegalAccessException) { // should never occur return false } } return true } """.trimIndent() } } private fun arraysDeepEquals(visibility: Visibility, language: CodegenLanguage): String = when (language) { CodegenLanguage.JAVA -> { """ ${visibility by language}static boolean arraysDeepEquals(Object arr1, Object arr2, java.util.Set<FieldsPair> visited) { final int length = java.lang.reflect.Array.getLength(arr1); if (length != java.lang.reflect.Array.getLength(arr2)) { return false; } for (int i = 0; i < length; i++) { if (!deepEquals(java.lang.reflect.Array.get(arr1, i), java.lang.reflect.Array.get(arr2, i), visited)) { return false; } } return true; } """.trimIndent() } CodegenLanguage.KOTLIN -> { """ ${visibility by language}fun arraysDeepEquals( arr1: kotlin.Any?, arr2: kotlin.Any?, visited: kotlin.collections.MutableSet<kotlin.Pair<kotlin.Any?, kotlin.Any?>> ): Boolean { val size = java.lang.reflect.Array.getLength(arr1) if (size != java.lang.reflect.Array.getLength(arr2)) return false for (i in 0 until size) { if (!deepEquals(java.lang.reflect.Array.get(arr1, i), java.lang.reflect.Array.get(arr2, i), visited)) { return false } } return true } """.trimIndent() } } private fun iterablesDeepEquals(visibility: Visibility, language: CodegenLanguage): String = when (language) { CodegenLanguage.JAVA -> { """ ${visibility by language}static boolean iterablesDeepEquals(Iterable<?> i1, Iterable<?> i2, java.util.Set<FieldsPair> visited) { final java.util.Iterator<?> firstIterator = i1.iterator(); final java.util.Iterator<?> secondIterator = i2.iterator(); while (firstIterator.hasNext() && secondIterator.hasNext()) { if (!deepEquals(firstIterator.next(), secondIterator.next(), visited)) { return false; } } if (firstIterator.hasNext()) { return false; } return !secondIterator.hasNext(); } """.trimIndent() } CodegenLanguage.KOTLIN -> { """ ${visibility by language}fun iterablesDeepEquals( i1: Iterable<*>, i2: Iterable<*>, visited: kotlin.collections.MutableSet<kotlin.Pair<kotlin.Any?, kotlin.Any?>> ): Boolean { val firstIterator = i1.iterator() val secondIterator = i2.iterator() while (firstIterator.hasNext() && secondIterator.hasNext()) { if (!deepEquals(firstIterator.next(), secondIterator.next(), visited)) return false } return if (firstIterator.hasNext()) false else !secondIterator.hasNext() } """.trimIndent() } } private fun streamsDeepEquals(visibility: Visibility, language: CodegenLanguage): String = when (language) { CodegenLanguage.JAVA -> { """ ${visibility by language}static boolean streamsDeepEquals( java.util.stream.BaseStream<?, ?> s1, java.util.stream.BaseStream<?, ?> s2, java.util.Set<FieldsPair> visited ) { final java.util.Iterator<?> firstIterator = s1.iterator(); final java.util.Iterator<?> secondIterator = s2.iterator(); while (firstIterator.hasNext() && secondIterator.hasNext()) { if (!deepEquals(firstIterator.next(), secondIterator.next(), visited)) { return false; } } if (firstIterator.hasNext()) { return false; } return !secondIterator.hasNext(); } """.trimIndent() } CodegenLanguage.KOTLIN -> { """ ${visibility by language}fun streamsDeepEquals( s1: java.util.stream.BaseStream<*, *>, s2: java.util.stream.BaseStream<*, *>, visited: kotlin.collections.MutableSet<kotlin.Pair<kotlin.Any?, kotlin.Any?>> ): Boolean { val firstIterator = s1.iterator() val secondIterator = s2.iterator() while (firstIterator.hasNext() && secondIterator.hasNext()) { if (!deepEquals(firstIterator.next(), secondIterator.next(), visited)) return false } return if (firstIterator.hasNext()) false else !secondIterator.hasNext() } """.trimIndent() } } private fun mapsDeepEquals(visibility: Visibility, language: CodegenLanguage): String = when (language) { CodegenLanguage.JAVA -> { """ ${visibility by language}static boolean mapsDeepEquals( java.util.Map<?, ?> m1, java.util.Map<?, ?> m2, java.util.Set<FieldsPair> visited ) { final java.util.Iterator<? extends java.util.Map.Entry<?, ?>> firstIterator = m1.entrySet().iterator(); final java.util.Iterator<? extends java.util.Map.Entry<?, ?>> secondIterator = m2.entrySet().iterator(); while (firstIterator.hasNext() && secondIterator.hasNext()) { final java.util.Map.Entry<?, ?> firstEntry = firstIterator.next(); final java.util.Map.Entry<?, ?> secondEntry = secondIterator.next(); if (!deepEquals(firstEntry.getKey(), secondEntry.getKey(), visited)) { return false; } if (!deepEquals(firstEntry.getValue(), secondEntry.getValue(), visited)) { return false; } } if (firstIterator.hasNext()) { return false; } return !secondIterator.hasNext(); } """.trimIndent() } CodegenLanguage.KOTLIN -> { """ ${visibility by language}fun mapsDeepEquals( m1: kotlin.collections.Map<*, *>, m2: kotlin.collections.Map<*, *>, visited: kotlin.collections.MutableSet<kotlin.Pair<kotlin.Any?, kotlin.Any?>> ): Boolean { val firstIterator = m1.entries.iterator() val secondIterator = m2.entries.iterator() while (firstIterator.hasNext() && secondIterator.hasNext()) { val firstEntry = firstIterator.next() val secondEntry = secondIterator.next() if (!deepEquals(firstEntry.key, secondEntry.key, visited)) return false if (!deepEquals(firstEntry.value, secondEntry.value, visited)) return false } return if (firstIterator.hasNext()) false else !secondIterator.hasNext() } """.trimIndent() } } private fun hasCustomEquals(visibility: Visibility, language: CodegenLanguage): String = when (language) { CodegenLanguage.JAVA -> { """ ${visibility by language}static boolean hasCustomEquals(Class<?> clazz) { while (!Object.class.equals(clazz)) { try { clazz.getDeclaredMethod("equals", Object.class); return true; } catch (Exception e) { // Interface should not appear here clazz = clazz.getSuperclass(); } } return false; } """.trimIndent() } CodegenLanguage.KOTLIN -> { """ ${visibility by language}fun hasCustomEquals(clazz: Class<*>): Boolean { var c = clazz while (kotlin.Any::class.java != c) { try { c.getDeclaredMethod("equals", kotlin.Any::class.java) return true } catch (e: Exception) { // Interface should not appear here c = c.superclass } } return false } """.trimIndent() } } private fun getArrayLength(visibility: Visibility, language: CodegenLanguage) = when (language) { CodegenLanguage.JAVA -> """ ${visibility by language}static int getArrayLength(Object arr) { return java.lang.reflect.Array.getLength(arr); } """.trimIndent() CodegenLanguage.KOTLIN -> """ ${visibility by language}fun getArrayLength(arr: kotlin.Any?): Int = java.lang.reflect.Array.getLength(arr) """.trimIndent() } private fun consumeBaseStream(visibility: Visibility, language: CodegenLanguage) = when (language) { CodegenLanguage.JAVA -> """ ${visibility by language}static void consumeBaseStream(java.util.stream.BaseStream stream) { stream.iterator().forEachRemaining(value -> {}); } """.trimIndent() CodegenLanguage.KOTLIN -> { """ ${visibility by language}fun consumeBaseStream(stream: java.util.stream.BaseStream<*, *>) { stream.iterator().forEachRemaining {} } """.trimIndent() } } private fun buildStaticLambda(visibility: Visibility, language: CodegenLanguage) = when (language) { CodegenLanguage.JAVA -> """ /** * @param samType a class representing a functional interface. * @param declaringClass a class where the lambda is declared. * @param lambdaName a name of the synthetic method that represents a lambda. * @param capturedArguments a vararg containing {@link CapturedArgument} instances representing * values that the given lambda has captured. * @return an {@link Object} that represents an instance of the given functional interface {@code samType} * and implements its single abstract method with the behavior of the given lambda. */ ${visibility by language}static Object buildStaticLambda( Class<?> samType, Class<?> declaringClass, String lambdaName, CapturedArgument... capturedArguments ) throws Throwable { // Create lookup for class where the lambda is declared in. java.lang.invoke.MethodHandles.Lookup caller = getLookupIn(declaringClass); // Obtain the single abstract method of a functional interface whose instance we are building. // For example, for `java.util.function.Predicate` it will be method `test`. java.lang.reflect.Method singleAbstractMethod = getSingleAbstractMethod(samType); String invokedName = singleAbstractMethod.getName(); // Method type of single abstract method of the target functional interface. java.lang.invoke.MethodType samMethodType = java.lang.invoke.MethodType.methodType(singleAbstractMethod.getReturnType(), singleAbstractMethod.getParameterTypes()); java.lang.reflect.Method lambdaMethod = getLambdaMethod(declaringClass, lambdaName); lambdaMethod.setAccessible(true); java.lang.invoke.MethodType lambdaMethodType = java.lang.invoke.MethodType.methodType(lambdaMethod.getReturnType(), lambdaMethod.getParameterTypes()); java.lang.invoke.MethodHandle lambdaMethodHandle = caller.findStatic(declaringClass, lambdaName, lambdaMethodType); Class<?>[] capturedArgumentTypes = getLambdaCapturedArgumentTypes(capturedArguments); java.lang.invoke.MethodType invokedType = java.lang.invoke.MethodType.methodType(samType, capturedArgumentTypes); java.lang.invoke.MethodType instantiatedMethodType = getInstantiatedMethodType(lambdaMethod, capturedArgumentTypes); // Create a CallSite for the given lambda. java.lang.invoke.CallSite site = java.lang.invoke.LambdaMetafactory.metafactory( caller, invokedName, invokedType, samMethodType, lambdaMethodHandle, instantiatedMethodType); Object[] capturedValues = getLambdaCapturedArgumentValues(capturedArguments); // Get MethodHandle and pass captured values to it to obtain an object // that represents the target functional interface instance. java.lang.invoke.MethodHandle handle = site.getTarget(); return handle.invokeWithArguments(capturedValues); } """.trimIndent() CodegenLanguage.KOTLIN -> """ /** * @param samType a class representing a functional interface. * @param declaringClass a class where the lambda is declared. * @param lambdaName a name of the synthetic method that represents a lambda. * @param capturedArguments a vararg containing [CapturedArgument] instances representing * values that the given lambda has captured. * @return an [Any] that represents an instance of the given functional interface `samType` * and implements its single abstract method with the behavior of the given lambda. */ ${visibility by language}fun buildStaticLambda( samType: Class<*>, declaringClass: Class<*>, lambdaName: String, vararg capturedArguments: CapturedArgument ): Any { // Create lookup for class where the lambda is declared in. val caller = getLookupIn(declaringClass) // Obtain the single abstract method of a functional interface whose instance we are building. // For example, for `java.util.function.Predicate` it will be method `test`. val singleAbstractMethod = getSingleAbstractMethod(samType) val invokedName = singleAbstractMethod.name // Method type of single abstract method of the target functional interface. val samMethodType = java.lang.invoke.MethodType.methodType(singleAbstractMethod.returnType, singleAbstractMethod.parameterTypes) val lambdaMethod = getLambdaMethod(declaringClass, lambdaName) lambdaMethod.isAccessible = true val lambdaMethodType = java.lang.invoke.MethodType.methodType(lambdaMethod.returnType, lambdaMethod.parameterTypes) val lambdaMethodHandle = caller.findStatic(declaringClass, lambdaName, lambdaMethodType) val capturedArgumentTypes = getLambdaCapturedArgumentTypes(*capturedArguments) val invokedType = java.lang.invoke.MethodType.methodType(samType, capturedArgumentTypes) val instantiatedMethodType = getInstantiatedMethodType(lambdaMethod, capturedArgumentTypes) // Create a CallSite for the given lambda. val site = java.lang.invoke.LambdaMetafactory.metafactory( caller, invokedName, invokedType, samMethodType, lambdaMethodHandle, instantiatedMethodType ) val capturedValues = getLambdaCapturedArgumentValues(*capturedArguments) // Get MethodHandle and pass captured values to it to obtain an object // that represents the target functional interface instance. val handle = site.target return handle.invokeWithArguments(*capturedValues) } """.trimIndent() } private fun buildLambda(visibility: Visibility, language: CodegenLanguage) = when (language) { CodegenLanguage.JAVA -> """ /** * @param samType a class representing a functional interface. * @param declaringClass a class where the lambda is declared. * @param lambdaName a name of the synthetic method that represents a lambda. * @param capturedReceiver an object of {@code declaringClass} that is captured by the lambda. * When the synthetic lambda method is not static, it means that the lambda captures an instance * of the class it is declared in. * @param capturedArguments a vararg containing {@link CapturedArgument} instances representing * values that the given lambda has captured. * @return an {@link Object} that represents an instance of the given functional interface {@code samType} * and implements its single abstract method with the behavior of the given lambda. */ ${visibility by language}static Object buildLambda( Class<?> samType, Class<?> declaringClass, String lambdaName, Object capturedReceiver, CapturedArgument... capturedArguments ) throws Throwable { // Create lookup for class where the lambda is declared in. java.lang.invoke.MethodHandles.Lookup caller = getLookupIn(declaringClass); // Obtain the single abstract method of a functional interface whose instance we are building. // For example, for `java.util.function.Predicate` it will be method `test`. java.lang.reflect.Method singleAbstractMethod = getSingleAbstractMethod(samType); String invokedName = singleAbstractMethod.getName(); // Method type of single abstract method of the target functional interface. java.lang.invoke.MethodType samMethodType = java.lang.invoke.MethodType.methodType(singleAbstractMethod.getReturnType(), singleAbstractMethod.getParameterTypes()); java.lang.reflect.Method lambdaMethod = getLambdaMethod(declaringClass, lambdaName); lambdaMethod.setAccessible(true); java.lang.invoke.MethodType lambdaMethodType = java.lang.invoke.MethodType.methodType(lambdaMethod.getReturnType(), lambdaMethod.getParameterTypes()); java.lang.invoke.MethodHandle lambdaMethodHandle = caller.findVirtual(declaringClass, lambdaName, lambdaMethodType); Class<?>[] capturedArgumentTypes = getLambdaCapturedArgumentTypes(capturedArguments); java.lang.invoke.MethodType invokedType = java.lang.invoke.MethodType.methodType(samType, capturedReceiver.getClass(), capturedArgumentTypes); java.lang.invoke.MethodType instantiatedMethodType = getInstantiatedMethodType(lambdaMethod, capturedArgumentTypes); // Create a CallSite for the given lambda. java.lang.invoke.CallSite site = java.lang.invoke.LambdaMetafactory.metafactory( caller, invokedName, invokedType, samMethodType, lambdaMethodHandle, instantiatedMethodType); Object[] capturedArgumentValues = getLambdaCapturedArgumentValues(capturedArguments); // This array will contain the value of captured receiver // (`this` instance of class where the lambda is declared) // and the values of captured arguments. Object[] capturedValues = new Object[capturedArguments.length + 1]; // Setting the captured receiver value. capturedValues[0] = capturedReceiver; // Setting the captured argument values. System.arraycopy(capturedArgumentValues, 0, capturedValues, 1, capturedArgumentValues.length); // Get MethodHandle and pass captured values to it to obtain an object // that represents the target functional interface instance. java.lang.invoke.MethodHandle handle = site.getTarget(); return handle.invokeWithArguments(capturedValues); } """.trimIndent() CodegenLanguage.KOTLIN -> """ /** * @param samType a class representing a functional interface. * @param declaringClass a class where the lambda is declared. * @param lambdaName a name of the synthetic method that represents a lambda. * @param capturedReceiver an object of `declaringClass` that is captured by the lambda. * When the synthetic lambda method is not static, it means that the lambda captures an instance * of the class it is declared in. * @param capturedArguments a vararg containing [CapturedArgument] instances representing * values that the given lambda has captured. * @return an [Any] that represents an instance of the given functional interface `samType` * and implements its single abstract method with the behavior of the given lambda. */ ${visibility by language}fun buildLambda( samType: Class<*>, declaringClass: Class<*>, lambdaName: String, capturedReceiver: Any, vararg capturedArguments: CapturedArgument ): Any { // Create lookup for class where the lambda is declared in. val caller = getLookupIn(declaringClass) // Obtain the single abstract method of a functional interface whose instance we are building. // For example, for `java.util.function.Predicate` it will be method `test`. val singleAbstractMethod = getSingleAbstractMethod(samType) val invokedName = singleAbstractMethod.name // Method type of single abstract method of the target functional interface. val samMethodType = java.lang.invoke.MethodType.methodType(singleAbstractMethod.returnType, singleAbstractMethod.parameterTypes) val lambdaMethod = getLambdaMethod(declaringClass, lambdaName) lambdaMethod.isAccessible = true val lambdaMethodType = java.lang.invoke.MethodType.methodType(lambdaMethod.returnType, lambdaMethod.parameterTypes) val lambdaMethodHandle = caller.findVirtual(declaringClass, lambdaName, lambdaMethodType) val capturedArgumentTypes = getLambdaCapturedArgumentTypes(*capturedArguments) val invokedType = java.lang.invoke.MethodType.methodType(samType, capturedReceiver.javaClass, *capturedArgumentTypes) val instantiatedMethodType = getInstantiatedMethodType(lambdaMethod, capturedArgumentTypes) // Create a CallSite for the given lambda. val site = java.lang.invoke.LambdaMetafactory.metafactory( caller, invokedName, invokedType, samMethodType, lambdaMethodHandle, instantiatedMethodType ) val capturedValues = mutableListOf<Any?>() .apply { add(capturedReceiver) addAll(getLambdaCapturedArgumentValues(*capturedArguments)) }.toTypedArray() // Get MethodHandle and pass captured values to it to obtain an object // that represents the target functional interface instance. val handle = site.target return handle.invokeWithArguments(*capturedValues) } """.trimIndent() } private fun getLookupIn(language: CodegenLanguage) = when (language) { CodegenLanguage.JAVA -> """ /** * @param clazz a class to create lookup instance for. * @return {@link java.lang.invoke.MethodHandles.Lookup} instance for the given {@code clazz}. * It can be used, for example, to search methods of this {@code clazz}, even the {@code private} ones. */ private static java.lang.invoke.MethodHandles.Lookup getLookupIn(Class<?> clazz) throws IllegalAccessException, NoSuchFieldException, java.lang.NoSuchMethodException, java.lang.reflect.InvocationTargetException { java.lang.invoke.MethodHandles.Lookup lookup = java.lang.invoke.MethodHandles.lookup().in(clazz); // Allow lookup to access all members of declaringClass, including the private ones. // For example, it is useful to access private synthetic methods representing lambdas. java.lang.reflect.Field allowedModes; java.lang.reflect.Field allModesField; ${getFieldRetrievingBlock(language, "java.lang.invoke.MethodHandles.Lookup", "allowedModes", "allowedModes")} ${getFieldRetrievingBlock(language, "java.lang.invoke.MethodHandles.Lookup", "ALL_MODES", "allModesField")} allModesField.setAccessible(true); allowedModes.setAccessible(true); allowedModes.setInt(lookup, (Integer) allModesField.get(null)); return lookup; } """.trimIndent() CodegenLanguage.KOTLIN -> """ /** * @param clazz a class to create lookup instance for. * @return [java.lang.invoke.MethodHandles.Lookup] instance for the given [clazz]. * It can be used, for example, to search methods of this [clazz], even the `private` ones. */ private fun getLookupIn(clazz: Class<*>): java.lang.invoke.MethodHandles.Lookup { val lookup = java.lang.invoke.MethodHandles.lookup().`in`(clazz) // Allow lookup to access all members of declaringClass, including the private ones. // For example, it is useful to access private synthetic methods representing lambdas. val allowedModes: java.lang.reflect.Field val allModesField: java.lang.reflect.Field ${getFieldRetrievingBlock(language, "java.lang.invoke.MethodHandles.Lookup", "allowedModes", "allowedModes")} ${getFieldRetrievingBlock(language, "java.lang.invoke.MethodHandles.Lookup", "ALL_MODES", "allModesField")} allowedModes.isAccessible = true allModesField.isAccessible = true allowedModes.setInt(lookup, allModesField.get(null) as Int) return lookup } """.trimIndent() } private fun getLambdaCapturedArgumentTypes(language: CodegenLanguage) = when (language) { CodegenLanguage.JAVA -> """ /** * @param capturedArguments values captured by some lambda. Note that this argument does not contain * the possibly captured instance of the class where the lambda is declared. * It contains all the other captured values. They are represented as arguments of the synthetic method * that the lambda is compiled into. Hence, the name of the argument. * @return types of the given {@code capturedArguments}. * These types are required to build {@code invokedType}, which represents * the target functional interface with info about captured values' types. * See {@link java.lang.invoke.LambdaMetafactory#metafactory} method documentation for more details on what {@code invokedType} is. */ private static Class<?>[] getLambdaCapturedArgumentTypes(CapturedArgument... capturedArguments) { Class<?>[] capturedArgumentTypes = new Class<?>[capturedArguments.length]; for (int i = 0; i < capturedArguments.length; i++) { capturedArgumentTypes[i] = capturedArguments[i].type; } return capturedArgumentTypes; } """.trimIndent() CodegenLanguage.KOTLIN -> """ /** * @param capturedArguments values captured by some lambda. Note that this argument does not contain * the possibly captured instance of the class where the lambda is declared. * It contains all the other captured values. They are represented as arguments of the synthetic method * that the lambda is compiled into. Hence, the name of the argument. * @return types of the given `capturedArguments`. * These types are required to build `invokedType`, which represents * the target functional interface with info about captured values' types. * See [java.lang.invoke.LambdaMetafactory.metafactory] method documentation for more details on what `invokedType` is. */ private fun getLambdaCapturedArgumentTypes(vararg capturedArguments: CapturedArgument): Array<Class<*>> { return capturedArguments .map { it.type } .toTypedArray() } """.trimIndent() } private fun getLambdaCapturedArgumentValues(language: CodegenLanguage) = when (language) { CodegenLanguage.JAVA -> """ /** * Obtain captured values to be used as captured arguments in the lambda call. */ private static Object[] getLambdaCapturedArgumentValues(CapturedArgument... capturedArguments) { return java.util.Arrays.stream(capturedArguments) .map(argument -> argument.value) .toArray(); } """.trimIndent() CodegenLanguage.KOTLIN -> """ /** * Obtain captured values to be used as captured arguments in the lambda call. */ private fun getLambdaCapturedArgumentValues(vararg capturedArguments: CapturedArgument): Array<Any?> { return capturedArguments .map { it.value } .toTypedArray() } """.trimIndent() } private fun getInstantiatedMethodType(language: CodegenLanguage) = when (language) { CodegenLanguage.JAVA -> """ /** * @param lambdaMethod {@link java.lang.reflect.Method} that represents a synthetic method for lambda. * @param capturedArgumentTypes types of values captured by lambda. * @return {@link java.lang.invoke.MethodType} that represents the value of argument {@code instantiatedMethodType} * of method {@link java.lang.invoke.LambdaMetafactory#metafactory}. */ private static java.lang.invoke.MethodType getInstantiatedMethodType(java.lang.reflect.Method lambdaMethod, Class<?>[] capturedArgumentTypes) { // Types of arguments of synthetic method (representing lambda) without the types of captured values. java.util.List<Class<?>> instantiatedMethodParamTypeList = java.util.Arrays.stream(lambdaMethod.getParameterTypes()) .skip(capturedArgumentTypes.length) .collect(java.util.stream.Collectors.toList()); // The same types, but stored in an array. Class<?>[] instantiatedMethodParamTypes = new Class<?>[instantiatedMethodParamTypeList.size()]; for (int i = 0; i < instantiatedMethodParamTypeList.size(); i++) { instantiatedMethodParamTypes[i] = instantiatedMethodParamTypeList.get(i); } return java.lang.invoke.MethodType.methodType(lambdaMethod.getReturnType(), instantiatedMethodParamTypes); } """.trimIndent() CodegenLanguage.KOTLIN -> """ /** * @param lambdaMethod [java.lang.reflect.Method] that represents a synthetic method for lambda. * @param capturedArgumentTypes types of values captured by lambda. * @return [java.lang.invoke.MethodType] that represents the value of argument `instantiatedMethodType` * of method [java.lang.invoke.LambdaMetafactory.metafactory]. */ private fun getInstantiatedMethodType( lambdaMethod: java.lang.reflect.Method, capturedArgumentTypes: Array<Class<*>> ): java.lang.invoke.MethodType { // Types of arguments of synthetic method (representing lambda) without the types of captured values. val instantiatedMethodParamTypes = lambdaMethod.parameterTypes .drop(capturedArgumentTypes.size) .toTypedArray() return java.lang.invoke.MethodType.methodType(lambdaMethod.returnType, instantiatedMethodParamTypes) } """.trimIndent() } private fun getLambdaMethod(language: CodegenLanguage) = when (language) { CodegenLanguage.JAVA -> """ /** * @param declaringClass class where a lambda is declared. * @param lambdaName name of synthetic method that represents a lambda. * @return {@link java.lang.reflect.Method} instance for the synthetic method that represent a lambda. */ private static java.lang.reflect.Method getLambdaMethod(Class<?> declaringClass, String lambdaName) { return java.util.Arrays.stream(declaringClass.getDeclaredMethods()) .filter(method -> method.getName().equals(lambdaName)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("No lambda method named " + lambdaName + " was found in class: " + declaringClass.getCanonicalName())); } """.trimIndent() CodegenLanguage.KOTLIN -> """ /** * @param declaringClass class where a lambda is declared. * @param lambdaName name of synthetic method that represents a lambda. * @return [java.lang.reflect.Method] instance for the synthetic method that represent a lambda. */ private fun getLambdaMethod(declaringClass: Class<*>, lambdaName: String): java.lang.reflect.Method { return declaringClass.declaredMethods.firstOrNull { it.name == lambdaName } ?: throw IllegalArgumentException("No lambda method named ${'$'}lambdaName was found in class: ${'$'}{declaringClass.canonicalName}") } """.trimIndent() } private fun getSingleAbstractMethod(language: CodegenLanguage) = when (language) { CodegenLanguage.JAVA -> """ private static java.lang.reflect.Method getSingleAbstractMethod(Class<?> clazz) { java.util.List<java.lang.reflect.Method> abstractMethods = java.util.Arrays.stream(clazz.getMethods()) .filter(method -> java.lang.reflect.Modifier.isAbstract(method.getModifiers())) .collect(java.util.stream.Collectors.toList()); if (abstractMethods.isEmpty()) { throw new IllegalArgumentException("No abstract methods found in class: " + clazz.getCanonicalName()); } if (abstractMethods.size() > 1) { throw new IllegalArgumentException("More than one abstract method found in class: " + clazz.getCanonicalName()); } return abstractMethods.get(0); } """.trimIndent() CodegenLanguage.KOTLIN -> """ /** * @param clazz functional interface * @return a [java.lang.reflect.Method] for the single abstract method of the given functional interface `clazz`. */ private fun getSingleAbstractMethod(clazz: Class<*>): java.lang.reflect.Method { val abstractMethods = clazz.methods.filter { java.lang.reflect.Modifier.isAbstract(it.modifiers) } require(abstractMethods.isNotEmpty()) { "No abstract methods found in class: " + clazz.canonicalName } require(abstractMethods.size <= 1) { "More than one abstract method found in class: " + clazz.canonicalName } return abstractMethods[0] } """.trimIndent() } private fun capturedArgumentClass(language: CodegenLanguage) = when (language) { CodegenLanguage.JAVA -> """ /** * This class represents the {@code type} and {@code value} of a value captured by lambda. * Captured values are represented as arguments of a synthetic method that lambda is compiled into, * hence the name of the class. */ public static class CapturedArgument { private Class<?> type; private Object value; public CapturedArgument(Class<?> type, Object value) { this.type = type; this.value = value; } } """.trimIndent() CodegenLanguage.KOTLIN -> { """ /** * This class represents the `type` and `value` of a value captured by lambda. * Captured values are represented as arguments of a synthetic method that lambda is compiled into, * hence the name of the class. */ data class CapturedArgument(val type: Class<*>, val value: Any?) """.trimIndent() } } internal fun CgContextOwner.importUtilMethodDependencies(id: MethodId) { // if util methods come from a separate UtUtils class and not from the test class, // then we don't need to import any other methods, hence we return from method val utilMethodProvider = utilMethodProvider as? TestClassUtilMethodProvider ?: return for (classId in utilMethodProvider.regularImportsByUtilMethod(id, codegenLanguage)) { importIfNeeded(classId) } for (methodId in utilMethodProvider.staticImportsByUtilMethod(id)) { collectedImports += StaticImport(methodId.classId.canonicalName, methodId.name) } } private fun TestClassUtilMethodProvider.regularImportsByUtilMethod( id: MethodId, codegenLanguage: CodegenLanguage ): List<ClassId> { return when (id) { getUnsafeInstanceMethodId -> listOf(fieldClassId) createInstanceMethodId -> listOf(java.lang.reflect.InvocationTargetException::class.id) createArrayMethodId -> listOf(java.lang.reflect.Array::class.id) setFieldMethodId -> listOf(fieldClassId, Modifier::class.id) setStaticFieldMethodId -> listOf(fieldClassId, Modifier::class.id) getFieldValueMethodId -> listOf(fieldClassId, Modifier::class.id) getStaticFieldValueMethodId -> listOf(fieldClassId, Modifier::class.id) getEnumConstantByNameMethodId -> listOf(fieldClassId) deepEqualsMethodId -> when (codegenLanguage) { CodegenLanguage.JAVA -> listOf( Objects::class.id, Iterable::class.id, Map::class.id, List::class.id, ArrayList::class.id, Set::class.id, HashSet::class.id, fieldClassId, Arrays::class.id ) CodegenLanguage.KOTLIN -> listOf(fieldClassId, Arrays::class.id) } arraysDeepEqualsMethodId -> when (codegenLanguage) { CodegenLanguage.JAVA -> listOf(java.lang.reflect.Array::class.id, Set::class.id) CodegenLanguage.KOTLIN -> listOf(java.lang.reflect.Array::class.id) } iterablesDeepEqualsMethodId -> when (codegenLanguage) { CodegenLanguage.JAVA -> listOf(Iterable::class.id, Iterator::class.id, Set::class.id) CodegenLanguage.KOTLIN -> emptyList() } streamsDeepEqualsMethodId -> when (codegenLanguage) { CodegenLanguage.JAVA -> listOf(java.util.stream.BaseStream::class.id, Set::class.id) CodegenLanguage.KOTLIN -> emptyList() } mapsDeepEqualsMethodId -> when (codegenLanguage) { CodegenLanguage.JAVA -> listOf(Map::class.id, Iterator::class.id, Set::class.id) CodegenLanguage.KOTLIN -> emptyList() } hasCustomEqualsMethodId -> emptyList() getArrayLengthMethodId -> listOf(java.lang.reflect.Array::class.id) consumeBaseStreamMethodId -> listOf(java.util.stream.BaseStream::class.id) buildStaticLambdaMethodId -> when (codegenLanguage) { CodegenLanguage.JAVA -> listOf( MethodHandles::class.id, Method::class.id, MethodType::class.id, MethodHandle::class.id, CallSite::class.id, LambdaMetafactory::class.id ) CodegenLanguage.KOTLIN -> listOf(MethodType::class.id, LambdaMetafactory::class.id) } buildLambdaMethodId -> when (codegenLanguage) { CodegenLanguage.JAVA -> listOf( MethodHandles::class.id, Method::class.id, MethodType::class.id, MethodHandle::class.id, CallSite::class.id, LambdaMetafactory::class.id ) CodegenLanguage.KOTLIN -> listOf(MethodType::class.id, LambdaMetafactory::class.id) } getLookupInMethodId -> when (codegenLanguage) { CodegenLanguage.JAVA -> listOf(MethodHandles::class.id, Field::class.id, Modifier::class.id) CodegenLanguage.KOTLIN -> listOf(MethodHandles::class.id, Modifier::class.id) } getLambdaCapturedArgumentTypesMethodId -> when (codegenLanguage) { CodegenLanguage.JAVA -> listOf(LambdaMetafactory::class.id) CodegenLanguage.KOTLIN -> listOf(LambdaMetafactory::class.id) } getLambdaCapturedArgumentValuesMethodId -> when (codegenLanguage) { CodegenLanguage.JAVA -> listOf(Arrays::class.id) CodegenLanguage.KOTLIN -> emptyList() } getInstantiatedMethodTypeMethodId -> when (codegenLanguage) { CodegenLanguage.JAVA -> listOf( Method::class.id, MethodType::class.id, LambdaMetafactory::class.id, java.util.List::class.id, Arrays::class.id, Collectors::class.id ) CodegenLanguage.KOTLIN -> listOf(Method::class.id, MethodType::class.id, LambdaMetafactory::class.id) } getLambdaMethodMethodId -> when (codegenLanguage) { CodegenLanguage.JAVA -> listOf(Method::class.id, Arrays::class.id) CodegenLanguage.KOTLIN -> listOf(Method::class.id) } getSingleAbstractMethodMethodId -> listOf( Method::class.id, java.util.List::class.id, Arrays::class.id, Modifier::class.id, Collectors::class.id ) else -> error("Unknown util method for class $this: $id") } } // Note: for now always returns an empty list, because no util method // requires static imports, but this may change in the future @Suppress("unused", "unused_parameter") private fun TestClassUtilMethodProvider.staticImportsByUtilMethod(id: MethodId): List<MethodId> = emptyList()
415
Kotlin
38
91
f9c95348acb59c1b4fc212ecb36e6b2968e9ac5a
73,653
UTBotJava
Apache License 2.0
HelloArchitectureRetrofit/data/src/main/java/dev/seabat/android/helloarchitectureretrofit/data/datasource/github/model/Owner.kt
seabat
636,759,391
false
{"Kotlin": 83756}
package dev.seabat.android.helloarchitectureretrofit.data.datasource.github.model import com.squareup.moshi.Json data class Owner( @Json(name = "avatar_url") val avatarUrl: String?, )
0
Kotlin
0
0
f8b7521282ed6a54415ecfef5a79dc41a350d047
189
hello-architecture-retrofit
Apache License 2.0
ui/uiDashboard/src/main/kotlin/siarhei/luskanau/android/test/task/ui/dashboard/DashboardViewModelImpl.kt
siarhei-luskanau
860,600,392
false
{"Kotlin": 8555}
package siarhei.luskanau.android.test.task.ui.dashboard class DashboardViewModelImpl : DashboardViewModel() { override fun onLaunched() = Unit }
0
Kotlin
0
0
2ea6379b50b81e590384e5a770bdde91c24ec984
150
android-test-task-09-2024
MIT License
AppSQLite/app/src/main/java/Modelo/BdOpenHelper.kt
Luis-Rmz
239,673,720
false
null
package Modelo import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper val DATABASE_NAME = "Eventos.db" val DATABASE_VERSION = 1 class BdOpenHelper(context: Context): SQLiteOpenHelper(context,DATABASE_NAME,null,DATABASE_VERSION) { override fun onCreate(db: SQLiteDatabase?) { db!!.execSQL(EventosDataSource.CREATE_EVENTOS_SCRIPT) db.execSQL(EventosDataSource.INSERT_EVENTOS_SCRIPT) } override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } }
0
Kotlin
0
0
64013966616fa7b0ddf43f591250bd889ca86f14
683
Kotlin
MIT License
AppSQLite/app/src/main/java/Modelo/BdOpenHelper.kt
Luis-Rmz
239,673,720
false
null
package Modelo import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper val DATABASE_NAME = "Eventos.db" val DATABASE_VERSION = 1 class BdOpenHelper(context: Context): SQLiteOpenHelper(context,DATABASE_NAME,null,DATABASE_VERSION) { override fun onCreate(db: SQLiteDatabase?) { db!!.execSQL(EventosDataSource.CREATE_EVENTOS_SCRIPT) db.execSQL(EventosDataSource.INSERT_EVENTOS_SCRIPT) } override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } }
0
Kotlin
0
0
64013966616fa7b0ddf43f591250bd889ca86f14
683
Kotlin
MIT License