path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/main/kotlin/eZmaxApi/models/BillingentityinternalResponseCompoundAllOf.kt
eZmaxinc
271,950,932
false
null
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package eZmaxApi.models import eZmaxApi.models.BillingentityinternalproductMinusResponseCompound import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * * * @param aObjBillingentityinternalproduct */ data class BillingentityinternalResponseCompoundAllOf ( @Json(name = "a_objBillingentityinternalproduct") val aObjBillingentityinternalproduct: kotlin.collections.List<BillingentityinternalproductMinusResponseCompound> )
0
Kotlin
0
0
775bfa1e6452d8ba1c6c4d7e1781b0977f5301b0
732
eZmax-SDK-kotlin
MIT License
src/main/kotlin/eZmaxApi/models/BillingentityinternalResponseCompoundAllOf.kt
eZmaxinc
271,950,932
false
null
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package eZmaxApi.models import eZmaxApi.models.BillingentityinternalproductMinusResponseCompound import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * * * @param aObjBillingentityinternalproduct */ data class BillingentityinternalResponseCompoundAllOf ( @Json(name = "a_objBillingentityinternalproduct") val aObjBillingentityinternalproduct: kotlin.collections.List<BillingentityinternalproductMinusResponseCompound> )
0
Kotlin
0
0
775bfa1e6452d8ba1c6c4d7e1781b0977f5301b0
732
eZmax-SDK-kotlin
MIT License
app/src/main/java/com/rainfool/md/avtivitystack/StackAActivity.kt
RainFool
113,412,056
false
null
package com.rainfool.md.avtivitystack import android.os.Bundle import android.util.Log import com.rainfool.md.BaseActivity import com.rainfool.md.R class StackAActivity : BaseActivity() { init { Log.d(tag, "constructor: ") } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_stack_a) } }
1
null
1
1
9fbae53d7bcd5299ffc9440ec3953fb0e3c35942
404
MDEffectDemo
MIT License
plugins/kotlin/idea/tests/testData/quickfix/replaceWithSafeCall/assignmentToPropertyWithNoExplicitType.kt
ingokegel
72,937,917
false
null
// "Replace with safe (?.) call" "true" // WITH_STDLIB class T(s: String?) { var i = s<caret>.length } // FUS_QUICKFIX_NAME: org.jetbrains.kotlin.idea.quickfix.ReplaceWithSafeCallFix // FUS_K2_QUICKFIX_NAME: org.jetbrains.kotlin.idea.quickfix.ReplaceWithSafeCallFix
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
270
intellij-community
Apache License 2.0
roboquant-core/src/jupyter/AssetAllocationChart.kt
neurallayer
406,929,056
false
null
/* * Copyright 2021 Neural Layer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.roboquant.jupyter import org.roboquant.brokers.Account import java.math.BigDecimal /** * Plot the allocation of assets as a pie chart * @property account the account to use * @property includeCash also include cash balances next to the portfolio, default is true * @property includeAssetClass group per assetClass, default is false * @constructor Create a new asset allocation chart */ class AssetAllocationChart( private val account: Account, private val includeCash: Boolean = true, private val includeAssetClass: Boolean = false, ) : Chart() { private class Entry(val name: String, val value: BigDecimal, val type: String) { fun toMap() = mapOf("name" to name, "value" to value, "type" to type) } private fun toSeriesData(): List<Entry> { val result = mutableListOf<Entry>() if (includeCash) { for (amount in account.cash.toAmounts()) { val localAmount = account.convert(amount).toBigDecimal() result.add(Entry(amount.currency.displayName, localAmount, "CASH")) } } for (position in account.positions.sortedBy { it.asset.symbol }) { val asset = position.asset val localAmount = account.convert(position.exposure).toBigDecimal() result.add(Entry(asset.symbol, localAmount, asset.type.name)) } return result } private fun renderPie(): String { val gson = gsonBuilder.create() val d = toSeriesData().map { it.toMap() } val data = gson.toJson(d) val series = """ { type: 'pie', radius: '80%', emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } }, data : $data } """.trimIndent() return """ { title: { text: 'Asset allocation' }, tooltip : {}, ${renderToolbox(false)}, ${renderGrid()}, series : [$series] } """ } /** * This custom toolbox enables to switch between a sunburst and treemap view of the asset allocation */ @Suppress("MaxLineLength") private val toolbox = """ toolbox: { feature: { dataZoom: { yAxisIndex: 'none' }, dataView: {readOnly: true}, saveAsImage: {}, restore: {}, myFeature: { show: true, title: 'Pie/Map', icon: 'path://M432.45,595.444c0,2.177-4.661,6.82-11.305,6.82c-6.475,0-11.306-4.567-11.306-6.82s4.852-6.812,11.306-6.812C427.841,588.632,432.452,593.191,432.45,595.444L432.45,595.444z M421.155,589.876c-3.009,0-5.448,2.495-5.448,5.572s2.439,5.572,5.448,5.572c3.01,0,5.449-2.495,5.449-5.572C426.604,592.371,424.165,589.876,421.155,589.876L421.155,589.876z M421.146,591.891c-1.916,0-3.47,1.589-3.47,3.549c0,1.959,1.554,3.548,3.47,3.548s3.469-1.589,3.469-3.548C424.614,593.479,423.062,591.891,421.146,591.891L421.146,591.891zM421.146,591.891', onclick: function () { let currentType = myChart.getOption().series[0].type; option.series[0].type = currentType === 'sunburst' ? 'treemap' : 'sunburst'; myChart.setOption(option); } } } }""".trimIndent() private fun renderSunburst(): String { val gson = gsonBuilder.create() val d = toSeriesData().groupBy { it.type } .map { entry -> mapOf("name" to entry.key, "children" to entry.value.map { it.toMap() }) } val data = gson.toJson(d) val series = """ { type: 'sunburst', radius: '80%', data : $data } """.trimIndent() return """ { title: { text: 'Asset allocation' }, tooltip : {}, $toolbox, series : [$series] } """.trimIndent() } /** @suppress */ override fun renderOption(): String { return if (includeAssetClass) renderSunburst() else renderPie() } }
4
Kotlin
9
27
601f0b39950a53b32889d6c3688b2bcfecae9323
5,011
roboquant
Apache License 2.0
source/android/adaptivecards/src/main/java/io/adaptivecards/renderer/typeaheadsearch/TypeAheadHelper.kt
microsoft
75,978,731
false
null
package io.adaptivecards.renderer.typeaheadsearch import android.graphics.Typeface import android.text.Html import android.text.SpannableString import android.text.SpannableStringBuilder import android.text.Spanned import android.text.style.BackgroundColorSpan import android.text.style.ForegroundColorSpan import android.text.style.StyleSpan import androidx.annotation.ColorInt import java.util.* import java.util.regex.PatternSyntaxException object TypeAheadHelper { fun createHighlightedSearchResultText( text: String?, highlightTexts: Array<String>?, @ColorInt backgroundColor: Int, @ColorInt highlightTextColor: Int ): Spanned { if (text != null && text.isEmpty()) { return SpannableString("") } val lowerCaseHighlightTexts: MutableList<String> = ArrayList() if (highlightTexts != null) { for (highlightText in highlightTexts) { if (highlightText.isNotBlank() && highlightText.isNotEmpty()) { lowerCaseHighlightTexts.add(highlightText.lowercase(Locale.getDefault())) } } } return if (lowerCaseHighlightTexts.size == 0) { Html.fromHtml(text) } else try { val spannableText = SpannableStringBuilder(text) for (lowerQuery in lowerCaseHighlightTexts) { highlightSpannableText( spannableText, lowerQuery, backgroundColor, highlightTextColor ) } spannableText } catch (ignored: PatternSyntaxException) { // as the user can input any string - it might lead to an invalid regex. in such case - do not highlight Html.fromHtml(text) } catch (ignored: IndexOutOfBoundsException) { // in rare cases the index can be out of bound when setting span. in such case - do not highlight Html.fromHtml(text) } } private fun highlightSpannableText( spannableText: SpannableStringBuilder, lowerQuery: String, @ColorInt backgroundColor: Int, @ColorInt highlightTextColor: Int ) { val lowerText = spannableText.toString().lowercase(Locale.getDefault()) val length = lowerQuery.length var idx = lowerText.indexOf(lowerQuery) while (idx != -1) { val span = StyleSpan(Typeface.BOLD) spannableText.setSpan(span, idx, idx + length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) spannableText.setSpan( BackgroundColorSpan(backgroundColor), idx, idx + length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) if (highlightTextColor != 0) { spannableText.setSpan( ForegroundColorSpan(highlightTextColor), idx, idx + length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) } idx = lowerText.indexOf(lowerQuery, idx + 1) } } }
868
C#
514
1,526
57bc90b1b50b24604146b447c560eb15a3ba3975
3,105
AdaptiveCards
MIT License
core/src/commonMain/kotlin/com/littlekt/graphics/HdpiMode.kt
littlektframework
442,309,478
false
{"Kotlin": 2170511, "Java": 1717152, "C": 111391}
package com.littlekt.graphics import com.littlekt.Graphics /** * @author <NAME> * @date 2/7/2023 */ enum class HdpiMode { /** * Mouse coordinates, [Graphics.width] and [Graphics.height] will return as logical coordinates * according to the defined HDPI scaling. */ LOGICAL, /** * Mouse coordinates, [Graphics.width] and [Graphics.height] will return as raw pixel * coordinates, ignoring any defined HDPI scaling. */ PIXELS }
14
Kotlin
12
316
100c37feefcfd65038a9cba4886aeb4a7d5632dc
477
littlekt
Apache License 2.0
mobile-ui/src/androidTest/java/com/lekaha/simpletube/ui/injection/component/TestApplicationComponent.kt
lekaha
122,983,306
false
null
package com.lekaha.simpletube.ui.injection.component import android.app.Application import com.lekaha.simpletube.domain.executor.PostExecutionThread import com.lekaha.simpletube.domain.repository.SimpletubeRepository import com.lekaha.simpletube.ui.injection.module.TestActivityBindingModule import com.lekaha.simpletube.ui.injection.module.TestApplicationModule import com.lekaha.simpletube.ui.injection.scopes.PerApplication import com.lekaha.simpletube.ui.test.TestApplication import dagger.BindsInstance import dagger.Component import dagger.android.support.AndroidSupportInjectionModule @Component( modules = [TestApplicationModule::class, TestActivityBindingModule::class, AndroidSupportInjectionModule::class] ) @PerApplication interface TestApplicationComponent : ApplicationComponent { fun simpletubeRepository(): SimpletubeRepository fun postExecutionThread(): PostExecutionThread fun inject(application: TestApplication) @Component.Builder interface Builder { @BindsInstance fun application(application: Application): Builder fun build(): TestApplicationComponent } }
0
Kotlin
1
2
6ee542991cb6d960e30c37b9b279a4f76c37b238
1,146
youtube-like-video-player
MIT License
persian/src/main/java/io/github/madmaximuus/persian/menus/PersianMenuItem.kt
MADMAXIMUUS
689,789,834
false
{"Kotlin": 712511}
package io.github.madmaximuus.persian.menus import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.widthIn import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.text.TextStyle import androidx.compose.ui.unit.dp import io.github.madmaximuus.persian.foundation.spacing import io.github.madmaximuus.persian.iconBox.PersianIconBox @Composable internal fun PersianMenuItem( title: String, modifier: Modifier = Modifier, onItemClick: () -> Unit, colors: MenuItemColors = PersianMenuDefaults.itemColors(), textStyle: TextStyle = MaterialTheme.typography.bodyLarge, enabled: Boolean = true, isNegative: Boolean = false, leadingIcon: Painter? = null, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() } ) { DropdownMenuItem( enabled = enabled, modifier = modifier, text = { Text( modifier = Modifier.widthIn(112.dp), text = title, style = textStyle, color = colors.titleColor(enabled = enabled, isNegative = isNegative).value ) }, leadingIcon = leadingIcon?.let { { CompositionLocalProvider( LocalContentColor provides colors.leadingIconColor( enabled = enabled, isNegative = isNegative ).value ) { PersianIconBox(icon = it) } } }, contentPadding = PaddingValues(horizontal = MaterialTheme.spacing.large), onClick = onItemClick, interactionSource = interactionSource ) }
0
Kotlin
1
1
dcbbf7d4883332be6be25232da1c3be76ae58ceb
2,188
Persian
MIT License
src/main/kotlin/io/kanro/idea/plugin/protobuf/lang/psi/stub/impl/ProtobufFileStubImpl.kt
yuxin-zhao
359,704,598
true
{"Kotlin": 311223, "Lex": 6288, "Java": 730}
package io.kanro.idea.plugin.protobuf.lang.psi.stub.impl import com.intellij.psi.stubs.PsiFileStubImpl import com.intellij.psi.util.QualifiedName import io.kanro.idea.plugin.protobuf.lang.psi.ProtobufFile import io.kanro.idea.plugin.protobuf.lang.psi.stub.ProtobufFileStub class ProtobufFileStubImpl(file: ProtobufFile?) : PsiFileStubImpl<ProtobufFile>(file), ProtobufFileStub { override fun scope(): QualifiedName { return QualifiedName.fromComponents(childrenStubs.filterIsInstance<ProtobufPackageNameStub>().map { it.name() }) } }
0
null
0
0
43fd148d80b7d11c17b12fb2be7df5b1fd68dba4
552
intellij-protobuf-plugin
Apache License 2.0
datastore/datastore-core/src/androidMain/kotlin/androidx/datastore/core/MulticastFileObserver.android.kt
androidx
256,589,781
false
null
/* * Copyright 2023 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 androidx.datastore.core import android.os.FileObserver import androidx.annotation.CheckResult import androidx.annotation.VisibleForTesting import java.io.File import java.util.concurrent.CopyOnWriteArrayList import kotlinx.coroutines.DisposableHandle import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.channels.trySendBlocking import kotlinx.coroutines.flow.channelFlow internal typealias FileMoveObserver = (String?) -> Unit /** * A [FileObserver] wrapper that works around the Android bug that breaks observers when multiple * observers are registered on the same directory. * * see: b/37017033, b/279997241 */ @Suppress("DEPRECATION") internal class MulticastFileObserver private constructor( val path: String, ) : FileObserver(path, MOVED_TO) { /** * The actual listeners. We are using a CopyOnWriteArrayList because this field is modified by * the companion object. */ private val delegates = CopyOnWriteArrayList<FileMoveObserver>() override fun onEvent(event: Int, path: String?) { delegates.forEach { it(path) } } companion object { private val LOCK = Any() // visible for tests to be able to validate all observers are removed at the end @VisibleForTesting internal val fileObservers = mutableMapOf<String, MulticastFileObserver>() /** * Returns a `Flow` that emits a `Unit` every time the give [file] is changed. It also emits * a `Unit` when the file system observer is established. Note that this class only observes * move events as it is the only event needed for DataStore. */ @CheckResult fun observe(file: File) = channelFlow { val flowObserver = { fileName: String? -> if (fileName == file.name) { // Note that, this block still be called after channel is closed as the disposal // of the listener happens after the channel is closed. // We don't need to check the result of `trySendBlocking` because we are not // worried about missed events that happen after the channel is closed. trySendBlocking(Unit) } } val disposeListener = observe(file.parentFile!!, flowObserver) // Send Unit after we create the observer on the filesystem, to denote "initialization". // This is not necessary for DataStore to function but it makes it easier to control // state in the MulticastFileObserverTest (e.g. test can know that the file system // observer is registered before continuing with assertions). send(Unit) awaitClose { disposeListener.dispose() } } /** * Creates a system level file observer (if needed) and starts observing the given [parent] * directory. * * Callers should dispose the returned handle when it is done. */ @CheckResult private fun observe(parent: File, observer: FileMoveObserver): DisposableHandle { val key = parent.canonicalFile.path synchronized(LOCK) { val filesystemObserver = fileObservers.getOrPut(key) { MulticastFileObserver(key) } filesystemObserver.delegates.add(observer) if (filesystemObserver.delegates.size == 1) { // start watching inside the lock so we can avoid the bug if multiple observers // are registered/unregistered in parallel filesystemObserver.startWatching() } } return DisposableHandle { synchronized(LOCK) { fileObservers[key]?.let { filesystemObserver -> filesystemObserver.delegates.remove(observer) // return the instance if it needs to be stopped if (filesystemObserver.delegates.isEmpty()) { fileObservers.remove(key) // stop watching inside the lock so we can avoid the bug if multiple // observers are registered/unregistered in parallel filesystemObserver.stopWatching() } } } } } /** * Used in tests to cleanup all observers. There are tests that will potentially leak * observers, which is usually OK but it is harmful for the tests of * [MulticastFileObserver], hence we provide this API to cleanup. */ @VisibleForTesting internal fun removeAllObservers() { synchronized(LOCK) { fileObservers.values.forEach { it.stopWatching() } fileObservers.clear() } } } }
29
null
1011
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
5,552
androidx
Apache License 2.0
di/src/main/java/com/grappim/hateitorrateit/di/RepoModule.kt
Grigoriym
704,244,986
false
{"Kotlin": 443700}
package com.grappim.hateitorrateit.di import com.grappim.hateitorrateit.data.repoapi.BackupImagesRepository import com.grappim.hateitorrateit.data.repoapi.ProductsRepository import com.grappim.hateitorrateit.data.repoimpl.BackupImagesRepositoryImpl import com.grappim.hateitorrateit.data.repoimpl.ProductsRepositoryImpl import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @[Module InstallIn(SingletonComponent::class)] interface RepoModule { @Binds fun bindProductsRepository(productsRepositoryImpl: ProductsRepositoryImpl): ProductsRepository @Binds fun bindTempImagesRepository( tempImagesRepositoryImpl: BackupImagesRepositoryImpl ): BackupImagesRepository }
7
Kotlin
0
1
6d34205597a6934f0f71b7120abfb5003997e8db
760
HateItOrRateIt
Apache License 2.0
otter-spring-boot-starter/src/test/resources/migrations/A.kts
GoodGoodJM
371,238,916
false
null
import io.github.goodgoodjm.otter.core.Migration import io.github.goodgoodjm.otter.core.dsl.Constraint.* import io.github.goodgoodjm.otter.core.dsl.createtable.and import io.github.goodgoodjm.otter.core.dsl.createtable.constraints import io.github.goodgoodjm.otter.core.dsl.type.Type.INT import io.github.goodgoodjm.otter.core.dsl.type.Type.VARCHAR object : Migration() { override val comment = "Create person" override fun up() { createTable("person") { "id" - INT constraints PRIMARY and AUTO_INCREMENT "name" - VARCHAR constraints UNIQUE "age" - INT } } override fun down() { dropTable("person") } }
2
Kotlin
1
0
18ef1f478ff707f093d054bde5f40236d811a33b
685
otter
MIT License
app/src/main/java/com/example/kdmeudinheiro/viewModel/NewsLetterViewModel.kt
KdMeuDinSerasa
401,728,969
false
{"Kotlin": 139545}
package com.example.kdmeudinheiro.viewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.kdmeudinheiro.model.ReciviedArticles import com.example.kdmeudinheiro.repository.NewsLetterRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class NewsLetterViewModel @Inject constructor(private val repository: NewsLetterRepository) : ViewModel() { private val _mNewsList = MutableLiveData<ReciviedArticles>() val mNewsList: LiveData<ReciviedArticles> = _mNewsList fun getNews(page: Int){ viewModelScope.launch { _mNewsList.value = repository.getNews(page) } } }
0
Kotlin
0
0
2d27b380dcaad70f7cb23c2b26a4e3119c1ddabe
815
kdmeudinAppFinal
MIT License
integration-tests/src/test/resources/srcs-gen/workload/src/main/kotlin/com/example/Baz.kt
google
297,744,725
false
{"Kotlin": 2173589, "Shell": 5321, "Java": 3893}
package com.example class Baz
370
Kotlin
268
2,854
a977fb96b05ec9c3e15b5a0cf32e8e7ea73ab3b3
31
ksp
Apache License 2.0
src/main/kotlin/me/shutkin/assur/Histogram.kt
shutkin
135,262,745
false
{"Kotlin": 58266}
package me.shutkin.assur import me.shutkin.assur.filters.MAX_SUB_ARRAYS import java.io.FileOutputStream import java.util.concurrent.atomic.AtomicInteger class HistogramData(val minValue: Double, val maxValue: Double, val histogram: DoubleArray) fun buildHistogram(minValue: Double, maxValue: Double, precision: Int, dataSize: Int, dataSource: (Int) -> Double): HistogramData { val counters = Array(precision) { AtomicInteger(0) } val blockSize = Math.ceil(dataSize.toDouble() / 16.0).toInt() val blocksNum = Math.ceil(dataSize.toDouble() / blockSize).toInt() (0 until blocksNum).map { blockIndex -> val blockStart = blockIndex * blockSize val blockEndUnbound = (blockIndex + 1) * blockSize val blockEnd = if (blockEndUnbound > dataSize) dataSize else blockEndUnbound (blockStart until blockEnd).forEach { val index = ((dataSource(it) - minValue) * (precision - 1) / (maxValue - minValue)).toInt() if (index in 0 until precision) counters[index].incrementAndGet() } } return HistogramData(minValue, maxValue, DoubleArray(precision) { counters[it].get().toDouble() / dataSize }) } fun getHistogramLowValue(data: HistogramData, threshold: Double) = convertIndexToValue(data, data.histogram.indexOfFirst { v -> v > threshold }) fun getHistogramHighValue(data: HistogramData, threshold: Double) = convertIndexToValue(data, data.histogram.indexOfLast { v -> v > threshold }) fun getHistogramMedianValue(data: HistogramData, threshold: Double): Double { var sum = 0.0 for (i in data.histogram.indices) { sum += data.histogram[i] if (sum > threshold) return convertIndexToValue(data, i) } return 0.5 * (data.minValue + data.maxValue) } private fun convertIndexToValue(data: HistogramData, index: Int) = if (index < 0) 0.0 else data.minValue + (data.maxValue - data.minValue) * index / (data.histogram.size - 1.0) fun saveHistogram(histogram: DoubleArray, filename: String) = saveHDRRaster(HDRRaster(histogram.size, 1024) { val x = it % histogram.size val y = it / histogram.size val v = histogram[x] * 1024.0 * 16.0 if (1024 - y < v) RGB(255f, 255f, 255f) else RGB(0f, 0f, 0f) }, FileOutputStream(filename))
0
Kotlin
0
0
c867705ff97ca18ea1f26f1f69b085711d0a9bd1
2,269
assur
Apache License 2.0
v1_29/src/main/java/de/loosetie/k8s/dsl/manifests/ContainerStateRunning.kt
loosetie
283,145,621
false
{"Kotlin": 8925107}
package de.loosetie.k8s.dsl.manifests import de.loosetie.k8s.dsl.K8sTopLevel import de.loosetie.k8s.dsl.K8sDslMarker import de.loosetie.k8s.dsl.K8sManifest import de.loosetie.k8s.dsl.HasMetadata @K8sDslMarker interface ContainerStateRunning_core_v1: K8sManifest { /** Time at which the container was last (re-)started */ val startedAt: Time_meta_v1? }
0
Kotlin
0
2
57d56ab780bc3134c43377e647e7f0336a5f17de
358
k8s-dsl
Apache License 2.0
bundles/github.com/korlibs/korge-bundles/7439e5c7de7442f2cd33a1944846d44aea31af0a/korau-opus/src/commonMain/kotlin/com/soywiz/korau/format/org/gragravarr/ogg/audio/OggAudioSetupHeader.kt
jfbilodeau
402,501,246
false
null
/* * 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 korlibs.audio.format.org.gragravarr.ogg.audio import korlibs.audio.format.org.gragravarr.ogg.* /** * Common interface for the Setup header near the * start of an [OggAudioStream]. * * Note that not all Ogg Audio formats have Setup headers. */ interface OggAudioSetupHeader : OggStreamPacket
0
Kotlin
1
2
306f034be2d9832743c3fb0acfbfd46b53c7f01f
868
BeyondBeachball
Apache License 2.0
plugins/full-line/src/org/jetbrains/completion/full/line/platform/handlers/FullLineInsertHandler.kt
xGreat
182,651,778
false
{"Text": 7190, "INI": 570, "YAML": 416, "Ant Build System": 10, "Batchfile": 28, "Shell": 616, "Markdown": 680, "Ignore List": 125, "Git Revision List": 1, "Git Attributes": 10, "EditorConfig": 244, "XML": 7188, "SVG": 3739, "Kotlin": 48905, "Java": 80666, "HTML": 3312, "Java Properties": 214, "Gradle": 419, "Maven POM": 82, "JavaScript": 212, "CSS": 69, "JFlex": 32, "JSON": 1374, "Groovy": 3308, "XSLT": 113, "desktop": 1, "Python": 15070, "JAR Manifest": 18, "PHP": 47, "Gradle Kotlin DSL": 477, "Protocol Buffer": 3, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Diff": 135, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 1, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 27, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 67, "GraphQL": 60, "OpenStep Property List": 47, "Tcl": 1, "Dockerfile": 5, "fish": 1, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "Elixir": 2, "Ruby": 5, "XML Property List": 81, "Starlark": 2, "E-mail": 18, "Roff": 38, "Roff Manpage": 2, "Swift": 3, "C": 84, "TOML": 153, "Proguard": 2, "PlantUML": 6, "Checksums": 72, "Java Server Pages": 8, "reStructuredText": 68, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 17, "C++": 32, "Handlebars": 1, "Rust": 9, "Makefile": 1, "Go": 34, "Go Checksums": 1, "Go Module": 1, "VBScript": 1, "NSIS": 5, "Thrift": 3, "Cython": 12, "Regular Expression": 3, "JSON5": 4}
package org.jetbrains.completion.full.line.platform.handlers import com.intellij.codeInsight.completion.InsertHandler import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.template.impl.LiveTemplateLookupElementImpl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Document import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.TextRange import org.jetbrains.completion.full.line.language.FullLineLanguageSupporter import org.jetbrains.completion.full.line.platform.FullLineLookupElement import org.jetbrains.completion.full.line.platform.diagnostics.FullLinePart import org.jetbrains.completion.full.line.platform.diagnostics.logger import org.jetbrains.completion.full.line.settings.state.MLServerCompletionSettings class FullLineInsertHandler private constructor(private val supporter: FullLineLanguageSupporter) : InsertHandler<FullLineLookupElement> { override fun handleInsert(context: InsertionContext, item: FullLineLookupElement) { ApplicationManager.getApplication().runWriteAction { val document = context.document val offset = context.tailOffset var completionRange = TextRange(context.startOffset + item.head.length, context.selectionEndOffset) if (item.suffix.isNotEmpty()) { context.document.insertString(context.selectionEndOffset, item.suffix) context.commitDocument() completionRange = completionRange.grown(item.suffix.length) } val endLine = document.getLineEndOffset(document.getLineNumber(offset)) if (LOG.isDebugEnabled) { val starLine = document.getLineStartOffset(document.getLineNumber(offset)) LOG.debug( "Full line with picked suggestion: `" + document.getText(starLine, context.startOffset) + "|${document.getText(context.startOffset, context.tailOffset)}|" + document.getText(context.tailOffset, endLine) + "`." ) } val elementAtStart = context.file.findElementAt(completionRange.startOffset) ?: return@runWriteAction removeOverwritingChars( document.getText(TextRange.create(completionRange.startOffset, offset)), document.getText(TextRange.create(context.selectionEndOffset, endLine)) ).takeIf { it > 0 }?.run { LOG.debug("Removing overwriting characters `${document.text.substring(offset, +offset)}`.") document.deleteString(offset, plus(offset)) } if ( MLServerCompletionSettings.getInstance().enableStringsWalking(supporter.language) && supporter.isStringWalkingEnabled(elementAtStart) ) { val template = supporter.createStringTemplate(context.file, TextRange(context.startOffset, completionRange.endOffset)) if (template != null) { LOG.debug("Create string-walking template `${template.string}`.") LiveTemplateLookupElementImpl.startTemplate(context, template) } } ProgressManager.getInstance().executeNonCancelableSection { val importedElements = supporter.autoImportFix(context.file, context.editor, completionRange) if (LOG.isDebugEnabled && importedElements.isNotEmpty()) { val a = "Elements were imported:" + importedElements.joinToString("--\n\t--") { it.text } LOG.debug(a) } } } } private fun removeOverwritingChars(completion: String, line: String): Int { var amount = 0 for (char in line) { var found = false for (charWithOffset in completion.drop(amount)) { if (!charWithOffset.isLetterOrWhitespace() && charWithOffset == char) { found = true break } } if (found) { amount++ } else { break } } return amount } private fun Char.isLetterOrWhitespace(): Boolean { return isWhitespace() || isLetter() } companion object { private val LOG = logger<FullLineInsertHandler>(FullLinePart.PRE_PROCESSING) fun of(context: InsertionContext, supporter: FullLineLanguageSupporter): InsertHandler<FullLineLookupElement> { return when (context.completionChar) { '\t' -> FirstTokenInsertHandler(supporter) else -> FullLineInsertHandler(supporter) } } } } fun Document.getText(start: Int, end: Int): String { return text.substring(start, end) }
1
null
1
1
fb5f23167ce9cc53bfa3ee054b445cf4d8f1ce98
4,446
intellij-community
Apache License 2.0
core/src/main/java/com/mobilepqi/core/data/repository/dashboard/GetTugasRepositoryImpl.kt
acalapatih
708,105,917
false
{"Kotlin": 524790}
package com.mobilepqi.core.data.repository.dashboard import com.mobilepqi.core.data.NetworkOnlyResource import com.mobilepqi.core.data.Resource import com.mobilepqi.core.data.source.remote.RemoteDataSource import com.mobilepqi.core.data.source.remote.network.ApiResponse import com.mobilepqi.core.data.source.remote.response.dashboard.GetTugasResponse import com.mobilepqi.core.domain.model.dashboard.GetTugasModel import com.mobilepqi.core.domain.repository.dashboard.GetTugasRepository import kotlinx.coroutines.flow.Flow class GetTugasRepositoryImpl( private val remoteDataSource: RemoteDataSource ): GetTugasRepository { override fun getTugas(idKelas: Int): Flow<Resource<GetTugasModel>> = object : NetworkOnlyResource<GetTugasModel, GetTugasResponse>() { override fun loadFromNetwork(data: GetTugasResponse): Flow<GetTugasModel> = GetTugasModel.mapResponseToModel(data) override suspend fun createCall(): Flow<ApiResponse<GetTugasResponse>> = remoteDataSource.getTugas(idKelas) }.asFlow() }
0
Kotlin
0
0
e4c7c4a93d1c2b1632a45c827b9df76652b0d0f7
1,080
MobilePQI_mobileApps
MIT License
app/src/main/java/com/xengar/android/deutscheverben/utils/FragmentUtils.kt
xanewton
137,806,030
false
null
/* * Copyright (C) 2018 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xengar.android.deutscheverben.utils import android.content.Context import android.net.ConnectivityManager import android.net.NetworkInfo import android.support.v4.app.FragmentActivity import android.view.View import fr.castorflex.android.circularprogressbar.CircularProgressBar /** * FragmentUtils */ object FragmentUtils { /** * Checks for internet connection. * @return true if connected or connecting */ fun checkInternetConnection(fragmentActivity: FragmentActivity): Boolean { val cm = fragmentActivity.getSystemService( Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetwork: NetworkInfo? = cm.activeNetworkInfo return activeNetwork != null && activeNetwork.isConnectedOrConnecting } /** * Changes to visible or gone the circular progress bar. * @param progressBar progress Bar * @param visibility boolean */ fun updateProgressBar(progressBar: CircularProgressBar?, visibility: Boolean) { if (progressBar != null) { progressBar.visibility = if (visibility) View.VISIBLE else View.GONE } } }
0
null
0
1
9fd81930d294927dfc99d54d0473fc14753bf888
1,754
DeutscheVerben
Apache License 2.0
bbfgradle/tmp/results/diffCompile/iwndnww_PROJECT.kt
DaniilStepanov
346,008,310
false
null
// Bug happens on JVM -Xuse-fir, JVM // TARGET_BACKEND: JVM // FILE: JavaCall.java class JavaCall { String call(Test test) { return test.call(); } } // FILE: Test.java interface Test { String call(); default String test() { return "K"; } static String testStatic() { return "K"; } } // FILE: sam.kt fun box(): String { val lambda = { "OK" } if (kotlin.test != "UNCHECKED_CAST") return "1" return JavaCall().call {"OK"} }
1
null
1
1
e772ef1f8f951873ebe7d8f6d73cf19aead480fa
493
kotlinWithFuzzer
Apache License 2.0
app/src/main/java/com/kamaltatyana/redgallery/di/ViewModelModule.kt
TatyanaBazhanova
132,364,766
false
null
package com.kamaltatyana.redgallery.di import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.kamaltatyana.redgallery.view.search.SearchViewModel import com.kamaltatyana.redgallery.viewmodel.GalleryViewModelFactory import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap @Suppress("unused") @Module abstract class ViewModelModule { @Binds @IntoMap @ViewModelKey(SearchViewModel::class) abstract fun bindSearchViewModel(searchViewModel: SearchViewModel): ViewModel @Binds abstract fun bindViewModelFactory(factory: GalleryViewModelFactory): ViewModelProvider.Factory }
0
Kotlin
0
0
da68677527fd797b73ce4c479da1a7b260510900
651
GalleryApp
Apache License 2.0
app/src/main/java/com/mob/lee/fastair/viewmodel/BeforeViewModel.kt
hongui
123,892,735
false
{"Kotlin": 223529, "HTML": 16935, "Svelte": 11650, "Java": 1951, "CSS": 1572, "JavaScript": 552}
package com.mob.lee.fastair.viewmodel import android.content.Context import com.mob.lee.fastair.model.DataWrap import com.mob.lee.fastair.model.Record import com.mob.lee.fastair.repository.DataBaseDataSource /** * * @Author: Andy(632518410) * @CreateDate: 2020/6/18 15:34 * @Description: 无 */ class BeforeViewModel : AppViewModel() { val database by lazy { DataBaseDataSource() } val waitRecords = HashSet<Record>() fun waitRecords(context: Context?) = asyncWithWrap { database.recordDao(context) { val records = waitRecords() waitRecords.clear() waitRecords.addAll(records) DataWrap.success(records) } } fun toggle(record: Record?) { record?.state = if (Record.STATE_WAIT == record?.state) { Record.STATE_ORIGIN } else { Record.STATE_WAIT } } fun submit(context: Context?) = asyncWithWrap { database.recordDao(context) { val records = waitRecords.filter { Record.STATE_WAIT != it.state } clearRecord(records) val size=waitRecords.filter { Record.STATE_WAIT == it.state }.size waitRecords.clear() DataWrap.success(size) } } }
3
Kotlin
15
82
ed357bc88292f77f0629cef8e969a5bc06a583a6
1,282
FastAir
Apache License 2.0
app/src/main/java/com/nrk/newsbreeze/di/DatabaseModule.kt
ningu2102
502,826,089
false
null
package com.nrk.newsbreeze.di import android.app.Application import androidx.room.Room import com.nrk.newsbreeze.data.local.ArticleDao import com.nrk.newsbreeze.data.local.ArticleDatabase import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object DatabaseModule { @Provides @Singleton fun provideDatabase(application: Application, callback: ArticleDatabase.Callback): ArticleDatabase{ return Room.databaseBuilder(application, ArticleDatabase::class.java, "news_database") .fallbackToDestructiveMigration() .addCallback(callback) .build() } @Provides fun provideArticleDao(db: ArticleDatabase): ArticleDao{ return db.getArticleDao() } }
1
Kotlin
0
0
5ac013f41360b05774c77d2ee5839eb5ce716a3a
865
NewsBreeze
Apache License 2.0
src/main/kotlin/nl/jackploeg/aoc/_2022/calendar/day08/Day08.kt
jackploeg
736,755,380
false
{"Kotlin": 318734}
package nl.jackploeg.aoc._2022.calendar.day08 import javax.inject.Inject import nl.jackploeg.aoc.generators.InputGenerator.InputGeneratorFactory import nl.jackploeg.aoc.utilities.readStringFile class Day08 @Inject constructor( private val generatorFactory: InputGeneratorFactory, ) { // count visible trees fun partOne(fileName: String): Int { val input = readStringFile(fileName) val grid = initTreeGrid(input) return countVisibleTrees(grid.first) } // get max scenic score fun partTwo(fileName: String): Int { val input = readStringFile(fileName) val grid = initTreeGrid(input) return grid.first.flatMap { it.trees }.maxOfOrNull { it.scenicScore() }!! } fun countVisibleTrees(rows: ArrayList<Row>): Int { return rows.flatMap { it.trees }.filter { it.isVisible() }.count() } fun initTreeGrid(lines: List<String>): Pair<ArrayList<Row>, ArrayList<Column>> { var i = 0 val rows: ArrayList<Row> = ArrayList() val columns: ArrayList<Column> = ArrayList() do { val trees = lines[i].toCharArray() if (i <= rows.size) { rows.add(Row(i)) } val row = rows[i] var j = 0 do { if (j <= columns.size) { columns.add(Column(j)) } val column = columns[j] val tree = Tree(row, i, column, j, lines[i][j].digitToInt()) row.trees.add(tree) column.trees.add(tree) j++ } while (j < trees.size) i++ } while (i < lines.size) return Pair(rows, columns) } class Row(val number: Int, val trees: ArrayList<Tree> = ArrayList()) class Column(val number: Int, val trees: ArrayList<Tree> = ArrayList()) class Tree(private val row: Row, private val rowIndex: Int, private val column: Column, private val columnIndex: Int, private val height: Int) { fun isVisible(): Boolean { return rowIndex == 0 || rowIndex == row.trees.size - 1 || columnIndex == 0 || columnIndex == column.trees.size - 1 || allSmaller(row.trees, columnIndex) || allSmaller(column.trees, rowIndex) } fun scenicScore(): Int { return scenicScore(row.trees, columnIndex) * scenicScore(column.trees, rowIndex) } private fun allSmaller(collection: ArrayList<Tree>, index: Int): Boolean { val before = collection.subList(0, index) val after = collection.subList(index + 1, collection.size) return before.map { it.height }.filter { it >= this.height }.isEmpty() || after.map { it.height }.filter { it >= this.height }.isEmpty() } private fun scenicScore(collection: ArrayList<Tree>, index: Int): Int { val before = collection.subList(0, index) var score1 = 0 if (index > 0) { for (i in index - 1 downTo 0) { score1++ if (before[i].height >= height) break } } var score2 = 0 if (index < collection.size) { for (i in index + 1 until collection.size) { score2++ if (collection[i].height >= height) break } } return score1 * score2 } } }
0
Kotlin
0
0
f2b873b6cf24bf95a4ba3d0e4f6e007b96423b76
3,618
advent-of-code
MIT License
app/src/main/java/com/projectAnya/stunthink/presentation/screen/food/FoodDetailViewModel.kt
MFachriA
646,533,160
false
null
package com.projectAnya.stunthink.presentation.screen.food import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.projectAnya.stunthink.domain.common.Resource import com.projectAnya.stunthink.domain.use_case.monitoring.child.AddChildFoodUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.receiveAsFlow import javax.inject.Inject @HiltViewModel class FoodDetailViewModel @Inject constructor( private val addChildFoodUseCase: AddChildFoodUseCase ): ViewModel() { val foodPortionState = MutableStateFlow(1f) private val _state = mutableStateOf(FoodDetailState()) val submitState: State<FoodDetailState> = _state private val validationEventChannel = Channel<ValidationEvent>() val validationEvents = validationEventChannel.receiveAsFlow() fun updateFoodPortion(portion: Float) { foodPortionState.value = portion } fun onSubmit( token: String, id: String, foodPercentage: Float, foodId: String, foodImageUrl: String? ) { addChildFoodUseCase.invoke( token = token, id = id, foodPercentage = foodPercentage, foodId = foodId, foodImageUrl = foodImageUrl ).onEach { result -> when (result) { is Resource.Success -> { _state.value = FoodDetailState( message = result.message ?: "Register berhasil!" ) if (result.success == true) { validationEventChannel.send(ValidationEvent.Success(_state.value.message)) } else if (result.success == false) { validationEventChannel.send(ValidationEvent.Failed(_state.value.message)) } } is Resource.Error -> { _state.value = FoodDetailState( message = result.message ?: "Terjadi kesalahan tak terduga" ) validationEventChannel.send(ValidationEvent.Failed(_state.value.message)) } is Resource.Loading -> { _state.value = FoodDetailState(isLoading = true) } } }.launchIn(viewModelScope) } sealed class ValidationEvent { data class Success(val message: String): ValidationEvent() data class Failed(val message: String): ValidationEvent() } }
0
Kotlin
0
1
6f08934e310bad0ff38065f0819f25173cd45499
2,792
StunThink
Freetype Project License
felles/src/main/kotlin/no/nav/helsearbeidsgiver/felles/rapidsrivers/IRedisStore.kt
navikt
495,713,363
false
null
package no.nav.helsearbeidsgiver.felles.rapidsrivers interface IRedisStore { fun set(key: String, value: String, ttl: Long = 60L) fun get(key: String): String? fun exist(vararg keys: String): Long fun shutdown() }
7
Kotlin
0
2
675e15bbbe24a959dd9425830a1724ca6f920588
231
helsearbeidsgiver-inntektsmelding
MIT License
mobile_app1/module72/src/main/java/module72packageKt0/Foo113.kt
uber-common
294,831,672
false
null
package module72packageKt0; annotation class Foo113Fancy @Foo113Fancy class Foo113 { fun foo0(){ module72packageKt0.Foo112().foo4() } fun foo1(){ foo0() } fun foo2(){ foo1() } fun foo3(){ foo2() } fun foo4(){ foo3() } }
6
Java
6
72
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
265
android-build-eval
Apache License 2.0
TabCommon/CommonLibrary/src/main/java/com/nextzy/library/base/utils/HawkPreference.kt
Nextzy
105,441,969
false
null
package com.nextzy.library.base.utils import com.orhanobut.hawk.Hawk import java.util.* /** * Created by「 <NAME> 」on 03 Oct 2017 :) */ object HawkPreference { val KEY_DATA_1 = "key_data_1" val KEY_DATA_2 = "key_data_3" val KEY_DATA_3 = "key_data_2" private val SEPARATE = "_" fun saveData(data1: String, data2: String, data3: String) { Hawk.put(KEY_DATA_1, data1) Hawk.put(KEY_DATA_2, data2) Hawk.put(KEY_DATA_3, data3) } fun loadData(): Map<String, String> { val result = HashMap<String, String>() result.put(KEY_DATA_1, Hawk.get<Any>(KEY_DATA_1, null) as String) result.put(KEY_DATA_2, Hawk.get<Any>(KEY_DATA_2, null) as String) result.put(KEY_DATA_3, Hawk.get<Any>(KEY_DATA_3, null) as String) return result } fun removeRemove() { Hawk.delete(KEY_DATA_1) Hawk.delete(KEY_DATA_1) Hawk.delete(KEY_DATA_1) } }
1
Kotlin
1
4
64c38c1078f952ff01eadebc45458530352eb798
985
nextdroid-architecture
Apache License 2.0
app/src/main/java/com/usu/rougelikev2/game/gameobjects/BossMonster.kt
SpencerPotter99
761,973,495
false
{"Kotlin": 64593}
package com.usu.rougelikev2.game.gameobjects import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import com.usu.rougelikev2.game.gameengine.Game import com.usu.rougelikev2.game.gameengine.GameObject import com.usu.rougelikev2.game.gameengine.Location import java.util.* import kotlin.math.roundToInt class BossMonster(game: Game?) : GameObject(game!!) { var pattern: ArrayList<Int>? = null var turnNumber = 0 override fun update(elapsedTime: Long) { if (pattern == null) { pattern = ArrayList() pattern!!.add(0) pattern!!.add(1) for (i in 0 until state.get("level")) { val move = Math.random().roundToInt() pattern!!.add(move) } } val isAlive = state.get<Boolean>("alive") val turn = game.gameState.get<String>("turn") if (turn !== "monster") return game.gameState["endTurn"] = true if (!isAlive) return val action = pattern!![turnNumber % pattern!!.size] if (action == 1) { // move turnNumber++ val map = game.gameState.get<Array<Array<GameObject?>>>("map") if (checkForPlayer()) { val player = game.getGameObjectWithTag("player") val playerLocation: Location = player!!.state["coords"] val myLocation: Location = state["coords"] if (myLocation.x != playerLocation.x && myLocation.y != playerLocation.y) { if (myLocation.y < playerLocation.y) { val other = map[myLocation.y.toInt() + 1][myLocation.x.toInt()] if (other == null) { map[myLocation.y.toInt()][myLocation.x.toInt()] = null myLocation.y = myLocation.y + 1 map[myLocation.y.toInt()][myLocation.x.toInt()] = this return } } if (myLocation.y > playerLocation.y) { val other = map[myLocation.y.toInt() - 1][myLocation.x.toInt()] if (other == null) { map[myLocation.y.toInt()][myLocation.x.toInt()] = null myLocation.y = myLocation.y - 1 map[myLocation.y.toInt()][myLocation.x.toInt()] = this return } } if (myLocation.x < playerLocation.x) { val other = map[myLocation.y.toInt()][myLocation.x.toInt() + 1] if (other == null) { map[myLocation.y.toInt()][myLocation.x.toInt()] = null myLocation.x = myLocation.x + 1 map[myLocation.y.toInt()][myLocation.x.toInt()] = this return } } if (myLocation.x > playerLocation.x) { val other = map[myLocation.y.toInt()][myLocation.x.toInt()] if (other == null) { map[myLocation.y.toInt()][myLocation.x.toInt()] = null myLocation.x = myLocation.x - 1 map[myLocation.y.toInt()][myLocation.x.toInt()] = this return } } moveRandom() } else if (myLocation.x == playerLocation.x) { // same column if (myLocation.y < playerLocation.y) { val other = map[myLocation.y.toInt()][myLocation.x.toInt()] if (other is Player) { // end the game other.state["alive"] = false game.gameState["playing"] = false return } else if (other == null) { map[myLocation.y.toInt()][myLocation.x.toInt()] = null myLocation.y = myLocation.y + 1 map[myLocation.y.toInt()][myLocation.x.toInt()] = this return } } if (myLocation.y > playerLocation.y) { val other = map[myLocation.y.toInt() - 1][myLocation.x.toInt()] if (other is Player) { // end the game other.state["alive"] = false game.gameState["playing"] = false return } else if (other == null) { map[myLocation.y.toInt()][myLocation.x.toInt()] = null myLocation.y = myLocation.y - 1 map[myLocation.y.toInt()][myLocation.x.toInt()] = this return } } moveRandom() } else if (myLocation.y == playerLocation.y) { // same row if (myLocation.x < playerLocation.x) { val other = map[myLocation.y.toInt()][myLocation.x.toInt() + 1] if (other is Player) { // end the game other.state["alive"] = false game.gameState["playing"] = false return } else if (other == null) { map[myLocation.y.toInt()][myLocation.x.toInt()] = null myLocation.x = myLocation.x + 1 map[myLocation.y.toInt()][myLocation.x.toInt()] = this return } } if (myLocation.x > playerLocation.x) { val other = map[myLocation.y.toInt()][myLocation.x.toInt() - 1] if (other is Player) { // end the game other.state["alive"] = false game.gameState["playing"] = false return } else if (other == null) { map[myLocation.y.toInt()][myLocation.x.toInt()] = null myLocation.x = myLocation.x - 1 map[myLocation.y.toInt()][myLocation.x.toInt()] = this return } } moveRandom() } } else { moveRandom() } } else { turnNumber++ } } private fun moveRandom() { val neighbors = mutableListOf<Int>() neighbors.add(1) neighbors.add(2) neighbors.add(3) neighbors.add(4) neighbors.shuffle() val map = game.gameState.get<Array<Array<GameObject?>>>("map") val myLocation: Location = state.get("coords") while (neighbors.isNotEmpty()) { val `val` = neighbors.removeAt(0) if (`val` == 1) { if (myLocation.y > 0 && map[myLocation.y.toInt() - 1][myLocation.x.toInt()] == null) { map[myLocation.y.toInt() - 1][myLocation.x.toInt()] = this map[myLocation.y.toInt()][myLocation.x.toInt()] = null myLocation.y = myLocation.y - 1 return } } if (`val` == 2) { if (myLocation.x < map[0].size - 1 && map[myLocation.y.toInt()][myLocation.x.toInt() + 1] == null) { map[myLocation.y.toInt()][myLocation.x.toInt() + 1] = this map[myLocation.y.toInt()][myLocation.x.toInt()] = null myLocation.x = myLocation.x + 1 return } } if (`val` == 3) { if (myLocation.y < map.size - 1 && map[myLocation.y.toInt() + 1][myLocation.x.toInt()] == null) { map[myLocation.y.toInt() + 1][myLocation.x.toInt()] = this map[myLocation.y.toInt()][myLocation.x.toInt()] = null myLocation.y = myLocation.y + 1 return } } if (`val` == 4) { if (myLocation.x > 0 && map[myLocation.y.toInt()][myLocation.x.toInt() - 1] == null) { map[myLocation.y.toInt()][myLocation.x.toInt() - 1] = this map[myLocation.y.toInt()][myLocation.x.toInt()] = null myLocation.x = myLocation.x - 1 return } } } } private fun checkForPlayer(): Boolean { val player = game.getGameObjectWithTag("player") val playerLocation: Location = player!!.state.get("coords") val myLocation: Location = state.get("coords") val distance = Math.sqrt( Math.pow( (playerLocation.x - myLocation.x).toDouble(), 2.0 ) + Math.pow((playerLocation.y - myLocation.y).toDouble(), 2.0) ) return distance < 5 } override fun render(canvas: Canvas, paint: Paint) { // things you can do in this render method for reference. // val coords: Location = state["coords"] // gets the location of the object in the grid // val cellSize: Int = game.gameState["cellSize"] // gets the size of each cell in the game // val myX = coords.x * cellSize // gets the current x position (in pixels) in screen space // val myY = coords.y * cellSize // gets the current y position (in pixels) in screen space // val alive: Boolean = state["alive"] // get whether or not the monster is alive // val level: Int = state["level"]; // gets the difficulty level of the monster // val health: Int = state["health"]; // gets how much health the monster has left val coords: Location = state["coords"] val cellSize: Int = game.gameState["cellSize"] val myX = coords.x * cellSize val myY = coords.y * cellSize canvas.translate(myX, myY) val alive: Boolean = state["alive"] if (alive) { paint.color = Color.GRAY canvas.drawCircle(-15f,84f, 10f, paint) canvas.drawCircle(0f,97f, 19f, paint) canvas.drawCircle(35f,120f, 25f, paint) canvas.drawCircle(80f,120f, 30f, paint) canvas.drawCircle(120f,100f, 35f, paint) canvas.drawCircle(150f,50f, 40f, paint) canvas.drawCircle(200f,40f, 60f, paint) paint.color = Color.BLACK paint.style = Paint.Style.STROKE paint.strokeWidth = 2f canvas.drawCircle(-15f,84f, 5f, paint) canvas.drawCircle(0f,97f, 14f, paint) canvas.drawCircle(35f,120f, 20f, paint) canvas.drawCircle(80f,120f, 25f, paint) canvas.drawCircle(120f,100f, 30f, paint) canvas.drawCircle(150f,50f, 35f, paint) canvas.drawCircle(200f,40f, 55f, paint) paint.style = Paint.Style.FILL canvas.drawCircle(230f,27f, 17f, paint) } else { paint.color = Color.GRAY canvas.drawCircle(40f,100f, 40f, paint) canvas.drawCircle(70f,60f, 45f, paint) canvas.drawCircle(100f,100f, 40f, paint) paint.style = Paint.Style.STROKE paint.strokeWidth = 4f paint.color = Color.BLACK canvas.drawCircle(40f, 100f,35f,paint ) canvas.drawCircle(70f,60f, 40f, paint) canvas.drawCircle(100f,100f, 35f, paint) paint.style = Paint.Style.FILL paint.color = Color.RED canvas.drawCircle(90f,50f, 15f, paint) } } init { state["alive"] = true state["health"] = 6 state["level"] = 1 // will be overridden by game after instantiation } }
0
Kotlin
0
0
7bf5f868a05b595280b7d460575f5ea869e24124
12,283
RogueLikeKotlin
MIT License
common/src/main/kotlin/org/valkyrienskies/mod/common/BlockStateInfoProvider.kt
AlphaMode
561,128,018
false
null
package org.valkyrienskies.mod.common import com.mojang.serialization.Lifecycle import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap import net.minecraft.core.BlockPos import net.minecraft.core.MappedRegistry import net.minecraft.core.Registry import net.minecraft.resources.ResourceKey import net.minecraft.resources.ResourceLocation import net.minecraft.world.level.Level import net.minecraft.world.level.block.Block import net.minecraft.world.level.block.state.BlockState import org.valkyrienskies.core.game.VSBlockType import org.valkyrienskies.mod.common.config.MassDatapackResolver import org.valkyrienskies.mod.event.RegistryEvents // Other mods can then provide weights and types based on their added content // NOTE: if we have block's in vs-core we should ask getVSBlock(blockstate: BlockStat): VSBlock since thatd be more handy // altough we might want to allow null properties in VSBlock that is returned since we do want partial data fetching // https://github.com/ValkyrienSkies/Valkyrien-Skies-2/issues/25 interface BlockStateInfoProvider { val priority: Int fun getBlockStateMass(blockState: BlockState): Double? fun getBlockStateType(blockState: BlockState): VSBlockType? } object BlockStateInfo { // registry for mods to add their weights val REGISTRY = MappedRegistry<BlockStateInfoProvider>( ResourceKey.createRegistryKey(ResourceLocation(ValkyrienSkiesMod.MOD_ID, "blockstate_providers")), Lifecycle.experimental() ) private lateinit var SORTED_REGISTRY: List<BlockStateInfoProvider> // init { doesn't work since the class gets loaded too late fun init() { Registry.register(REGISTRY, ResourceLocation(ValkyrienSkiesMod.MOD_ID, "data"), MassDatapackResolver) Registry.register( REGISTRY, ResourceLocation(ValkyrienSkiesMod.MOD_ID, "default"), DefaultBlockStateInfoProvider ) RegistryEvents.onRegistriesComplete { SORTED_REGISTRY = REGISTRY.sortedByDescending { it.priority } } } // This is [ThreadLocal] because in single-player games the Client thread and Server thread will read/write to // [CACHE] simultaneously. This creates a data race that can crash the game (See https://github.com/ValkyrienSkies/Valkyrien-Skies-2/issues/126). val CACHE: ThreadLocal<Int2ObjectOpenHashMap<Pair<Double, VSBlockType>>> = ThreadLocal.withInitial { Int2ObjectOpenHashMap<Pair<Double, VSBlockType>>() } // NOTE: this caching can get allot better, ex. default just returns constants so it might be more faster // if we store that these values do not need to be cached by double and blocktype but just that they use default impl // this gets the weight and type provided by providers; or it gets it out of the cache fun get(blockState: BlockState): Pair<Double, VSBlockType>? = getId(blockState)?.let { CACHE.get().getOrPut(it) { iterateRegistry(blockState) } } fun getId(blockState: BlockState): Int? { val r = Block.getId(blockState) if (r == -1) return null return r } private fun iterateRegistry(blockState: BlockState): Pair<Double, VSBlockType> = Pair( SORTED_REGISTRY.firstNotNullOf { it.getBlockStateMass(blockState) }, SORTED_REGISTRY.firstNotNullOf { it.getBlockStateType(blockState) }, ) // NOTE: this gets called irrelevant if the block is actually on a ship; so it needs to be changed that // shipObjectWorld only requests the data if needed (maybe supplier?) // NOTE2: spoken of in discord in the future well have prob block's in vs-core with id's and then // the above issue shall be fixed // https://github.com/ValkyrienSkies/Valkyrien-Skies-2/issues/25 fun onSetBlock(level: Level, blockPos: BlockPos, prevBlockState: BlockState, newBlockState: BlockState) = onSetBlock(level, blockPos.x, blockPos.y, blockPos.z, prevBlockState, newBlockState) fun onSetBlock(level: Level, x: Int, y: Int, z: Int, prevBlockState: BlockState, newBlockState: BlockState) { if (!::SORTED_REGISTRY.isInitialized) return val shipObjectWorld = level.shipObjectWorld val (prevBlockMass, prevBlockType) = get(prevBlockState) ?: return val (newBlockMass, newBlockType) = get(newBlockState) ?: return shipObjectWorld.onSetBlock( x, y, z, level.dimensionId, prevBlockType, newBlockType, prevBlockMass, newBlockMass ) } }
1
null
1
2
545394e1bcb200cecfd2a0d451610941e6d3d9d4
4,474
Valkyrien-Skies-2
Apache License 2.0
compiler/backend/src/org/jetbrains/kotlin/codegen/inline/TryBlockClustering.kt
virtuoushub
32,282,897
true
{"Markdown": 21, "XML": 504, "Ant Build System": 33, "Ignore List": 8, "Kotlin": 14560, "Java": 4036, "Protocol Buffer": 2, "Roff": 18, "Roff Manpage": 4, "Text": 3020, "JAR Manifest": 1, "INI": 6, "HTML": 102, "Groovy": 7, "Gradle": 62, "Maven POM": 39, "Java Properties": 10, "CSS": 10, "JavaScript": 53, "JFlex": 3, "Shell": 8, "Batchfile": 8}
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.codegen.inline import org.jetbrains.org.objectweb.asm.tree.TryCatchBlockNode import org.jetbrains.org.objectweb.asm.tree.LabelNode import org.jetbrains.kotlin.codegen.inline.InlineCodegenUtil.* enum class TryCatchPosition { START END INNER } trait IntervalWithHandler { val startLabel: LabelNode val endLabel: LabelNode val handler: LabelNode val type: String? } class TryCatchBlockNodeInfo(val node: TryCatchBlockNode, val onlyCopyNotProcess: Boolean) : IntervalWithHandler { override val startLabel: LabelNode get() = node.start override val endLabel: LabelNode get() = node.end override val handler: LabelNode get() = node.handler override val type: String? get() = node.type } class TryCatchBlockNodePosition(val nodeInfo: TryCatchBlockNodeInfo, var position: TryCatchPosition): IntervalWithHandler by nodeInfo class TryBlockCluster<T : IntervalWithHandler>(val blocks: MutableList<T>) { val defaultHandler: T? get() = blocks.firstOrNull() { it.type == null } } fun <T: IntervalWithHandler> doClustering(blocks: List<T>) : List<TryBlockCluster<T>> { [data] class TryBlockInterval(val startLabel: LabelNode, val endLabel: LabelNode) val clusters = linkedMapOf<TryBlockInterval, TryBlockCluster<T>>() blocks.forEach { block -> val interval = TryBlockInterval(firstLabelInChain(block.startLabel), firstLabelInChain(block.endLabel)) val cluster = clusters.getOrPut(interval, {TryBlockCluster(arrayListOf())}) cluster.blocks.add(block) } return clusters.values().toList() }
0
Java
0
0
e0a394ec62f364a4a96c15b2d2adace32ce61e9e
2,262
kotlin
Apache License 2.0
src/mazesolver/objects/Grid.kt
btipling
41,580,063
false
{"XML": 9, "Text": 1, "Ignore List": 1, "Markdown": 1, "Kotlin": 9, "Java": 1}
package mazesolver.objects class Grid(columns: Int, rows: Int) { public val columns: Int = columns public val rows: Int = rows private val grid = Array<Array<Marker>>(columns, {Array<Marker>(rows, {Marker.DEFAULT}) }) private var startPos: MarkerPos? = null private var endPos: MarkerPos? = null public enum class Marker { DEFAULT, WALL, OVER, START, END, PATH, VISITED } private class MarkerPos(x: Int, y: Int) { public val x: Int = x public val y: Int = y } init { set(0, 0, Marker.START) set(columns - 1, rows - 1, Marker.END) } public fun get(x: Int, y: Int) : Marker { return grid[x][y] } public fun set(x: Int, y: Int, value: Marker) { val currentValue = grid[x][y] if (value == Marker.DEFAULT || value == Marker.WALL) { if (currentValue == Marker.START || currentValue == Marker.END) { return } } if (value == Marker.START) { if (startPos != null) { grid[startPos!!.x][startPos!!.y] = Marker.DEFAULT } startPos = MarkerPos(x, y) } if (value == Marker.END) { if (endPos != null) { grid[endPos!!.x][endPos!!.y] = Marker.DEFAULT } endPos = MarkerPos(x, y) } grid[x][y] = value } fun clearAll() { for (x in 0..grid.size()-1) { val row = grid[x] for (y in 0..row.size()-1) { val m = row[y] if (!m.equals(Marker.START) && !m.equals(Marker.END)) { row[y] = Marker.DEFAULT } } } } fun clearPath() { for (x in 0..grid.size()-1) { val row = grid[x] for (y in 0..row.size()-1) { if (row[y].equals(Marker.PATH) || row[y].equals(Marker.VISITED)) { row[y] = Marker.DEFAULT } } } } }
1
null
1
1
2b195d6bcfd98d634cbdf689bf6a5840510c8886
2,039
maze-solver
Apache License 2.0
rsocket-transports/nodejs-tcp/src/jsTest/kotlin/io/rsocket/kotlin/transport/nodejs/tcp/TcpTransportTest.kt
rsocket
109,894,810
false
null
/* * Copyright 2015-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.rsocket.kotlin.transport.nodejs.tcp import io.rsocket.kotlin.transport.tests.* import kotlinx.coroutines.* @Suppress("DEPRECATION_ERROR") class TcpTransportTest : TransportTest() { private lateinit var server: TcpServer override suspend fun before() { val port = PortProvider.next() server = startServer(TcpServerTransport(port, "127.0.0.1")) client = connectClient(TcpClientTransport(port, "127.0.0.1", testContext)) } override suspend fun after() { delay(100) //TODO close race super.after() server.close() } } class NodejsTcpTransportTest : TransportTest() { override suspend fun before() { val port = PortProvider.next() startServer(NodejsTcpServerTransport(testContext).target("127.0.0.1", port)) client = connectClient(NodejsTcpClientTransport(testContext).target("127.0.0.1", port)) } }
27
null
38
550
b7f27ba4c3a0d639d375731231f347e595ed307c
1,531
rsocket-kotlin
Apache License 2.0
app/src/main/java/com/atakaya/quoteofday/presentation/ui/screens/fav_screens/FavoriteViewModel.kt
ata-kaya
840,894,197
false
{"Kotlin": 34916}
package com.atakaya.quoteofday.presentation.ui.screens.fav_screens import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.atakaya.quoteofday.domain.usecase.GetAllFavoritesUseCase import com.atakaya.quoteofday.presentation.ui.models.QuoteModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.launch class FavoriteViewModel( private val getAllFavoritesUseCase: GetAllFavoritesUseCase ) : ViewModel() { private val _favList = MutableStateFlow<List<QuoteModel?>>(listOf()) val favList = _favList.asStateFlow() fun getAllFaves() { viewModelScope.launch(Dispatchers.IO) { getAllFavoritesUseCase.execute().catch { }.collect { _favList.value = it } } } }
0
Kotlin
0
2
68db11daadb23db2ed481f9481b462454eb1a6c1
929
QuoteOfDay
MIT License
lib/src/main/java/debug_artist/menu/utils/device/Device.kt
go-cristian
87,992,400
true
{"Kotlin": 57080, "Java": 22482, "Prolog": 2046, "IDL": 664, "Shell": 583}
package debug_artist.menu.utils.device interface Device { @Throws(Exception::class) fun takeScreenshot(fileName: String): String fun readLogFile(): String }
0
Kotlin
0
0
876447d045b0b677bc96957787d19f37bb450c76
164
debug-artist
Apache License 2.0
triad-core/src/main/kotlin/com/nhaarman/triad/Backstack.kt
lyhappy
61,973,384
true
{"Gradle": 19, "Markdown": 4, "INI": 6, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 1, "YAML": 1, "Kotlin": 55, "XML": 29, "Java": 78, "Java Properties": 1}
/* * Copyright 2016 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nhaarman.triad import java.util.* /** * Describes the history of a [Triad] instance at a specific point in time. */ class Backstack private constructor(private val backstack: Deque<Entry<out Any>>) : Iterable<Screen<out Any>> { override fun iterator(): Iterator<Screen<out Any>> { return ReadIterator(backstack.iterator()) } fun reverseIterator(): Iterator<Screen<out Any>> { return ReadIterator(backstack.descendingIterator()) } internal fun reverseEntryIterator(): Iterator<Entry<out Any>> { return EntryReadIterator(backstack.descendingIterator()) } fun size(): Int { return backstack.size } internal fun <T : Any> current(): Entry<T>? { return backstack.peek() as Entry<T>? } /** * Get a builder to modify a copy of this backstack. */ fun buildUpon(): Builder { return Builder(backstack) } override fun toString(): String { return backstack.toString() } internal data class Entry<T : Any>(val screen: Screen<T>, val animator: TransitionAnimator?) class Builder internal constructor(backstack: Collection<Entry<out Any>>) { private val backstack: Deque<Entry<out Any>> = ArrayDeque(backstack) @JvmOverloads fun push(screen: Screen<out Any>, animator: TransitionAnimator? = null): Builder { return push(Entry(screen, animator)) } internal fun push(entry: Entry<out Any>): Builder { backstack.push(entry) return this } internal fun pop(): Entry<out Any>? { return backstack.pop() } fun clear(): Builder { backstack.clear() return this } fun build(): Backstack { return Backstack(backstack) } } private class ReadIterator internal constructor(private val iterator: Iterator<Entry<*>>) : Iterator<Screen<out Any>> { override fun hasNext(): Boolean { return iterator.hasNext() } override fun next(): Screen<out Any> { return iterator.next().screen } } private class EntryReadIterator internal constructor(private val iterator: Iterator<Entry<*>>) : Iterator<Entry<out Any>> { override fun hasNext(): Boolean { return iterator.hasNext() } override fun next(): Entry<out Any> { return iterator.next() } } companion object { fun emptyBuilder(): Builder { return Builder(emptyList<Entry<Any>>()) } /** * Create a backstack that contains a single screen. */ @JvmOverloads @JvmStatic fun single(screen: Screen<out Any>, animator: TransitionAnimator? = null): Backstack { return emptyBuilder().push(screen, animator).build() } /** * Creates a backstack that contains given screens. */ @JvmStatic fun of(vararg screens: Screen<out Any>): Backstack { val builder = emptyBuilder() for (screen in screens) { builder.push(screen) } return builder.build() } } }
0
Java
0
0
0c6e75e23638dbb0e95ec54ac154bd971ed9be3a
3,840
Triad
Apache License 2.0
app/src/main/java/com/linx/playAndroid/repo/HomeRepo.kt
xiaolanlaia
556,618,505
false
{"Kotlin": 261798}
package com.linx.playAndroid.repo import com.linx.net.base.ServiceCreator import com.linx.playAndroid.service.HomeService object HomeRepo { //首页列表 suspend fun getHomeList(page: Int) = ServiceCreator.getService<HomeService>().getHomeList(page) //首页轮播图 fun getBanner() = ServiceCreator.getService<HomeService>().getBanner() //获取置顶文章列表 fun getArticleTopList() = ServiceCreator.getService<HomeService>().getArticleTopList() }
0
Kotlin
0
1
e4af1f69f29f255f2987df8866259a769c7bcfa9
451
WanAndroidCompose
Apache License 2.0
program/find-sum-of-cubes-of-numbers-by-recursion/FindSumOfCubesOfNumbersByRecursion.kt
isyuricunha
632,079,464
false
null
import kotlin.math.pow fun main() { print("Enter the numbers:") val nums = readln() print("Sum of Cubes of Number: ${sumOfCubes(nums)}") } private fun sumOfCubes(nums: String): Int { val list = mutableListOf<Int>() var str = "" nums.forEach { if (it == ' ') { list.add(str.toInt()) str = "" } else str += it } if (str != "") list.add(str.toInt()) return sumRecursion(0, list) } private fun sumRecursion(index: Int, nums: MutableList<Int>): Int { if (index == nums.lastIndex) return nums[index].toDouble().pow(3).toInt() return nums[index].toDouble().pow(3).toInt() + sumRecursion(index + 1, nums) }
824
null
174
6
c3949d3d4bae20112e007af14d4657cc96142d69
686
program
MIT License
communication/src/main/java/com/joel/communication/response/ResponseBuilder.kt
jogcaetano13
524,525,946
false
{"Kotlin": 85255}
package com.joel.communication.response import com.joel.communication.annotations.CommunicationsMarker import com.joel.communication.builders.OfflineBuilder @CommunicationsMarker class ResponseBuilder<T> @PublishedApi internal constructor(){ @PublishedApi internal var offlineBuilder: OfflineBuilder<T>? = null @PublishedApi internal var post: (suspend () -> Unit)? = null @PublishedApi internal var onNetworkSuccess: (suspend (model: T) -> Unit)? = null /** * Call this function to access the [OfflineBuilder] and handle local calls. */ fun local(builder: OfflineBuilder<T>. () -> Unit) { offlineBuilder = OfflineBuilder<T>().also(builder) } /** * Call this function to handle the success response and do anything with the data (ex: Inserting into database) * The lambda is invoked when the response is success. * * @param onSuccess The lambda with a success data response of type [T] and it is suspended. */ fun onNetworkSuccess(onSuccess: suspend (data: T) -> Unit) { this.onNetworkSuccess = onSuccess } /** * Call this function to handle the post response (whether is success or not) * The lambda is invoked when after the request is made. * * @param post The lambda to handle the post call response. It is suspended. */ fun postCall(post: suspend () -> Unit) { this.post = post } }
0
Kotlin
0
1
491d46c1925a1ffb8120b91a5f2c8e9e701ad4df
1,438
communication
MIT License
app/src/main/kotlin/com/atychang/developeroptions/DeveloperOptionsQsTileService.kt
atychang
376,260,763
false
{"Kotlin": 1891}
package com.atychang.developeroptions import android.annotation.SuppressLint import android.app.PendingIntent import android.content.Intent import android.os.Build import android.provider.Settings import android.service.quicksettings.TileService import android.widget.Toast class DeveloperOptionsQsTileService : TileService() { override fun onClick() { super.onClick() val isDeveloperOptionsEnabled = Settings.Secure.getInt( contentResolver, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0 ) == 1 if (isDeveloperOptionsEnabled) { openSettings(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS) } else { openSettings(Settings.ACTION_SETTINGS) Toast.makeText( this, R.string.developer_options_is_disabled, Toast.LENGTH_SHORT ).show() } } private fun openSettings(settingsAction: String) { val intent = getIntent(settingsAction) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { startActivityAndCollapseLegacy(intent) } else { val pendingIntent: PendingIntent = getPendingIntent(intent) startActivityAndCollapse(pendingIntent) } } @Suppress("DEPRECATION") @SuppressLint("StartActivityAndCollapseDeprecated") private fun startActivityAndCollapseLegacy(intent: Intent) { startActivityAndCollapse(intent) } private fun getIntent(action: String): Intent { return Intent(action).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK } } private fun getPendingIntent(intent: Intent): PendingIntent { return PendingIntent.getActivity( this, 0, intent, PendingIntent.FLAG_IMMUTABLE ) } }
0
Kotlin
0
0
7487a948a358c029ad8c601596b5122805222757
1,891
DeveloperOptions
MIT License
example/android/app/src/main/kotlin/br/com/dextra/bifrost_example/App.kt
dextra
349,193,599
false
null
package br.com.dextra.bifrost_example import android.app.Application import br.com.dextra.bifrost.Bifrost import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel class App : Application() { override fun onCreate() { super.onCreate() // start flutter engine Bifrost.startFlutterEngine(this, CommonHandler()) } // application common handler private class CommonHandler : MethodChannel.MethodCallHandler { override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { when (call.method) { "getAppVersion" -> result.success(BuildConfig.VERSION_NAME) } } } }
1
null
1
27
40bbdec890f8672a6e41302061f019ee16bc6b86
655
flutter_bifrost
MIT License
tools/shell/src/main/kotlin/net/corda/tools/shell/CordaAuthenticationPlugin.kt
corda
70,137,417
false
null
package net.corda.tools.shell import net.corda.core.messaging.CordaRPCOps import net.corda.core.utilities.loggerFor import org.apache.activemq.artemis.api.core.ActiveMQSecurityException import org.crsh.auth.AuthInfo import org.crsh.auth.AuthenticationPlugin import org.crsh.plugin.CRaSHPlugin internal class CordaAuthenticationPlugin(private val rpcOpsProducer: RPCOpsProducer) : CRaSHPlugin<AuthenticationPlugin<String>>(), AuthenticationPlugin<String> { companion object { private val logger = loggerFor<CordaAuthenticationPlugin>() } override fun getImplementation(): AuthenticationPlugin<String> = this override fun getName(): String = "corda" override fun authenticate(username: String?, credential: String?): AuthInfo { if (username == null || credential == null) { return AuthInfo.UNSUCCESSFUL } try { val cordaSSHAuthInfo = CordaSSHAuthInfo(rpcOpsProducer, username, credential, isSsh = true) // We cannot guarantee authentication happened successfully till `RCPClient` session been established, hence doing a dummy call cordaSSHAuthInfo.getOrCreateRpcOps(CordaRPCOps::class.java).protocolVersion return cordaSSHAuthInfo } catch (e: ActiveMQSecurityException) { logger.warn(e.message) } catch (e: Exception) { logger.warn(e.message, e) } return AuthInfo.UNSUCCESSFUL } override fun getCredentialType(): Class<String> = String::class.java }
233
null
2
3,777
efaf1549a9a4575c104f6849be494eb1f0186df0
1,535
corda
Apache License 2.0
kotlin-multiplatform/src/commonMain/kotlin/com/ricoh360/thetaclient/transferred/getMySettingCommand.kt
ricohapi
592,574,011
false
null
package com.ricoh360.thetaclient.transferred import kotlinx.serialization.Serializable /** * get my setting request */ @Serializable data class GetMySettingRequest( override val name: String = "camera._getMySetting", override val parameters: GetMySettingParams, ) : CommandApiRequest /** * get my setting parameters */ @Serializable data class GetMySettingParams( /** * The target shooting mode * ("image": still image capture mode, "video": video capture) * In RICOH THETA S and SC, do not set then it can be acquired for still image. */ val mode: CaptureMode? = null, /** * option name list to be acquired * Other than Theta S and SC, do not set value then all properties are acquired. */ val optionNames: List<String>? = null, ) /** * get my setting response */ @Serializable data class GetMySettingResponse( /** * Executed command */ override val name: String, /** * Command execution status * @see CommandState */ override val state: CommandState, /** * Command ID used to check the execution status with * Commands/Status */ override val id: String? = null, /** * Results when each command is successfully executed. This * output occurs in state "done" */ override val results: ResultGetMySetting? = null, /** * Error information (See Errors for details). This output occurs * in state "error" */ override val error: CommandError? = null, /** * Progress information. This output occurs in state * "inProgress" */ override val progress: CommandProgress? = null, ) : CommandApiResponse /** * get options results */ @Serializable data class ResultGetMySetting( /** * option key value pair */ val options: Options, )
3
null
9
9
bc2ba2109056aeaececfc19a2f09634a6c9c8d4f
1,849
theta-client
MIT License
application/src/test/kotlin/com/ziemsky/uploader/stats/reporting/logging/HumanReadableStatsLogsRendererSpec.kt
ziemsky
137,949,351
false
{"Kotlin": 222979}
package com.ziemsky.uploader.stats.reporting.logging import com.ziemsky.uploader.UploaderAbstractBehaviourSpec import com.ziemsky.uploader.securing.model.SecuredFilesBatchStats import com.ziemsky.uploader.stats.reporting.logging.model.Line import io.kotest.matchers.shouldBe import java.time.Instant import java.util.stream.Collectors.joining class HumanReadableStatsLogsRendererSpec : UploaderAbstractBehaviourSpec() { init { val humanReadableStatsLogsRenderer = HumanReadableStatsLogsRenderer() Given("secured files batch stats") { val securedFilesBatchStats = SecuredFilesBatchStats( 3, Instant.parse("2019-08-18T19:10:00Z"), Instant.parse("2019-08-18T19:11:01Z"), 60000 ) When("rendering stats") { val actualRenderedLines = humanReadableStatsLogsRenderer.render(securedFilesBatchStats) Then("renders log lines, each with individual stat") { val actualRenderedLinesText = actualRenderedLines.stream() .map(Line::text) .collect(joining("\n")) // @formatter:off actualRenderedLinesText shouldBe """ ------------------------------------------- Secured files: 3 Upload duration: 00:01:01.000 Upload size: 58.6 KiB Upload speed: 983 B/s Upload start: 2019-08-18T19:10:00Z Upload end: 2019-08-18T19:11:01Z ------------------------------------------- """.trimIndent() // @formatter:on } } } } }
15
Kotlin
0
0
bcaab60a52abc473e259da32ad5c73839ffc5c59
1,886
gdrive-uploader
MIT License
app/src/main/java/com/umc/history/TestActivity.kt
duck-positive
582,929,737
false
null
package com.umc.history import android.content.Intent import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.umc.history.databinding.ActivityTestBinding import com.umc.history.ui.MainActivity class TestActivity : AppCompatActivity(), TestView { private var mBinding: ActivityTestBinding?=null private val binding get() = mBinding!! override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mBinding = ActivityTestBinding.inflate(layoutInflater) setContentView(binding.root) binding.testExitLy.setOnClickListener{ val intent = Intent(applicationContext,MainActivity::class.java) startActivity(intent) } binding.testAllIv.setOnClickListener { getTest("all") } binding.testKoreanHistoryIv.setOnClickListener { getTest("KOREAN") } binding.testOrientalIv.setOnClickListener { getTest("ASIAN") } binding.testWesternIv.setOnClickListener { getTest("WESTERN") } } override fun onGetTestSuccess(body: List<Test>?) { val testList = arrayListOf<Test>() testList.clear() for(i in body!!) testList.add(i) val intent = Intent(this, QuestionActivity::class.java) intent.putExtra("Test", testList) startActivity(intent) } override fun onGetTestLoading() { } override fun onGetTestFailure() { Toast.makeText(this,"퀴즈를 불러오는데 실패했습니다.",Toast.LENGTH_SHORT).show() } private fun getTest(category: String){ val spf = this.getSharedPreferences("token", MODE_PRIVATE) val token = spf?.getString("accessToken", null) when(token){ null -> Toast.makeText(this, "로그인 후에 사용할 수 있는 기능입니다.", Toast.LENGTH_SHORT).show() else -> { val testService = TestService() testService.setTestView(this) testService.getTest(token, category) } } } }
0
Kotlin
0
0
bae06314e26b1e91bedb7b766065f183c562ddae
2,109
HiStory_Refactoring
MIT License
app/src/main/kotlin/com/adriangl/pokeapi_mvvm/di/Di.kt
davidbaena
209,520,325
true
{"Kotlin": 47564}
package com.adriangl.pokeapi_mvvm.di import android.content.Context import com.adriangl.pokeapi_mvvm.network.PokeApi import com.squareup.moshi.Moshi import com.squareup.moshi.adapters.Rfc3339DateJsonAdapter import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import mini.Store import okhttp3.Cache import okhttp3.HttpUrl import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.kodein.di.Kodein import org.kodein.di.generic.bind import org.kodein.di.generic.instance import org.kodein.di.generic.setBinding import org.kodein.di.generic.singleton import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import java.util.* import java.util.concurrent.TimeUnit val networkModule = Kodein.Module("network") { val cacheSize = 300L * 1024 * 1024 // 300 MB bind<OkHttpClient>() with singleton { val context: Context = instance() OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .writeTimeout(60, TimeUnit.SECONDS) .cache(Cache(context.cacheDir, cacheSize)) .addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }) .build() } bind<Retrofit>() with singleton { val endpoint = "https://pokeapi.co" Retrofit.Builder() .baseUrl(HttpUrl.parse(endpoint)!!) .client(instance()) .addConverterFactory(MoshiConverterFactory.create(instance())) .build() } bind<PokeApi>() with singleton { val retrofit: Retrofit = instance() retrofit.create(PokeApi::class.java) } } val utilsModule = Kodein.Module("utils") { bind<Moshi>() with singleton { Moshi.Builder() .add(KotlinJsonAdapterFactory()) // Add adapter to parse RFC3339 dates to Date objects .add( Date::class.java, Rfc3339DateJsonAdapter() ) .build() } } val storeModule = Kodein.Module("store") { bind() from setBinding<Store<*>>() }
0
null
0
0
964c0254c243102d92fa3c29f32863700c2e8b09
2,164
PokeApiMiniMVVM
Apache License 2.0
app/src/main/java/br/brunodorea/coinconverter/domain/ListExchangeUseCase.kt
BH-Tec
397,825,979
false
null
package br.brunodorea.coinconverter.domain import br.brunodorea.coinconverter.core.UseCase import br.brunodorea.coinconverter.data.model.ExchangeResponseValue import br.brunodorea.coinconverter.data.repository.CoinRepository import kotlinx.coroutines.flow.Flow class ListExchangeUseCase( private val repository: CoinRepository ) : UseCase.NoParam<List<ExchangeResponseValue>>() { override suspend fun execute(): Flow<List<ExchangeResponseValue>> { return repository.list() } }
0
Kotlin
0
0
b3d50b368c3cc6cbc31a6198d82f9999b3cb2fa0
499
CoinConverter
MIT License
decentrifi-markets/src/main/java/io/defitrack/protocol/application/qidao/QiDaoArbitrumVaultProvider.kt
decentri-fi
426,174,152
false
null
package io.defitrack.protocol.application.qidao import arrow.fx.coroutines.parMap import io.defitrack.common.network.Network import io.defitrack.common.utils.refreshable import io.defitrack.architecture.conditional.ConditionalOnCompany import io.defitrack.market.port.out.LendingMarketProvider import io.defitrack.market.domain.lending.LendingMarket import io.defitrack.protocol.Company import io.defitrack.protocol.Protocol import io.defitrack.protocol.qidao.QidaoArbitrumService import io.defitrack.protocol.qidao.contract.QidaoVaultContract import org.springframework.stereotype.Component import java.math.BigDecimal @Component @ConditionalOnCompany(Company.QIDAO) class QiDaoArbitrumVaultProvider( private val qidaoArbitrumService: QidaoArbitrumService, ) : LendingMarketProvider() { override suspend fun fetchMarkets(): List<LendingMarket> { return qidaoArbitrumService.provideVaults().parMap { val vault = with(getBlockchainGateway()) { QidaoVaultContract(it) } val collateral = getToken(vault.collateral.await()) create( name = vault.name(), identifier = vault.address, token = getToken(collateral.address), marketSize = refreshable { getMarketSize( collateral, vault.address, ) }, poolType = "mai_vault", metadata = mapOf( "address" to vault.address, "vaultContract" to vault ), totalSupply = refreshable(BigDecimal.ZERO) ) } } override fun getProtocol(): Protocol { return Protocol.QIDAO } override fun getNetwork(): Network { return Network.ARBITRUM } }
59
null
6
11
8b8d6713c9734d2b4015e7affe658e797c9a00be
1,849
defi-hub
MIT License
libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/targets/native/toolchain/NativeToolchainProjectSetupAction.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
/* * Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.gradle.targets.native.toolchain import org.jetbrains.kotlin.gradle.dsl.multiplatformExtension import org.jetbrains.kotlin.gradle.internal.properties.nativeProperties import org.jetbrains.kotlin.gradle.plugin.KotlinPluginLifecycle import org.jetbrains.kotlin.gradle.plugin.KotlinProjectSetupCoroutine import org.jetbrains.kotlin.gradle.plugin.PropertiesProvider.Companion.kotlinPropertiesProvider import org.jetbrains.kotlin.gradle.plugin.await import org.jetbrains.kotlin.gradle.plugin.mpp.AbstractKotlinNativeCompilation import org.jetbrains.kotlin.gradle.plugin.mpp.enabledOnCurrentHostForKlibCompilation import org.jetbrains.kotlin.gradle.targets.native.toolchain.KotlinNativeBundleArtifactFormat.addKotlinNativeBundleConfiguration internal val NativeToolchainProjectSetupAction = KotlinProjectSetupCoroutine { val kotlinTargets = project.multiplatformExtension.awaitTargets() if (!project.nativeProperties.isToolchainEnabled.get()) return@KotlinProjectSetupCoroutine KotlinPluginLifecycle.Stage.AfterFinaliseCompilations.await() if (kotlinTargets.flatMap { target -> target.compilations } .filterIsInstance<AbstractKotlinNativeCompilation>() .any { it.konanTarget.enabledOnCurrentHostForKlibCompilation(project.kotlinPropertiesProvider) } ) { addKotlinNativeBundleConfiguration(project) KotlinNativeBundleArtifactFormat.setupAttributesMatchingStrategy(project.dependencies.attributesSchema) KotlinNativeBundleArtifactFormat.setupTransform(project) } }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,768
kotlin
Apache License 2.0
generativeai/src/main/java/com/google/ai/client/generativeai/internal/api/Response.kt
google
727,310,537
false
{"Kotlin": 193548, "Shell": 1825}
/* * Copyright 2023 Google LLC * * 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.google.ai.client.generativeai.internal.api import com.google.ai.client.generativeai.internal.api.server.Candidate import com.google.ai.client.generativeai.internal.api.server.GRpcError import com.google.ai.client.generativeai.internal.api.server.PromptFeedback import kotlinx.serialization.Serializable internal sealed interface Response @Serializable internal data class GenerateContentResponse( val candidates: List<Candidate>? = null, val promptFeedback: PromptFeedback? = null, ) : Response @Serializable internal data class CountTokensResponse(val totalTokens: Int) : Response @Serializable internal data class GRpcErrorResponse(val error: GRpcError) : Response
1
Kotlin
10
78
440f960d8ddd96b846ded23d7f20a983b635fa03
1,283
generative-ai-android
Apache License 2.0
src/main/kotlin/com/sbl/sulmun2yong/user/controller/LoginController.kt
SUIN-BUNDANG-LINE
819,257,518
false
{"Kotlin": 405689}
package com.sbl.sulmun2yong.user.controller import com.sbl.sulmun2yong.user.controller.doc.LoginApiDoc import jakarta.servlet.http.HttpServletRequest import org.springframework.beans.factory.annotation.Value import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.ResponseBody import org.springframework.web.bind.annotation.RestController import org.springframework.web.util.UriComponentsBuilder import java.net.URI @RestController("/api/v1/login") class LoginController( @Value("\${frontend.base-url}") private val frontendBaseUrl: String, ) : LoginApiDoc { @GetMapping("/oauth/{provider}") @ResponseBody override fun login( @PathVariable provider: String, @RequestParam("redirect_path") redirectPathAfterLogin: String?, request: HttpServletRequest, ): ResponseEntity<Any> { val httpHeaders = HttpHeaders() val redirectUriAfterLogin = redirectPathAfterLogin?. let { URI.create(frontendBaseUrl + it) } val redirectUriForOAuth2 = UriComponentsBuilder .fromPath("/oauth2/authorization/{provider}") .queryParam("redirect_uri", redirectUriAfterLogin) .buildAndExpand(provider) .toUriString() httpHeaders.location = URI.create(redirectUriForOAuth2) return ResponseEntity(httpHeaders, HttpStatus.FOUND) } }
0
Kotlin
1
3
cf5258613f242199b73d8b5d31b14a2a8b095ebd
1,718
Backend
MIT License
src/main/kotlin/com/sbl/sulmun2yong/user/controller/LoginController.kt
SUIN-BUNDANG-LINE
819,257,518
false
{"Kotlin": 405689}
package com.sbl.sulmun2yong.user.controller import com.sbl.sulmun2yong.user.controller.doc.LoginApiDoc import jakarta.servlet.http.HttpServletRequest import org.springframework.beans.factory.annotation.Value import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.ResponseBody import org.springframework.web.bind.annotation.RestController import org.springframework.web.util.UriComponentsBuilder import java.net.URI @RestController("/api/v1/login") class LoginController( @Value("\${frontend.base-url}") private val frontendBaseUrl: String, ) : LoginApiDoc { @GetMapping("/oauth/{provider}") @ResponseBody override fun login( @PathVariable provider: String, @RequestParam("redirect_path") redirectPathAfterLogin: String?, request: HttpServletRequest, ): ResponseEntity<Any> { val httpHeaders = HttpHeaders() val redirectUriAfterLogin = redirectPathAfterLogin?. let { URI.create(frontendBaseUrl + it) } val redirectUriForOAuth2 = UriComponentsBuilder .fromPath("/oauth2/authorization/{provider}") .queryParam("redirect_uri", redirectUriAfterLogin) .buildAndExpand(provider) .toUriString() httpHeaders.location = URI.create(redirectUriForOAuth2) return ResponseEntity(httpHeaders, HttpStatus.FOUND) } }
0
Kotlin
1
3
cf5258613f242199b73d8b5d31b14a2a8b095ebd
1,718
Backend
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsmanageprisonvisitsorchestration/dto/whereabouts/ScheduledEventDto.kt
ministryofjustice
575,484,836
false
{"Kotlin": 441412, "Dockerfile": 1199}
package uk.gov.justice.digital.hmpps.hmppsmanageprisonvisitsorchestration.dto.whereabouts import io.swagger.v3.oas.annotations.media.Schema import java.math.BigDecimal import java.time.LocalDate import java.time.LocalDateTime /** * Scheduled Event */ data class ScheduledEventDto( @Schema(required = true, description = "Offender booking id") val bookingId: Long, @Schema(description = "Class of event") val eventClass: String? = null, @Schema(description = "Activity id if any. Used to attend or pay an activity.") val eventId: Long? = null, @Schema(description = "Status of event") val eventStatus: String? = null, @Schema(description = "Type of scheduled event (as a code)") val eventType: String? = null, @Schema(description = "Description of scheduled event type") val eventTypeDesc: String? = null, @Schema(description = "Sub type (or reason) of scheduled event (as a code)") val eventSubType: String? = null, @Schema(description = "Description of scheduled event sub type") val eventSubTypeDesc: String? = null, @Schema(description = "Date on which event occurs") val eventDate: LocalDate? = null, @Schema(description = "Date and time at which event starts") val startTime: LocalDateTime? = null, @Schema(description = "Date and time at which event ends") val endTime: LocalDateTime? = null, @Schema(description = "Location at which event takes place (could be an internal location, agency or external address).") val eventLocation: String? = null, @Schema(description = "Id of an internal event location") val eventLocationId: Long? = null, @Schema(description = "The agency ID for the booked internal location", example = "WWI") val agencyId: String? = null, @Schema(description = "Code identifying underlying source of event data") val eventSource: String? = null, @Schema(description = "Source-specific code for the type or nature of the event") val eventSourceCode: String? = null, @Schema(description = "Source-specific description for type or nature of the event") val eventSourceDesc: String? = null, @Schema(description = "Activity attendance, possible values are the codes in the 'PS_PA_OC' reference domain.") val eventOutcome: String? = null, @Schema(description = "Activity performance, possible values are the codes in the 'PERFORMANCE' reference domain.") val performance: String? = null, @Schema(description = "Activity no-pay reason.") val outcomeComment: String? = null, @Schema(description = "Activity paid flag.") val paid: Boolean? = null, @Schema(description = "Amount paid per activity session in pounds") val payRate: BigDecimal? = null, @Schema(description = "The code for the activity location") val locationCode: String? = null, @Schema(description = "Staff member who created the appointment") val createUserId: String? = null, )
1
Kotlin
0
4
1844fc116d20d5747eeb5bc35a9209682655563a
2,888
hmpps-manage-prison-visits-orchestration
MIT License
api/src/test/kotlin/com/starter/api/rest/subscriptions/core/SubscriptionServiceTest.kt
EmirDelicR
772,962,825
false
{"Kotlin": 208236, "TypeScript": 196132, "SCSS": 16567, "Shell": 2646, "Dockerfile": 1150, "JavaScript": 410, "HTML": 365}
package com.starter.api.rest.subscriptions.core import com.starter.api.rest.subscriptions.dtos.SubscriptionRequest import com.starter.api.rest.subscriptions.enums.SubscriptionType import com.starter.api.testUtils.sampleSubscription import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.mockito.BDDMockito.given import org.mockito.BDDMockito.times import org.mockito.BDDMockito.verify import org.mockito.kotlin.any import org.mockito.kotlin.argForWhich import org.mockito.kotlin.mock @DisplayName("SubscriptionService test") class SubscriptionServiceTest { private val subscriptionResponseMock = sampleSubscription() private lateinit var subscriptionService: SubscriptionService private val subscriptionRepository = mock<SubscriptionRepository>() @BeforeEach fun setUp() { subscriptionService = SubscriptionService(subscriptionRepository) } @Test fun `should return list of subscriptions`() { val listOfSubs = listOf(subscriptionResponseMock) given(subscriptionRepository.findAll()).willReturn(listOfSubs) assertThat(subscriptionService.findAll()).isEqualTo(listOfSubs) } @Test fun `should create subscription and store it to DB`() { val subRequest = SubscriptionRequest(SubscriptionType.NEWS) given(subscriptionRepository.saveAndFlush(any())).willReturn(subscriptionResponseMock) subscriptionService.create(subRequest) verify( subscriptionRepository, times(1), ).saveAndFlush( argForWhich { this.name == subRequest.name }, ) } }
0
Kotlin
0
0
e1bf0cce14aef75208b647f48b2a8edc10ba4abf
1,750
kotlin-starter-pack
MIT License
src/main/kotlin/com/example/bootkotlin/handler/LoginSuccessHandler.kt
licxi
126,296,770
false
{"JavaScript": 1232633, "Kotlin": 87830, "HTML": 66857, "CSS": 6644}
package com.example.bootkotlin.handler import org.springframework.security.core.Authentication import org.springframework.security.web.DefaultRedirectStrategy import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse class LoginSuccessHandler : SavedRequestAwareAuthenticationSuccessHandler() { private val redirectStrategy = DefaultRedirectStrategy() override fun onAuthenticationSuccess(request: HttpServletRequest?, response: HttpServletResponse?, authentication: Authentication?) { //super.onAuthenticationSuccess(request, response, authentication) request?.setAttribute("authentication", authentication) redirectStrategy.sendRedirect(request, response, "/admin/login_success")//自定义登录成功处理 } }
0
JavaScript
0
0
1413ad600dd09eb1c4bc503e58ee53cf5f453ac1
870
spring-boot-kotlin
Apache License 2.0
compose/ui/ui-test/src/skikoMain/kotlin/androidx/compose/ui/test/InputDispatcher.skiko.kt
VexorMC
838,305,267
false
{"Kotlin": 104238872, "Java": 66757679, "C++": 9111230, "AIDL": 628952, "Python": 306842, "Shell": 199496, "Objective-C": 47117, "TypeScript": 38627, "HTML": 28384, "Swift": 21386, "Svelte": 20307, "ANTLR": 19860, "C": 15043, "CMake": 14435, "JavaScript": 6457, "GLSL": 3842, "CSS": 1760, "Batchfile": 295}
/* * Copyright 2020 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 androidx.compose.ui.test import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.InternalComposeUiApi import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.KeyEvent import androidx.compose.ui.input.key.KeyEventType import androidx.compose.ui.input.pointer.PointerButton import androidx.compose.ui.input.pointer.PointerEventType import androidx.compose.ui.input.pointer.PointerId import androidx.compose.ui.input.pointer.PointerType import androidx.compose.ui.node.RootForTest import androidx.compose.ui.platform.PlatformRootForTest import androidx.compose.ui.scene.ComposeScenePointer @OptIn(InternalComposeUiApi::class) internal actual fun createInputDispatcher( testContext: TestContext, root: RootForTest ): InputDispatcher { return SkikoInputDispatcher(testContext, root as PlatformRootForTest) } private class TestInputEvent( val eventTime: Long, val action: () -> Unit ) @OptIn(InternalComposeUiApi::class, ExperimentalComposeUiApi::class) internal class SkikoInputDispatcher( private val testContext: TestContext, private val root: PlatformRootForTest ) : InputDispatcher( testContext, root, exitHoverOnPress = false, moveOnScroll = false, ) { private var currentClockTime = currentTime private var batchedEvents = mutableListOf<TestInputEvent>() override fun PartialGesture.enqueueDown(pointerId: Int) { val timeMillis = currentTime val pointers = lastPositions.map { ComposeScenePointer( id = PointerId(it.key.toLong()), position = it.value, pressed = true, type = PointerType.Touch ) } enqueue(timeMillis) { root.sendPointerEvent( PointerEventType.Press, pointers = pointers, timeMillis = timeMillis ) } } override fun PartialGesture.enqueueMove() { val timeMillis = currentTime val pointers = lastPositions.map { ComposeScenePointer( id = PointerId(it.key.toLong()), position = it.value, pressed = true, type = PointerType.Touch ) } enqueue(timeMillis) { root.sendPointerEvent( PointerEventType.Move, pointers = pointers, timeMillis = timeMillis ) } } override fun PartialGesture.enqueueMoves( relativeHistoricalTimes: List<Long>, historicalCoordinates: List<List<Offset>> ) { // TODO: add support for historical events enqueueMove() } override fun PartialGesture.enqueueUp(pointerId: Int) { val timeMillis = currentTime val pointers = lastPositions.map { ComposeScenePointer( id = PointerId(it.key.toLong()), position = it.value, pressed = pointerId != it.key, type = PointerType.Touch ) } enqueue(timeMillis) { root.sendPointerEvent( PointerEventType.Release, pointers = pointers, timeMillis = timeMillis ) } } override fun PartialGesture.enqueueCancel() { // desktop don't have cancel events as Android does } override fun MouseInputState.enqueuePress(buttonId: Int) { val position = lastPosition val timeMillis = currentTime enqueue(timeMillis) { root.sendPointerEvent( PointerEventType.Press, position = position, type = PointerType.Mouse, timeMillis = timeMillis, button = PointerButton(buttonId) ) } } override fun MouseInputState.enqueueMove() { val position = lastPosition val timeMillis = currentTime enqueue(timeMillis) { root.sendPointerEvent( PointerEventType.Move, position = position, type = PointerType.Mouse, timeMillis = timeMillis ) } } override fun MouseInputState.enqueueRelease(buttonId: Int) { val position = lastPosition val timeMillis = currentTime enqueue(timeMillis) { root.sendPointerEvent( PointerEventType.Release, position = position, type = PointerType.Mouse, timeMillis = timeMillis, button = PointerButton(buttonId) ) } } override fun MouseInputState.enqueueEnter() { val position = lastPosition val timeMillis = currentTime enqueue(timeMillis) { root.sendPointerEvent( PointerEventType.Enter, position = position, type = PointerType.Mouse, timeMillis = timeMillis ) } } override fun MouseInputState.enqueueExit() { val position = lastPosition val timeMillis = currentTime enqueue(timeMillis) { root.sendPointerEvent( PointerEventType.Exit, position = position, type = PointerType.Mouse, timeMillis = timeMillis ) } } override fun MouseInputState.enqueueCancel() { // desktop don't have cancel events as Android does } @OptIn(ExperimentalTestApi::class) override fun MouseInputState.enqueueScroll(delta: Float, scrollWheel: ScrollWheel) { val position = lastPosition val timeMillis = currentTime enqueue(timeMillis) { root.sendPointerEvent( PointerEventType.Scroll, position = position, type = PointerType.Mouse, timeMillis = timeMillis, scrollDelta = if (scrollWheel == ScrollWheel.Vertical) Offset(0f, delta) else Offset(delta, 0f) ) } } override fun KeyInputState.enqueueDown(key: Key) { enqueue(currentTime) { root.sendKeyEvent(KeyEvent( key = key, type = KeyEventType.KeyDown, codePoint = key.codePoint )) } } override fun KeyInputState.enqueueUp(key: Key) { enqueue(currentTime) { root.sendKeyEvent(KeyEvent( key = key, type = KeyEventType.KeyUp, codePoint = key.codePoint )) } } override fun RotaryInputState.enqueueRotaryScrollHorizontally(horizontalScrollPixels: Float) { // desktop don't have rotary events as Android Wear does } override fun RotaryInputState.enqueueRotaryScrollVertically(verticalScrollPixels: Float) { // desktop don't have rotary events as Android Wear does } private fun enqueue(timeMillis: Long, action: () -> Unit) { batchedEvents.add(TestInputEvent(timeMillis, action)) } @OptIn(InternalTestApi::class) private fun advanceClockTime(millis: Long) { // Don't bother advancing the clock if there's nothing to advance if (millis > 0) { testContext.testOwner.mainClock.advanceTimeBy(millis, ignoreFrameDuration = true) } } override fun flush() { val copy = batchedEvents.toList() batchedEvents.clear() for (event in copy) { advanceClockTime(event.eventTime - currentClockTime) currentClockTime = event.eventTime event.action() } } override fun onDispose() { batchedEvents.clear() } private val isUpperCase get() = isCapsLockOn xor (isKeyDown(Key.ShiftLeft) || isKeyDown(Key.ShiftRight)) // Avoid relying on [keyCode] here - it might be platform dependent bitmasks/codes // Support only basics for now, but it should be ok for tests. private val Key.codePoint get() = when (this) { Key.Zero -> '0'.code Key.One -> '1'.code Key.Two -> '2'.code Key.Three -> '3'.code Key.Four -> '4'.code Key.Five -> '5'.code Key.Six -> '6'.code Key.Seven -> '7'.code Key.Eight -> '8'.code Key.Nine -> '9'.code Key.Plus -> '+'.code Key.Minus -> '-'.code Key.Multiply -> '*'.code Key.Equals -> '='.code Key.Pound -> '#'.code Key.A -> if (isUpperCase) 'A'.code else 'a'.code Key.B -> if (isUpperCase) 'B'.code else 'b'.code Key.C -> if (isUpperCase) 'C'.code else 'c'.code Key.D -> if (isUpperCase) 'D'.code else 'd'.code Key.E -> if (isUpperCase) 'E'.code else 'e'.code Key.F -> if (isUpperCase) 'F'.code else 'f'.code Key.G -> if (isUpperCase) 'G'.code else 'g'.code Key.H -> if (isUpperCase) 'H'.code else 'h'.code Key.I -> if (isUpperCase) 'I'.code else 'i'.code Key.J -> if (isUpperCase) 'J'.code else 'j'.code Key.K -> if (isUpperCase) 'K'.code else 'k'.code Key.L -> if (isUpperCase) 'L'.code else 'l'.code Key.M -> if (isUpperCase) 'M'.code else 'm'.code Key.N -> if (isUpperCase) 'N'.code else 'n'.code Key.O -> if (isUpperCase) 'O'.code else 'o'.code Key.P -> if (isUpperCase) 'P'.code else 'p'.code Key.Q -> if (isUpperCase) 'Q'.code else 'q'.code Key.R -> if (isUpperCase) 'R'.code else 'r'.code Key.S -> if (isUpperCase) 'S'.code else 's'.code Key.T -> if (isUpperCase) 'T'.code else 't'.code Key.U -> if (isUpperCase) 'U'.code else 'u'.code Key.V -> if (isUpperCase) 'V'.code else 'v'.code Key.W -> if (isUpperCase) 'W'.code else 'w'.code Key.X -> if (isUpperCase) 'X'.code else 'x'.code Key.Y -> if (isUpperCase) 'Y'.code else 'y'.code Key.Z -> if (isUpperCase) 'Z'.code else 'z'.code Key.Comma -> ','.code Key.Period -> '.'.code else -> 0 } }
0
Kotlin
0
2
9730aa39ce1cafe408f28962a59b95b82c68587f
10,783
compose
Apache License 2.0
app/src/main/kotlin/vitalii/pankiv/dev/android/features/login/domain/dto/LoginUserDto.kt
pankivV
679,640,982
false
null
package vitalii.pankiv.dev.android.features.login.domain.dto import vitalii.pankiv.dev.android.basedata.network.responses.ApiLoginRequest data class LoginUserDto( val email: String? = null, val password: String? = null, ) fun LoginUserDto.toLoginRequest(): ApiLoginRequest { return ApiLoginRequest( email = email, password = <PASSWORD>, ) }
1
Kotlin
0
0
9c20c6914da6eb15d7a893cc4332ee7f892694eb
376
code-sample
Apache License 2.0
heroesdesk/src/test/kotlin/org/hexastacks/heroesdesk/kotlin/impl/scope/ScopeTest.kt
ManoManoTech
739,443,317
false
{"Kotlin": 122086}
package org.hexastacks.heroesdesk.kotlin.impl.scope import arrow.core.getOrElse import org.hexastacks.heroesdesk.kotlin.impl.user.* import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotEquals import kotlin.test.Test class ScopeTest { @Test fun `scopes with same keys and different content are equals`() { val scopeKey = scopeKey("COD") val scope1 = Scope(name("Write code"), scopeKey, Heroes.empty) val scope2 = Scope(name("Read coode"), scopeKey, Heroes(hero())) assertEquals(scope1, scope2) } @Test fun `scopes with different ids and same content aren't equals`() { val name = name("Write code") val assignees = Heroes.empty val scope1 = Scope(name, scopeKey("COD"), assignees) val scope2 = Scope(name, scopeKey("WRI"), assignees) assertNotEquals(scope1, scope2) } @Test fun `scopes with same ids and different content have same hashcode`() { val scopeKey = scopeKey("COD") val scope1 = Scope(name("Write code"), scopeKey, Heroes.empty).hashCode() val scope2 = Scope(name("Read coode"), scopeKey, Heroes(hero())).hashCode() assertEquals(scope1, scope2) } private fun hero() = Hero( UserName("heroName").getOrElse { throw RuntimeException("HeroName should be valid") }, HeroId("id").getOrElse { throw RuntimeException("HeroId should be valid") }) private fun scopeKey(scopeKey: String): ScopeKey = ScopeKey(scopeKey).getOrElse { throw RuntimeException("ScopeKey should be valid") } private fun name(scopeName: String): Name = Name(scopeName).getOrElse { throw RuntimeException("ScopeName should be valid") } }
8
Kotlin
1
0
8e8e2371b2be9893b633c74e9c9c982da60db02c
1,772
hexa-playground
MIT License
subprojects/delivery/tests-summary/src/main/kotlin/com/avito/test/summary/TestSummaryFactory.kt
avito-tech
230,265,582
false
null
package com.avito.test.summary import Slf4jGradleLoggerFactory import com.avito.android.stats.StatsDConfig import com.avito.android.stats.StatsDSender import com.avito.http.HttpClientProvider import com.avito.notification.NotificationClient import com.avito.notification.NotificationClientFactory import com.avito.reportviewer.ReportsApi import com.avito.reportviewer.ReportsApiFactory import com.avito.time.DefaultTimeProvider import com.avito.time.TimeProvider import org.gradle.api.provider.Provider internal class TestSummaryFactory( private val statsDConfig: Provider<StatsDConfig>, ) { private val serviceName = "test-summary-slack" val timeProvider: TimeProvider get() = DefaultTimeProvider() fun createSlackClient(token: String, workspace: String): NotificationClient { return NotificationClientFactory.createSlackClient( serviceName = serviceName, token = token, workspace = workspace, httpClientProvider = createHttpClientProvider(statsDConfig) ) } fun createReportsApi(reportsHost: String): ReportsApi { return ReportsApiFactory.create( host = reportsHost, httpClientProvider = createHttpClientProvider(statsDConfig) ) } private fun createHttpClientProvider(statsDConfig: Provider<StatsDConfig>): HttpClientProvider { return HttpClientProvider( statsDSender = StatsDSender.create(statsDConfig.get(), Slf4jGradleLoggerFactory), timeProvider = timeProvider, loggerFactory = Slf4jGradleLoggerFactory ) } }
4
Kotlin
37
331
44a9f33b2e4ac4607a8269cbf4f7326ba40402fe
1,621
avito-android
MIT License
app/src/main/java/com/example/android/politicalpreparedness/repository/ElectionsRepository.kt
mohammed-uzair
389,309,710
false
null
package com.example.android.politicalpreparedness.repository import com.example.android.politicalpreparedness.data_source.network.models.Election import com.example.android.politicalpreparedness.data_source.network.models.ElectionResponse import com.example.android.politicalpreparedness.data_source.network.models.RepresentativeResponse import com.example.android.politicalpreparedness.data_source.network.models.VoterInfoResponse interface ElectionsRepository { suspend fun getUpcomingElections(): ElectionResponse suspend fun getVoterInfo(address: String, electionId : Int): VoterInfoResponse suspend fun getRepresentatives( address: String, includeOffices: Boolean = true ): RepresentativeResponse suspend fun getSavedElections(): List<Election> suspend fun saveElection(election: Election) suspend fun getAllSavedElections(): List<Election> suspend fun getElectionBy(electionId: Int): Election suspend fun removeElection(id: Int) }
0
Kotlin
0
0
954b63a9821489eeb16894b7abd427f2ae003ebf
991
udacity-final-political-preparedness
Apache License 2.0
app/src/main/java/com/bsuir/bsuirschedule/domain/models/ErrorMessageText.kt
Saydullin
526,953,048
false
{"Kotlin": 678273, "HTML": 7301}
package com.bsuir.bsuirschedule.domain.models data class ErrorMessageText( val title: String, val caption: String )
0
Kotlin
0
4
989325e764d14430d5d124efd063f7190b075f4a
127
BSUIR_Schedule
Creative Commons Zero v1.0 Universal
analysis/low-level-api-fir/tests/org/jetbrains/kotlin/analysis/low/level/api/fir/AbstractStdLibBasedGetOrBuildFirTest.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.analysis.low.level.api.fir import org.jetbrains.kotlin.analysis.low.level.api.fir.api.resolveToFirSymbol import org.jetbrains.kotlin.analysis.low.level.api.fir.test.base.AbstractLowLevelApiSingleFileTest import org.jetbrains.kotlin.analysis.low.level.api.fir.test.configurators.AnalysisApiFirSourceTestConfigurator import org.jetbrains.kotlin.analysis.project.structure.ProjectStructureProvider import org.jetbrains.kotlin.analysis.test.framework.services.expressionMarkerProvider import org.jetbrains.kotlin.analysis.test.framework.utils.unwrapMultiReferences import org.jetbrains.kotlin.idea.references.KtReference import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.test.services.TestModuleStructure import org.jetbrains.kotlin.test.services.TestServices import org.jetbrains.kotlin.test.services.assertions abstract class AbstractStdLibBasedGetOrBuildFirTest : AbstractLowLevelApiSingleFileTest() { override val configurator = AnalysisApiFirSourceTestConfigurator(analyseInDependentSession = false) override fun doTestByFileStructure(ktFile: KtFile, moduleStructure: TestModuleStructure, testServices: TestServices) { val project = ktFile.project assert(!project.isDisposed) { "$project is disposed" } val caretPosition = testServices.expressionMarkerProvider.getCaretPosition(ktFile) val ktReferences = ktFile.findReferenceAt(caretPosition)?.unwrapMultiReferences().orEmpty().filterIsInstance<KtReference>() if (ktReferences.size != 1) { testServices.assertions.fail { "No references at caret found" } } val declaration = analyseForTest(ktReferences.first().element) { ktReferences.first().resolveToSymbol()?.psi as KtDeclaration } val module = ProjectStructureProvider.getModule(project, ktFile, contextualModule = null) val resolveSession = LLFirResolveSessionService.getInstance(project).getFirResolveSession(module) val fir = declaration.resolveToFirSymbol(resolveSession).fir testServices.assertions.assertEqualsToTestDataFileSibling(renderActualFir(fir, declaration)) } }
162
null
5729
46,436
c902e5f56504e8572f9bc13f424de8bfb7f86d39
2,387
kotlin
Apache License 2.0
src/main/kotlin/dev/virefire/yok/types/ClientConfig.kt
Virefire
488,748,227
false
{"Kotlin": 23035}
package dev.virefire.yok.types import java.net.Proxy class ClientConfig { var baseUrl: String? = null var headers: Headers = headersOf() var proxy: Proxy? = null var connectTimeout = 10000 var readTimeout = 10000 var followRedirects = true var addDefaultUserAgent = true internal val interceptors: MutableList<Interceptor> = mutableListOf() fun interceptor(interceptor: Interceptor) { interceptors.add(interceptor) } }
0
Kotlin
0
1
6a816daf46cfe7ad9a7d792ffa93a0b1da905c2f
468
Yok
MIT License
client/src/main/java/pro/panopticon/client/sensor/impl/ReportTimeSensor.kt
nsbno
250,489,449
false
null
package pro.panopticon.client.sensor.impl import pro.panopticon.client.model.Measurement import pro.panopticon.client.sensor.Sensor import java.time.LocalDateTime class ReportTimeSensor : Sensor { override fun measure(): List<Measurement> { return listOf( Measurement( key = "report.generated", status = Measurement.Status.INFO, displayValue = LocalDateTime.now().toString(), description = "", ) ) } }
1
null
1
1
85af845330747cf554265ae1d63a79af72888711
516
panopticon
Apache License 2.0
touch/src/androidTest/java/de/nicidienase/chaosflix/PersistenceTest.kt
NiciDieNase
108,323,466
false
null
package de.nicidienase.chaosflix import android.arch.lifecycle.ViewModelProviders import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 import android.test.ActivityInstrumentationTestCase2 import android.view.View import de.nicidienase.chaosflix.common.entities.userdata.PlaybackProgress import org.junit.Test import org.junit.runner.RunWith import de.nicidienase.chaosflix.touch.ViewModelFactory import io.reactivex.functions.Consumer /** * Created by felix on 31.10.17. */ @RunWith(AndroidJUnit4::class) class PersistenceTest { @Test fun test1() { val playbackProgressDao = ViewModelFactory.database.playbackProgressDao() playbackProgressDao.saveProgress(PlaybackProgress(23,1337)) playbackProgressDao.getProgressForEvent(23) .observeForever { it -> assert(it?.eventId == 23L && it?.progress == 1337L) } } }
0
Kotlin
3
3
4e39165c9b15395f3c3053fdb74f14646efd69d3
917
chaosflix-touch
MIT License
src/test/kotlin/com/github/shiraji/databindinglayout/intentions/WrapWith2WayDatabindingExpressionIntentionTest.kt
shiraji
74,247,187
false
null
package com.github.shiraji.databindinglayout.intentions class WrapWith2WayDatabindingExpressionIntentionTest : BaseIntentionTestCase("WrapWith2WayDatabindingExpressionIntention")
6
Kotlin
5
87
4b6942213d752f8a178c6e669860e61dfd5d0f53
179
databinding-support
Apache License 2.0
src/main/kotlin/es/urjc/realfood/shipping/domain/Shipment.kt
MasterCloudApps-Projects
391,104,322
false
null
package es.urjc.realfood.shipping.domain import java.time.Instant import java.util.* import javax.persistence.Entity import javax.persistence.Enumerated import javax.persistence.Id @Entity class Shipment( val orderId: String, val clientId: String, ) { @Id val id = UUID.randomUUID().toString() private val createdAt = Date() private var lastUpdate: Date = Date() @Enumerated var status: ShipmentStatus = ShipmentStatus.PENDING fun updateStatus(status: ShipmentStatus) { if(this.status.next != status) throw IllegalStateException("Shipment '$id' invalid next status '$status', it must be '${this.status.next}'") if(status == this.status) return this.status = status this.lastUpdate = Date() } fun getCreatedAt(): Instant { return createdAt.toInstant() } fun getLastUpdate(): Instant { return lastUpdate.toInstant() } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Shipment if (id != other.id) return false return true } override fun hashCode(): Int { return id.hashCode() } }
0
Kotlin
0
1
8717cdf9ae5c0393d0df6567aa83e4ed9963093c
1,266
realfood-shipping
Apache License 2.0
library/file/src/commonMain/kotlin/io/matthewnelson/kmp/file/KmpFile.kt
05nelsonm
729,001,287
false
{"Kotlin": 124336}
/* * Copyright (c) 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 * * 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. **/ @file:JvmName("KmpFile") package io.matthewnelson.kmp.file import io.matthewnelson.kmp.file.internal.* import io.matthewnelson.kmp.file.internal.normalize import io.matthewnelson.kmp.file.internal.platformResolve import io.matthewnelson.kmp.file.internal.platformWriteBytes import io.matthewnelson.kmp.file.internal.platformWriteUtf8 import kotlin.jvm.JvmField import kotlin.jvm.JvmName /** * The operating system's path separator character * */ @JvmField public val SysPathSep: Char = PlatformPathSeparator /** * The system temporary directory * */ @JvmField public val SysTempDir: File = PlatformTempDirectory @JvmName("get") public fun String.toFile(): File = File(this) @get:JvmName("nameOf") public val File.name: String get() = getName() @get:JvmName("parentPathOf") public val File.parentPath: String? get() = getParent() @get:JvmName("parentFileOf") public val File.parentFile: File? get() = getParentFile() @get:JvmName("pathOf") public val File.path: String get() = getPath() @get:JvmName("absolutePathOf") public val File.absolutePath: String get() = getAbsolutePath() @get:JvmName("absoluteFileOf") public val File.absoluteFile: File get() = getAbsoluteFile() @Throws(IOException::class) @JvmName("canonicalPathOf") public fun File.canonicalPath(): String = getCanonicalPath() @Throws(IOException::class) @JvmName("canonicalFileOf") public fun File.canonicalFile(): File = getCanonicalFile() /** * Removes all `.` and resolves all possible `..` for * the provided [File.path]. * */ @JvmName("normalizedFileOf") public fun File.normalize(): File { val normalized = path.normalize() if (normalized == path) return this return File(normalized) } /** * Read the full contents of the file (as bytes). * * Should only be utilized for smallish files. * */ @Throws(IOException::class) @JvmName("readBytesFrom") public fun File.readBytes(): ByteArray = platformReadBytes() /** * Read the full contents of the file (as UTF-8 text). * * Should only be utilized for smallish files. * */ @Throws(IOException::class) @JvmName("readUtf8From") public fun File.readUtf8(): String = platformReadUtf8() /** * Writes the full contents of [array] to the file * */ @Throws(IOException::class) @JvmName("writeBytesTo") public fun File.writeBytes(array: ByteArray) { platformWriteBytes(array) } /** * Writes the full contents of [text] to the file (as UTF-8) * */ @Throws(IOException::class) @JvmName("writeUtf8To") public fun File.writeUtf8(text: String) { platformWriteUtf8(text) } /** * Resolves the [File] for provided [relative]. If [relative] * is absolute, returns [relative], otherwise will concatenate * the [File.path]s. * */ public fun File.resolve(relative: File): File = platformResolve(relative) public fun File.resolve(relative: String): File = resolve(relative.toFile())
0
Kotlin
0
0
bd7c151f81d52608ff3326dde8b225bc3a2b6d65
3,426
kmp-file
Apache License 2.0
src/main/kotlin/ru/yoomoney/gradle/plugins/release/bitbucket/BitbucketPullRequestCommitsResponse.kt
yoomoney
320,603,497
false
null
package ru.yoomoney.gradle.plugins.release.bitbucket import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import java.util.Objects import javax.annotation.Nonnull /** * Ответ запроса получения коммитов pull request * * @author <NAME> (<EMAIL>) * @since 11.02.2020 */ internal class BitbucketPullRequestCommitsResponse @JsonCreator private constructor( @Nonnull @JsonProperty("values") pullRequestsCommits: List<BitbucketPullRequestCommit> ) { @get:Nonnull @Nonnull val pullRequestsCommits: List<BitbucketPullRequestCommit> init { this.pullRequestsCommits = Objects.requireNonNull(pullRequestsCommits) } }
2
Kotlin
0
2
581f070c324efcb2b8235e411ec0a1628ec310ce
697
artifact-release-plugin
MIT License
src/test/kotlin/io/github/tobi/laa/spring/boot/embedded/redis/StopSafelyTest.kt
tobi-laa
755,903,685
false
{"Kotlin": 212961}
package io.github.tobi.laa.spring.boot.embedded.redis import io.github.netmikey.logunit.api.LogCapturer import io.mockk.every import io.mockk.impl.annotations.RelaxedMockK import io.mockk.junit5.MockKExtension import io.mockk.verify import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.junit.jupiter.api.extension.RegisterExtension import org.slf4j.event.Level import redis.embedded.Redis @ExtendWith(MockKExtension::class) @DisplayName("Tests for stopSafely") internal class StopSafelyTest { @RelaxedMockK private lateinit var redis: Redis @RegisterExtension val logs: LogCapturer = LogCapturer.create().captureForLogger("io.github.tobi.laa.spring.boot.embedded.redis", Level.DEBUG) @Test @DisplayName("stopSafely() should call stop() on the given Redis") fun stopSafely_shouldCallCloseOnGivenAutoCloseable() { stopSafely(redis) verify { redis.stop() } logs.assertDoesNotContain("Failed to stop Redis $redis") } @Test @DisplayName("stopSafely() should log an error if stop() on the given Redis throws an exception") fun stopSafely_shouldLogErrorIfStopThrowsException() { val exception = RuntimeException("close() failed") every { redis.stop() } throws exception stopSafely(redis) verify { redis.stop() } val logEvent = logs.assertContains("Failed to stop Redis $redis") assertThat(logEvent.throwable).isSameAs(exception) } }
1
Kotlin
0
2
d85c9b33dd87b1026894b177a7dac20cbb8fcb84
1,592
spring-boot-embedded-redis
Apache License 2.0
korio/src/commonMain/kotlin/com/soywiz/korio/annotations/Keep.kt
korlibs
77,343,418
false
null
package com.soywiz.korio.annotations @Retention(AnnotationRetention.RUNTIME) annotation class Keep
15
Kotlin
33
349
e9e89804f5682db0a70e58b91f469b49698dd72b
100
korio
MIT License
RoomWordSample/app/src/main/java/com/booknara/android/app/roomwordsample/MainActivity.kt
booknara
609,625,084
false
null
package com.booknara.android.app.roomwordsample import android.app.Activity import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import androidx.activity.result.ActivityResult import androidx.activity.viewModels import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.booknara.android.app.roomwordsample.NewWordActivity.Companion.EXTRA_REPLY import com.booknara.android.app.roomwordsample.db.Word import com.google.android.material.floatingactionbutton.FloatingActionButton class MainActivity : AppCompatActivity() { private lateinit var adapter: WordListAdapter val wordViewModel: WordViewModel by viewModels { WordViewModelFactory((application as WordApplication).repository) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val recyclerView = findViewById<RecyclerView>(R.id.recyclerview) val fab = findViewById<FloatingActionButton>(R.id.fab) adapter = WordListAdapter() recyclerView.adapter = adapter recyclerView.layoutManager = LinearLayoutManager(this) fab.setOnClickListener { val intent = Intent(this@MainActivity, NewWordActivity::class.java) startActivityForResult(intent, newWordActivityRequestCode) } initObserver() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == newWordActivityRequestCode && resultCode == Activity.RESULT_OK) { data?.getStringExtra(EXTRA_REPLY)?.let { val word = Word(it) wordViewModel.insert(word) } } else { Toast.makeText(this, R.string.empty_not_saved, Toast.LENGTH_SHORT).show() } } private fun initObserver() { wordViewModel.allWords.observe(this) { words -> words.let { adapter.submitList(it) } } } companion object { private val newWordActivityRequestCode = 1 } }
0
Kotlin
0
0
c7aadefe95fb1326ef2690b4b418e9cde6dc4946
2,294
android-playground
MIT License
coroutine-cancellation/app/src/main/java/com/example/coroutine_cancellation/homework/assignmenttwo/MoneyTransferScreen.kt
revs87
855,464,049
false
{"Kotlin": 45473}
package com.example.coroutine_cancellation.homework.assignmenttwo import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp @Composable fun MoneyTransferScreen( state: MoneyTransferState, onAction: (MoneyTransferAction) -> Unit, ) { val focusManager = LocalFocusManager.current val primaryGreen = Color(0xFF4CAF50) val secondaryGreen = Color(0xFF81C784) val background = Color(0xFFE8F5E9) Column( modifier = Modifier .fillMaxSize() .background(background) .padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text( text = "Savings: $${String.format("%.2f", state.savingsBalance)}", color = primaryGreen, style = MaterialTheme.typography.titleMedium ) Spacer(modifier = Modifier.height(8.dp)) Text( text = "Checking: $${String.format("%.2f", state.checkingBalance)}", color = primaryGreen, style = MaterialTheme.typography.titleMedium ) Spacer(modifier = Modifier.height(16.dp)) BasicTextField( state = state.transferAmount, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Number, imeAction = ImeAction.Done ), enabled = !state.isTransferring, modifier = Modifier .clip(RoundedCornerShape(8.dp)) .background(Color.White) .padding(16.dp), decorator = { innerBox -> Row( verticalAlignment = Alignment.CenterVertically, ) { Box(modifier = Modifier.weight(1f)) { if (state.transferAmount.text.isEmpty()) { Text( text = "Enter amount", color = MaterialTheme.colorScheme.onSecondaryContainer.copy( alpha = 0.4f ) ) } innerBox() } } } ) Spacer(modifier = Modifier.height(16.dp)) Button( onClick = { focusManager.clearFocus() onAction((MoneyTransferAction.TransferFunds)) }, colors = ButtonDefaults.buttonColors( containerColor = secondaryGreen ), modifier = Modifier .height(IntrinsicSize.Min) ) { Box( contentAlignment = Alignment.Center ) { CircularProgressIndicator( modifier = Modifier .size(15.dp) .alpha(if (state.isTransferring) 1f else 0f), strokeWidth = 1.5.dp, color = MaterialTheme.colorScheme.onPrimary ) Text( text = "Transfer Funds", color = Color.White, modifier = Modifier .alpha(if (state.isTransferring) 0f else 1f) ) } } if (state.isTransferring) { Button( onClick = { onAction(MoneyTransferAction.CancelTransfer) }, colors = ButtonDefaults.buttonColors( containerColor = secondaryGreen ), ) { Text(text = "Cancel Transfer") } } val processingStateText = when (state.processingState) { ProcessingState.CheckingFunds -> { "Checking if there is enough funds..." } ProcessingState.CreditingAccount -> { "Depositing money to checking account..." } ProcessingState.DebitingAccount -> { "Withdrawing money from savings account..." } ProcessingState.CleanupResources -> { "Cleaning up resources used..." } else -> null } if (processingStateText != null) { Text(text = processingStateText) } if (state.resultMessage != null) { Text(text = state.resultMessage) } } }
0
Kotlin
0
0
c48746cd9ffe561089787c9c233689bceebd01e1
5,815
coroutines-flow-study
Apache License 2.0
kpages/src/jsMain/kotlin/preferences/Preference.kt
Monkopedia
316,826,954
false
null
/* * 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.kpages.preferences import com.ccfraser.muirwik.components.MTypographyColor import com.ccfraser.muirwik.components.MTypographyVariant import com.ccfraser.muirwik.components.button.MButtonVariant import com.ccfraser.muirwik.components.button.mButton import com.ccfraser.muirwik.components.mTypography import com.ccfraser.muirwik.components.table.MTableCellPadding import com.ccfraser.muirwik.components.table.mTableCell import com.ccfraser.muirwik.components.table.mTableRow import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.css.Align import kotlinx.css.Display import kotlinx.css.FlexDirection import kotlinx.css.LinearDimension import kotlinx.css.Position import kotlinx.css.alignItems import kotlinx.css.display import kotlinx.css.flexDirection import kotlinx.css.height import kotlinx.css.left import kotlinx.css.padding import kotlinx.css.pct import kotlinx.css.position import kotlinx.css.px import kotlinx.css.width import react.RBuilder import react.RComponent import react.RProps import react.RState import styled.css import styled.styledDiv actual external interface PreferenceBaseProps : RProps { actual var onClick: (suspend (Any) -> Unit)? } actual external interface PreferenceProps : PreferenceBaseProps { actual var title: String? actual var subtitle: String? } abstract class PreferenceBase<P : PreferenceBaseProps, S : RState> : RComponent<P, S>() { override fun RBuilder.render() { mTableRow { mTableCell(padding = MTableCellPadding.none) { styledDiv { css { display = Display.flex width = LinearDimension.auto height = LinearDimension.maxContent flexDirection = FlexDirection.column position = Position.relative } styledDiv { css { padding(16.px) } renderPreference() } props.onClick?.let { listener -> styledDiv { css { width = 100.pct height = 100.pct position = Position.absolute left = 0.px } mButton( "", variant = MButtonVariant.text, onClick = { GlobalScope.launch { listener(this@PreferenceBase) } } ) { css { height = 100.pct width = 100.pct } styledDiv { css { asDynamic().all = "revert" alignItems = Align.start } } } } } } } } } abstract fun RBuilder.renderPreference() } class Preference : PreferenceBase<PreferenceProps, RState>() { override fun RBuilder.renderPreference() { props.title?.let { mTypography( it, MTypographyVariant.subtitle1, color = MTypographyColor.textPrimary ) } props.subtitle?.let { mTypography( it, MTypographyVariant.body2, color = MTypographyColor.textSecondary ) } } } actual inline fun PreferenceBuilder.preference(noinline handler: PreferenceProps.() -> Unit) { base.child(Preference::class) { attrs(handler) } }
0
Kotlin
0
0
be2e9583641261db13aeec7faf6050a6f483d3a4
4,777
kpages
Apache License 2.0
app/src/main/java/com/example/moviedb/data/remote/response/GetTvListResponse.kt
dangquanuet
127,717,732
false
{"Kotlin": 277738, "Makefile": 1159}
package com.example.moviedb.data.remote.response import com.example.moviedb.data.model.Tv class GetTvListResponse : BaseListResponse<Tv>()
3
Kotlin
93
413
c5031dcfa879243c0ea44d0973153078e568c013
140
The-Movie-DB-Kotlin
Apache License 2.0
app/src/main/java/com/example/moviedb/data/remote/response/GetTvListResponse.kt
dangquanuet
127,717,732
false
{"Kotlin": 277738, "Makefile": 1159}
package com.example.moviedb.data.remote.response import com.example.moviedb.data.model.Tv class GetTvListResponse : BaseListResponse<Tv>()
3
Kotlin
93
413
c5031dcfa879243c0ea44d0973153078e568c013
140
The-Movie-DB-Kotlin
Apache License 2.0
app/src/main/java/com/filipibrentegani/marvelheroes/heroeslist/domain/IFavoriteHeroesRepository.kt
filipibrentegani
347,464,333
false
null
package com.filipibrentegani.marvelheroes.heroeslist.domain import com.filipibrentegani.marvelheroes.entity.domain.Hero interface IFavoriteHeroesRepository { suspend fun getFavoriteHero(heroId: Int) : Hero? suspend fun getFavoriteHeroes() : List<Hero> suspend fun addFavoriteHeroes(hero: Hero) suspend fun removeFavoriteHero(hero: Hero) }
0
Kotlin
0
0
f8ac6e2a1e3fc9b9e244c08417d9584f3ac51cbe
356
MalvelHeroes
Apache License 2.0
quality/src/main/kotlin/net/twisterrob/gradle/quality/report/html/XMLStreamWriterDSL.kt
TWiStErRob
116,494,236
false
null
@file:Suppress("NOTHING_TO_INLINE") package net.twisterrob.gradle.quality.report.html import java.io.Writer import javax.xml.stream.XMLStreamWriter fun Writer.xmlWriter(): XMLStreamWriter = javax.xml.stream.XMLOutputFactory.newInstance().createXMLStreamWriter(this) fun XMLStreamWriter.use(block: (XMLStreamWriter) -> Unit) { AutoCloseable { [email protected]() [email protected]() }.use { block(this@use) } } /** * Based on the amazing idea from https://www.schibsted.pl/blog/back-end/readable-xml-kotlin-extensions/ * @param encoding be sure to set the underlying Writer's encoding to the same */ inline fun XMLStreamWriter.document( version: String = "1.0", encoding: String = "utf-8", crossinline content: XMLStreamWriter.() -> Unit ): XMLStreamWriter = apply { writeStartDocument(encoding, version) content() writeEndDocument() } inline fun XMLStreamWriter.element( name: String, crossinline content: XMLStreamWriter.() -> Unit ): XMLStreamWriter = apply { writeStartElement(name) content() writeEndElement() } inline fun XMLStreamWriter.element(name: String, content: String) { element(name) { writeCharacters(content) } } inline fun XMLStreamWriter.element(name: String, content: Any) { element(name) { writeCharacters(content.toString()) } } inline fun XMLStreamWriter.attribute(name: String, value: String) { writeAttribute(name, value) } inline fun XMLStreamWriter.attribute(name: String, value: Any) { writeAttribute(name, value.toString()) } inline fun XMLStreamWriter.cdata(content: String) { writeCData(content.escapeForCData()) } inline fun XMLStreamWriter.cdata(content: Any) { writeCData(content.toString().escapeForCData()) } fun String.escapeForCData(): String { val cdataEnd = """]]>""" val cdataStart = """<![CDATA[""" return this // split cdataEnd into two pieces so XML parser doesn't recognize it .replace(cdataEnd, """]]${cdataEnd}${cdataStart}>""") }
37
Kotlin
1
7
b207c0bce0c0f7f3405fb54d10071547f60a0eb4
1,934
net.twisterrob.gradle
MIT License
kotlin-node/src/jsMain/generated/node/inspector/debugger/EvaluateOnCallFrameReturnType.kt
JetBrains
93,250,841
false
{"Kotlin": 12635434, "JavaScript": 423801}
// Generated by Karakum - do not modify it manually! package node.inspector.debugger sealed external interface EvaluateOnCallFrameReturnType { /** * Object wrapper for the evaluation result. */ var result: node.inspector.runtime.RemoteObject /** * Exception details. */ var exceptionDetails: node.inspector.runtime.ExceptionDetails? }
40
Kotlin
165
1,347
997ed3902482883db4a9657585426f6ca167d556
376
kotlin-wrappers
Apache License 2.0
src/main/kotlin/dev/alluvial/sink/iceberg/io/DebeziumTaskWriter.kt
dungdm93
446,678,188
false
{"Kotlin": 549736, "Java": 60814, "Smarty": 3194, "Dockerfile": 1470, "Shell": 1359}
package dev.alluvial.sink.iceberg.io import dev.alluvial.sink.iceberg.type.IcebergSchema import dev.alluvial.sink.iceberg.type.KafkaSchema import dev.alluvial.sink.iceberg.type.KafkaStruct import dev.alluvial.stream.debezium.RecordTracker import dev.alluvial.utils.TableTruncatedException import org.apache.iceberg.ContentFile import org.apache.iceberg.PartitionKey import org.apache.iceberg.PartitionSpec import org.apache.iceberg.deletes.PositionDelete import org.apache.iceberg.io.FileIO import org.apache.iceberg.io.TaskWriter import org.apache.iceberg.io.WriteResult import org.apache.iceberg.io.copy import org.apache.iceberg.util.Pair import org.apache.iceberg.util.StructLikeMap import org.apache.iceberg.util.Tasks import org.apache.kafka.connect.sink.SinkRecord class DebeziumTaskWriter( partitioningWriterFactory: PartitioningWriterFactory<KafkaStruct>, private val spec: PartitionSpec, private val io: FileIO, private val partitioner: Partitioner<KafkaStruct>, sSchema: KafkaSchema, iSchema: IcebergSchema, equalityFieldIds: Set<Int>, private val tracker: RecordTracker, ) : TaskWriter<SinkRecord> { private val insertWriter by lazy { partitioningWriterFactory.newDataWriter() as TrackedPartitioningWriter } private val equalityDeleteWriter by lazy(partitioningWriterFactory::newEqualityDeleteWriter) private val positionDeleteWriter by lazy(partitioningWriterFactory::newPositionDeleteWriter) /** * A container for `PositionDelete`. FileWriters MUST use `StructCopy.copy(...)` if it holds this value in-memory */ private val positionDelete: PositionDelete<KafkaStruct> /** * For read / create records, we don't have clue about previous value. * So `useGlobalDelete` is a mechanism to prevent previous value is in different partition. */ private val useGlobalDelete: Boolean /** * partition is immutable. It could be re-used by in-memory cache to reduce memory usage */ private val cachedPartitions: MutableMap<Partition, Partition> /** * Track `PathOffset` and `Partition` for every inserted records */ private val insertedRowMap: MutableMap<Key, Pair<PathOffset, Partition?>> private val keyer: Keyer<SinkRecord> private var key: Key? = null init { val equalityFieldNames = equalityFieldIds.map { iSchema.findField(it).name() } val iKeySchema = iSchema.select(equalityFieldNames) keyer = keyerFor(sSchema, iKeySchema) insertedRowMap = StructLikeMap.create(iKeySchema.asStruct()) cachedPartitions = StructLikeMap.create(spec.partitionType()) useGlobalDelete = spec.fields().any { it.sourceId() !in equalityFieldIds } positionDelete = PositionDelete.create() } override fun write(record: SinkRecord) { val value = record.value() as KafkaStruct? ?: return // Tombstone events val before = value.getStruct("before") val after = value.getStruct("after") key = if (record.key() != null) keyer(record) else null val operation = value.getString("op") when (operation) { // read (snapshot) events "r" -> insert(after, true) // forceDelete to ensure no duplicate data when re-snapshot // create events "c" -> insert(after, tracker.maybeDuplicate(record)) // update events "u" -> { delete(before) insert(after) } // delete events "d" -> delete(before) // truncate events "t" -> throw TableTruncatedException() else -> {} // ignore } } private fun internalPosDelete(key: Key): Boolean { val previous = insertedRowMap.remove(key) if (previous != null) { val prePathOffset = previous.first() val prePartition = previous.second() positionDeleteWriter.write(prePathOffset.setTo(positionDelete), spec, prePartition) return true } return false } private fun insert(row: KafkaStruct, forceDelete: Boolean = false) { val partition = partitioner(row) val copiedKey = key.copy()!! if (forceDelete) { delete(row, useGlobalDelete) } else { internalPosDelete(copiedKey) } val pathOffset = insertWriter.trackedWrite(row, spec, partition) insertedRowMap[copiedKey] = Pair.of(pathOffset, cachedPartition(partition)) } private fun delete(row: KafkaStruct, globalDelete: Boolean = false) { if (internalPosDelete(key!!)) return val spec = if (globalDelete) PartitionSpec.unpartitioned() else spec val partition = if (globalDelete) null else partitioner(row) equalityDeleteWriter.write(row, spec, partition) } override fun abort() { close() // clean up files created by this writer val files = with(writeResult()) { buildList { addAll(dataFiles()) addAll(deleteFiles()) } } Tasks.foreach(files) .throwFailureWhenFinished() .noRetry() .run { file: ContentFile<*> -> io.deleteFile(file.path().toString()) } } override fun complete(): WriteResult { close() return writeResult() } override fun close() { insertWriter.close() equalityDeleteWriter.close() positionDeleteWriter.close() } private fun writeResult(): WriteResult { val insertResult = insertWriter.result() val equalityDeleteResult = equalityDeleteWriter.result() val positionDeleteResult = positionDeleteWriter.result() return WriteResult.builder() .addDataFiles(insertResult.dataFiles()) .addDeleteFiles(equalityDeleteResult.deleteFiles()) .addDeleteFiles(positionDeleteResult.deleteFiles()) .addReferencedDataFiles(positionDeleteResult.referencedDataFiles()) .build() } private fun cachedPartition(partition: Partition?): Partition? { if (partition == null) return null return cachedPartitions.computeIfAbsent(partition) { partition.copy()!! } } companion object { val unpartition: Partitioner<KafkaStruct> = { _ -> null } fun partitionerFor( spec: PartitionSpec, sSchema: KafkaSchema, iSchema: IcebergSchema, ): Partitioner<KafkaStruct> { return object : Partitioner<KafkaStruct> { private val wrapper: StructWrapper = StructWrapper(sSchema, iSchema) private val partitionKey = PartitionKey(spec, iSchema) override fun invoke(record: KafkaStruct): Partition { partitionKey.partition(wrapper.wrap(record)) return partitionKey } } } fun keyerFor(sSchema: KafkaSchema, iSchema: IcebergSchema): Keyer<SinkRecord> { return object : Keyer<SinkRecord> { private val wrapper: StructWrapper = StructWrapper(sSchema, iSchema) override fun invoke(record: SinkRecord): Key { val key = record.key() as KafkaStruct return wrapper.wrap(key) } } } } }
0
Kotlin
0
1
51a2d30fc45b25e6763d33c84dd2ac2b71a8a4c0
7,418
alluvial
Apache License 2.0
lib/src/test/java/com/sha/rxrequester/handler/OutOfMemoryErrorHandler.kt
thasneemp
216,811,559
true
{"Kotlin": 33828, "Java": 660}
package com.sha.rxrequester.handler import com.sha.rxrequester.exception.handler.throwable.ThrowableHandler import com.sha.rxrequester.exception.handler.throwable.ThrowableInfo class OutOfMemoryErrorHandler : ThrowableHandler<OutOfMemoryError>() { override fun supportedErrors(): List<Class<OutOfMemoryError>> { return listOf(OutOfMemoryError::class.java) } override fun handle(info: ThrowableInfo){ info.presentable.showError("OutOfMemoryError") } }
0
null
0
0
ad38fff6e7061212d80ec8e201ca59bc58feb728
487
RxRequester
Apache License 2.0
app/src/main/java/com/hypertrack/android/ui/common/select_destination/reducer/MapMoveCause.kt
hypertrack
241,723,736
false
null
package com.hypertrack.android.ui.common.select_destination.reducer sealed class MapMoveCause object MovedByUser : MapMoveCause() object MovedToPlace : MapMoveCause() object MovedToUserLocation : MapMoveCause()
1
Kotlin
17
31
c5dd23621aed11ff188cf98ac037b67f435e9f5b
212
visits-android
MIT License
00-minimal-buildsrc/buildSrc/src/main/kotlin/Deps.kt
reul
297,798,004
false
null
object Deps { val coreKtx = "androidx.core:core-ktx:1.3.1" val appcompat = "androidx.appcompat:appcompat:1.2.0" val androidBuildTools = "com.android.tools.build:gradle:4.0.1" }
0
Kotlin
0
0
b7810109a76a1a9ee2651a36ad686712bf774772
189
gradle-notes
The Unlicense
packages/library-sync/src/commonMain/kotlin/io/realm/mongodb/internal/KtorNetworkTransport.kt
AnnaKandel
440,053,483
true
{"Kotlin": 1066638, "C++": 74855, "SWIG": 9542, "JavaScript": 8846, "Shell": 8468, "CMake": 2507, "Dockerfile": 2460, "C": 1762}
/* * Copyright 2021 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.realm.mongodb.internal import io.ktor.client.call.receive import io.ktor.client.features.ClientRequestException import io.ktor.client.features.ServerResponseException import io.ktor.client.features.logging.Logger import io.ktor.client.request.HttpRequestBuilder import io.ktor.client.request.delete import io.ktor.client.request.get import io.ktor.client.request.headers import io.ktor.client.request.patch import io.ktor.client.request.post import io.ktor.client.request.put import io.ktor.client.statement.HttpResponse import io.ktor.http.Headers import io.ktor.http.HttpHeaders import io.ktor.http.HttpMethod import io.ktor.utils.io.errors.IOException import io.realm.internal.interop.sync.NetworkTransport import io.realm.internal.interop.sync.Response import io.realm.internal.interop.sync.ResponseCallback import io.realm.mongodb.AppConfiguration.Companion.DEFAULT_AUTHORIZATION_HEADER_NAME import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.async import kotlin.collections.set class KtorNetworkTransport( override val authorizationHeaderName: String = DEFAULT_AUTHORIZATION_HEADER_NAME, override val customHeaders: Map<String, String> = mapOf(), // FIXME Rework timeout to take a Duration instead // https://github.com/realm/realm-kotlin/issues/408 timeoutMs: Long, private val dispatcher: CoroutineDispatcher, logger: Logger? = null, ) : NetworkTransport { // FIXME Figure out how to reuse the HttpClient across all network requests. private val clientCache: HttpClientCache = HttpClientCache(timeoutMs, logger) @Suppress("ComplexMethod", "TooGenericExceptionCaught") override fun sendRequest( method: String, url: String, headers: Map<String, String>, body: String, callback: ResponseCallback, ) { // FIXME When using a shared HttpClient we are seeing sporadic // network failures on macOS. They manifest as ClientRequestException // even though the request appear to be valid. This could indicate // that some state isn't cleaned up correctly between requests, but // it is unclear what. As a temporary work-around, we now create a // HttpClient pr. request. val client = clientCache.getClient() CoroutineScope(dispatcher).async { val response = try { val requestBuilderBlock: HttpRequestBuilder.() -> Unit = { headers { // 1. First of all add all custom headers customHeaders.forEach { append(it.key, it.value) } // 2. Then add all headers received from OS headers.forEach { (key, value) -> // It is not allowed to set content type on gets https://github.com/ktorio/ktor/issues/1127 if (method != "get" || key != HttpHeaders.ContentType) { append(key, value) } } // 3. Finally, if we have a non-default auth header name, replace the OS // default with the custom one if (authorizationHeaderName != DEFAULT_AUTHORIZATION_HEADER_NAME && contains(DEFAULT_AUTHORIZATION_HEADER_NAME) ) { this[DEFAULT_AUTHORIZATION_HEADER_NAME]?.let { originalAuthValue -> this[authorizationHeaderName] = originalAuthValue } this.remove(DEFAULT_AUTHORIZATION_HEADER_NAME) } } addBody(method, body) addMethod(method) } when (method) { "delete" -> client.delete<HttpResponse>(url, requestBuilderBlock) "patch" -> client.patch<HttpResponse>(url, requestBuilderBlock) "post" -> client.post<HttpResponse>(url, requestBuilderBlock) "put" -> client.put<HttpResponse>(url, requestBuilderBlock) "get" -> client.get<HttpResponse>(url, requestBuilderBlock) else -> throw IllegalArgumentException("Wrong request method: '$method'") }.let { processHttpResponse(it) } } catch (e: ClientRequestException) { processHttpResponse(e.response) } catch (e: ServerResponseException) { // 500s are thrown as ServerResponseException processHttpResponse(e.response) } catch (e: IOException) { Response(0, ERROR_IO, mapOf(), e.toString()) } catch (e: CancellationException) { // FIXME Validate we propagate the custom codes as an actual exception to the user // https://github.com/realm/realm-kotlin/issues/451 Response(0, ERROR_INTERRUPTED, mapOf(), e.toString()) } catch (e: Exception) { // FIXME Validate we propagate the custom codes as an actual exception to the user // https://github.com/realm/realm-kotlin/issues/451 Response(0, ERROR_UNKNOWN, mapOf(), e.toString()) } callback.response(response) } } private suspend fun processHttpResponse(response: HttpResponse): Response { val responseBody = response.receive<String>() val responseStatusCode = response.status.value val responseHeaders = parseHeaders(response.headers) return createHttpResponse(responseStatusCode, responseHeaders, responseBody) } private fun HttpRequestBuilder.addBody(method: String, body: String) { when (method) { "delete", "patch", "post", "put" -> this.body = body } } private fun HttpRequestBuilder.addMethod(method: String) { when (method) { "delete" -> this.method = HttpMethod.Delete "patch" -> this.method = HttpMethod.Patch "post" -> this.method = HttpMethod.Post "put" -> this.method = HttpMethod.Put "get" -> this.method = HttpMethod.Get } } private fun parseHeaders(headers: Headers): Map<String, String> { val parsedHeaders: MutableMap<String, String> = mutableMapOf() for (key in headers.names()) { parsedHeaders[key] = requireNotNull(headers[key]) { "Header '$key' cannot be null" } } return parsedHeaders } companion object { // Custom error codes. These must not match any HTTP response error codes const val ERROR_IO = 1000 const val ERROR_INTERRUPTED = 1001 const val ERROR_UNKNOWN = 1002 private fun createHttpResponse( responseStatusCode: Int, responseHeaders: Map<String, String>, responseBody: String ): Response = Response(responseStatusCode, 0, responseHeaders, responseBody) } }
0
null
0
1
fc0d6ceaa45cbf960a4a1f56c188f4d9f1f2c699
7,860
realm-kotlin
DOC License
shared/src/commonMain/kotlin/io.newm.shared/public/usecases/mocks/MockConnectWalletUseCase.kt
projectNEWM
435,674,758
false
{"Kotlin": 438865, "Swift": 258701}
package io.newm.shared.public.usecases.mocks import io.newm.shared.public.usecases.ConnectWalletUseCase import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow class MockConnectWalletUseCase : ConnectWalletUseCase { private var xpub: String? = null override fun connect(xpub: String) { this.xpub = xpub } override fun disconnect() { xpub = null } override fun isConnected(): Boolean { return xpub != null } override fun isConnectedFlow(): Flow<Boolean> = flow<Boolean> { emit(isConnected()) } }
0
Kotlin
8
14
3173d70a43046945a836462c7a01ad57b028bfe7
572
newm-mobile
Apache License 2.0
androidOlympusBlog/src/main/java/com/olympusblog/android/presentation/screens/comments/create/CreateCommentState.kt
sentrionic
551,827,184
false
null
package com.olympusblog.android.presentation.screens.comments.create import com.olympusblog.android.presentation.core.validation.CommentTextState import com.olympusblog.domain.core.StateMessage import com.olympusblog.domain.util.KQueue data class CreateCommentState( val isSubmitting: Boolean = false, val isDirty: Boolean = false, val slug: String? = null, val body: CommentTextState = CommentTextState(), val onPublishSuccess: Boolean = false, val queue: KQueue<StateMessage> = KQueue(mutableListOf()), )
0
Kotlin
0
0
bb61f26adcdded63b83c505d2f67c50715e8b859
533
OlympusKMM
MIT License
compose_todo/app/src/main/java/com/example/compose_todo/common/CategoryIconToggleButton.kt
SamedHrmn
697,496,141
false
{"Kotlin": 68514}
package com.example.compose_todo.common import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.OutlinedIconToggleButton import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.vectorResource import androidx.compose.ui.unit.dp import com.example.compose_todo.R enum class TodoCategory { NONE, WORK, GOAL, MEET; fun getIconRes(): Int? { return when (this) { WORK -> R.drawable.file_list_line_icon GOAL -> R.drawable.trophy_icon MEET -> R.drawable.calendar_event_icon else -> null } } fun getContainerColor(): Color? { return when (this) { WORK -> Color(0xFFDBECF6) GOAL -> Color(0xFFFEF5D3) MEET -> Color(0xFFE7E2F3) else -> null } } } @Composable fun CategoryIconToggleButton( category: TodoCategory, isChecked: Boolean = false, onCheckedChange: ((Boolean) -> Unit)? = null ) { if (category == TodoCategory.NONE) { Spacer(modifier = Modifier.size(0.dp)) } else { Surface(shadowElevation = 1.dp, shape = CircleShape) { OutlinedIconToggleButton( checked = if (onCheckedChange == null) false else !isChecked, onCheckedChange = {checked-> onCheckedChange?.invoke(!checked) }, shape = CircleShape, colors = IconButtonDefaults.iconToggleButtonColors( containerColor = category.getContainerColor()!! ), border = BorderStroke(2.dp, color = Color.White), modifier = Modifier .size(48.dp) ) { Image( imageVector = ImageVector.vectorResource(category.getIconRes()!!), contentDescription = null ) } } } }
0
Kotlin
0
0
b5a8010e3d737a95755f607349b11d6f6507b083
2,370
android-compose-playground
MIT License
app/src/main/java/com/sebastijanzindl/galore/data/repository/FlavourRepository.kt
m1thrandir225
743,270,603
false
{"Kotlin": 400176}
package com.sebastijanzindl.galore.data.repository import com.sebastijanzindl.galore.domain.models.Flavour import com.sebastijanzindl.galore.domain.models.UserLikedFlavour interface FlavourRepository { suspend fun getAllFlavours(): List<Flavour> suspend fun getUserFlavours(userId: String): List<Flavour> suspend fun addFlavoursToFavourites(flavourIds: List<String>, userId: String): List<UserLikedFlavour> }
0
Kotlin
0
0
3a8523e4c8f38020c909ab04c98275b13bb329d9
425
galore-android
MIT License
base/src/commonTest/kotlin/com/github/fsbarata/functional/data/monoid/FirstKtTest.kt
fsbarata
277,280,202
false
null
package com.github.fsbarata.functional.data.monoid import com.github.fsbarata.functional.assertEquals import com.github.fsbarata.functional.data.Monoid import com.github.fsbarata.functional.data.MonoidLaws import com.github.fsbarata.functional.data.SemigroupLaws import kotlin.test.Test class FirstNotNullSemigroupTest: SemigroupLaws<FirstNotNull<String>> { override val possibilities: Int = 10 override fun factory(possibility: Int) = FirstNotNull(possibility.takeIf { it > 0 }?.toString()) @Test fun concatWith() { assertEquals(FirstNotNull(3), FirstNotNull(3) .concatWith(FirstNotNull(1)) .concatWith(FirstNotNull(5))) assertEquals(FirstNotNull(1), FirstNotNull<Int>(null) .concatWith(FirstNotNull(null)) .concatWith(FirstNotNull(1)) .concatWith(FirstNotNull(null)) .concatWith(FirstNotNull(5))) } } class FirstNotNullMonoidTest: MonoidLaws<String?> { override val monoid: Monoid<String?> = firstNotNullMonoid() override val possibilities: Int = 10 override fun factory(possibility: Int) = possibility.takeIf { it > 0 }?.toString() @Test fun concat() { with(firstNotNullMonoid<Int>()) { assertEquals(3, 3.concatWith(1).concatWith(5)) assertEquals(1, null.concatWith(1).concatWith(null).concatWith(5).concatWith(null)) } } }
0
Kotlin
1
0
ce4b63f6326efcc92fcc9a2c69dcda1e45b1e4be
1,290
kotlin-functional
Apache License 2.0
src/main/kotlin/com/github/sword/game/bukkit/changeDamage.kt
zhibeigg
573,402,193
false
{"Kotlin": 42715}
package com.github.sword.game.bukkit import com.github.sword.sword import com.github.sword.sword.config import org.bukkit.entity.EntityType import org.bukkit.entity.Player import org.bukkit.event.entity.EntityDamageByBlockEvent import org.bukkit.event.entity.EntityDamageEvent import org.bukkit.event.entity.EntityDamageEvent.DamageCause import taboolib.common.platform.event.SubscribeEvent object changeDamage { @SubscribeEvent fun e(e: EntityDamageByBlockEvent) { val type = e.cause val config = sword.config if (type == DamageCause.HOT_FLOOR && config.getInt("magma") == 0) e.isCancelled = true if (type == DamageCause.HOT_FLOOR && config.getInt("magma") != 0) e.damage = config.getInt("magma").toDouble() if (type == DamageCause.CONTACT && config.getInt("touch") == 0) e.isCancelled = true if (type == DamageCause.CONTACT && config.getInt("touch") != 0) e.damage = config.getInt("touch").toDouble() } @SubscribeEvent fun fire(e: EntityDamageEvent) { if (!e.isCancelled ) { if (e.cause == DamageCause.FIRE || e.cause == DamageCause.FIRE_TICK) { e.damage = config.getInt("fire-damage").toDouble() } } } @SubscribeEvent fun drop(e: EntityDamageEvent) { if (e.entityType == EntityType.PLAYER) { val player = e.entity as Player if (e.cause == DamageCause.FALL && config.getStringList("no-fall").contains(player.world.name)) { e.isCancelled = true } } return } }
0
Kotlin
0
0
b818e34d24ee863561f5dae00ee0478c8713f050
1,628
sword
Creative Commons Zero v1.0 Universal
src/main/java/net/oxyopia/vice/features/misc/ConsumeItemBlocker.kt
Oxyopiia
689,119,282
false
null
package net.oxyopia.vice.features.misc import net.minecraft.item.Items import net.minecraft.util.ActionResult import net.oxyopia.vice.Vice import net.oxyopia.vice.events.BlockInteractEvent import net.oxyopia.vice.events.core.SubscribeEvent import net.oxyopia.vice.utils.ItemUtils.cleanName object ConsumeItemBlocker { @SubscribeEvent fun onBlockInteract(event: BlockInteractEvent) { if (!Vice.config.PREVENT_PLACING_PLAYER_HEADS) return val stack = event.itemStack val new = when { stack.item == Items.PLAYER_HEAD -> ActionResult.PASS stack.item == Items.TRIPWIRE_HOOK && stack.cleanName().contains("Train Key") -> ActionResult.PASS else -> return } event.setReturnValue(new) } }
5
null
1
2
7dcfa2ba3ce8a76de6bae2017ddc4a4b88e4e2f1
705
ViceMod
MIT License
camposer/src/main/java/com/ujizin/camposer/state/ImplementationMode.kt
ujizin
537,219,026
false
{"Kotlin": 95177}
package com.ujizin.camposer.state import androidx.camera.view.PreviewView /** * Camera implementation mode. * * @param value internal implementation mode from cameraX * @see PreviewView.ImplementationMode * */ public enum class ImplementationMode(internal val value: PreviewView.ImplementationMode) { Compatible(PreviewView.ImplementationMode.COMPATIBLE), Performance(PreviewView.ImplementationMode.PERFORMANCE); /** * Inverse currently implementation mode. * */ public val inverse: ImplementationMode get() = when (this) { Compatible -> Performance else -> Compatible } }
4
Kotlin
13
248
c6e30149e92b9df37f7837f5e29aecf9ab7b34c5
646
Camposer
Apache License 2.0
Example/app/src/main/java/com/sum/room/viewmodel/UserViewModel.kt
sumeyraozugur
511,247,099
false
{"Kotlin": 19815}
package com.sum.room.viewmodel import android.app.Application import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.sum.room.UserDatabase import com.sum.room.repository.UserRepository import com.sum.room.model.User import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class UserViewModel(application: Application): AndroidViewModel(application) { val readAllData: LiveData<List<User>> private val repository: UserRepository var tempList = MutableLiveData<List<User>>() init { val userDao = UserDatabase.getDatabase(application).userDao() repository = UserRepository(userDao) readAllData = repository.readAllData } fun addUser(user: User){ viewModelScope.launch( Dispatchers.IO){ repository.addUser(user) } } fun updateUser(user: User){ viewModelScope.launch(Dispatchers.IO){ repository.updateUser(user) } } fun deleteUser(user: User){ viewModelScope.launch(Dispatchers.IO){ repository.deleteUser(user) } } fun deleteAllUsers(){ viewModelScope.launch(Dispatchers.IO){ repository.deleteAllUsers() } } fun searchDatabase(searchQuery:String){ viewModelScope.launch(Dispatchers.IO){ tempList.postValue(repository.searchDatabase(searchQuery)) Log.v("ViewModel",repository.searchDatabase(searchQuery).toString()) } } }
0
Kotlin
0
2
cf7c98b34f2113e6302572796b7aa4e3761f97dd
1,624
RoomSample
Apache License 2.0
src/commonMain/kotlin/com/adyen/model/checkout/EcontextVoucherDetails.kt
tjerkw
733,432,442
false
{"Kotlin": 5043126, "Makefile": 6356}
/** * Adyen Checkout API * * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! * * The version of the OpenAPI document: 71 * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package com.adyen.model.checkout import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* /** * * * @param firstName The shopper's first name. * @param lastName The shopper's last name. * @param shopperEmail The shopper's email. * @param telephoneNumber The shopper's contact number. It must have an international number format, for example **+31 20 779 1846**. Formats like **+31 (0)20 779 1846** or **0031 20 779 1846** are not accepted. * @param type **econtextvoucher** * @param checkoutAttemptId The checkout attempt identifier. */ @Serializable data class EcontextVoucherDetails ( /* The shopper's first name. */ @SerialName(value = "firstName") @Required val firstName: kotlin.String, /* The shopper's last name. */ @SerialName(value = "lastName") @Required val lastName: kotlin.String, /* The shopper's email. */ @SerialName(value = "shopperEmail") @Required val shopperEmail: kotlin.String, /* The shopper's contact number. It must have an international number format, for example **+31 20 779 1846**. Formats like **+31 (0)20 779 1846** or **0031 20 779 1846** are not accepted. */ @SerialName(value = "telephoneNumber") @Required val telephoneNumber: kotlin.String, /* **econtextvoucher** */ @SerialName(value = "type") @Required val type: EcontextVoucherDetails.Type, /* The checkout attempt identifier. */ @SerialName(value = "checkoutAttemptId") val checkoutAttemptId: kotlin.String? = null ) { /** * **econtextvoucher** * * Values: Seveneleven,Stores */ @Serializable enum class Type(val value: kotlin.String) { @SerialName(value = "econtext_seveneleven") Seveneleven("econtext_seveneleven"), @SerialName(value = "econtext_stores") Stores("econtext_stores"); } }
0
Kotlin
0
0
2da5aea5519b2dfa84454fe1665e9699edc87507
4,093
adyen-kotlin-multiplatform-api-library
MIT License
ui/src/main/java/com/rock/ui/CircleImageView.kt
sunjinbo
393,235,502
false
null
// Copyright 2021, Sun Jinbo, All rights reserved. package com.rock.ui import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.util.AttributeSet import com.rock.core.metrology.DisplayUtil class CircleImageView : AbsImageView { /** * 边线宽度. */ var strokeWidth: Float = 0F get() = DisplayUtil.px2dip(context, field).toFloat() set(value) { field = DisplayUtil.dip2px(context, value).toFloat() postInvalidate() } /** * 边线颜色. */ var strokeColor: Int = Color.LTGRAY set(value) { field = value postInvalidate() } constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super( context, attrs, defStyleAttr ) override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) } }
0
Kotlin
0
0
2988a16da7c013b10ff41c4c3ad057bc677f7e31
1,040
rock
MIT License
src/com/price_of_command/platform/Extensions.kt
atlanticaccent
409,181,802
false
{"Kotlin": 164486}
package com.price_of_command.platform import com.fs.starfarer.api.campaign.InteractionDialogAPI import com.fs.starfarer.campaign.fleet.CampaignFleet import com.price_of_command.forPlatform import com.price_of_command.platform.linux.LinuxShipPickerWrapper import com.price_of_command.platform.macos.MacShipPickerWrapper import com.price_of_command.platform.shared.ShipPickerWrapper import com.price_of_command.platform.windows.WindowsShipPickerWrapper fun ShipPickerWrapper.Companion.reassign(target: Any, inner: Any, dialog: InteractionDialogAPI, fleet: CampaignFleet, dismiss: (Any, Any) -> Unit) { forPlatform( { WindowsShipPickerWrapper(inner, dialog, fleet, dismiss) }, { LinuxShipPickerWrapper(inner, dialog, fleet, dismiss) }, { MacShipPickerWrapper(inner, dialog, fleet, dismiss) }, ).reassign(target) }
0
Kotlin
0
1
cfca5d765f40acc569bd05a9ef480a021e6a3c38
845
price-of-command
The Unlicense
data/src/main/java/com/trian/data/repository/UserRepository.kt
Jocerdikiawann
419,014,173
true
{"Kotlin": 564661, "Shell": 2435}
package com.trian.data.repository import android.app.Activity import android.graphics.Bitmap import com.google.firebase.auth.FirebaseUser import com.google.firebase.auth.PhoneAuthCredential import com.google.firebase.auth.PhoneAuthProvider import com.trian.domain.models.Store import com.trian.domain.models.network.CurrentUser import com.trian.domain.models.network.DataOrException import com.trian.domain.models.User import com.trian.domain.models.network.GetStatus import kotlinx.coroutines.flow.Flow /** * Persistence Class * Author PT Cexup Telemedicine * Created by <NAME> * 21/10/2021 */ interface UserRepository { fun firebaseUser():FirebaseUser? fun getCurrentUser(onResult:(hasUser:Boolean,user:User)->Unit) fun createUser(user:User,onComplete: (success: Boolean, url: String) -> Unit) fun setLocalUser(user:User) fun updateUser(user: User,onComplete: (success: Boolean, url: String) -> Unit) fun uploadImageProfile(bitmap: Bitmap,onComplete:(success:Boolean,url:String)->Unit) fun sendOTP(otp:String,activity: Activity,callbacks: PhoneAuthProvider.OnVerificationStateChangedCallbacks) fun signIn(credential: PhoneAuthCredential,finish:(success:Boolean,shouldUpdate:Boolean,user:User,message:String)->Unit) fun signOut() suspend fun syncUser() suspend fun getUserById(id:String): GetStatus<User> suspend fun getUserByUid(id:String): User? }
0
Kotlin
0
0
ffd154a3dfa1fbf28cb91a4264afaf8b5794fde1
1,412
Kopra.id
Apache License 2.0
app/src/main/java/com/example/andriiginting/news/NewsApp.kt
andriiginting
142,031,035
false
null
package com.example.andriiginting.news import android.app.Application import com.example.andriiginting.news.di.Component.ApplicationComponent import com.example.andriiginting.news.di.Component.DaggerApplicationComponent import com.example.andriiginting.news.di.module.ApplicationModule import com.example.andriiginting.news.utils.ConnectivityCheck.Companion.connectivityCheck import com.example.andriiginting.news.utils.ConnectivityListener class NewsApp: Application() { private var component: ApplicationComponent? = null override fun onCreate() { super.onCreate() appInstance = this component = DaggerApplicationComponent .builder() .applicationModule(ApplicationModule(this)) .build() } companion object { @get:Synchronized lateinit var appInstance: NewsApp fun connectivityListener(listener: ConnectivityListener){ connectivityCheck = listener } } }
0
Kotlin
0
0
90e3606b5ee80c39de7207e53d4984170c77206f
999
news-app
Apache License 2.0