path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/angelicao/countrieslearn/ui/MainActivity.kt
angelica-oliv
207,349,558
false
null
package com.angelicao.countrieslearn.ui import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.angelicao.countrieslearn.R class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
0
Kotlin
1
3
d9f4dfcf54168fd2b9b0d994a051fa93dd9822d4
352
countries-learn
Apache License 2.0
source/src/main/java/ru/g000sha256/wallet/feature/cards/adapter/carousel/CardsAdapterCarouselViewHolder.kt
g000sha256
317,877,385
false
null
package ru.g000sha256.wallet.feature.cards.adapter.carousel import android.graphics.Rect import android.view.View import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.RequestManager import ru.g000sha256.wallet.extension.dpF import ru.g000sha256.wallet.feature.cards.adapter.CardsAdapter import ru.g000sha256.wallet.feature.cards.adapter.CardsItem import ru.g000sha256.wallet.feature.cards.adapter.card.CardsAdapterCardListener class CardsAdapterCarouselViewHolder( cardsAdapterCardListener: CardsAdapterCardListener, carouselCardWidth: Int, requestManager: RequestManager, view: View ) : RecyclerView.ViewHolder(view) { private val recyclerView = view as RecyclerView private val cardsAdapter = CardsAdapter(cardsAdapterCardListener, carouselCardWidth, carouselCardWidth, requestManager) private var scroll = 0 init { recyclerView.adapter = cardsAdapter val itemDecoration = object : RecyclerView.ItemDecoration() { override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { val position = parent.getChildAdapterPosition(view) when (position) { 0 -> { view.elevation = 0F outRect.set(scroll, 0, 0, 0) } 1 -> { when { scroll >= carouselCardWidth -> { view.elevation = 0F outRect.set(-carouselCardWidth, 0, 0, 0) } else -> { view.elevation = 2.dpF outRect.set(-scroll, 0, 0, 0) } } } else -> { when { scroll <= carouselCardWidth * (position - 1) -> { view.elevation = 2.dpF outRect.set(0, 0, 0, 0) } scroll <= carouselCardWidth * position -> { view.elevation = 2.dpF outRect.set(carouselCardWidth * (position - 1) - scroll, 0, 0, 0) } else -> { view.elevation = 0F outRect.set(-carouselCardWidth, 0, 0, 0) } } } } } } recyclerView.addItemDecoration(itemDecoration) val onScrollListener = object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { scroll = recyclerView.computeHorizontalScrollOffset() recyclerView.invalidateItemDecorations() } } recyclerView.addOnScrollListener(onScrollListener) } fun bind(fromPayload: Boolean, cardsItem: CardsItem.Carousel) { cardsAdapter.setCardsItems(cardsItem.cards) cardsAdapter.notifyDataSetChanged() if (fromPayload) return recyclerView.scrollToPosition(0) scroll = 0 } }
0
Kotlin
0
0
61d0cc14b1613209b953c546fbd472e82a9d955f
3,381
wallet_demo
MIT License
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/twotone/Rulerandpen.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.twotone import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Round import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import moe.tlaster.icons.vuesax.vuesaxicons.TwotoneGroup public val TwotoneGroup.Rulerandpen: ImageVector get() { if (_rulerandpen != null) { return _rulerandpen!! } _rulerandpen = Builder(name = "Rulerandpen", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(21.4707f, 19.0f) verticalLineTo(5.0f) curveTo(21.4707f, 3.0f, 20.4707f, 2.0f, 18.4707f, 2.0f) horizontalLineTo(14.4707f) curveTo(12.4707f, 2.0f, 11.4707f, 3.0f, 11.4707f, 5.0f) verticalLineTo(19.0f) curveTo(11.4707f, 21.0f, 12.4707f, 22.0f, 14.4707f, 22.0f) horizontalLineTo(18.4707f) curveTo(20.4707f, 22.0f, 21.4707f, 21.0f, 21.4707f, 19.0f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(11.4707f, 6.0f) horizontalLineTo(16.4707f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(11.4707f, 18.0f) horizontalLineTo(15.4707f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(11.4707f, 13.9502f) lineTo(16.4707f, 14.0002f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(11.4707f, 10.0f) horizontalLineTo(14.4707f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(5.4893f, 2.0f) curveTo(3.8593f, 2.0f, 2.5293f, 3.33f, 2.5293f, 4.95f) verticalLineTo(17.91f) curveTo(2.5293f, 18.36f, 2.7193f, 19.04f, 2.9493f, 19.43f) lineTo(3.7693f, 20.79f) curveTo(4.7093f, 22.36f, 6.2593f, 22.36f, 7.1993f, 20.79f) lineTo(8.0193f, 19.43f) curveTo(8.2493f, 19.04f, 8.4393f, 18.36f, 8.4393f, 17.91f) verticalLineTo(4.95f) curveTo(8.4393f, 3.33f, 7.1093f, 2.0f, 5.4893f, 2.0f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(8.4393f, 7.0f) horizontalLineTo(2.5293f) } } .build() return _rulerandpen!! } private var _rulerandpen: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
4,758
VuesaxIcons
MIT License
shared/src/androidMain/kotlin/com/drahovac/weatherstationdisplay/viewmodel/Stable.kt
drahovac
667,016,953
false
null
package com.drahovac.weatherstationdisplay.viewmodel actual typealias Stable = androidx.compose.runtime.Stable
0
Kotlin
0
0
e7709216aa42be27b1f9dedbc7430c84a00a3dce
111
WeatherStationDataDisplay
MIT License
identity-management/idm-core-model/src/main/kotlin/org/orkg/auth/domain/Role.kt
TIBHannover
197,416,205
false
{"Kotlin": 2994730, "Cypher": 216833, "Python": 4881, "Groovy": 1936, "Shell": 1803, "HTML": 240}
package org.orkg.auth.domain data class Role(val name: String)
0
Kotlin
1
5
0186bb4cfe4ef7116ba121327f13d9e4c2e9938a
64
orkg-backend
MIT License
src/main/kotlin/io/github/crackthecodeabhi/kreds/protocol/Command.kt
fossabot
441,535,850
true
{"Kotlin": 189219}
package io.github.crackthecodeabhi.kreds.protocol import io.netty.handler.codec.redis.* import io.github.crackthecodeabhi.kreds.args.* import io.github.crackthecodeabhi.kreds.commands.* import io.github.crackthecodeabhi.kreds.toByteBuf import kotlin.jvm.Throws internal fun Command.toRedisMessageList(): List<FullBulkStringRedisMessage> { return if(subCommand != null){ listOf(FullBulkStringRedisMessage(string.toByteBuf()),*subCommand!!.toRedisMessageList().toTypedArray()) } else listOf(FullBulkStringRedisMessage(string.toByteBuf())) } internal interface ICommandProcessor { fun encode(command: Command, vararg args: Argument): RedisMessage @Throws(KredsRedisDataException::class) fun <T> decode(message: RedisMessage): T } internal interface CommandExecutor { suspend fun <T> execute(command: Command, processor: ICommandProcessor, vararg args: Argument): T suspend fun <T> execute(commandExecution: CommandExecution): T suspend fun executeCommands(commands: List<CommandExecution>): List<RedisMessage> } internal val IntegerCommandProcessor = CommandProcessor(IntegerHandler) internal val BulkStringCommandProcessor = CommandProcessor(BulkStringHandler) internal val SimpleStringCommandProcessor = CommandProcessor(SimpleStringHandler) internal val ArrayCommandProcessor = CommandProcessor(ArrayHandler) internal open class CommandProcessor(private vararg val outputTypeHandlers: MessageHandler<*>): ICommandProcessor { override fun encode(command: Command,vararg args: Argument): RedisMessage { if(args.isEmpty()) return ArrayRedisMessage(command.toRedisMessageList()) val x = command.toRedisMessageList().toMutableList() x.addAll(args.map { FullBulkStringRedisMessage(it.toString().toByteBuf()) }) return ArrayRedisMessage(x as List<RedisMessage>) } @Throws(KredsRedisDataException::class) @Suppress("UNCHECKED_CAST") override fun <T> decode(message:RedisMessage): T { if(message is ErrorRedisMessage) throw KredsRedisDataException(message.content()) val handler = outputTypeHandlers.first { it.canHandle(message) } return handler.doHandle(message) as T } }
0
Kotlin
0
0
1b0c1130ae514f965d84021d95457f1d7dccbc91
2,193
kreds
Apache License 2.0
src/main/kotlin/io/github/crackthecodeabhi/kreds/protocol/Command.kt
fossabot
441,535,850
true
{"Kotlin": 189219}
package io.github.crackthecodeabhi.kreds.protocol import io.netty.handler.codec.redis.* import io.github.crackthecodeabhi.kreds.args.* import io.github.crackthecodeabhi.kreds.commands.* import io.github.crackthecodeabhi.kreds.toByteBuf import kotlin.jvm.Throws internal fun Command.toRedisMessageList(): List<FullBulkStringRedisMessage> { return if(subCommand != null){ listOf(FullBulkStringRedisMessage(string.toByteBuf()),*subCommand!!.toRedisMessageList().toTypedArray()) } else listOf(FullBulkStringRedisMessage(string.toByteBuf())) } internal interface ICommandProcessor { fun encode(command: Command, vararg args: Argument): RedisMessage @Throws(KredsRedisDataException::class) fun <T> decode(message: RedisMessage): T } internal interface CommandExecutor { suspend fun <T> execute(command: Command, processor: ICommandProcessor, vararg args: Argument): T suspend fun <T> execute(commandExecution: CommandExecution): T suspend fun executeCommands(commands: List<CommandExecution>): List<RedisMessage> } internal val IntegerCommandProcessor = CommandProcessor(IntegerHandler) internal val BulkStringCommandProcessor = CommandProcessor(BulkStringHandler) internal val SimpleStringCommandProcessor = CommandProcessor(SimpleStringHandler) internal val ArrayCommandProcessor = CommandProcessor(ArrayHandler) internal open class CommandProcessor(private vararg val outputTypeHandlers: MessageHandler<*>): ICommandProcessor { override fun encode(command: Command,vararg args: Argument): RedisMessage { if(args.isEmpty()) return ArrayRedisMessage(command.toRedisMessageList()) val x = command.toRedisMessageList().toMutableList() x.addAll(args.map { FullBulkStringRedisMessage(it.toString().toByteBuf()) }) return ArrayRedisMessage(x as List<RedisMessage>) } @Throws(KredsRedisDataException::class) @Suppress("UNCHECKED_CAST") override fun <T> decode(message:RedisMessage): T { if(message is ErrorRedisMessage) throw KredsRedisDataException(message.content()) val handler = outputTypeHandlers.first { it.canHandle(message) } return handler.doHandle(message) as T } }
0
Kotlin
0
0
1b0c1130ae514f965d84021d95457f1d7dccbc91
2,193
kreds
Apache License 2.0
app/src/main/java/co/tiagoaguiar/course/instagram/splash/data/SplashDataSource.kt
Felipe-Borba
751,564,839
false
{"Kotlin": 163910}
package co.tiagoaguiar.course.instagram.splash.data interface SplashDataSource { fun session(callback: SplashCallback) }
0
Kotlin
0
0
cba9539fa99b280f33f5bf8a9015decfecd70a4f
125
instagram
MIT License
sources/common/components/DateTimeComponent.kt
kpgalligan
212,849,950
true
{"Kotlin": 94921}
package com.github.fluidsonic.fluid.time interface DateTimeComponent<Component : DateTimeComponent<Component, Measurement>, Measurement : TemporalMeasurement<Measurement>> : Comparable<Component> { fun map(transform: (Long) -> Long): Component operator fun minus(other: Measurement): Component operator fun minus(other: Component): Measurement operator fun plus(other: Measurement): Component fun toInt(): Int fun toLong(): Long companion object interface CompanionInterface<Component : DateTimeComponent<Component, *>> { val max: Component val min: Component fun of(value: Long): Component } }
0
null
0
0
6e1f9cc2fcdb51bce019f3218861e7d9a1010dba
618
fluid-time
Apache License 2.0
src/main/kotlin/no/nav/klage/oppgave/clients/axsys/DefaultAxsysGateway.kt
navikt
429,756,485
false
null
package no.nav.klage.oppgave.clients.axsys import no.nav.klage.oppgave.domain.saksbehandler.Enhet import no.nav.klage.oppgave.gateway.AxsysGateway import org.springframework.stereotype.Service @Service class DefaultAxsysGateway( private val axsysClient: AxsysClient, private val tilgangerMapper: TilgangerMapper ) : AxsysGateway { @Deprecated("Erstattet av enhet i SaksbehandlerPersonligInfo som vi henter fra Azure") override fun getEnheterForSaksbehandler(ident: String): List<Enhet> = tilgangerMapper.mapTilgangerToEnheter(axsysClient.getTilgangerForSaksbehandler(ident)) }
3
Kotlin
0
0
0f9ab17bacec56ed8f15900d8a361a238c98b0c0
603
kabal-innstillinger
MIT License
feature_article_list/src/main/java/com/phicdy/mycuration/articlelist/FavoriteArticlesListActivity.kt
phicdy
24,188,186
false
{"Kotlin": 688608, "HTML": 1307, "Shell": 1127}
package com.phicdy.mycuration.articlelist import android.app.SearchManager import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.SearchView import androidx.appcompat.widget.Toolbar import com.google.android.material.floatingactionbutton.FloatingActionButton import com.phicdy.mycuration.feature.util.changeTheme import com.phicdy.mycuration.feature.util.getThemeColor import com.phicdy.mycuration.tracker.TrackerHelper import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class FavoriteArticlesListActivity : AppCompatActivity(), FavoriteArticlesListFragment.OnArticlesListFragmentListener { companion object { private const val TAG_FRAGMENT = "TAG_FRAGMENT" fun createIntent(context: Context) = Intent(context, FavoriteArticlesListActivity::class.java) } private lateinit var searchView: SearchView private lateinit var fbTitle: String private lateinit var fab: FloatingActionButton override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_favorite_articles_list) if (savedInstanceState == null) { val fragment = FavoriteArticlesListFragment.newInstance() supportFragmentManager.beginTransaction() .add(R.id.container, fragment, TAG_FRAGMENT) .commit() } title = getString(R.string.favorite) fbTitle = getString(R.string.ga_favorite) TrackerHelper.sendUiEvent(fbTitle) initToolbar() fab = findViewById(R.id.fab_article_list) fab.setOnClickListener { val fragment = supportFragmentManager.findFragmentByTag(TAG_FRAGMENT) as? FavoriteArticlesListFragment fragment?.onFabButtonClicked() TrackerHelper.sendButtonEvent(getString(R.string.scroll_article_list)) } } private fun initToolbar() { val toolbar = findViewById<Toolbar>(R.id.toolbar_article_list) setSupportActionBar(toolbar) val actionBar = supportActionBar if (actionBar != null) { // Show back arrow icon actionBar.setDisplayHomeAsUpEnabled(true) actionBar.setDisplayShowHomeEnabled(true) actionBar.title = title } } override fun onCreateOptionsMenu(menu: Menu): Boolean { val inflater = menuInflater inflater.inflate(R.menu.menu_article, menu) // Associate searchable configuration with the SearchView val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager val searchMenuItem = menu.findItem(R.id.search_article) searchView = searchMenuItem.actionView as SearchView searchView.setSearchableInfo( searchManager .getSearchableInfo(componentName) ) searchView.queryHint = getString(R.string.search_article) searchView.setOnQueryTextFocusChangeListener { _, queryTextFocused -> if (!queryTextFocused) { searchMenuItem.collapseActionView() searchView.setQuery("", false) } } searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextChange(newText: String?): Boolean { return true } override fun onQueryTextSubmit(query: String?): Boolean { if (query == null) return false val intent = Intent( this@FavoriteArticlesListActivity, ArticleSearchResultActivity::class.java ) intent.action = Intent.ACTION_SEARCH intent.putExtra(SearchManager.QUERY, query) startActivity(intent) return false } }) val color = getThemeColor(R.attr.colorPrimary) val searchAutoComplete: TextView = searchView.findViewById(androidx.appcompat.R.id.search_src_text) searchAutoComplete.setTextColor(color) searchAutoComplete.setHintTextColor(color) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.all_read -> { TrackerHelper.sendButtonEvent(getString(R.string.read_all_articles)) val fragment = supportFragmentManager.findFragmentByTag(TAG_FRAGMENT) as? FavoriteArticlesListFragment fragment?.handleAllRead() } android.R.id.home -> finish() else -> { } } return super.onOptionsItemSelected(item) } override fun onResume() { super.onResume() changeTheme() } }
46
Kotlin
9
30
c270cb9f819dfcb6a2ac4b9ee5ddc459c698497f
4,990
MyCuration
The Unlicense
crowdproj-ad-back/crowdproj-ad-app-ktor/src/commonMain/kotlin/Application.kt
crowdproj
420,616,237
false
{"Kotlin": 269469, "Rust": 11536, "Go": 1543, "JavaScript": 676, "HTML": 380, "HCL": 360, "Makefile": 332, "CSS": 109}
package com.crowdproj.ad.app import com.crowdproj.ad.app.configs.CwpAdAppSettings import com.crowdproj.ad.app.plugins.configureRouting import com.crowdproj.ad.app.plugins.initAppSettings import io.ktor.server.application.* //fun main(args: Array<String>) = io.ktor.server.cio.EngineMain.main(args) expect fun main(args: Array<String>) @Suppress("unused") fun Application.module(appSettings: CwpAdAppSettings = initAppSettings()) { configureRouting(appSettings) }
1
Kotlin
0
0
33c2e62fb4700deb7339000e0de7c706619c8098
470
crowdproj-ad
Apache License 2.0
shared/src/commonMain/kotlin/korsi/sher/poem/presentation/like/LikeState.kt
hamidrezasahraei
680,321,487
false
null
package korsi.sher.poem.presentation.like import korsi.sher.poem.domain.history.PoemItem import korsi.sher.poem.domain.poem.PoemError import korsi.sher.poem.presentation.util.generateRandomColors data class LikeState( val isLoading: Boolean = false, val likedPoems: List<PoemItem> = emptyList(), val error: PoemError? = null, val colors: Triple<Int, Int, Int> = generateRandomColors() )
0
Kotlin
0
9
9f2b000ea8e14f31fca34522b344dbfafdd69365
404
KorsiSher
MIT License
domain/src/main/java/project/penadidik/geocoding/domain/model/Detail.kt
penadidik
562,671,216
false
null
package project.penadidik.geocoding.domain.model class Detail : Model() { var dt: Int? = null var main: Main? = null var weather: List<Weather>? = arrayListOf() var clouds: Clouds? = null var wind: Wind? = null var pop: Double? = null var visibility: Int? = null var dt_txt: String? = null var lat: Double? = null var lon: Double? = null var isFavorite: Boolean? = false }
0
Kotlin
0
0
48896b285bc1e7fbe73221b5140008a46ae1ee74
417
Geocoding
Apache License 2.0
ui/src/main/java/es/fnmtrcm/ceres/certificadoDigitalFNMT/ui/forms/InsertEmailView.kt
CodeNationDev
757,931,525
false
{"Kotlin": 1417005, "C": 485745, "C++": 480977, "CMake": 283671, "Java": 166491}
package es.fnmtrcm.ceres.certificadoDigitalFNMT.ui.forms import android.content.res.Configuration import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Checkbox import androidx.compose.material3.CheckboxDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.platform.LocalTextToolbar import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import es.fnmtrcm.ceres.certificadoDigitalFNMT.common.BaseLoadingRetryComponent import es.fnmtrcm.ceres.certificadoDigitalFNMT.common.R import es.fnmtrcm.ceres.certificadoDigitalFNMT.common.extensions.noRippleClickable import es.fnmtrcm.ceres.certificadoDigitalFNMT.common.models.FNMTRequestValidationType import es.fnmtrcm.ceres.certificadoDigitalFNMT.common.ui.theme.FnmtTS import es.fnmtrcm.ceres.certificadoDigitalFNMT.common.ui.utils.FNMTDefaultButtonStyle import es.fnmtrcm.ceres.certificadoDigitalFNMT.common.ui.utils.boldSpan import es.fnmtrcm.ceres.certificadoDigitalFNMT.common.ui.view.FNMTDefaultButton import es.fnmtrcm.ceres.certificadoDigitalFNMT.common.ui.view.FNMTDefaultTextField import es.fnmtrcm.ceres.certificadoDigitalFNMT.ui.NavigatorManager import es.fnmtrcm.ceres.certificadoDigitalFNMT.ui.common.FNMTFlowStepsView import es.fnmtrcm.ceres.certificadoDigitalFNMT.ui.forms.components.FormsTopAppBar import es.fnmtrcm.ceres.certificadoDigitalFNMT.ui.forms.utils.NoTextFieldToolbar import es.fnmtrcm.ceres.certificadoDigitalFNMT.ui.forms.viewmodel.FormsViewModel import es.fnmtrcm.ceres.certificadoDigitalFNMT.ui.forms.viewmodel.IFormsViewModel import es.fnmtrcm.ceres.certificadoDigitalFNMT.ui.navigation.FNMTNavRoutes import es.fnmtrcm.ceres.certificadoDigitalFNMT.ui.onboarding.utils.OnboardingType @OptIn(ExperimentalComposeUiApi::class) @Composable fun InsertEmailView( viewModel: IFormsViewModel = hiltViewModel<FormsViewModel>(), onClose: () -> Unit, navigatorManager: NavigatorManager ) { val lastName = navigatorManager.params().lastName val contractDate = navigatorManager.params().contractDate val validationType = FNMTRequestValidationType.getType(navigatorManager.params().validationTypeName) BaseLoadingRetryComponent( loading = viewModel.loadingState, error = viewModel.error ) { Column( modifier = Modifier.fillMaxSize() ) { var email1 by rememberSaveable { mutableStateOf("") } var email2 by rememberSaveable { mutableStateOf("") } var associateEmail by rememberSaveable { mutableStateOf(false) } var requestFocusOnEmail2 by rememberSaveable { mutableStateOf(false) } val email1FocusRequester = remember { FocusRequester() } val email2FocusRequester = remember { FocusRequester() } val focusManager = LocalFocusManager.current val keyboardController = LocalSoftwareKeyboardController.current fun sendRequest() { viewModel.sendRequest( dni = navigatorManager.params().dni, lastName = lastName, email = email1.trim(), associateEmail = associateEmail, validationType = FNMTRequestValidationType.getType(navigatorManager.params().validationTypeName), contractDate = contractDate ) } LaunchedEffect(viewModel.requestSuccess) { if (viewModel.requestSuccess) { viewModel.requestSuccess = false navigatorManager.params().apply { email = email1.trim() this.associateEmail = associateEmail } navigatorManager.goToEmailCheck() } } LaunchedEffect(viewModel.emailValidationRequested) { if (viewModel.emailValidationRequested) { viewModel.emailValidationRequested = false navigatorManager.params().apply { email = email1.trim() this.associateEmail = associateEmail } navigatorManager.goToEmailOTP() } } LaunchedEffect(viewModel.dnieRequestWithEmailChecked) { if (viewModel.dnieRequestWithEmailChecked) { viewModel.dnieRequestWithEmailChecked = false sendRequest() } } // Top action bar FormsTopAppBar( extraView = if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE) { { FNMTFlowStepsView( navigatorManager = navigatorManager, route = FNMTNavRoutes.RequestRoute.InsertEmailForm ) } } else null, onCloseClick = { onClose() }, onBackPressed = { navigatorManager.pop(FNMTNavRoutes.RequestRoute.InsertEmailForm) } ) // Content Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxSize() .padding( dimensionResource(id = R.dimen.fnmt_margin_32), 0.dp, dimensionResource(id = R.dimen.fnmt_margin_32), 0.dp ) .noRippleClickable { keyboardController?.hide() focusManager.clearFocus() } .verticalScroll(rememberScrollState()) ) { if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) { Spacer(modifier = Modifier.height(dimensionResource(R.dimen.fnmt_margin_16))) Row(modifier = Modifier.fillMaxWidth()) { Image( painter = painterResource(R.drawable.ic_fnmt_icon_black), modifier = Modifier.size(dimensionResource(R.dimen.app_header_icon_size)), contentDescription = null ) // TODO Add contentDescription for accessibility Spacer(modifier = Modifier.weight(1f)) } Spacer(modifier = Modifier.height(dimensionResource(R.dimen.fnmt_margin_16))) Row(modifier = Modifier.fillMaxWidth()) { FNMTFlowStepsView( navigatorManager = navigatorManager, route = FNMTNavRoutes.RequestRoute.InsertEmailForm ) Spacer(modifier = Modifier.weight(1f)) } } Spacer(modifier = Modifier.height(dimensionResource(R.dimen.fnmt_margin_16))) Text( text = stringResource(id = R.string.cert_req_insert_email_title), textAlign = TextAlign.Start, style = FnmtTS.h3(LocalContext.current), color = colorResource(id = R.color.fnmt_dark), modifier = Modifier.fillMaxWidth() ) Spacer(modifier = Modifier.height(dimensionResource(R.dimen.fnmt_margin_18))) Text( text = boldSpan( stringResource(id = R.string.cert_req_insert_email_subtitle), stringResource(id = R.string.cert_req_insert_email_subtitle_bold) ), textAlign = TextAlign.Start, style = FnmtTS.body(LocalContext.current), color = colorResource(id = R.color.fnmt_dark), modifier = Modifier.fillMaxWidth() ) Spacer(modifier = Modifier.height(dimensionResource(R.dimen.fnmt_margin_32))) FNMTDefaultTextField( value = email1, onChange = { email1 = it viewModel.viewErrorState = null viewModel.viewErrorState2 = null }, placeholder = R.string.cert_req_insert_email_text_field_email_placeholder, hint = R.string.cert_req_insert_email_text_field_email_title, isError = viewModel.viewErrorState != null, onDoneOrNext = { email2FocusRequester.requestFocus() }, errorText = viewModel.viewErrorState, keyboardType = KeyboardType.Email, textAutoCorrectEnabled = false, imeAction = ImeAction.Next, clearCallback = { email1 = "" viewModel.viewErrorState = null viewModel.viewErrorState2 = null }, modifier = Modifier .focusRequester(email1FocusRequester) ) Spacer(modifier = Modifier.height(dimensionResource(R.dimen.fnmt_margin_32))) CompositionLocalProvider( LocalTextToolbar provides NoTextFieldToolbar ) { FNMTDefaultTextField( value = email2, onChange = { email2 = it viewModel.viewErrorState = null viewModel.viewErrorState2 = null }, placeholder = R.string.cert_req_insert_email_text_field_verified_email_placeholder, hint = R.string.cert_req_insert_email_text_field_verified_email_title, isError = viewModel.viewErrorState2 != null, onDoneOrNext = { keyboardController?.hide() focusManager.clearFocus() }, errorText = viewModel.viewErrorState2, keyboardType = KeyboardType.Email, textAutoCorrectEnabled = false, imeAction = ImeAction.Done, clearCallback = { email2 = "" viewModel.viewErrorState = null viewModel.viewErrorState2 = null }, modifier = Modifier .focusRequester(email2FocusRequester) ) } Spacer(modifier = Modifier.height(dimensionResource(R.dimen.fnmt_margin_16))) if (viewModel.associateEmailRemoteConfig) { Row(verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.Start) { Checkbox( enabled = viewModel.bothEmailsValidated, checked = associateEmail, onCheckedChange = { associateEmail = it }, colors = CheckboxDefaults.colors( checkedColor = colorResource(id = R.color.fnmt_primary), uncheckedColor = colorResource(id = R.color.fnmt_primary) ) ) Column( verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.Start, modifier = Modifier.padding(top = dimensionResource(id = R.dimen.fnmt_margin_12)) ) { Text( text = stringResource(id = R.string.cert_req_insert_email_title_checkbox), style = FnmtTS.body(LocalContext.current), color = colorResource( id = if (viewModel.bothEmailsValidated) R.color.fnmt_dark else R.color.fnmt_disabled_dark ) ) Spacer(modifier = Modifier.height(dimensionResource(id = R.dimen.fnmt_margin_4))) Text( text = stringResource(id = R.string.cert_req_insert_email_description_checkbox), style = FnmtTS.tag(LocalContext.current), color = colorResource(id = R.color.fnmt_gray_dark) ) } } } Spacer(modifier = Modifier.height(dimensionResource(R.dimen.fnmt_margin_32))) Spacer(modifier = Modifier.weight(1f)) FNMTDefaultButton( onClick = { viewModel.validateEmails( email1.trim(), email2.trim(), validationType, OnboardingType.getType(navigatorManager.params().onBoardingTypeName) ) if (viewModel.bothEmailsValidated && validationType != FNMTRequestValidationType.DNIE) { sendRequest() } }, text = stringResource(id = R.string.cert_req_insert_email_continue_button), style = FNMTDefaultButtonStyle.PRIMARY, modifier = Modifier.fillMaxWidth() ) Spacer(modifier = Modifier.height(dimensionResource(id = R.dimen.fnmt_margin_32))) } LaunchedEffect(viewModel.email1Validated) { if (viewModel.email1Validated && requestFocusOnEmail2) { requestFocusOnEmail2 = false email2FocusRequester.requestFocus() } } } } } @Preview @Composable fun PreviewInsertEmailView() { InsertEmailView( navigatorManager = NavigatorManager(), onClose = {}, viewModel = object : IFormsViewModel() { override var buttonTextId: Int = R.string.cert_req_insert_dni_continue_button override var goToLastNameView: LiveData<Boolean> = MutableLiveData(false) override var viewErrorState: Int? = null override var viewErrorState2: Int? = null override var loadingState: Boolean = false override var phoneNumberValidated: Boolean = false override var canValidated: Boolean = true override var pinValidated: Boolean = true override var lastNameValidated: Boolean = true override var email1Validated: Boolean = true override var email2Validated: Boolean = true override var bothEmailsValidated: Boolean = true override var requestSuccess: Boolean = true override var certPass1Validated: Boolean = true override var bothCertPassValidated: Boolean = true override var associateEmailRemoteConfig: Boolean = true override var emailValidationRequested: Boolean = true override var emailOTPValidationSuccess: Boolean = true override var emailOTPCode: String = "123456" override var emailOTPFilled: Boolean = true override var dnieRequestWithEmailChecked: Boolean = false override fun invalidateEmail1() {} override fun invalidateEmail2() {} override fun invalidateEmails() {} override fun invalidateCertPasswords() {} override fun validateEmails( email1: String, email2: String, validationType: FNMTRequestValidationType, onboardingType: OnboardingType ) {} override fun validateCertPasswords(pass1: String, pass2: String) {} override fun validateLastName(lastName: String, focusLost: Boolean) {} override fun validatePhoneNumber(number: String, focusLost: Boolean) {} override fun validateDniNie( dniNie: String, focusLost: Boolean, validationType: FNMTRequestValidationType, nif: String, onboardingType: OnboardingType ) {} override fun validateCan(can: String) {} override fun validatePin(pin: String) {} override fun sendRequest( dni: String, lastName: String, email: String, associateEmail: Boolean, contractDate: String, validationType: FNMTRequestValidationType ) {} override fun clearViewErrorState() {} override fun clearLastNameNavigation() {} override fun setUpdateDetail() {} override fun validateEmailOTP(email: String, validationCode: String) {} } ) }
0
Kotlin
0
0
9c5d7b9355c406992ff9126d4bd01d49d4778048
19,235
FabricK
MIT License
composeApp/src/commonMain/kotlin/ru/rznnike/demokmp/domain/interactor/preferences/SetTestCounterUseCase.kt
RznNike
834,057,164
false
{"Kotlin": 147652}
package ru.rznnike.demokmp.domain.interactor.preferences import ru.rznnike.demokmp.domain.common.DispatcherProvider import ru.rznnike.demokmp.domain.common.interactor.UseCaseWithParams import ru.rznnike.demokmp.domain.gateway.PreferencesGateway class SetTestCounterUseCase( private val preferencesGateway: PreferencesGateway, dispatcherProvider: DispatcherProvider ) : UseCaseWithParams<Int, Unit>(dispatcherProvider) { override suspend fun execute(parameters: Int) = preferencesGateway.setTestCounter(parameters) }
0
Kotlin
0
0
f91233d28ff9167a3867e2800e1935253b76be3a
537
DemoKMP
MIT License
maps-kt-compose/src/commonMain/kotlin/center/sciprog/maps/compose/MapFeaturesState.kt
SciProgCentre
514,287,233
false
null
package center.sciprog.maps.compose import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.remember import androidx.compose.runtime.snapshots.SnapshotStateMap import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PointMode import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp import center.sciprog.maps.coordinates.* public typealias FeatureId = String public object DraggableAttribute : MapFeaturesState.Attribute<Boolean> public class MapFeaturesState internal constructor( private val features: MutableMap<FeatureId, MapFeature>, private val attributes: MutableMap<FeatureId, SnapshotStateMap<Attribute<out Any?>, in Any?>>, ) { public interface Attribute<T> //TODO use context receiver for that public fun FeatureId.draggable(enabled: Boolean = true) { setAttribute(this, DraggableAttribute, enabled) } public fun features(): Map<FeatureId, MapFeature> = features private fun generateID(feature: MapFeature): FeatureId = "@feature[${feature.hashCode().toUInt()}]" public fun addFeature(id: FeatureId?, feature: MapFeature): FeatureId { val safeId = id ?: generateID(feature) features[id ?: generateID(feature)] = feature return safeId } public fun <T> setAttribute(id: FeatureId, key: Attribute<T>, value: T) { attributes.getOrPut(id) { mutableStateMapOf() }[key] = value } @Suppress("UNCHECKED_CAST") public fun <T> getAttribute(id: FeatureId, key: Attribute<T>): T? = attributes[id]?.get(key)?.let { it as T } @Suppress("UNCHECKED_CAST") public fun <T> findAllWithAttribute(key: Attribute<T>, condition: (T) -> Boolean): Set<FeatureId> { return attributes.filterValues { condition(it[key] as T) }.keys } public companion object{ /** * Build, but do not remember map feature state */ public fun build( builder: MapFeaturesState.() -> Unit = {}, ): MapFeaturesState = MapFeaturesState( mutableStateMapOf(), mutableStateMapOf() ).apply(builder) /** * Build and remember map feature state */ @Composable public fun remember( builder: MapFeaturesState.() -> Unit = {}, ): MapFeaturesState = remember(builder) { build(builder) } } } public fun MapFeaturesState.circle( center: GeodeticMapCoordinates, zoomRange: IntRange = defaultZoomRange, size: Float = 5f, color: Color = Color.Red, id: FeatureId? = null, ): FeatureId = addFeature( id, MapCircleFeature(center, zoomRange, size, color) ) public fun MapFeaturesState.circle( centerCoordinates: Pair<Double, Double>, zoomRange: IntRange = defaultZoomRange, size: Float = 5f, color: Color = Color.Red, id: FeatureId? = null, ): FeatureId = addFeature( id, MapCircleFeature(centerCoordinates.toCoordinates(), zoomRange, size, color) ) public fun MapFeaturesState.rectangle( centerCoordinates: Pair<Double, Double>, zoomRange: IntRange = defaultZoomRange, size: DpSize = DpSize(5.dp, 5.dp), color: Color = Color.Red, id: FeatureId? = null, ): FeatureId = addFeature( id, MapRectangleFeature(centerCoordinates.toCoordinates(), zoomRange, size, color) ) public fun MapFeaturesState.draw( position: Pair<Double, Double>, zoomRange: IntRange = defaultZoomRange, id: FeatureId? = null, drawFeature: DrawScope.() -> Unit, ): FeatureId = addFeature(id, MapDrawFeature(position.toCoordinates(), zoomRange, drawFeature)) public fun MapFeaturesState.line( aCoordinates: Gmc, bCoordinates: Gmc, zoomRange: IntRange = defaultZoomRange, color: Color = Color.Red, id: FeatureId? = null, ): FeatureId = addFeature( id, MapLineFeature(aCoordinates, bCoordinates, zoomRange, color) ) public fun MapFeaturesState.line( curve: GmcCurve, zoomRange: IntRange = defaultZoomRange, color: Color = Color.Red, id: FeatureId? = null, ): FeatureId = addFeature( id, MapLineFeature(curve.forward.coordinates, curve.backward.coordinates, zoomRange, color) ) public fun MapFeaturesState.line( aCoordinates: Pair<Double, Double>, bCoordinates: Pair<Double, Double>, zoomRange: IntRange = defaultZoomRange, color: Color = Color.Red, id: FeatureId? = null, ): FeatureId = addFeature( id, MapLineFeature(aCoordinates.toCoordinates(), bCoordinates.toCoordinates(), zoomRange, color) ) public fun MapFeaturesState.arc( oval: GmcRectangle, startAngle: Angle, arcLength: Angle, zoomRange: IntRange = defaultZoomRange, color: Color = Color.Red, id: FeatureId? = null, ): FeatureId = addFeature( id, MapArcFeature(oval, startAngle, arcLength, zoomRange, color) ) public fun MapFeaturesState.arc( center: Pair<Double, Double>, radius: Distance, startAngle: Angle, arcLength: Angle, zoomRange: IntRange = defaultZoomRange, color: Color = Color.Red, id: FeatureId? = null, ): FeatureId = addFeature( id, MapArcFeature( oval = GmcRectangle.square(center.toCoordinates(), radius, radius), startAngle = startAngle, arcLength = arcLength, zoomRange = zoomRange, color = color ) ) public fun MapFeaturesState.points( points: List<Gmc>, zoomRange: IntRange = defaultZoomRange, stroke: Float = 2f, color: Color = Color.Red, pointMode: PointMode = PointMode.Points, id: FeatureId? = null, ): FeatureId = addFeature(id, MapPointsFeature(points, zoomRange, stroke, color, pointMode)) @JvmName("pointsFromPairs") public fun MapFeaturesState.points( points: List<Pair<Double, Double>>, zoomRange: IntRange = defaultZoomRange, stroke: Float = 2f, color: Color = Color.Red, pointMode: PointMode = PointMode.Points, id: FeatureId? = null, ): FeatureId = addFeature(id, MapPointsFeature(points.map { it.toCoordinates() }, zoomRange, stroke, color, pointMode)) public fun MapFeaturesState.image( position: Pair<Double, Double>, image: ImageVector, size: DpSize = DpSize(20.dp, 20.dp), zoomRange: IntRange = defaultZoomRange, id: FeatureId? = null, ): FeatureId = addFeature(id, MapVectorImageFeature(position.toCoordinates(), image, size, zoomRange)) public fun MapFeaturesState.group( zoomRange: IntRange = defaultZoomRange, id: FeatureId? = null, builder: MapFeaturesState.() -> Unit, ): FeatureId { val map = MapFeaturesState( mutableStateMapOf(), mutableStateMapOf() ).apply(builder).features() val feature = MapFeatureGroup(map, zoomRange) return addFeature(id, feature) } public fun MapFeaturesState.text( position: GeodeticMapCoordinates, text: String, zoomRange: IntRange = defaultZoomRange, color: Color = Color.Red, font: MapTextFeatureFont.() -> Unit = { size = 16f }, id: FeatureId? = null, ): FeatureId = addFeature(id, MapTextFeature(position, text, zoomRange, color, font)) public fun MapFeaturesState.text( position: Pair<Double, Double>, text: String, zoomRange: IntRange = defaultZoomRange, color: Color = Color.Red, font: MapTextFeatureFont.() -> Unit = { size = 16f }, id: FeatureId? = null, ): FeatureId = addFeature(id, MapTextFeature(position.toCoordinates(), text, zoomRange, color, font))
6
Kotlin
3
15
e7cb006a3c9ef6ccf587598f5a0e216670346c7a
7,616
maps-kt
Apache License 2.0
src/main/kotlin/krafana/app/GeneralDashboard.kt
asubb
562,912,474
false
null
package krafana.app import krafana.* import krafana.Measure.* fun generalDashboard(dataSource: DataSource) = dashboard { title = "General metrics" editable = true liveNow = true refresh = 10.s time = (now - 15.m)..now with(dataSource, tile()) { timeseries("Last minute load average on the machine and vCPU count") { // measure = none query { expr = metric("plexnode_cpu_vcpus_count") } val load1min = query { expr = metric("plexnode_cpu_load_1min_average") } resampleExpression(load1min, 5.m) { legend("cpu_load_5min_average") } resampleExpression(load1min, 15.m) { legend("cpu_load_15min_average") } } timeseries("System/Process CPU Utilization (as % of total)") { measure = percent val cpuLoad = query { expr = metric("plexnode_cpu_load_pct") } val cpuProcessLoad = query { expr = cpuProcessLoad } resampleExpression(cpuLoad, 5.m) { legend("cpu_load_pct_5min_average") } resampleExpression(cpuProcessLoad, 5.m) { legend("cpu_proces_load_pct_5min_average") } } timeseries("Heap usage in bytes") { measure = bytes query { expr = metric("plexnode_java_heap_total_bytes") } query { expr = metric("plexnode_java_heap_max_bytes") } val heapUsed = query { expr = javaHeapUsedBytes } resampleExpression(heapUsed, 5.m) { legend("java_heap_used_5min_mean", instance) } } timeseries("Percentage of the heap being used (of total and max)") { measure = percent val heapUsed = query { expr = metric("plexnode_java_heap_used_pct") } resampleExpression(heapUsed, 5.m) { legend("java_heap_used_pct_5min_mean", instance) } val heapUsedOfMax = query { expr = metric("plexnode_java_heap_used_of_max_pct") } resampleExpression(heapUsedOfMax, 5.m) { legend("java_heap_used_of_max_pct_5min_mean", instance) } } timeseries("Non-heap usage in bytes") { measure = bytes query { expr = metric("plexnode_java_nonheap_total_bytes") } query { expr = metric("plexnode_java_nonheap_max_bytes") } val nonheapUsed = query { expr = javaNonHeapUsedBytes } resampleExpression(nonheapUsed, 5.m) { legend("java_nonheap_used_5min_mean", instance) } } timeseries("Percentage of the non-heap being used (of total and max)") { measure = percent val nonheapUsed = query { expr = metric("plexnode_java_non_heap_used_pct") } resampleExpression(nonheapUsed, 5.m) { legend("java_nonheap_used_pct_5min_mean", instance) } val nonheapUsedOfMax = query { expr = metric("plexnode_java_nonheap_used_of_max_pct") } resampleExpression(nonheapUsedOfMax, 5.m) { legend("java_heap_used_of_max_pct_5min_mean", instance) } } timeseries("Disk usage in bytes") { measure = bytes query { expr = metric("plexnode_disk_total_bytes") } query { expr = metric("plexnode_disk_usable_bytes") } query { expr = metric("plexnode_disk_used_bytes") } } timeseries("Percentage usable/used on the disk") { measure = percent query { expr = metric("plexnode_disk_usable_pct") } query { expr = metric("plexnode_disk_used_pct") } } timeseries("Physical memory") { measure = bytes query { expr = metric("plexnode_mem_physical_total_bytes") } query { expr = metric("plexnode_mem_physical_used_bytes") } query { expr = metric("plexnode_mem_physical_free_bytes") } } timeseries("Swap memory") { measure = bytes query { expr = metric("plexnode_mem_swap_total_bytes") } query { expr = metric("plexnode_mem_swap_used_bytes") } query { expr = metric("plexnode_mem_swap_free_bytes") } } timeseries("Virtual committed memory") { measure = bytes query { expr = metric("plexnode_mem_virtual_committed_bytes") } } timeseries("Physical/Swap used percentage") { measure = percent query { expr = metric("plexnode_mem_physical_used_pct") } query { expr = metric("plexnode_mem_swap_used_pct") } } timeseries("Physical/Swap free percentage") { measure = percent query { expr = metric("plexnode_mem_physical_free_pct") } query { expr = metric("plexnode_mem_swap_free_pct") } } timeseries("File Descriptors") { measure = none query { expr = metric("plexnode_file_descriptor_used_count") } query { expr = metric("plexnode_file_descriptor_free_count") } query { expr = metric("plexnode_file_descriptor_max") } } timeseries("File Descriptors used percentage") { measure = percent query { expr = metric("plexnode_file_descriptor_used_pct") } query { expr = metric("plexnode_file_descriptor_free_pct") } } timeseries("Threads/Slots") { query { expr = metric("plexnode_thread_jvm_count") } query { expr = metric("plexnode_slots_leased") } query { expr = metric("plexnode_slots_max") } } timeseries("Slot leased percentage") { measure = percent query { expr = metric("plexnode_slots_leased_pct") } } timeseries("Slot leased per path") { query { expr = metric("plexnode_slots_leased_meter_total") } } timeseries("Slot leased per path rate") { measure = Measure.pps query { expr = metric("plexnode_slots_leased_meter_oneminrate") } query { expr = metric("plexnode_slots_leased_meter_meanrate") } } timeseries("Network recv/sent bytes") { measure = bytes query { expr = metric("plexnode_net_received_bytes") } query { expr = metric("plexnode_net_sent_bytes") } } timeseries("Network recv/sent/inError/outError/inDrops packet") { query { expr = metric("plexnode_net_received_packets") } query { expr = metric("plexnode_net_sent_packets") } query { expr = metric("plexnode_net_in_errors") } query { expr = metric("plexnode_net_out_errors") } query { expr = metric("plexnode_net_in_drops") } } timeseries("Network speed") { measure = Measure.binbps query { expr = metric("plexnode_net_speed") } } timeseries("Pipelines") { query { expr = metric("plexnode_pipelines_initiated_meter_total") } query { expr = metric("plexnode_pipelines_finished_meter_total") } query { expr = pipelinesActiveTotal } query { expr = metric("plexnode_pipelines_requested_meter_total") } } timeseries("Scheduled tasks") { config { drawStyle = DrawStyle.Bars fillOpacity = 100.0 } query { expr = scheduledTriggered.ideltaInterval() } query { expr = scheduledRetried.ideltaInterval() } query { expr = scheduledFailed.ideltaInterval() } } timeseries("Scheduled tasks delay") { measure = Measure.ms query { expr = scheduledTriggeredP95 } query { expr = scheduledTriggeredP99 } query { expr = scheduledTriggeredMax } } // timeseries("Tasks loading") { // target { // expr = tasksLoaded.ideltaInterval() // } // } // timeseries("Tasks loading duration") { // measure = ms // target { // expr = tasksLoadedP95 // } // target { // expr = tasksLoadedMax // } // } // timeseries("Task by path loading") { // target { // expr = taskLoaded.ideltaInterval() // } // } // timeseries("Task by path loading duration") { // measure = ms // target { // expr = taskLoadedP95 // } // target { // expr = taskLoadedMax // } // } timeseries("Feedmaster Broker") { query { expr = feedmasterEnqueued } query { expr = feedmasterDequeued } } } }
0
Kotlin
0
1
8f7fc878792b5acbdef4af1a306a7e99e6cd54f4
10,601
krafana
Apache License 2.0
migrated-projects/compose-multiplatform-ios-android-template/shared/src/commonMain/kotlin/App.kt
JetBrains
709,379,874
false
{"Kotlin": 1917051, "Java": 288926, "Shell": 107894, "Batchfile": 66223, "Lex": 16216, "Swift": 14457, "Ruby": 4736, "Dockerfile": 1327}
import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import compose_multiplatform_ios_android_template.shared.generated.resources.Res import compose_multiplatform_ios_android_template.shared.generated.resources.compose_multiplatform import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.painterResource @OptIn(ExperimentalResourceApi::class) @Composable fun App() { MaterialTheme { var greetingText by remember { mutableStateOf("Hello, World!") } var showImage by remember { mutableStateOf(false) } Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { Button(onClick = { greetingText = "Hello, ${getPlatformName()}" showImage = !showImage }) { Text(greetingText) } AnimatedVisibility(showImage) { Image( painterResource(Res.drawable.compose_multiplatform), null ) } } } } expect fun getPlatformName(): String
0
Kotlin
30
988
6a2c7f0b86b36c85e9034f3de9bfe416516b323b
1,491
amper
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/Sauce.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Bold.Sauce: ImageVector get() { if (_sauce != null) { return _sauce!! } _sauce = Builder(name = "Sauce", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(17.0f, 8.05f) verticalLineTo(5.0f) horizontalLineTo(13.833f) lineTo(13.0f, 0.0f) horizontalLineTo(11.0f) lineToRelative(-0.833f, 5.0f) horizontalLineTo(7.0f) verticalLineTo(8.05f) arcTo(3.5f, 3.5f, 0.0f, false, false, 4.0f, 11.5f) verticalLineTo(24.0f) horizontalLineTo(20.0f) verticalLineTo(11.5f) arcTo(3.5f, 3.5f, 0.0f, false, false, 17.0f, 8.05f) close() moveTo(17.0f, 21.0f) horizontalLineTo(7.0f) verticalLineTo(11.5f) arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.5f, -0.5f) horizontalLineToRelative(9.0f) arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.5f, 0.5f) close() moveTo(8.974f, 14.0f) horizontalLineToRelative(6.0f) verticalLineToRelative(4.0f) horizontalLineToRelative(-6.0f) close() } } .build() return _sauce!! } private var _sauce: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,309
icons
MIT License
kaff4-core/src/test/kotlin/net/navatwo/kaff4/Aff4ImageTestModuleBaseLinearExtensions.kt
Nava2
555,850,412
false
null
package net.navatwo.kaff4 import net.navatwo.kaff4.streams.compression.Aff4SnappyPlugin val Aff4ImageTestModule.Companion.BaseLinear: Aff4ImageTestModule get() = object : Aff4ImageTestModule(imageName = "Base-Linear.aff4") { override fun configureOther() { install(Aff4SnappyPlugin) } } val Aff4ImageTestModule.Companion.BaseLinearStriped: Aff4ImageTestModule get() = object : Aff4ImageTestModule(imageName = "base-linear_striped/Base-Linear_2.aff4") { override fun configureOther() { install(Aff4SnappyPlugin) } }
12
Kotlin
0
1
ff828b90e8adc106e8573eb03596b33366edd085
554
kaff4
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/locationsinsideprison/resource/MigrationResource.kt
ministryofjustice
738,978,080
false
null
package uk.gov.justice.digital.hmpps.locationsinsideprison.resource import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.media.Content import io.swagger.v3.oas.annotations.media.Schema import io.swagger.v3.oas.annotations.responses.ApiResponse import io.swagger.v3.oas.annotations.tags.Tag import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.security.access.prepost.PreAuthorize import org.springframework.validation.annotation.Validated import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestController import uk.gov.justice.digital.hmpps.locationsinsideprison.dto.ChangeHistory import uk.gov.justice.digital.hmpps.locationsinsideprison.dto.MigrateHistoryRequest import uk.gov.justice.digital.hmpps.locationsinsideprison.dto.UpsertLocationRequest import uk.gov.justice.digital.hmpps.locationsinsideprison.service.SyncService import java.util.* @RestController @Validated @RequestMapping("/migrate", produces = [MediaType.APPLICATION_JSON_VALUE]) @Tag( name = "Migrate", description = "Migrate NOMIS to Locations Inside Prison Service API endpoints.", ) @PreAuthorize("hasRole('ROLE_MIGRATE_LOCATIONS')") class MigrationResource( private val syncService: SyncService, ) : EventBaseResource() { @PostMapping("/location") @ResponseStatus(HttpStatus.CREATED) @Operation( summary = "Migrate a location", description = "Requires role MIGRATE_LOCATIONS and write scope", responses = [ ApiResponse( responseCode = "201", description = "Migrated location", ), ApiResponse( responseCode = "400", description = "Invalid Request", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "401", description = "Unauthorized to access this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "403", description = "Missing required role. Requires the MIGRATE_LOCATIONS role with write scope.", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "404", description = "Data not found", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ], ) fun migrateLocation( @RequestBody @Validated migrateRequest: UpsertLocationRequest, ) = syncService.migrate(migrateRequest) @PostMapping("/location/{id}/history") @ResponseStatus(HttpStatus.CREATED) @Operation( summary = "Migrate a location history", description = "Requires role MIGRATE_LOCATIONS and write scope", responses = [ ApiResponse( responseCode = "201", description = "Migrated history", ), ApiResponse( responseCode = "400", description = "Invalid Request", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "401", description = "Unauthorized to access this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "403", description = "Missing required role. Requires the MIGRATE_LOCATIONS role with write scope.", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "404", description = "Data not found", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ], ) fun migrateHistory( @Schema(description = "The location Id", example = "de91dfa7-821f-4552-a427-bf2f32eafeb0", required = true) @PathVariable id: UUID, @RequestBody @Validated locationHistory: MigrateHistoryRequest, ): ChangeHistory? = syncService.migrateHistory(id, locationHistory) }
1
null
0
2
370e1e459ed4b56e9ced70ac2067f9bc9164368b
4,587
hmpps-locations-inside-prison-api
MIT License
WorkIt/app/src/main/java/prot3ct/workit/views/task_details/TaskDetailsFragment.kt
prot3ct
510,755,420
false
{"Kotlin": 213557, "C#": 92299, "Java": 2259, "ASP.NET": 107}
package prot3ct.workit.views.task_details import android.content.Context import com.google.android.gms.maps.OnMapReadyCallback import prot3ct.workit.view_models.TaskDetailViewModel import com.google.android.gms.maps.GoogleMap import android.widget.TextView import prot3ct.workit.utils.WorkItProgressDialog import android.view.LayoutInflater import android.view.ViewGroup import android.os.Bundle import prot3ct.workit.R import com.google.android.gms.maps.SupportMapFragment import prot3ct.workit.views.navigation.DrawerUtil import android.content.Intent import android.view.View import android.widget.Button import prot3ct.workit.views.profile.ProfileActivity import android.widget.Toast import androidx.appcompat.widget.Toolbar import androidx.fragment.app.Fragment import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MarkerOptions import com.google.android.gms.maps.CameraUpdateFactory import prot3ct.workit.view_models.IsUserAssignableToTaskViewModel import prot3ct.workit.views.task_details.base.TaskDetailsContract import java.text.DateFormat import java.text.DateFormatSymbols import java.text.ParseException import java.text.SimpleDateFormat import java.util.* import kotlin.properties.Delegates class TaskDetailsFragment : Fragment(), TaskDetailsContract.View, OnMapReadyCallback { private lateinit var presenter: TaskDetailsContract.Presenter private lateinit var taskDetails: TaskDetailViewModel private var flag by Delegates.notNull<Int>() private lateinit var mMap: GoogleMap private lateinit var taskTitle: TextView private lateinit var taskDescription: TextView private lateinit var taskStartDate: TextView private lateinit var reward: TextView private lateinit var city: TextView private lateinit var supervisorName: TextView private lateinit var supervisorRating: TextView private lateinit var toolbar: Toolbar private lateinit var applyForTask: Button private lateinit var dialog: WorkItProgressDialog override fun onAttach(context: Context) { super.onAttach(context) dialog = WorkItProgressDialog(context) } override fun setPresenter(presenter: TaskDetailsContract.Presenter) { this.presenter = presenter } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_task_details, container, false) val mapFragment = childFragmentManager .findFragmentById(R.id.map) as SupportMapFragment? mapFragment!!.getMapAsync(this) applyForTask = view.findViewById(R.id.id_apply_for_task_button) toolbar = view.findViewById(R.id.id_drawer_toolbar) taskTitle = view.findViewById(R.id.id_title_details_edit_text) reward = view.findViewById(R.id.id_reward_details_edit_text) taskDescription = view.findViewById(R.id.id_description_details_edit_text) taskStartDate = view.findViewById(R.id.id_date_details_text_view) city = view.findViewById(R.id.id_city_details_text_view) supervisorName = view.findViewById(R.id.id_supervisor_text_view) supervisorRating = view.findViewById(R.id.id_supervisor_rating_text_view) val drawer = DrawerUtil(this.requireActivity(), toolbar) drawer.getDrawer() return view } override fun updateTask(taskDetails: TaskDetailViewModel) { this.taskDetails = taskDetails taskTitle.text = this.taskDetails.title taskDescription.text = this.taskDetails.description val format: DateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm", Locale.ENGLISH) var date: Date? = null try { date = format.parse(this.taskDetails.startDate) } catch (e: ParseException) { e.printStackTrace() } val currentDate = Calendar.getInstance().time val calendar = Calendar.getInstance() calendar.time = date taskStartDate.text = getOrdinal(calendar[Calendar.DAY_OF_MONTH]) + " " + getMonthForInt(calendar[Calendar.MONTH]) + " at " + String.format( "%02d:%02d", calendar[Calendar.HOUR_OF_DAY], calendar[Calendar.MINUTE] ) + " for " + this.taskDetails!!.length + " hours" reward.text = "BGN " + this.taskDetails!!.reward + "/hr" city.text = this.taskDetails!!.city + ", " + this.taskDetails!!.address // for supervisorName.text = "For " + taskDetails.supervisorName supervisorRating.text = taskDetails.supervisorRating.toString() + "" supervisorName.setOnClickListener { val intent = Intent(context, ProfileActivity::class.java) intent.putExtra("userId", taskDetails.supervisorId) requireContext().startActivity(intent) } presenter.getLatLng(this.taskDetails.city + ", " + this.taskDetails.address) } override fun notifySuccessful(message: String) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show() } override fun notifyError(errorMessage: String) { Toast.makeText(context, errorMessage, Toast.LENGTH_LONG).show() } override fun showDialogforLoading() { dialog.showProgress("Logging in...") } override fun dismissDialog() { dialog.dismissProgress() } private fun getMonthForInt(num: Int): String { var month = "wrong" val dfs = DateFormatSymbols() val months = dfs.months if (num in 0..11) { month = months[num] } return month } private fun getOrdinal(i: Int): String { val sufixes = arrayOf("th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th") return when (i % 100) { 11, 12, 13 -> i.toString() + "th" else -> i.toString() + sufixes[i % 10] } } override fun onMapReady(googleMap: GoogleMap) { mMap = googleMap val taskId = requireActivity().intent.getIntExtra("taskId", 0) presenter.getTaskDetails(taskId) presenter.getCanAssignToTask(taskId) } override fun updateMap(lat: Double, lng: Double) { val location = LatLng(lat, lng) mMap.addMarker(MarkerOptions().position(location)) mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 17.0f)) } override fun updateButton(canAssignToTask: IsUserAssignableToTaskViewModel) { applyForTask.setOnClickListener { when (flag) { 0 -> { presenter.declineTaskRequest(canAssignToTask.pendingRequestId, 2) applyForTask.text = "I'll do it" applyForTask.setTextColor(resources.getColor(R.color.md_black_1000)) applyForTask.setBackgroundColor(resources.getColor(R.color.bg_login)) flag = 2 } 1 -> { presenter.removeAssignedUser(taskDetails.taskId) requireActivity().finish() } else -> { presenter.createTaskRequest(taskDetails.taskId) applyForTask.text = "Cancel pending request" applyForTask.setTextColor(resources.getColor(R.color.md_white_1000)) applyForTask.setBackgroundColor(resources.getColor(R.color.md_red_400)) flag = 0 } } } when (canAssignToTask.isUserAssignableToTaskMessage) { "Cancel pending request" -> { applyForTask.text = canAssignToTask.isUserAssignableToTaskMessage applyForTask.setTextColor(resources.getColor(R.color.md_white_1000)) applyForTask.setBackgroundColor(resources.getColor(R.color.md_red_400)) flag = 0 } "I can't do this task anymore" -> { applyForTask.text = canAssignToTask.isUserAssignableToTaskMessage applyForTask.setTextColor(resources.getColor(R.color.md_white_1000)) applyForTask.setBackgroundColor(resources.getColor(R.color.md_red_900)) flag = 1 } else -> { flag = 2 } } } companion object { fun newInstance(): TaskDetailsFragment { return TaskDetailsFragment() } } }
0
Kotlin
0
0
b4381df44e222232c6a8c08e9453080742d9e3df
8,483
WorkItNow
MIT License
data/src/main/java/ru/hse/toolsdetector/data/models/YoloResultModel.kt
padjal
626,557,752
false
null
package ru.hse.toolsdetector.data.models import android.graphics.Bitmap data class YoloResultModel( val annotatedImage: Bitmap?, val recognizedObjects: Map<String, Int> ) { }
0
Kotlin
0
0
db35b11ccaf1fe47d07be0be2e640af66ec4f302
184
tools-detector
Apache License 2.0
app/src/main/java/com/patel/programmingzone/pythontheory/VideoPy.kt
lalit-patel
456,964,451
false
{"Kotlin": 44875}
package com.patel.programmingzone.pythontheory import android.os.Bundle import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.patel.programmingzone.R import com.patel.programmingzone.adapter.VideoAdapter class VideoPy : AppCompatActivity() { var recyclerView: RecyclerView? = null var customAdapter: VideoAdapter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.videolist) recyclerView = findViewById<View>(R.id.recyclerView) as RecyclerView recyclerView!!.setHasFixedSize(true) val title = arrayOf( "Get Started","Variables and Datatype","List","Set","Data Type","Operators","If Else", "While loop","For loop","Array","Functions","Recursion","Oop","Classes", "Constructor","Inheritance","Exception Handling" ) val htmlfiles = arrayOf( "DWgzHbglNIo","TqPzwenhMj0","Eaz5e6M8tL4","Mf7eFtbVxFM","gCCVsvgR2KU","v5MR5JnKcZI","PqFKRqpHrjw", "HZARImviDxg","0ZvaDa8eT5s","6a39OjkCN5","BVfCWuca9nw","XkL3SUioNvo","gZwPdqC2Os0","8O5kX73OkIY", "ic6wdPxcHc0","Cn7AkDb4pIU","6SPDvPK38tw" ) customAdapter = VideoAdapter(this, title, htmlfiles) recyclerView!!.layoutManager = LinearLayoutManager(this) recyclerView!!.adapter = customAdapter } }
0
Kotlin
0
0
4d249af0d39b55487817068c01dda57415635606
1,545
Programming-Zone
MIT License
backend/data/src/main/kotlin/io/tolgee/dtos/request/export/ExportFormat.kt
tolgee
303,766,501
false
null
package io.tolgee.dtos.request.export enum class ExportFormat(val extension: String, val mediaType: String) { JSON("json", "application/json"), XLIFF("xlf", "application/x-xliff+xml"), }
100
Kotlin
40
666
38c1064783f3ec5d60d0502ec0420698395af539
192
tolgee-platform
Apache License 2.0
app/src/main/java/br/com/alura/boardgamestore/ui/recyclerview/adapter/ShoppingCartAdapter.kt
abarcellosrv
424,033,457
false
{"Kotlin": 18135}
package br.com.alura.boardgamestore.ui.recyclerview.adapter class ShoppingCartAdapter { }
0
Kotlin
0
0
61816fac753e8fa9763a377c612dafc55a9cf67c
90
BoardGameStoreAppProject
MIT License
services/csm.cloud.project.project/src/main/kotlin/com/bosch/pt/iot/smartsite/project/message/shared/repository/impl/MessageRepositoryExtensionImpl.kt
boschglobal
805,348,245
false
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
/* * ************************************************************************ * * Copyright: Robert Bosch Power Tools GmbH, 2018 - 2023 * * ************************************************************************ */ package com.bosch.pt.iot.smartsite.project.message.shared.repository.impl import com.bosch.pt.iot.smartsite.project.message.shared.model.Message import com.bosch.pt.iot.smartsite.project.message.shared.model.Message_ import com.bosch.pt.iot.smartsite.project.message.shared.repository.MessageRepositoryExtension import com.google.common.collect.Lists import jakarta.persistence.EntityManager import jakarta.persistence.PersistenceContext import org.springframework.beans.factory.annotation.Value class MessageRepositoryExtensionImpl : MessageRepositoryExtension { @Value("\${db.in.max-size}") private val partitionSize = 0 @PersistenceContext private val entityManager: EntityManager? = null override fun getIdsByTopicIdsPartitioned(topicIds: List<Long>) = Lists.partition(topicIds, partitionSize) .map { partition: List<Long> -> val cb = entityManager!!.criteriaBuilder val query = cb.createQuery(Long::class.java) val root = query.from(Message::class.java) val joinTopic = root.join(Message_.topic) query.where(cb.`in`(joinTopic.get<Any>("id")).value(partition)) // workaround because JPA works with Java classes and kotlin.Long maps to primitive long // which results in error: Specified result type [long] did not match Query selection // type [java.io.Serializable] @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") query.select(root.get<java.lang.Long>("id").`as`(Long::class.java)) entityManager.createQuery(query).resultList } .flatten() override fun deletePartitioned(ids: List<Long>) { Lists.partition(ids, partitionSize).forEach { partition: List<Long> -> val cb = entityManager!!.criteriaBuilder val delete = cb.createCriteriaDelete(Message::class.java) val root = delete.from(Message::class.java) delete.where(cb.`in`(root.get<Any>("id")).value(partition)) entityManager.createQuery(delete).executeUpdate() } } }
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
2,273
bosch-pt-refinemysite-backend
Apache License 2.0
core/core-lib/src/main/java/qsos/core/lib/utils/image/GlideCore.kt
hslooooooool
205,824,032
false
null
package qsos.core.lib.utils.image import android.content.Context import android.graphics.drawable.PictureDrawable import android.util.Log import com.bumptech.glide.Glide import com.bumptech.glide.GlideBuilder import com.bumptech.glide.Registry import com.bumptech.glide.annotation.GlideModule import com.bumptech.glide.load.Options import com.bumptech.glide.load.ResourceDecoder import com.bumptech.glide.load.engine.Resource import com.bumptech.glide.load.engine.cache.ExternalPreferredCacheDiskCacheFactory import com.bumptech.glide.load.engine.cache.LruResourceCache import com.bumptech.glide.load.resource.SimpleResource import com.bumptech.glide.load.resource.transcode.ResourceTranscoder import com.bumptech.glide.module.AppGlideModule import com.caverock.androidsvg.SVG import com.caverock.androidsvg.SVGParseException import qsos.core.lib.config.CoreConfig import java.io.IOException import java.io.InputStream @GlideModule class GlideCore : AppGlideModule() { override fun registerComponents(context: Context, glide: Glide, registry: Registry) { registry.register(SVG::class.java, PictureDrawable::class.java, SvgToDrawableTranscoder()) .append(InputStream::class.java, SVG::class.java, SvgDecoder()) } override fun applyOptions(context: Context, builder: GlideBuilder) { // 运存缓存限制50M builder.setMemoryCache(LruResourceCache(50L * 1024 * 1024)) // 磁盘缓存限制500M builder.setDiskCache(ExternalPreferredCacheDiskCacheFactory(context, diskCache(context), 500L * 1024 * 1024)) // 日志级别 builder.setLogLevel(Log.ERROR) // DEBUG模式才打印日志 builder.setLogRequestOrigins(CoreConfig.DEBUG) } override fun isManifestParsingEnabled(): Boolean { return false } /**缓存路径,优先SD卡,否则内部存储*/ private fun diskCache(context: Context): String { return (context.externalCacheDir?.path ?: context.cacheDir.path) + "/glide" } } /** * @author : 华清松 * 自定义ResourceTranscoder,将SVG转为Drawable对象 */ class SvgToDrawableTranscoder : ResourceTranscoder<SVG, PictureDrawable> { override fun transcode(toTranscode: Resource<SVG>, options: Options): Resource<PictureDrawable>? { val svg = toTranscode.get() val picture = svg.renderToPicture() val drawable = PictureDrawable(picture) return SimpleResource(drawable) } } class SvgDecoder : ResourceDecoder<InputStream, SVG> { override fun handles(source: InputStream, options: Options): Boolean { return true } @Throws(IOException::class) override fun decode(source: InputStream, width: Int, height: Int, options: Options): Resource<SVG>? { try { val svg = SVG.getFromInputStream(source) return SimpleResource(svg) } catch (ex: SVGParseException) { throw IOException("Cannot load SVG from stream", ex) } } }
0
Kotlin
1
4
0ff2d8ab0ec98a0618759ce2d052729340f67541
2,899
abcl-c
Apache License 2.0
finch-kotlin-core/src/test/kotlin/com/tryfinch/api/models/CompanyBenefitTest.kt
Finch-API
688,609,420
false
{"Kotlin": 2681250, "Shell": 3626, "Dockerfile": 366}
// File generated from our OpenAPI spec by Stainless. package com.tryfinch.api.models import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class CompanyBenefitTest { @Test fun createCompanyBenefit() { val companyBenefit = CompanyBenefit.builder() .benefitId("benefit_id") .description("description") .frequency(BenefitFrequency.ONE_TIME) .type(BenefitType._401K) .build() assertThat(companyBenefit).isNotNull assertThat(companyBenefit.benefitId()).isEqualTo("benefit_id") assertThat(companyBenefit.description()).isEqualTo("description") assertThat(companyBenefit.frequency()).isEqualTo(BenefitFrequency.ONE_TIME) assertThat(companyBenefit.type()).isEqualTo(BenefitType._401K) } }
0
Kotlin
1
0
3350d31c56edc0ca4c851a40a5cf1564547cb156
868
finch-api-kotlin
Apache License 2.0
v1_29/src/main/java/de/loosetie/k8s/dsl/manifests/LoadBalancerStatus.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 LoadBalancerStatus_core_v1: K8sManifest { /** Ingress is a list containing ingress points for the load-balancer. Traffic intended for the service should be sent to these ingress points. */ val ingress: List<LoadBalancerIngress_core_v1>? }
0
Kotlin
0
2
57d56ab780bc3134c43377e647e7f0336a5f17de
464
k8s-dsl
Apache License 2.0
src/main/kotlin/com/github/mikesafonov/jira/telegram/service/telegram/handlers/AddUserTelegramCommandHandler.kt
gagapopa
226,065,130
true
{"Kotlin": 271856, "TSQL": 6615, "Dockerfile": 281}
package com.github.mikesafonov.jira.telegram.service.telegram.handlers import com.github.mikesafonov.jira.telegram.config.BotProperties import com.github.mikesafonov.jira.telegram.dao.State import com.github.mikesafonov.jira.telegram.service.AddChatException import com.github.mikesafonov.jira.telegram.service.ChatService import com.github.mikesafonov.jira.telegram.service.telegram.TelegramClient import com.github.mikesafonov.jira.telegram.service.telegram.TelegramCommand import mu.KotlinLogging import org.springframework.stereotype.Service private val logger = KotlinLogging.logger {} /** * @author <NAME> */ @Service class AddUserTelegramCommandHandler( private val chatService: ChatService, botProperties: BotProperties, telegramClient: TelegramClient ) : AdminCommandTelegramCommandHandler(botProperties, telegramClient) { private val commandPrefix = "/add_user" override fun isHandle(command: TelegramCommand): Boolean { return super.isHandle(command) && command.isInState(State.INIT) && command.isStartsWithText(commandPrefix) } override fun handle(command: TelegramCommand): State { val id = command.chatId val commandArgs = getCommandArgs(command.text!!) if (commandArgs.size < 3) { telegramClient.sendTextMessage(id, "Wrong command syntax\n Should be: $commandPrefix <jiraLogin> <telegramId>") } else { try { val jiraLogin = commandArgs[1] val telegramId = commandArgs[2].toLong() chatService.addNewChat(jiraLogin, telegramId) telegramClient.sendTextMessage(id, "Jira user $jiraLogin with telegram id $telegramId was added successfully") } catch (e: NumberFormatException) { telegramClient.sendTextMessage(id, "Wrong command args: telegramId must be a positive number") } catch (e: AddChatException) { telegramClient.sendTextMessage(id, e.message!!) } catch (e: Exception) { logger.error(e.message, e) telegramClient.sendTextMessage(id, "Unexpected error") } } return State.INIT } /** * Method collects command arguments from full command text [message] * @param message text command * @return list of command arguments */ private fun getCommandArgs(message: String): List<String> { return message.split(" ") } }
0
Kotlin
0
0
4b5b335b98217476b3239100d15533f038536524
2,485
jira-telegram-bot
MIT License
app/src/main/java/com/voltage/flash/ext/MutableLiveData.kt
VoltageOS
676,782,120
false
null
/* * SPDX-FileCopyrightText: 2023 The LineageOS Project * SPDX-License-Identifier: Apache-2.0 */ package com.statix.flash.ext import android.os.Looper import androidx.lifecycle.MutableLiveData import kotlin.reflect.KProperty /** * Set the value immediately if we're in the main thread, else it will post it to be set later. */ fun <T> MutableLiveData<T>.setOrPostValue(value: T) { if (Looper.getMainLooper().isCurrentThread) { this.value = value } else { postValue(value) } } class LiveDataDelegate<T>(private val initializer: () -> MutableLiveData<T>) { private var cached: MutableLiveData<T>? = null val value: MutableLiveData<T> get() = cached ?: run { initializer().also { cached = it } cached!! } operator fun getValue(thisRef: Any?, property: KProperty<*>) = value.value!! operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = this.value.setOrPostValue(value) } inline fun <reified T> propertyDelegate(noinline initializer: () -> MutableLiveData<T>) = LiveDataDelegate(initializer)
0
Kotlin
3
0
5cc3da78929cbee409c31e8d433120593dcc1968
1,116
packages_apps_Flash
Apache License 2.0
app/src/main/java/com/ardentsoft/weather/demo/domain/thread/IBackgroundThreadExecutorImpl.kt
ravi1805
512,244,393
false
{"Kotlin": 56386, "Java": 1905}
package com.ardentsoft.weather.demo.domain.thread import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.ThreadPoolExecutor import java.util.concurrent.TimeUnit import javax.inject.Inject import javax.inject.Singleton @Singleton class IBackgroundThreadExecutorImpl @Inject constructor() : IBackgroundThreadExecutor { private val threadPoolExecutor: ThreadPoolExecutor = ThreadPoolExecutor( 5, 10, 20L, TimeUnit.SECONDS, LinkedBlockingQueue() ) override fun execute(runnable: Runnable) { this.threadPoolExecutor.execute(runnable) } }
0
Kotlin
0
0
e21a53573f6ff17086cc35ae2e6e8daf57c00948
607
WeatherAppDemo
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/Radiation.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Bold.Radiation: ImageVector get() { if (_radiation != null) { return _radiation!! } _radiation = Builder(name = "Radiation", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(23.968f, 9.101f) curveToRelative(-0.468f, -2.877f, -2.163f, -5.629f, -4.652f, -7.551f) curveToRelative(-0.565f, -0.435f, -1.292f, -0.609f, -1.991f, -0.483f) curveToRelative(-0.697f, 0.129f, -1.311f, 0.548f, -1.68f, 1.15f) lineToRelative(-2.042f, 3.317f) curveToRelative(-0.434f, 0.705f, -0.215f, 1.628f, 0.489f, 2.062f) curveToRelative(1.071f, 0.661f, 1.777f, 1.797f, 1.889f, 3.038f) curveToRelative(0.069f, 0.772f, 0.718f, 1.365f, 1.494f, 1.365f) horizontalLineToRelative(4.019f) curveToRelative(0.736f, 0.0f, 1.433f, -0.322f, 1.911f, -0.885f) curveToRelative(0.476f, -0.559f, 0.681f, -1.294f, 0.563f, -2.015f) close() moveTo(18.704f, 9.0f) curveToRelative(-0.345f, -1.147f, -0.983f, -2.194f, -1.847f, -3.03f) lineToRelative(1.047f, -1.701f) curveToRelative(1.497f, 1.291f, 2.556f, 2.97f, 2.984f, 4.731f) horizontalLineToRelative(-2.185f) close() moveTo(16.113f, 14.94f) curveToRelative(-0.205f, -0.342f, -0.537f, -0.588f, -0.923f, -0.684f) curveToRelative(-0.389f, -0.098f, -0.795f, -0.035f, -1.136f, 0.169f) curveToRelative(-1.25f, 0.752f, -2.859f, 0.752f, -4.109f, 0.0f) curveToRelative(-0.341f, -0.204f, -0.749f, -0.267f, -1.136f, -0.169f) curveToRelative(-0.386f, 0.096f, -0.718f, 0.342f, -0.923f, 0.684f) lineToRelative(-2.036f, 3.394f) curveToRelative(-0.363f, 0.605f, -0.454f, 1.341f, -0.249f, 2.017f) curveToRelative(0.206f, 0.677f, 0.689f, 1.238f, 1.328f, 1.54f) curveToRelative(1.604f, 0.758f, 3.31f, 1.142f, 5.07f, 1.142f) reflectiveCurveToRelative(3.468f, -0.384f, 5.069f, -1.142f) curveToRelative(0.64f, -0.302f, 1.124f, -0.862f, 1.329f, -1.539f) curveToRelative(0.206f, -0.676f, 0.115f, -1.411f, -0.248f, -2.017f) lineToRelative(-2.037f, -3.395f) close() moveTo(8.712f, 19.396f) lineToRelative(1.058f, -1.765f) curveToRelative(1.436f, 0.486f, 3.025f, 0.486f, 4.461f, 0.0f) lineToRelative(1.059f, 1.765f) curveToRelative(-2.103f, 0.844f, -4.475f, 0.845f, -6.577f, 0.0f) close() moveTo(8.02f, 10.634f) curveToRelative(0.11f, -1.233f, 0.81f, -2.364f, 1.868f, -3.025f) curveToRelative(0.7f, -0.437f, 0.916f, -1.356f, 0.483f, -2.059f) lineToRelative(-2.051f, -3.332f) curveToRelative(-0.37f, -0.604f, -0.983f, -1.023f, -1.681f, -1.152f) curveToRelative(-0.699f, -0.126f, -1.426f, 0.048f, -1.992f, 0.483f) curveTo(2.144f, 3.483f, 0.502f, 6.165f, 0.025f, 9.1f) curveToRelative(-0.117f, 0.722f, 0.088f, 1.457f, 0.563f, 2.016f) curveToRelative(0.479f, 0.562f, 1.175f, 0.885f, 1.911f, 0.885f) horizontalLineToRelative(4.025f) curveToRelative(0.776f, 0.0f, 1.425f, -0.593f, 1.494f, -1.365f) close() moveTo(3.104f, 8.999f) curveToRelative(0.429f, -1.772f, 1.477f, -3.451f, 2.956f, -4.731f) lineToRelative(1.061f, 1.724f) curveToRelative(-0.852f, 0.832f, -1.482f, 1.87f, -1.824f, 3.008f) horizontalLineToRelative(-2.192f) close() moveTo(12.0f, 8.999f) curveToRelative(1.105f, 0.0f, 2.0f, 0.895f, 2.0f, 2.0f) reflectiveCurveToRelative(-0.895f, 2.0f, -2.0f, 2.0f) reflectiveCurveToRelative(-2.0f, -0.895f, -2.0f, -2.0f) reflectiveCurveToRelative(0.895f, -2.0f, 2.0f, -2.0f) close() } } .build() return _radiation!! } private var _radiation: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
5,217
icons
MIT License
lib/src/main/java/uk/co/glass_software/android/shared_preferences/utils/StoreKey.kt
TrendingTechnology
152,872,541
true
{"Kotlin": 86731, "Java": 33533}
/* * Copyright (C) 2017 Glass Software Ltd * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package uk.co.glass_software.android.shared_preferences.utils import uk.co.glass_software.android.shared_preferences.persistence.preferences.StoreEntry open class StoreKey(parent: Enum<*>, final override val mode: StoreMode, final override val valueClass: Class<*>) : StoreEntry.KeyClassProvider, StoreMode.Provider { override val uniqueKey = parent.javaClass.simpleName + "." + parent.name interface Holder { val key: StoreKey } }
0
Kotlin
0
0
15bd4a39c1ea82ff24a435f2e8a97c054822a33d
1,362
SharedPreferenceStore
Apache License 2.0
src/main/kotlin/nl/knaw/huc/broccoli/service/anno/TextSelector.kt
knaw-huc
508,656,826
false
{"Kotlin": 78117, "Makefile": 1185, "Dockerfile": 465, "HTML": 267, "Shell": 56}
package nl.knaw.huc.broccoli.service.anno data class TextSelector(private val context: Map<String, Any>) { fun start(): Int = context["start"] as Int fun beginCharOffset(): Int? = context["beginCharOffset"] as Int? fun end(): Int = context["end"] as Int fun endCharOffset(): Int? = context["endCharOffset"] as Int? }
4
Kotlin
1
0
295f1bd3abe1d6a4d50050c8284069478430eaba
334
broccoli
MIT License
app/src/main/java/com/example/wisechoice/BlockDetailsActivity.kt
IsratTasnimEsha
727,580,459
false
{"Kotlin": 224238}
package com.example.wisechoice import android.content.Context import android.content.Intent import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.annotation.RequiresApi import androidx.cardview.widget.CardView import androidx.core.content.ContextCompat import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import java.security.KeyFactory import java.security.MessageDigest import java.security.Signature import java.security.spec.X509EncodedKeySpec import java.util.Base64 class BlockDetailsAdapter( private val context: Context, private val senders: List<String>, private val receivers: List<String>, private val amounts: List<String>, private val feeses: List<String>, private val verifies: List<String>, private val ids: List<String>, private val signatures: List<String>, private val transaction_times: List<String>, private val st_id: String, private var databaseReference: DatabaseReference = FirebaseDatabase.getInstance().getReference() ) : RecyclerView.Adapter<BlockDetailsAdapter.MyViewHolder>() { private fun retrieveSenderPublicKey(senderPhone: String, callback: (String?) -> Unit) { val databaseReference = FirebaseDatabase.getInstance().getReference("PublicKeys").child(senderPhone) databaseReference.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val publicKey = snapshot.child("Public_Key").getValue(String::class.java) callback(publicKey) } override fun onCancelled(error: DatabaseError) { callback(null) } }) } @RequiresApi(Build.VERSION_CODES.O) private fun verifySignature(publicKey: String, signature: String, data: String): Boolean { try { Log.d("SignatureVerification", "Public Key: $publicKey") Log.d("SignatureVerification", "Signature: $signature") Log.d("SignatureVerification", "Data: $data") val publicBytes = Base64.getDecoder().decode(publicKey) val keySpec = X509EncodedKeySpec(publicBytes) val keyFactory = KeyFactory.getInstance("RSA") val public_key = keyFactory.generatePublic(keySpec) val signatureBytes = Base64.getDecoder().decode(signature) val signature = Signature.getInstance("SHA256withRSA") signature.initVerify(public_key) signature.update(data.toByteArray()) return signature.verify(signatureBytes) } catch (e: Exception) { e.printStackTrace() return false } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val view: View = LayoutInflater.from(context).inflate(R.layout.temp_block_xml, parent, false) return MyViewHolder(view) } @RequiresApi(Build.VERSION_CODES.O) override fun onBindViewHolder(holder: MyViewHolder, position: Int) { val sharedPreferences = context.getSharedPreferences("MySharedPref", Context.MODE_PRIVATE) val st_phone = sharedPreferences.getString("Account", "") ?: "" if("${senders[position]}" == st_phone || "${receivers[position]}" == st_phone) { holder.sender.text = "${senders[position]}" holder.receiver.text = "${receivers[position]}" } else { holder.sender.text = "${hashText(senders[position])}.." holder.receiver.text = "${hashText(receivers[position])}.." } holder.amount.text = "${amounts[position]}" holder.fees.text = "${feeses[position]}" holder.verify.text = "${verifies[position]}" val idValue = ids[position] val signatureValue = signatures[position] val timeval = transaction_times[position] if(verifies[position] == "Unrecognized") { holder.verify_button.isEnabled = true holder.verify_button.text = "Verify" holder.transaction_card.setBackgroundColor(ContextCompat.getColor(context, R.color.white)) } else if(verifies[position] == "Verified") { holder.verify_button.isEnabled = false holder.transaction_card.setBackgroundColor(ContextCompat.getColor(context, R.color.green)) } else if(verifies[position] == "Not Verified") { holder.verify_button.isEnabled = false holder.transaction_card.setBackgroundColor(ContextCompat.getColor(context, R.color.dark_green )) } holder.verify_button.setOnClickListener { val sharedPreferences = context.getSharedPreferences("MySharedPref", Context.MODE_PRIVATE) val st_phone = sharedPreferences.getString("Account", "") ?: "" if(holder.verify.text == "Unrecognized") { retrieveSenderPublicKey(senders[position]) { publicKey -> if (publicKey != null) { val signatureVerified = verifySignature(publicKey, signatures[position], "${receivers[position]}${amounts[position]}${feeses[position]}$timeval") if (signatureVerified) { Toast.makeText(context, "Signature Verified.\nSignature Algorithm: SHA256withRSA\nKey-Factory Algorithm: RSA", Toast.LENGTH_LONG).show() val newTransactionRef = databaseReference.child("miners").child(st_phone) .child("block_queue").child(st_id).child("transaction_details").child(idValue) newTransactionRef.child("Status").setValue("Verified") holder.verify.text = "Verified" holder.verify_button.isEnabled = true holder.transaction_card.setBackgroundColor(ContextCompat.getColor(context, R.color.green)) } else { val newTransactionRef = databaseReference.child("miners").child(st_phone) .child("block_queue").child(st_id).child("transaction_details").child(idValue) newTransactionRef.child("Status").setValue("Not Verified") holder.verify.text = "Not Verified" holder.verify_button.isEnabled = true holder.transaction_card.setBackgroundColor(ContextCompat.getColor(context, R.color.dark_green)) } } } } } holder.transaction_card.setOnClickListener { val intent = Intent(context, TransactionDetailsActivity::class.java) intent.putExtra("transaction_id", idValue) intent.putExtra("activity", "not_inbox") context.startActivity(intent) } } private fun hashText(text: String): String { val digest = MessageDigest.getInstance("SHA-256") val hashedBytes = digest.digest(text.toByteArray()) return bytesToHex(hashedBytes).substring(0, 3) } private fun bytesToHex(bytes: ByteArray): String { val hexChars = CharArray(bytes.size * 2) for (i in bytes.indices) { val v = bytes[i].toInt() and 0xFF hexChars[i * 2] = "0123456789ABCDEF"[v ushr 4] hexChars[i * 2 + 1] = "0123456789ABCDEF"[v and 0x0F] } return String(hexChars) } override fun getItemCount(): Int { return senders.size } class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var sender: TextView = itemView.findViewById(R.id.sender) var receiver: TextView = itemView.findViewById(R.id.receiver) var amount: TextView = itemView.findViewById(R.id.amount) var fees: TextView = itemView.findViewById(R.id.fees) var verify: TextView = itemView.findViewById(R.id.verify) var verify_button: Button = itemView.findViewById(R.id.verify_button) var transaction_card = itemView.findViewById<CardView>(R.id.transaction_card) } } class BlockDetailsActivity : AppCompatActivity() { private lateinit var st_id: String private lateinit var blockIDTextView: TextView private lateinit var blockHashTextView: TextView private lateinit var previousHashTextView: TextView private lateinit var nonceTextView: TextView private lateinit var minerTextView: TextView private lateinit var noOfTransactionsTextView: TextView private lateinit var totalSentTextView: TextView private lateinit var sizeTextView: TextView private lateinit var totalFeesTextView: TextView private lateinit var minedTextView: TextView private lateinit var acceptButton: Button private lateinit var databaseReference: DatabaseReference private lateinit var recyclerView: RecyclerView private lateinit var adapterClass: BlockDetailsAdapter private val senders = mutableListOf<String>() private val receivers = mutableListOf<String>() private val amounts = mutableListOf<String>() private val feeses = mutableListOf<String>() private val verifies = mutableListOf<String>() private val ids = mutableListOf<String>() private val signatures = mutableListOf<String>() private val transaction_times = mutableListOf<String>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_block_details) blockIDTextView = findViewById(R.id.block_id) blockHashTextView = findViewById(R.id.block_hash) previousHashTextView = findViewById(R.id.previous_hash) nonceTextView = findViewById(R.id.nonce) minerTextView = findViewById(R.id.miner) noOfTransactionsTextView = findViewById(R.id.no_of_transactions) totalSentTextView = findViewById(R.id.total_sent) sizeTextView = findViewById(R.id.size) totalFeesTextView = findViewById(R.id.total_fees) minedTextView = findViewById(R.id.mined) acceptButton = findViewById(R.id.accept_button) st_id = intent.getStringExtra("block_id") ?: "" val sharedPreferences = getSharedPreferences("MySharedPref", Context.MODE_PRIVATE) val st_phone = sharedPreferences.getString("Account", "") ?: "" fetchTransactionDetails(st_phone) databaseReference = FirebaseDatabase.getInstance().getReference("miners").child(st_phone) .child("block_queue").child(st_id).child("transaction_details") recyclerView = findViewById(R.id.recycler) recyclerView.setHasFixedSize(true) recyclerView.layoutManager = LinearLayoutManager(this) adapterClass = BlockDetailsAdapter( this, senders, receivers, amounts, feeses, verifies, ids, signatures, transaction_times, st_id ) recyclerView.adapter = adapterClass databaseReference.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { senders.clear() receivers.clear() amounts.clear() feeses.clear() verifies.clear() ids.clear() signatures.clear() transaction_times.clear() for (dataSnapshot in snapshot.children) { val sender = dataSnapshot.child("Sender").value.toString() val receiver = dataSnapshot.child("Receiver").value.toString() val amount = dataSnapshot.child("Amount").value.toString() val fees = dataSnapshot.child("Fees").value.toString() val verify = dataSnapshot.child("Status").value.toString() val transaction_time = dataSnapshot.child("Transaction_Time").value.toString() val id = dataSnapshot.child("Transaction_ID").value.toString() val signature = dataSnapshot.child("Signature").value.toString() senders.add(sender) receivers.add(receiver) amounts.add(amount) feeses.add(fees) verifies.add(verify) ids.add(id) signatures.add(signature) transaction_times.add(transaction_time) } adapterClass.notifyDataSetChanged() } override fun onCancelled(error: DatabaseError) {} }) } private fun fetchTransactionDetails(st_phone: String) { val sharedPreferences = this.getSharedPreferences("MySharedPref", Context.MODE_PRIVATE) val st_phone = sharedPreferences.getString("Account", "") ?: "" databaseReference = FirebaseDatabase.getInstance().getReference("miners").child(st_phone) .child("block_queue").child(st_id) databaseReference.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { if (snapshot.exists()) { val blockID = st_id val blockHash = snapshot.child("Block_Hash").value.toString() val previousHash = snapshot.child("Previous_Hash").value.toString() val nonce = snapshot.child("Nonce").value.toString() val miner = snapshot.child("Miner").value.toString() val noOfTransactions = snapshot.child("No_Of_Transactions").value.toString() val totalSent = snapshot.child("Total_Amount").value.toString() val size = snapshot.child("Size").value.toString() val totalFees = snapshot.child("Total_Fees").value.toString() val minedTime = snapshot.child("Mined_Time").value.toString() blockIDTextView.text = blockID blockHashTextView.text = blockHash previousHashTextView.text = previousHash nonceTextView.text = nonce if(miner == st_phone) { minerTextView.text = miner } else { minerTextView.text = hashText(miner) } noOfTransactionsTextView.text = noOfTransactions totalSentTextView.text = totalSent sizeTextView.text = size totalFeesTextView.text = totalFees minedTextView.text = minedTime acceptButton.setOnClickListener { acceptBlock() } } } override fun onCancelled(error: DatabaseError) { } }) } private fun hashText(text: String): String { val digest = MessageDigest.getInstance("SHA-256") val hashedBytes = digest.digest(text.toByteArray()) return bytesToHex(hashedBytes) } private fun bytesToHex(bytes: ByteArray): String { val hexChars = CharArray(bytes.size * 2) for (i in bytes.indices) { val v = bytes[i].toInt() and 0xFF hexChars[i * 2] = "0123456789ABCDEF"[v ushr 4] hexChars[i * 2 + 1] = "0123456789ABCDEF"[v and 0x0F] } return String(hexChars) } private fun acceptBlock() { val sharedPreferences = this.getSharedPreferences("MySharedPref", Context.MODE_PRIVATE) val st_phone = sharedPreferences.getString("Account", "") ?: "" val blockchainReference = FirebaseDatabase.getInstance().getReference("miners") .child(st_phone).child("blockchain").child(st_id) FirebaseDatabase.getInstance().getReference("miners") .child(st_phone).child("notifications").child(st_id).removeValue() FirebaseDatabase.getInstance().getReference("miners").child(st_phone) .child("block_queue").child(st_id) .addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { if (snapshot.exists()) { val transactionDetailsSnapshot = snapshot.child("transaction_details") val allVerified = transactionDetailsSnapshot.children.all { transactionSnapshot -> transactionSnapshot.child("Status") .getValue(String::class.java) == "Verified" } val anyNotVerified = transactionDetailsSnapshot.children.any { transactionSnapshot -> transactionSnapshot.child("Status") .getValue(String::class.java) == "Not Verified" } if (anyNotVerified) { Toast.makeText( this@BlockDetailsActivity, "Corrupted Block Can't Be Added To Blockchain." + "Please Try Another Block From Block Queue", Toast.LENGTH_SHORT ).show() } else if (allVerified) { FirebaseDatabase.getInstance().getReference("miners") .child(st_phone) .child("blockchain").child(st_id).removeValue() blockchainReference.setValue(snapshot.value) FirebaseDatabase.getInstance().getReference("miners") .child(st_phone) .child("block_queue").removeValue() Toast.makeText( this@BlockDetailsActivity, "This Block Has Been Added To Your Blockchain Successfully. " + "Mine The Next Block Of It To Add It To The Main Blockchain.", Toast.LENGTH_SHORT ).show() } else { Toast.makeText( this@BlockDetailsActivity, "Please Make Sure That All Transactions Have Been Verified.", Toast.LENGTH_SHORT ).show() } } } override fun onCancelled(error: DatabaseError) { } }) } }
0
Kotlin
0
0
4d5ec290b2767f96ffb2ff90c3a6b866f88c0c8b
19,562
Blockchain-Based-Transaction-App
MIT License
amazon-chime-sdk/src/test/java/com/amazonaws/services/chime/sdk/meetings/device/MediaDeviceTest.kt
ribafish
288,103,745
false
null
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package com.amazonaws.services.chime.sdk.meetings.device import android.media.AudioDeviceInfo import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test class MediaDeviceTest { @Test fun `MediaDevice should be able to sort by order`() { val speaker = MediaDevice( "speaker", MediaDeviceType.AUDIO_BUILTIN_SPEAKER ) val receiver = MediaDevice( "handset", MediaDeviceType.AUDIO_HANDSET ) val wiredHeadset = MediaDevice( "wired headset", MediaDeviceType.AUDIO_WIRED_HEADSET ) val bluetoothAudio = MediaDevice( "bluetooth", MediaDeviceType.AUDIO_BLUETOOTH ) val sortedDevices = listOf(speaker, receiver, wiredHeadset, bluetoothAudio).sortedBy { it.order } assertTrue( sortedDevices[0] == bluetoothAudio && sortedDevices[1] == wiredHeadset && sortedDevices[2] == speaker && sortedDevices[3] == receiver ) } @Test fun `MediaDeviceType fromAudioDeviceInfo should return known type when defined value`() { val type = MediaDeviceType.fromAudioDeviceInfo(AudioDeviceInfo.TYPE_BUILTIN_SPEAKER) assertEquals(MediaDeviceType.AUDIO_BUILTIN_SPEAKER, type) } @Test fun `MediaDeviceType fromAudioDeviceInfo should return OTHER type when undefined value`() { val type = MediaDeviceType.fromAudioDeviceInfo(-99) assertEquals(MediaDeviceType.OTHER, type) } }
1
null
1
1
58f709504b525861a9d27145b6aa0598d3af4610
1,733
amazon-chime-sdk-android
Apache License 2.0
src/main/kotlin/io/github/cafeteriaguild/coffeecomputers/block/ComputerBlockEntity.kt
CafeteriaGuild
279,180,738
false
{"Gradle": 2, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "INI": 1, "Java": 1, "JSON": 8, "Kotlin": 10}
package io.github.cafeteriaguild.coffeecomputers.block import io.github.cafeteriaguild.coffeecomputers.CoffeeComputers import net.minecraft.block.entity.BlockEntity class ComputerBlockEntity : BlockEntity(CoffeeComputers.computerBlockEntity)
0
Kotlin
0
3
9f9575de518619edf62f97e60d32b7df84d07f02
243
CoffeeComputers
Apache License 2.0
compiler/fir/checkers/src/org/jetbrains/kotlin/fir/analysis/checkers/expression/FirNamedVarargChecker.kt
SunitRoy2703
415,845,689
false
null
/* * Copyright 2010-2021 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. */ /* * Copyright 2010-2021 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.fir.analysis.checkers.expression import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext import org.jetbrains.kotlin.fir.analysis.diagnostics.DiagnosticReporter import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors import org.jetbrains.kotlin.fir.analysis.diagnostics.reportOn import org.jetbrains.kotlin.fir.expressions.* import org.jetbrains.kotlin.fir.languageVersionSettings import org.jetbrains.kotlin.fir.references.FirErrorNamedReference import org.jetbrains.kotlin.fir.types.FirErrorTypeRef import org.jetbrains.kotlin.fir.types.isArrayType object FirNamedVarargChecker : FirCallChecker() { override fun check(expression: FirCall, context: CheckerContext, reporter: DiagnosticReporter) { if (expression !is FirFunctionCall && expression !is FirAnnotation && expression !is FirDelegatedConstructorCall && expression !is FirArrayOfCall) return val isAnnotation = expression is FirAnnotation val singleElementToVarargErrorFactory = if (isAnnotation) FirErrors.ASSIGNING_SINGLE_ELEMENT_TO_VARARG_IN_NAMED_FORM_ANNOTATION else FirErrors.ASSIGNING_SINGLE_ELEMENT_TO_VARARG_IN_NAMED_FORM_FUNCTION val redundantSpreadWarningFactory = if (isAnnotation) FirErrors.REDUNDANT_SPREAD_OPERATOR_IN_NAMED_FORM_IN_ANNOTATION else FirErrors.REDUNDANT_SPREAD_OPERATOR_IN_NAMED_FORM_IN_FUNCTION val allowAssignArray = context.session.languageVersionSettings.supportsFeature( if (isAnnotation) LanguageFeature.AssigningArraysToVarargsInNamedFormInAnnotations else LanguageFeature.AllowAssigningArrayElementsToVarargsInNamedFormForFunctions ) fun checkArgument(argument: FirExpression, isVararg: Boolean) { if (argument !is FirNamedArgumentExpression) return if (argument.isSpread) { if (isVararg && (expression as? FirResolvable)?.calleeReference !is FirErrorNamedReference) { reporter.reportOn(argument.expression.source, redundantSpreadWarningFactory, context) } return } val typeRef = argument.expression.typeRef if (typeRef is FirErrorTypeRef) return if (argument.expression is FirArrayOfCall) return if (allowAssignArray && typeRef.isArrayType) return reporter.reportOn(argument.expression.source, singleElementToVarargErrorFactory, context) } if (expression is FirArrayOfCall) { // FirArrayOfCall has the `vararg` argument expression pre-flattened and doesn't have an argument mapping. expression.arguments.forEach { checkArgument(it, it is FirNamedArgumentExpression) } } else { val argumentMap = expression.argumentMapping ?: return for ((argument, parameter) in argumentMap) { if (!parameter.isVararg) continue if (argument is FirVarargArgumentsExpression) { argument.arguments.forEach { checkArgument(it, true) } } else { checkArgument(argument, false) } } } } }
0
null
1
1
f760cd6736c7a6405945bc6151637827b597f9f1
3,724
kotlin
Apache License 2.0
mvvm-hilt/src/main/java/com/example/mvvm_hilt/net/PokeDexApi.kt
silladus
145,500,576
false
{"Java": 150183, "Kotlin": 62878}
package com.example.mvvm_hilt.net import com.example.mvvm_hilt.entity.PokemonInfo import com.example.mvvm_hilt.entity.PokemonResponse import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query interface PokeDexApi { @GET("pokemon") suspend fun fetchPokemonList( @Query("limit") limit: Int = 20, @Query("offset") offset: Int = 0 ): PokemonResponse @GET("pokemon/{name}") suspend fun fetchPokemonInfo(@Path("name") name: String): PokemonInfo }
0
Java
0
1
bf6639de672f651ebe5e6cc6cbe27a9f4f523faf
512
basiclib
Apache License 2.0
src/compiler/evaluator/builtins/types/PyFloat.kt
Rami-Sabbagh
597,864,940
false
{"Markdown": 3, "XML": 11, "Ignore List": 2, "Python": 2, "Java": 10, "Kotlin": 41, "Lex": 1, "Makefile": 1, "Yacc": 1}
package compiler.evaluator.builtins.types import compiler.evaluator.builtins.constants.PyNone import compiler.evaluator.builtins.constants.PyNotImplemented import compiler.evaluator.core.PyObject import kotlin.math.pow class PyFloat private constructor( val value: Double ) : PyObject { override fun __repr__(): PyString = PyString("$value") /* ========== Arithmetic Operators ========== */ override fun __add__(other: PyObject): PyObject { if (other !is PyFloat) return PyNotImplemented return of(this.value + other.value) } override fun __sub__(other: PyObject): PyObject { if (other !is PyFloat) return PyNotImplemented return of(this.value - other.value) } override fun __mul__(other: PyObject): PyObject { if (other !is PyFloat) return PyNotImplemented return of(this.value * other.value) } override fun __truediv__(other: PyObject): PyObject { if (other !is PyFloat) return PyNotImplemented return of(this.value / other.value) } override fun __mod__(other: PyObject): PyObject { if (other !is PyFloat) return PyNotImplemented return of(this.value % other.value) } override fun __pow__(exp: PyObject, mod: PyObject): PyObject { if (exp !is PyFloat) return PyNotImplemented if (mod !== PyNone && mod !is PyFloat) return PyNotImplemented var result = this.value.pow(exp.value) if (mod is PyFloat) result %= mod.value return of(result) } /* ========== Rich Comparison Operators ========== */ override fun __eq__(other: PyObject): PyObject { if (other !is PyFloat) return PyNotImplemented return PyBool.of(value == other.value) } override fun __ne__(other: PyObject): PyObject { if (other !is PyFloat) return PyNotImplemented return PyBool.of(value != other.value) } override fun __lt__(other: PyObject): PyObject { if (other !is PyFloat) return PyNotImplemented return PyBool.of(value < other.value) } override fun __gt__(other: PyObject): PyObject { if (other !is PyFloat) return PyNotImplemented return PyBool.of(value > other.value) } override fun __le__(other: PyObject): PyObject { if (other !is PyFloat) return PyNotImplemented return PyBool.of(value <= other.value) } override fun __ge__(other: PyObject): PyObject { if (other !is PyFloat) return PyNotImplemented return PyBool.of(value >= other.value) } companion object { fun of(value: Double): PyFloat { // TODO: Cache the PyFloat instances return PyFloat(value) } } }
1
null
1
1
17ad1bebcff6e84d77dfeab198be80fc4963219a
2,726
kotlin-python
MIT License
app/src/main/java/com/ifttt/groceryexpress/MainActivity.kt
ray1345
248,501,561
false
null
package com.ifttt.groceryexpress import android.content.Intent import android.os.Bundle import android.text.TextUtils import android.view.LayoutInflater import android.view.Menu import android.view.MenuItem import android.view.Window import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import com.google.android.material.textfield.TextInputLayout import com.ifttt.connect.ConnectionApiClient import com.ifttt.connect.ui.ConnectButton import com.ifttt.connect.ui.ConnectResult import com.ifttt.connect.ui.CredentialsProvider import com.ifttt.groceryexpress.ApiHelper.REDIRECT_URI class MainActivity : AppCompatActivity() { private lateinit var connectButton: ConnectButton private lateinit var toolbar: Toolbar private lateinit var emailPreferencesHelper: EmailPreferencesHelper private val credentialsProvider = object : CredentialsProvider { override fun getUserToken() = ApiHelper.getUserToken(emailPreferencesHelper.getEmail()) override fun getOAuthCode() = emailPreferencesHelper.getEmail() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) emailPreferencesHelper = EmailPreferencesHelper(this) toolbar = findViewById(R.id.toolbar) setSupportActionBar(toolbar) title = null connectButton = findViewById(R.id.connect_button) val hasEmailSet = !TextUtils.isEmpty(emailPreferencesHelper.getEmail()) val suggestedEmail = if (!hasEmailSet) { EMAIL } else { emailPreferencesHelper.getEmail()!! } val configuration = ConnectButton.Configuration.Builder.withConnectionId( CONNECTION_ID, suggestedEmail, credentialsProvider , REDIRECT_URI ).setOnFetchCompleteListener { connection -> findViewById<TextView>(R.id.connection_title).text = connection.name }.build() connectButton.setup(configuration) if (!hasEmailSet) { promptLogin() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.set_email) { promptLogin() return true } return super.onOptionsItemSelected(item) } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) connectButton.setConnectResult(ConnectResult.fromIntent(intent)) } // For development and testing purpose: this dialog simulates a login process, where the user enters their // email, and the app tries to fetch the IFTTT user token for the user. In the case where the user token // is empty, we treat it as the user have never connected the service to IFTTT before. private fun promptLogin() { val emailView = LayoutInflater.from(this).inflate( R.layout.view_email, findViewById(Window.ID_ANDROID_CONTENT), false ) as TextInputLayout emailView.editText!!.setText(emailPreferencesHelper.getEmail()) AlertDialog.Builder(this) .setView(emailView) .setTitle(R.string.email_title) .setPositiveButton(R.string.login) { _, _ -> val newEmail = emailView.editText!!.text.toString() emailPreferencesHelper.setEmail(newEmail) val configuration = ConnectButton.Configuration.Builder.withConnectionId( CONNECTION_ID, newEmail, credentialsProvider , REDIRECT_URI ).setOnFetchCompleteListener { connection -> findViewById<TextView>(R.id.connection_title).text = connection.name }.build() connectButton.setup(configuration) }.setNegativeButton(R.string.logout) { _, _ -> emailPreferencesHelper.clear() val configuration = ConnectButton.Configuration.Builder.withConnectionId( CONNECTION_ID, EMAIL, credentialsProvider , REDIRECT_URI ).setOnFetchCompleteListener { connection -> findViewById<TextView>(R.id.connection_title).text = connection.name } .setConnectionApiClient(ConnectionApiClient.Builder(this).build()) // Provide a new ConnectionApiClient to reset the authorization header. .build() connectButton.setup(configuration) } .show() } private companion object { const val CONNECTION_ID = "fWj4fxYg" const val EMAIL = "<EMAIL>" } }
1
null
1
1
4c3c4abe9516a65cc4e2d268249dbe0a9c02c5a1
5,049
ConnectSDK-Android
MIT License
app/src/main/java/infosecadventures/allsafe/MainActivity.kt
t0thkr1s
312,809,182
false
null
package infosecadventures.allsafe import android.os.Bundle import android.view.WindowManager import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.drawerlayout.widget.DrawerLayout import androidx.navigation.Navigation import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.NavigationUI import com.google.android.material.navigation.NavigationView import infosecadventures.allsafe.utils.SnackUtil class MainActivity : AppCompatActivity() { private var mAppBarConfiguration: AppBarConfiguration? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE) setContentView(R.layout.activity_main) val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) val drawer = findViewById<DrawerLayout>(R.id.drawer_layout) val navigationView = findViewById<NavigationView>(R.id.nav_view) mAppBarConfiguration = AppBarConfiguration.Builder( R.id.nav_main, R.id.nav_insecure_logging, R.id.nav_hardcoded_credentials, R.id.nav_firebase_database, R.id.nav_insecure_shared_preferences, R.id.nav_sql_injection, R.id.nav_deep_link_exploitation, R.id.nav_insecure_broadcast_receiver, R.id.nav_weak_cryptography, R.id.nav_insecure_service, R.id.nav_object_serialization, R.id.nav_insecure_providers, R.id.nav_certificate_pinning, R.id.nav_pin_bypass, R.id.nav_root_detection, R.id.nav_secure_flag_bypass, R.id.nav_vulnerable_web_view, R.id.nav_arbitrary_code_execution, R.id.nav_smali_patch, R.id.nav_native_library, R.id.nav_about) .setOpenableLayout(drawer) .build() val navController = Navigation.findNavController(this, R.id.nav_host_fragment) NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration!!) NavigationUI.setupWithNavController(navigationView, navController) } override fun onSupportNavigateUp(): Boolean { val navController = Navigation.findNavController(this, R.id.nav_host_fragment) return (NavigationUI.navigateUp(navController, mAppBarConfiguration!!) || super.onSupportNavigateUp()) } override fun onBackPressed() { when { mAppBarConfiguration?.openableLayout?.isOpen!! -> mAppBarConfiguration!!.openableLayout?.close() supportFragmentManager.backStackEntryCount > 1 -> supportFragmentManager.popBackStack() else -> SnackUtil.confirmExit(this) } } }
2
null
66
95
e7314018383916bc437b7399e346dc10c3c77608
2,999
allsafe
Apache License 2.0
doc-examples/example-kotlin-ksp/src/main/kotlin/example/Product.kt
micronaut-projects
417,139,497
false
{"Java": 1329795, "Groovy": 735076, "Kotlin": 22455}
package example class Product(val name: String, val quantity: Int)
50
Java
18
26
e239903659ba09a1c3d9453a446ae6147dd5fffe
67
micronaut-serialization
Apache License 2.0
af-android-sdk/src/main/java/com/faramarzaf/sdk/af_android_sdk/core/interfaces/GenericGuardCallBack.kt
faramarzaf
277,380,328
false
{"Gradle": 4, "Markdown": 11, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Proguard": 2, "Kotlin": 52, "XML": 27, "INI": 1, "Java": 3}
package com.faramarzaf.sdk.af_android_sdk.core.interfaces interface GenericGuardCallBack<in T> { fun onClick(myObj: T) }
0
Kotlin
0
2
64a4325c47523f178a2fdbf1fb9baa83ab867c5e
125
Android-SDK
Apache License 2.0
src/main/java/cn/cloudself/model/OrderEntity.kt
HerbLuo
91,303,763
false
{"Java": 95356, "Kotlin": 60280}
package cn.cloudself.model import org.hibernate.annotations.DynamicInsert import javax.persistence.* import java.sql.Timestamp /** * @author HerbLuo * @version 1.0.0.d */ @Entity @DynamicInsert @Table(name = "`order`", schema = "shop") data class OrderEntity ( @get:Id @get:Column(name = "id", nullable = false) @get:GeneratedValue(strategy = GenerationType.IDENTITY) var id: Int = 0, @get:Basic @get:Column(name = "enabled") var enabled: Boolean? = null, @get:Basic @get:Column(name = "create_time", nullable = true) var createTime: Timestamp? = null, @get:Basic @get:Column(name = "user_id", nullable = false) var userId: Int = 0, @get:Basic @get:Column(name = "is_finished", nullable = true) var areFinished: Boolean? = null, @get:Basic @get:Column(name = "is_paied", nullable = true) var arePaied: Boolean? = null, @get:OneToMany(cascade = arrayOf(CascadeType.PERSIST)) @get:JoinColumn(name = "order_id", referencedColumnName = "id", nullable = true) var orderAShops: Collection<OrderAShopEntity>? = null )
1
null
1
1
2e4f3ff5cdd4ac3d6b006616e96d5e92efb08009
1,199
shop-api
MIT License
core/src/main/java/com/nimbusframework/nimbuscore/persisted/FileUploadDescription.kt
thomasjallerton
163,180,980
false
null
package com.nimbusframework.nimbuscore.persisted data class FileUploadDescription( val localFile: String = "", val targetFile: String = "", val substituteVariables: Boolean = false )
6
Kotlin
4
36
12f25ba344d33a3fc66403c9c8d516b9e7809b3c
208
nimbus-core
MIT License
EvoMaster/core/src/main/kotlin/org/evomaster/core/search/EvaluatedAction.kt
mitchellolsthoorn
364,836,402
false
null
package org.evomaster.core.search class EvaluatedAction(val action: Action, val result: ActionResult)
1
null
1
1
50e9fb327fe918cc64c6b5e30d0daa2d9d5d923f
103
ASE-Technical-2021-api-linkage-replication
MIT License
src/main/kotlin/cookiedragon/luchadora/module/impl/player/NoEntityTraceModule.kt
DarkiBoi
236,686,394
true
{"INI": 1, "Shell": 1, "XML": 1, "Markdown": 1, "Batchfile": 1, "Gradle": 1, "Ignore List": 1, "Kotlin": 26, "Java": 94, "JSON": 2, "Java Properties": 1}
package cookiedragon.luchadora.module.impl.player import cookiedragon.luchadora.event.api.Subscriber import cookiedragon.luchadora.event.entity.GetEntitiesMouseOverEvent import cookiedragon.luchadora.module.AbstractModule import cookiedragon.luchadora.module.Category /** * @author cookiedragon234 12/Jan/2020 */ class NoEntityTraceModule : AbstractModule("No Entity Trace", "You can hit blocks through entities", Category.PLAYER) { @Subscriber private fun onEntityTrace(event: GetEntitiesMouseOverEvent) { event.size = 0 } }
0
null
2
1
b91411e8aa0f9dd5c61baca5de8340568fd17397
535
Luchadora
RSA Message-Digest License
src/main/kotlin/cookiedragon/luchadora/module/impl/player/NoEntityTraceModule.kt
DarkiBoi
236,686,394
true
{"INI": 1, "Shell": 1, "XML": 1, "Markdown": 1, "Batchfile": 1, "Gradle": 1, "Ignore List": 1, "Kotlin": 26, "Java": 94, "JSON": 2, "Java Properties": 1}
package cookiedragon.luchadora.module.impl.player import cookiedragon.luchadora.event.api.Subscriber import cookiedragon.luchadora.event.entity.GetEntitiesMouseOverEvent import cookiedragon.luchadora.module.AbstractModule import cookiedragon.luchadora.module.Category /** * @author cookiedragon234 12/Jan/2020 */ class NoEntityTraceModule : AbstractModule("No Entity Trace", "You can hit blocks through entities", Category.PLAYER) { @Subscriber private fun onEntityTrace(event: GetEntitiesMouseOverEvent) { event.size = 0 } }
0
null
2
1
b91411e8aa0f9dd5c61baca5de8340568fd17397
535
Luchadora
RSA Message-Digest License
src/test/kotlin/no/nav/familie/ef/sak/api/beregning/BeregningTest.kt
blommish
359,371,467
false
{"YAML": 13, "Ignore List": 2, "CODEOWNERS": 1, "Maven POM": 1, "Dockerfile": 1, "Text": 1, "Markdown": 1, "XML": 4, "JSON": 21, "Kotlin": 394, "Java": 1, "GraphQL": 8, "SQL": 43, "Shell": 1}
package no.nav.familie.ef.sak.api.beregning import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.DynamicTest import org.junit.jupiter.api.DynamicTest.dynamicTest import org.junit.jupiter.api.TestFactory import java.time.LocalDate internal class BeregningTest { @TestFactory fun `skal finne grunnbeløp mellom perioder`(): List<DynamicTest> { val testData = listOf( Pair("2000-01-01", "2005-01-01") to listOf(Triple("2000-01-01", "2000-05-01", 46950), Triple("2000-05-01", "2001-05-01", 49090), Triple("2001-05-01", "2002-05-01", 51360), Triple("2002-05-01", "2003-05-01", 54170), Triple("2003-05-01", "2004-05-01", 56861), Triple("2004-05-01", "2005-01-01", 58778)), Pair("2020-04-30", "2020-05-01") to listOf(Triple("2020-04-30", "2020-05-01", 99858), Triple("2020-05-01", "2020-05-01", 101351)), Pair("2019-05-01", "2020-05-01") to listOf(Triple("2019-05-01", "2020-05-01", 99858), Triple("2020-05-01", "2020-05-01", 101351)), Pair("2019-05-01", "2020-04-30") to listOf(Triple("2019-05-01", "2020-04-30", 99858)), Pair("2021-01-01", "2021-03-01") to listOf(Triple("2021-01-01", "2021-03-01", 101351)) ) return testData .map { (periode, fasit) -> dynamicTest("skal finne grunnbeløp for perioden=[${periode.first}-${periode.second}] med forventet svar: $fasit") { assertThat(finnGrunnbeløpsPerioder(LocalDate.parse(periode.first), LocalDate.parse(periode.second))) .isEqualTo(fasit.map { Beløpsperiode(LocalDate.parse(it.first), LocalDate.parse(it.second), it.third.toBigDecimal()) }) } } } }
1
null
1
1
0e850df593c82a910c68c2393e6d2f30fc49eaa7
2,421
familie-ef-sak
MIT License
src/main/kotlin/coffee/cypher/kettle/tickers/Tickers.kt
Cypher121
174,577,171
false
null
package coffee.cypher.kettle.tickers import net.minecraft.block.BlockState import net.minecraft.block.BlockWithEntity import net.minecraft.block.entity.BlockEntity import net.minecraft.block.entity.BlockEntityTicker import net.minecraft.util.math.BlockPos import net.minecraft.world.World /** * Wraps a function taking the arguments for [BlockEntityTicker.tick] * into a [BlockEntityTicker]. */ public fun <T : BlockEntity> ((World, BlockPos, BlockState, T) -> Unit).asSimpleTicker(): BlockEntityTicker<T> = BlockEntityTicker { world, blockPos, blockState, be -> this(world, blockPos, blockState, be) } /** * Casts a [BlockEntityTicker] to the specified [BlockEntity] type [E]. * * Mainly used when returning from [BlockWithEntity.getTicker] to return * the correct generic type, when it's expected to match this ticker's. */ @Suppress("UNCHECKED_CAST") public fun <T : BlockEntity, E : BlockEntity> BlockEntityTicker<T>.cast(): BlockEntityTicker<E> = BlockEntityTicker { world, blockPos, blockState, be -> tick(world, blockPos, blockState, be as T) }
1
Kotlin
1
4
287257c38d89d05234dd3b78b46a9c95466f5989
1,095
kettle
MIT License
test-common/src/main/java/com/freshdigitable/udonroad2/test_common/TwitterRobotBase.kt
akihito104
149,869,805
false
{"YAML": 4, "Gradle Kotlin DSL": 7, "JSON": 1, "Kotlin": 263, "Java Properties": 10, "Shell": 1, "Text": 1, "Ignore List": 17, "Batchfile": 1, "EditorConfig": 1, "Gradle": 12, "Proguard": 17, "XML": 147, "Java": 3, "INI": 7, "PlantUML": 3}
/* * Copyright (c) 2021. Matsuda, Akihit (akihito104) * * 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.freshdigitable.udonroad2.test_common import com.freshdigitable.udonroad2.model.UserId import io.mockk.confirmVerified import io.mockk.every import io.mockk.just import io.mockk.mockk import io.mockk.runs import io.mockk.verify import org.junit.rules.TestWatcher import org.junit.runner.Description import twitter4j.GeoLocation import twitter4j.HashtagEntity import twitter4j.MediaEntity import twitter4j.PagableResponseList import twitter4j.Paging import twitter4j.Place import twitter4j.Query import twitter4j.QueryResult import twitter4j.RateLimitStatus import twitter4j.Relationship import twitter4j.ResponseList import twitter4j.Scopes import twitter4j.Status import twitter4j.SymbolEntity import twitter4j.Twitter import twitter4j.TwitterResponse import twitter4j.URLEntity import twitter4j.User import twitter4j.UserList import twitter4j.UserMentionEntity import twitter4j.auth.AccessToken import twitter4j.auth.RequestToken import java.util.Date abstract class TwitterRobotBase : TestWatcher() { protected abstract val twitter: Twitter private val expected: MutableCollection<() -> Unit> = mutableListOf() fun setupSetOAuthAccessToken(block: MatcherScopedBlock<AccessToken?>) { every { twitter.setOAuthAccessToken(block()) } just runs expected.add { verify { twitter.setOAuthAccessToken(block()) } } } fun setupGetOAuthRequestToken( block: MatcherScopedBlock<String> = { "oob" }, response: RequestToken ) { every { twitter.getOAuthRequestToken(block()) } returns response expected.add { verify { twitter.getOAuthRequestToken(block()) } } } fun setupGetOAuthAccessToken( requestTokenBlock: MatcherScopedBlock<RequestToken>, pinBlock: MatcherScopedBlock<String>, response: AccessToken ) { every { twitter.getOAuthAccessToken(requestTokenBlock(), pinBlock()) } returns response expected.add { verify { twitter.getOAuthAccessToken(requestTokenBlock(), pinBlock()) } } } fun setupGetHomeTimeline( pagingBlock: MatcherScopedBlock<Paging> = { any() }, response: List<Status>, onAnswer: AnswerScopedBlock<ResponseList<Status>, ResponseList<Status>> = {} ) { val res = createResponseListMock(response) setupResponseWithVerify({ twitter.getHomeTimeline(pagingBlock()) }, res, onAnswer) } fun setupGetFavorites( userId: UserId? = null, pagingBlock: MatcherScopedBlock<Paging> = { any() }, response: List<Status>, onAnswer: AnswerScopedBlock<ResponseList<Status>, ResponseList<Status>> = {} ) { val res = createResponseListMock(response) if (userId == null) { setupResponseWithVerify({ twitter.getFavorites(pagingBlock()) }, res, onAnswer) } else { setupResponseWithVerify( { twitter.getFavorites(userId.value, pagingBlock()) }, res, onAnswer ) } } fun setupGetSearchList( pagingBlock: MatcherScopedBlock<Query> = { any() }, response: List<Status>, nextQuery: Query? = null, onAnswer: AnswerScopedBlock<QueryResult, QueryResult> = {} ) { val res = mockk<QueryResult>().apply { every { tweets } returns response every { nextQuery() } returns nextQuery } setupResponseWithVerify({ twitter.search(pagingBlock()) }, res, onAnswer) } fun setupGetUserTimeline( userId: UserId, pagingBlock: MatcherScopedBlock<Paging> = { any() }, response: List<Status>, onAnswer: AnswerScopedBlock<ResponseList<Status>, ResponseList<Status>> = {} ) { setupResponseWithVerify( { twitter.getUserTimeline(userId.value, pagingBlock()) }, createResponseListMock(response), onAnswer ) } fun setupGetUserListMemberships( userId: UserId, count: MatcherScopedBlock<Int> = { any() }, nextCursor: MatcherScopedBlock<Long> = { any() }, response: List<UserList>, onAnswer: AnswerScopedBlock<PagableResponseList<UserList>, PagableResponseList<UserList>> = {} ) { setupResponseWithVerify( { twitter.getUserListMemberships(userId.value, count(), nextCursor()) }, createPagableResponseListMock(response), onAnswer ) } fun setupGetFollowersList( userId: UserId, response: List<User>, onAnswer: AnswerScopedBlock<ResponseList<User>, ResponseList<User>> = {} ) { val res = createPagableResponseListMock(response) setupResponseWithVerify({ twitter.getFollowersList(userId.value, -1) }, res, onAnswer) } fun setupGetFriendsList( userId: UserId, response: List<User>, onAnswer: AnswerScopedBlock<ResponseList<User>, ResponseList<User>> = {} ) { val res = createPagableResponseListMock(response) setupResponseWithVerify({ twitter.getFriendsList(userId.value, -1) }, res, onAnswer) } fun setupShowUser(user: User) { setupResponseWithVerify({ twitter.showUser(user.id) }, user) } fun setupVerifyCredential(user: User) { setupResponseWithVerify({ twitter.verifyCredentials() }, user) } fun setupRelationships(userId: UserId, targetUserId: UserId) { setupResponseWithVerify({ twitter.id }, userId.value) val relationship = mockk<Relationship>().apply { every { getTargetUserId() } returns targetUserId.value every { isSourceFollowingTarget } returns false every { isSourceBlockingTarget } returns false every { isSourceMutingTarget } returns false every { isSourceWantRetweets } returns false every { isSourceNotificationsEnabled } returns false every { sourceUserId } returns userId.value } setupResponseWithVerify( { twitter.showFriendship(userId.value, targetUserId.value) }, relationship ) } override fun succeeded(description: Description?) { super.succeeded(description) expected.forEach { it() } confirmVerified(twitter) } private fun <T> createResponseListMock(response: List<T>): ResponseList<T> { val resList = mockk<ResponseList<T>>(relaxed = true) val mutableList = response.toMutableList() return object : ResponseList<T>, MutableList<T> by mutableList { override fun getRateLimitStatus(): RateLimitStatus = resList.rateLimitStatus override fun getAccessLevel(): Int = resList.accessLevel } } private fun <T : TwitterResponse> createPagableResponseListMock( response: List<T> ): PagableResponseList<T> { val resList = mockk<PagableResponseList<T>>(relaxed = true) val mutableList = createResponseListMock(response) return object : PagableResponseList<T>, ResponseList<T> by mutableList { override fun hasPrevious(): Boolean = resList.hasPrevious() override fun getPreviousCursor(): Long = resList.previousCursor override fun hasNext(): Boolean = resList.hasNext() override fun getNextCursor(): Long = resList.nextCursor } } private fun <T> setupResponseWithVerify( target: MatcherScopedBlock<T>, res: T, alsoOnAnswer: AnswerScopedBlock<T, T> = {}, ) { every(target) answers { alsoOnAnswer() res } expected.add { verify { target() } } } } fun createRequestToken( userId: Long, token: String, tokenSecret: String ): RequestToken { return RequestToken("$userId-$token", tokenSecret) } fun createStatus( id: Long, text: String = "", user: User = createUser(1000, "user1", "user1"), createdAt: Date = Date(1000000), mediaEntities: Array<MediaEntity> = emptyArray(), userMentionEntities: Array<UserMentionEntity> = emptyArray(), quotedStatus: Status? = null, currentUserRetweetId: Long = -1, isRetweeted: Boolean = false, isFavorited: Boolean = false, retweetedStatus: Status? = null, urlEntities: Array<URLEntity> = emptyArray(), ): Status { return object : Status { override fun getUser(): User = user override fun getCreatedAt(): Date = createdAt override fun getId(): Long = id override fun getText(): String = text override fun getFavoriteCount(): Int = 0 override fun getRetweetCount(): Int = 0 override fun getQuotedStatusId(): Long = quotedStatus?.id ?: -1 override fun getQuotedStatus(): Status? = quotedStatus override fun getSource(): String = "Twitter Web App" override fun getRetweetedStatus(): Status? = retweetedStatus override fun getInReplyToStatusId(): Long = -1 override fun isFavorited(): Boolean = isFavorited override fun isRetweeted(): Boolean = isRetweeted override fun isPossiblySensitive(): Boolean = false override fun getMediaEntities(): Array<MediaEntity> = mediaEntities override fun getCurrentUserRetweetId(): Long = currentUserRetweetId override fun getUserMentionEntities(): Array<UserMentionEntity> = userMentionEntities override fun getURLEntities(): Array<URLEntity> = urlEntities override fun compareTo(other: Status): Int = this.createdAt.compareTo(other.createdAt) override fun getRateLimitStatus(): RateLimitStatus = TODO("Not yet implemented") override fun getAccessLevel(): Int = TODO("Not yet implemented") override fun getHashtagEntities(): Array<HashtagEntity> = TODO("Not yet implemented") override fun getSymbolEntities(): Array<SymbolEntity> = TODO("Not yet implemented") override fun getDisplayTextRangeStart(): Int = TODO("Not yet implemented") override fun getDisplayTextRangeEnd(): Int = TODO("Not yet implemented") override fun isTruncated(): Boolean = TODO("Not yet implemented") override fun getInReplyToUserId(): Long = TODO("Not yet implemented") override fun getInReplyToScreenName(): String = TODO("Not yet implemented") override fun getGeoLocation(): GeoLocation = TODO("Not yet implemented") override fun getPlace(): Place = TODO("Not yet implemented") override fun isRetweet(): Boolean = TODO("Not yet implemented") override fun getContributors(): LongArray = TODO("Not yet implemented") override fun isRetweetedByMe(): Boolean = TODO("Not yet implemented") override fun getLang(): String = TODO("Not yet implemented") override fun getScopes(): Scopes = TODO("Not yet implemented") override fun getWithheldInCountries(): Array<String> = TODO("Not yet implemented") override fun getQuotedStatusPermalink(): URLEntity = TODO("Not yet implemented") } } fun createUser( id: Long, name: String, screenName: String ): User { return object : User { override fun getId(): Long = id override fun getName(): String = name override fun getScreenName(): String = screenName override fun getDescription(): String = "" override fun getProfileImageURLHttps(): String = "" override fun getProfileBanner600x200URL(): String = "" override fun getFollowersCount(): Int = 0 override fun getFriendsCount(): Int = 0 override fun getStatusesCount(): Int = 0 override fun getFavouritesCount(): Int = 0 override fun getListedCount(): Int = 0 override fun getProfileLinkColor(): String = "FFFFFF" override fun getLocation(): String = "" override fun getURL(): String = "" override fun isVerified(): Boolean = false override fun isProtected(): Boolean = false override fun getProfileImageURL(): String = "" override fun getProfileBanner1500x500URL(): String = TODO("Not yet implemented") override fun isProfileBackgroundTiled(): Boolean = TODO("Not yet implemented") override fun getLang(): String = TODO("Not yet implemented") override fun getStatus(): Status = TODO("Not yet implemented") override fun getProfileBackgroundColor(): String = TODO("Not yet implemented") override fun getProfileTextColor(): String = TODO("Not yet implemented") override fun getCreatedAt(): Date = TODO("Not yet implemented") override fun getUtcOffset(): Int = TODO("Not yet implemented") override fun getTimeZone(): String = TODO("Not yet implemented") override fun getProfileBackgroundImageURL(): String = TODO("Not yet implemented") override fun getProfileBackgroundImageUrlHttps(): String = TODO("Not yet implemented") override fun getProfileBannerURL(): String = TODO("Not yet implemented") override fun getProfileBannerRetinaURL(): String = TODO("Not yet implemented") override fun getProfileBannerIPadURL(): String = TODO("Not yet implemented") override fun getProfileBannerIPadRetinaURL(): String = TODO("Not yet implemented") override fun getProfileBannerMobileURL(): String = TODO("Not yet implemented") override fun getProfileBannerMobileRetinaURL(): String = TODO("Not yet implemented") override fun getProfileBanner300x100URL(): String = TODO("Not yet implemented") override fun isGeoEnabled(): Boolean = TODO("Not yet implemented") override fun isFollowRequestSent(): Boolean = TODO("Not yet implemented") override fun getDescriptionURLEntities(): Array<URLEntity> = TODO("Not yet implemented") override fun getURLEntity(): URLEntity = TODO("Not yet implemented") override fun getWithheldInCountries(): Array<String> = TODO("Not yet implemented") override fun getProfileSidebarFillColor(): String = TODO("Not yet implemented") override fun getProfileSidebarBorderColor(): String = TODO("Not yet implemented") override fun isProfileUseBackgroundImage(): Boolean = TODO("Not yet implemented") override fun isDefaultProfile(): Boolean = TODO("Not yet implemented") override fun isShowAllInlineMedia(): Boolean = TODO("Not yet implemented") override fun compareTo(other: User?): Int = TODO("Not yet implemented") override fun getRateLimitStatus(): RateLimitStatus = TODO("Not yet implemented") override fun getAccessLevel(): Int = TODO("Not yet implemented") override fun getEmail(): String = TODO("Not yet implemented") override fun isContributorsEnabled(): Boolean = TODO("Not yet implemented") override fun isTranslator(): Boolean = TODO("Not yet implemented") override fun getBiggerProfileImageURL(): String = TODO("Not yet implemented") override fun getMiniProfileImageURL(): String = TODO("Not yet implemented") override fun getOriginalProfileImageURL(): String = TODO("Not yet implemented") override fun get400x400ProfileImageURL(): String = TODO("Not yet implemented") override fun getBiggerProfileImageURLHttps(): String = TODO("Not yet implemented") override fun getMiniProfileImageURLHttps(): String = TODO("Not yet implemented") override fun getOriginalProfileImageURLHttps(): String = TODO("Not yet implemented") override fun get400x400ProfileImageURLHttps(): String = TODO("Not yet implemented") override fun isDefaultProfileImage(): Boolean = TODO("Not yet implemented") } }
21
null
1
1
7ec50f204fda79cf222b24623f22e80d05301555
16,165
UdonRoad2
Apache License 2.0
app/src/main/java/com/akexorcist/snaptimepicker/sample/MainActivity.kt
krzbbaranowski
237,181,329
true
{"Kotlin": 38655}
package com.akexorcist.snaptimepicker.sample import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.akexorcist.snaptimepicker.SnapTimePickerDialog import com.akexorcist.snaptimepicker.TimeRange import com.akexorcist.snaptimepicker.TimeValue import com.akexorcist.snaptimepicker.extension.SnapTimePickerUtil import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) buttonNoCustomTimePicker.setOnClickListener { // No custom time picker SnapTimePickerDialog.Builder().apply { setTitle(R.string.title) setTitleColor(R.color.colorWhite)}.build().apply { setListener { hour, minute -> onTimePicked(hour, minute) } }.show(supportFragmentManager, SnapTimePickerDialog.TAG) } buttonFullCustomTimePicker.setOnClickListener { // Custom text and color SnapTimePickerDialog.Builder().apply { setTitle(R.string.title) setPrefix(R.string.time_prefix) setSuffix(R.string.time_suffix) setPreselectedTime(TimeValue(11, 34)) setSelectableTimeRange(TimeRange(TimeValue(11, 0), TimeValue(0, 0))) setThemeColor(R.color.colorAccent) setTitleColor(R.color.colorWhite) setMinutesStep(30) }.build().apply { setListener { hour, minute -> onTimePicked(hour, minute) } }.show(supportFragmentManager, SnapTimePickerDialog.TAG) } buttonPreselectedTime.setOnClickListener { // Set pre-selected time SnapTimePickerDialog.Builder().apply { setPreselectedTime(TimeValue(2, 15)) }.build().apply { setListener { hour, minute -> onTimePicked(hour, minute) } }.show(supportFragmentManager, SnapTimePickerDialog.TAG) } buttonTimeRange.setOnClickListener { // Set selectable time range SnapTimePickerDialog.Builder().apply { val start = TimeValue(2, 15) val end = TimeValue(14, 30) setSelectableTimeRange(TimeRange(start, end)) }.build().apply { setListener { hour, minute -> onTimePicked(hour, minute) } }.show(supportFragmentManager, SnapTimePickerDialog.TAG) } buttonViewModelCallback.setOnClickListener { // Get event callback from ViewModel observing. No need listener // // This very useful when you use ViewModel. Although user do // something that make configuration changes occur, you still get // event callback from LiveData. // // See how can you get event callback from ViewModel at line 73. SnapTimePickerDialog.Builder().apply { useViewModel() }.build().show(supportFragmentManager, SnapTimePickerDialog.TAG) } // This code is work with `useViewModel()` at line 68 SnapTimePickerUtil.observe(this) { selectedHour: Int, selectedMinute: Int -> onTimePicked(selectedHour, selectedMinute) } } private fun onTimePicked(selectedHour: Int, selectedMinute: Int) { val hour = selectedHour.toString().padStart(2, '0') val minute = selectedMinute.toString().padStart(2, '0') textViewTime.text = String.format(getString(R.string.selected_time_format, hour, minute)) } }
0
Kotlin
0
0
4877ffb53710b7ce6b798879a6f81412bbdfd675
3,703
Android-SnapTimePicker
Apache License 2.0
src/main/kotlin/jp/ac/titech/cs/se/refactorhub/app/interfaces/controller/CodeElementController.kt
salab
208,590,763
false
null
package jp.ac.titech.cs.se.refactorhub.app.interfaces.controller import com.fasterxml.jackson.module.jsonSchema.JsonSchema import jp.ac.titech.cs.se.refactorhub.app.usecase.service.CodeElementService import org.koin.core.component.KoinApiExtension import org.koin.core.component.KoinComponent import org.koin.core.component.inject @KoinApiExtension class CodeElementController : KoinComponent { private val codeElementService: CodeElementService by inject() fun getTypes(): List<String> { return codeElementService.getTypes() } fun getSchemas(): List<JsonSchema> { return codeElementService.getSchemas() } }
0
Kotlin
0
6
f876da7bcc7bceed549586f0f0300d20f2108fe0
648
RefactorHub
MIT License
shared/account/src/commonMain/kotlin/io/edugma/features/account/domain/model/SemestersWithCourse.kt
Edugma
474,423,768
false
{"Kotlin": 937476, "Swift": 1255, "Ruby": 102}
package io.edugma.features.account.domain.model import kotlinx.serialization.Serializable @Serializable data class SemestersWithCourse( val coursesWithSemesters: Map<Int, Int>, )
1
Kotlin
0
2
f864876406b8da6294fc51af89589c4b80cccba2
185
app
MIT License
native/objcexport-header-generator/testData/headers/manyClassesAndInterfaces/A.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}
package com.a class A2 class A1 interface A0 class A3
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
55
kotlin
Apache License 2.0
src/main/kotlin/abc/041-c.kt
kirimin
197,707,422
false
null
package abc import java.util.* fun main(args: Array<String>) { val sc = Scanner(System.`in`) val n = sc.nextInt() val a = (0 until n).map { sc.next().toLong() } println(problem041c(n, a)) } fun problem041c(n: Int, a: List<Long>): String { return a.mapIndexed { index, l -> index to l } .sortedBy { it.second } .reversed() .map { it.first + 1 } .joinToString("\n") }
0
Kotlin
1
5
fc41f7269c08694decaf241c3e8991c87a5a85b4
420
AtCoderLog
The Unlicense
src/main/kotlin/abc/041-c.kt
kirimin
197,707,422
false
null
package abc import java.util.* fun main(args: Array<String>) { val sc = Scanner(System.`in`) val n = sc.nextInt() val a = (0 until n).map { sc.next().toLong() } println(problem041c(n, a)) } fun problem041c(n: Int, a: List<Long>): String { return a.mapIndexed { index, l -> index to l } .sortedBy { it.second } .reversed() .map { it.first + 1 } .joinToString("\n") }
0
Kotlin
1
5
fc41f7269c08694decaf241c3e8991c87a5a85b4
420
AtCoderLog
The Unlicense
tmp/arrays/youTrackTests/6806.kt
DaniilStepanov
228,623,440
false
null
// Original bug: KT-8221 class A { fun foo(): Boolean { return true } } fun bar(): A? { return A() } fun baz() { val x = bar() if (x?.foo() != null) { x.foo() // <- error: x may be null ?! } }
1
null
1
1
602285ec60b01eee473dcb0b08ce497b1c254983
236
bbfgradle
Apache License 2.0
core/src/main/kotlin/info/laht/threekt/core/Raycaster.kt
Dominaezzz
199,304,218
true
{"Kotlin": 546195, "GLSL": 105344}
package info.laht.threekt.core import info.laht.threekt.cameras.Camera import info.laht.threekt.math.Ray import info.laht.threekt.math.Vector2 import info.laht.threekt.math.Vector3 class Intersection( val distance: Float, val distanceToRay: Float?, val point: Vector3, val index: Int?, val face: Face3?, val faceIndex: Int?, val `object`: Object3D, val uv: Vector2? ) class Raycaster( origin: Vector3, direction: Vector3, val near: Float = 0f, val far: Float = Float.POSITIVE_INFINITY ) { private val ray = Ray(origin, direction) /** * Updates the ray with a new origin and direction. * @param origin The origin vector where the ray casts from. * @param direction The normalized direction vector that gives direction to the ray. */ fun set(origin: Vector3, direction: Vector3) { TODO() } /** * Updates the ray with a new origin and direction. * @param coords 2D coordinates of the mouse, in normalized device coordinates (NDC)---X and Y components should be between -1 and 1. * @param camera camera from which the ray should originate */ fun setFromCamera(coords: Vector2, camera: Camera) { TODO() } /** * Checks all intersection between the ray and the object with or without the descendants. Intersections are returned sorted by distance, closest first. * @param object The object to check for intersection with the ray. * @param recursive If true, it also checks all descendants. Otherwise it only checks intersecton with the object. Default is false. * @param optionalTarget (optional) target to set the result. Otherwise a new Array is instantiated. If set, you must clear this array prior to each call (i.e., array.length = 0) */ fun intersectObject( `object`: Object3D, recursive: Boolean = false, optionalTarget: List<Intersection>? ): List<Intersection> { TODO() } /** * Checks all intersection between the ray and the objects with or without the descendants. Intersections are returned sorted by distance, closest first. Intersections are of the same form as those returned by .intersectObject. * @param objects The objects to check for intersection with the ray. * @param recursive If true, it also checks all descendants of the objects. Otherwise it only checks intersecton with the objects. Default is false. * @param optionalTarget (optional) target to set the result. Otherwise a new Array is instantiated. If set, you must clear this array prior to each call (i.e., array.length = 0) */ fun intersectObjects( objects: List<Object3D>, recursive: Boolean = false, optionalTarget: List<Intersection>? ): List<Intersection> { TODO() } }
0
Kotlin
0
1
f5803ac4982dd7b89303eda059c95c5ac00488b5
2,839
three.kt
MIT License
settings/ui/src/main/java/com/vlad1m1r/bltaxi/settings/ui/SettingsViewModel.kt
VladimirWrites
192,170,187
false
{"Kotlin": 150749, "HTML": 15579}
package com.vlad1m1r.bltaxi.settings.ui import androidx.appcompat.app.AppCompatDelegate.* import androidx.databinding.ObservableInt import androidx.lifecycle.ViewModel import com.vlad1m1r.basedata.StringResolver import com.vlad1m1r.bltaxi.analytics.CrashReport import com.vlad1m1r.bltaxi.analytics.Tracker import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class SettingsViewModel @Inject constructor( private val stringResolver: StringResolver, private val crashReport: CrashReport, private val tracker: Tracker ) : ViewModel() { val mode = ObservableInt(Int.MIN_VALUE) fun enableCrashReport(enabled: Boolean) { crashReport.enableCrashReporting(enabled) } fun enableTracking(enabled: Boolean) { tracker.enableTracking(enabled) } fun changeTheme(theme: String) { val newMode = when (theme) { stringResolver.getString(R.string.theme_value_dark) -> MODE_NIGHT_YES stringResolver.getString(R.string.theme_value_light) -> MODE_NIGHT_NO stringResolver.getString(R.string.theme_value_default) -> MODE_NIGHT_FOLLOW_SYSTEM else -> throw IllegalArgumentException("Mode with value: $theme is not supported") } mode.set(newMode) } }
0
Kotlin
39
350
33b03dbdf4f7c2b7384ffa6259de52a813673c77
1,298
BLTaxi
Apache License 2.0
buildSrc/private/src/main/kotlin/androidx/build/testConfiguration/GenerateMediaTestConfigurationTask.kt
androidx
256,589,781
false
null
/* * 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.build.testConfiguration import androidx.build.dependencyTracker.ProjectSubset import androidx.build.renameApkForTesting import com.android.build.api.variant.BuiltArtifact import com.android.build.api.variant.BuiltArtifacts import com.android.build.api.variant.BuiltArtifactsLoader import java.io.File import org.gradle.api.DefaultTask import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.Property import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFiles import org.gradle.api.tasks.Internal import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction import org.gradle.work.DisableCachingByDefault /** * Writes three configuration files to test combinations of media client & service in * <a href=https://source.android.com/devices/tech/test_infra/tradefed/testing/through-suite/android-test-structure>AndroidTest.xml</a> * format that gets zipped alongside the APKs to be tested. The combinations are of previous and * tip-of-tree versions client and service. We want to test every possible pairing that includes * tip-of-tree. * * This config gets ingested by Tradefed. */ @DisableCachingByDefault(because = "Doesn't benefit from caching") abstract class GenerateMediaTestConfigurationTask : DefaultTask() { @get:InputFiles @get:PathSensitive(PathSensitivity.RELATIVE) abstract val clientToTFolder: DirectoryProperty @get:Internal abstract val clientToTLoader: Property<BuiltArtifactsLoader> @get:InputFiles @get:PathSensitive(PathSensitivity.RELATIVE) abstract val clientPreviousFolder: DirectoryProperty @get:Internal abstract val clientPreviousLoader: Property<BuiltArtifactsLoader> @get:InputFiles @get:PathSensitive(PathSensitivity.RELATIVE) abstract val serviceToTFolder: DirectoryProperty @get:Internal abstract val serviceToTLoader: Property<BuiltArtifactsLoader> @get:InputFiles @get:PathSensitive(PathSensitivity.RELATIVE) abstract val servicePreviousFolder: DirectoryProperty @get:Internal abstract val servicePreviousLoader: Property<BuiltArtifactsLoader> @get:Input abstract val affectedModuleDetectorSubset: Property<ProjectSubset> @get:Input abstract val clientToTPath: Property<String> @get:Input abstract val clientPreviousPath: Property<String> @get:Input abstract val serviceToTPath: Property<String> @get:Input abstract val servicePreviousPath: Property<String> @get:Input abstract val minSdk: Property<Int> @get:Input abstract val testRunner: Property<String> @get:Input abstract val presubmit: Property<Boolean> @get:OutputFile abstract val jsonClientPreviousServiceToTClientTests: RegularFileProperty @get:OutputFile abstract val jsonClientPreviousServiceToTServiceTests: RegularFileProperty @get:OutputFile abstract val jsonClientToTServicePreviousClientTests: RegularFileProperty @get:OutputFile abstract val jsonClientToTServicePreviousServiceTests: RegularFileProperty @get:OutputFile abstract val jsonClientToTServiceToTClientTests: RegularFileProperty @get:OutputFile abstract val jsonClientToTServiceToTServiceTests: RegularFileProperty @TaskAction fun generateAndroidTestZip() { val clientToTApk = resolveApk(clientToTFolder, clientToTLoader) val clientPreviousApk = resolveApk(clientPreviousFolder, clientPreviousLoader) val serviceToTApk = resolveApk(serviceToTFolder, serviceToTLoader) val servicePreviousApk = resolveApk( servicePreviousFolder, servicePreviousLoader ) writeConfigFileContent( clientApk = clientToTApk, serviceApk = serviceToTApk, clientPath = clientToTPath.get(), servicePath = serviceToTPath.get(), jsonClientOutputFile = jsonClientToTServiceToTClientTests, jsonServiceOutputFile = jsonClientToTServiceToTServiceTests, isClientPrevious = false, isServicePrevious = false ) writeConfigFileContent( clientApk = clientToTApk, serviceApk = servicePreviousApk, clientPath = clientToTPath.get(), servicePath = servicePreviousPath.get(), jsonClientOutputFile = jsonClientToTServicePreviousClientTests, jsonServiceOutputFile = jsonClientToTServicePreviousServiceTests, isClientPrevious = false, isServicePrevious = true ) writeConfigFileContent( clientApk = clientPreviousApk, serviceApk = serviceToTApk, clientPath = clientPreviousPath.get(), servicePath = serviceToTPath.get(), jsonClientOutputFile = jsonClientPreviousServiceToTClientTests, jsonServiceOutputFile = jsonClientPreviousServiceToTServiceTests, isClientPrevious = true, isServicePrevious = false ) } private fun resolveApk( apkFolder: DirectoryProperty, apkLoader: Property<BuiltArtifactsLoader> ): BuiltArtifacts { return apkLoader.get().load(apkFolder.get()) ?: throw RuntimeException("Cannot load required APK for task: $name") } private fun BuiltArtifact.resolveName(path: String): String { return outputFile.substringAfterLast("/").renameApkForTesting(path) } private fun writeConfigFileContent( clientApk: BuiltArtifacts, serviceApk: BuiltArtifacts, clientPath: String, servicePath: String, jsonClientOutputFile: RegularFileProperty, jsonServiceOutputFile: RegularFileProperty, isClientPrevious: Boolean, isServicePrevious: Boolean, ) { val clientBuiltArtifact = clientApk.elements.single() val serviceBuiltArtifact = serviceApk.elements.single() val clientApkName = clientBuiltArtifact.resolveName(clientPath) val clientApkSha256 = sha256(File(clientBuiltArtifact.outputFile)) val serviceApkName = serviceBuiltArtifact.resolveName(servicePath) val serviceApkSha256 = sha256(File(serviceBuiltArtifact.outputFile)) createOrFail(jsonClientOutputFile).writeText( buildMediaJson( configName = jsonClientOutputFile.asFile.get().name, forClient = true, clientApkName = clientApkName, clientApkSha256 = clientApkSha256, isClientPrevious = isClientPrevious, isServicePrevious = isServicePrevious, minSdk = minSdk.get().toString(), serviceApkName = serviceApkName, serviceApkSha256 = serviceApkSha256, tags = listOf( "androidx_unit_tests", "media_compat" ), ) ) createOrFail(jsonServiceOutputFile).writeText( buildMediaJson( configName = jsonServiceOutputFile.asFile.get().name, forClient = false, clientApkName = clientApkName, clientApkSha256 = clientApkSha256, isClientPrevious = isClientPrevious, isServicePrevious = isServicePrevious, minSdk = minSdk.get().toString(), serviceApkName = serviceApkName, serviceApkSha256 = serviceApkSha256, tags = listOf( "androidx_unit_tests", "media_compat" ), ) ) } }
23
Kotlin
740
4,353
3492e5e1782b1524f2ab658f1728c89a35c7336d
8,369
androidx
Apache License 2.0
src/main/kotlin/parser/Ast.kt
reutermj
623,244,412
false
{"Kotlin": 223132}
package parser import errors.* import kotlinx.serialization.* import typechecker.* sealed interface Ast { val span: Span val errors: CortecsErrors fun firstTokenOrNull(): Token? fun shouldKeep(start: Span, end: Span) = end < Span.zero || span < start fun shouldDelete(start: Span, end: Span) = span == Span.zero || start <= Span.zero && span <= end fun createChangeIterator(change: Change): ParserIterator { val iterator = ParserIterator() addToIterator(change, iterator, false) if(change.start == Span.zero) iterator.add(change.text) return iterator } fun addToIterator(change: Change, iter: ParserIterator, wasNextTokenModified: Boolean): Boolean fun addAllButFirstToIterator(iter: ParserIterator) fun forceReparse(iter: ParserIterator) fun stringify(builder: StringBuilder) } @Serializable sealed class AstImpl: Ast { abstract val nodes: List<Ast> private var _firstToken: Token? = null override fun firstTokenOrNull(): Token? { if(_firstToken != null) return _firstToken for(node in nodes) { val first = node.firstTokenOrNull() if(first != null) { _firstToken = first return first } } return null } override fun addAllButFirstToIterator(iter: ParserIterator) { for(node in nodes.drop(1).reversed()) iter.add(node) nodes.firstOrNull()?.addAllButFirstToIterator(iter) } private var _span: Span? = null override val span: Span get() { if(_span == null) _span = nodes.fold(Span.zero) { acc, e -> acc + e.span } return _span!! } override fun forceReparse(iter: ParserIterator) { val nonEmptyNodes = nodes.filter { it.span != Span.zero } //TODO have a better way of dealing with empty nodes nonEmptyNodes.last().forceReparse(iter) for(node in nonEmptyNodes.dropLast(1).reversed()) iter.add(node) } override fun addToIterator(change: Change, iter: ParserIterator, wasNextTokenModified: Boolean): Boolean { if(nodes.isEmpty()) return wasNextTokenModified if(shouldDelete(change.start, change.end)) return true if(shouldKeep(change.start, change.end)) { if(wasNextTokenModified) forceReparse(iter) // the next element has changed so need to reparse the last element of this node else iter.add(this) //the token following this node is kept; don't force reparse return false } var s = Span.zero val spans = Array(nodes.size) { val span = s s += nodes[it].span span } var modified = wasNextTokenModified for (i in nodes.indices.reversed()) { val start = change.start - spans[i] val end = change.end - spans[i] modified = nodes[i].addToIterator(change.copy(start = start, end = end), iter, modified) } return modified } override fun stringify(builder: StringBuilder) { for(node in nodes) node.stringify(builder) } } @Serializable data class ProgramAst(override val nodes: List<Ast>, override val height: Int): StarAst<TopLevelAst>() { val environment: Environment by lazy { fold(EmptyEnvironment as Environment) { acc, ast -> acc + ast.environment } } companion object { val empty = ProgramAst(emptyList(), 0) } override fun ctor(nodes: List<Ast>, height: Int) = ProgramAst(nodes, height) } @Serializable data class GarbageAst(override val nodes: List<Ast>, override val height: Int): StarAst<Ast>() { companion object { val empty = GarbageAst(emptyList(), 0) } override fun ctor(nodes: List<Ast>, height: Int) = GarbageAst(nodes, height) } sealed class TopLevelAst: AstImpl() { abstract val environment: Environment } @Serializable data class FunctionAst(override val nodes: List<Ast>, override val errors: CortecsErrors, val nameIndex: Int, val parametersIndex: Int, val returnTypeIndex: Int, val blockIndex: Int): TopLevelAst() { override val environment: Environment by lazy { generateFunctionEnvironment(this) } fun name(): NameToken = if(nameIndex == -1) throw Exception("Name not available") else nodes[nameIndex] as NameToken fun parameters(): ParametersAst = if(parametersIndex == -1) throw Exception("Parameters not available") else nodes[parametersIndex] as ParametersAst fun returnType(): TypeAnnotationToken = if(returnTypeIndex == -1) throw Exception("Return type not available") else nodes[returnTypeIndex] as TypeAnnotationToken fun block(): BlockAst = if(blockIndex == -1) throw Exception("Block not available") else nodes[blockIndex] as BlockAst } @Serializable data class GarbageTopLevelAst(val garbageAst: GarbageAst): TopLevelAst() { override val environment: Environment get() = EmptyEnvironment override val nodes: List<Ast> get() = garbageAst.nodes override val errors: CortecsErrors get() = CortecsErrors(span, emptyList()) } @Serializable data class ParametersAst(override val nodes: List<Ast>, override val height: Int): StarAst<ParameterAst>() { companion object { val empty = ParametersAst(emptyList(), 0) } override fun ctor(nodes: List<Ast>, height: Int) = ParametersAst(nodes, height) } @Serializable data class ParameterAst(override val nodes: List<Ast>, override val errors: CortecsErrors, val nameIndex: Int, val typeAnnotationIndex: Int): AstImpl() { fun name(): NameToken = if(nameIndex == -1) throw Exception("Name not available") else nodes[nameIndex] as NameToken fun typeAnnotation(): TypeAnnotationToken = if(typeAnnotationIndex == -1) throw Exception("Type annotation not available") else nodes[typeAnnotationIndex] as TypeAnnotationToken } @Serializable data class BlockAst(override val nodes: List<Ast>, override val height: Int): StarAst<BodyAst>() { val environment: Environment by lazy { fold(EmptyEnvironment as Environment) { emptyEnvironment, bodyAst -> emptyEnvironment + bodyAst.environment } } companion object { val empty = BlockAst(emptyList(), 0) } override fun ctor(nodes: List<Ast>, height: Int) = BlockAst(nodes, height) } sealed class BodyAst: AstImpl() { abstract val environment: Environment } @Serializable data class GarbageBodyAst(val garbageAst: GarbageAst): BodyAst() { override val environment: Environment get() = BlockEnvironment(Substitution.empty, emptyMap(), emptyMap(), emptySet()) override val nodes: List<Ast> get() = garbageAst.nodes override val errors: CortecsErrors get() = CortecsErrors(span, emptyList()) } @Serializable data class LetAst(override val nodes: List<Ast>, override val errors: CortecsErrors, val nameIndex: Int, val typeAnnotationIndex: Int, val expressionIndex: Int): BodyAst() { override val environment: Environment by lazy { generateLetEnvironment(this) } fun name(): NameToken = if(nameIndex == -1) throw Exception("Name not available") else nodes[nameIndex] as NameToken fun typeAnnotation(): TypeAnnotationToken = if(typeAnnotationIndex == -1) throw Exception("TypeAnnotation not available") else nodes[typeAnnotationIndex] as TypeAnnotationToken fun expression(): Expression = if(expressionIndex == -1) throw Exception("Expression not available") else nodes[expressionIndex] as Expression } @Serializable data class ReturnAst(override val nodes: List<Ast>, override val errors: CortecsErrors, val expressionIndex: Int): BodyAst() { override val environment: Environment by lazy { generateReturnEnvironment(this) } fun expression(): Expression = if(expressionIndex == -1) throw Exception("Expression not available") else nodes[expressionIndex] as Expression } @Serializable data class IfAst(override val nodes: List<Ast>, override val errors: CortecsErrors, val conditionIndex: Int, val blockIndex: Int): BodyAst() { override val environment: Environment by lazy { generateIfEnvironment(this) } fun condition(): Expression = if(conditionIndex == -1) throw Exception("Expression not available") else nodes[conditionIndex] as Expression fun block(): BlockAst = if(blockIndex == -1) throw Exception("Expression not available") else nodes[blockIndex] as BlockAst } //P1 -> P2 P1' //P1' -> `|` P2 P1' | epsilon //P2 -> P3 P2' //P2' -> ^ P3 P2' | epsilon //P3 -> P4 P3' //P3' -> & P4 P3' | epsilon //P4 -> P5 P4' //P4' -> = P5 P4' | ! P5 P4' | epsilon //P5 -> P6 P5' //P5' -> > P6 P5' | < P6 P5' | epsilon //P6 -> P7 P6' //P6' -> + P7 P6' | - P7 P6' | epsilon //P7 -> E P7' //P7' -> * E P7' | / E P7' | % E P7' | epsilon //E -> (P1) | atom @Serializable sealed class Expression: AstImpl() { abstract val environment: Environment abstract val expressionType: Type } @Serializable sealed class BaseExpression: Expression() @Serializable data class AtomicExpression(override val nodes: List<Ast>, override val errors: CortecsErrors, val atomIndex: Int): BaseExpression() { override lateinit var expressionType: Type override val environment: Environment by lazy { val (t, e) = generateAtomicExpressionEnvironment(this) expressionType = t e } fun atom(): AtomicExpressionToken = if(atomIndex == -1) throw Exception("Name not available") else nodes[atomIndex] as AtomicExpressionToken } @Serializable data class GroupingExpression(override val nodes: List<Ast>, override val errors: CortecsErrors, val expressionIndex: Int): BaseExpression() { override lateinit var expressionType: Type override val environment: Environment by lazy { val (t, e) = generateGroupingExpressionEnvironment(this) expressionType = t e } fun expression(): Expression = if(expressionIndex == -1) throw Exception("Name not available") else nodes[expressionIndex] as Expression } @Serializable data class UnaryExpression(override val nodes: List<Ast>, override val errors: CortecsErrors, val opIndex: Int, val expressionIndex: Int): BaseExpression() { override lateinit var expressionType: Type override val environment: Environment by lazy { val (t, e) = generateUnaryExpressionEnvironment(this) expressionType = t e } fun op(): OperatorToken = if(opIndex == -1) throw Exception("op not available") else nodes[opIndex] as OperatorToken fun expression(): Expression = if(expressionIndex == -1) throw Exception("Name not available") else nodes[expressionIndex] as Expression } @Serializable data class ArgumentsAst(override val nodes: List<Ast>, override val height: Int): StarAst<ArgumentAst>() { companion object { val empty = ArgumentsAst(emptyList(), 0) } override fun ctor(nodes: List<Ast>, height: Int) = ArgumentsAst(nodes, height) } @Serializable data class ArgumentAst(override val nodes: List<Ast>, override val errors: CortecsErrors, val expressionIndex: Int): AstImpl() { fun expression(): Expression = if(expressionIndex == -1) throw Exception("Expression not available") else nodes[expressionIndex] as Expression } @Serializable data class FunctionCallExpression(override val nodes: List<Ast>, override val errors: CortecsErrors, val functionIndex: Int, val argumentsIndex: Int): BaseExpression() { override lateinit var expressionType: Type override val environment: Environment by lazy { val (t, e) = generateFunctionCallExpressionEnvironment(this) expressionType = t e } fun function(): Expression = if(functionIndex == -1) throw Exception("Name not available") else nodes[functionIndex] as Expression fun arguments(): ArgumentsAst = if(argumentsIndex == -1) throw Exception("Name not available") else nodes[argumentsIndex] as ArgumentsAst } @Serializable sealed class BinaryExpression: Expression() { abstract val lhsIndex: Int abstract val rhsIndex: Int abstract val opIndex: Int override lateinit var expressionType: Type override val environment: Environment by lazy { val (t, e) = generateBinaryExpressionEnvironment(this) expressionType = t e } fun lhs(): Expression = if(lhsIndex == -1) throw Exception("lhs not available") else nodes[lhsIndex] as Expression fun rhs(): Expression = if(rhsIndex == -1) throw Exception("rhs not available") else nodes[rhsIndex] as Expression fun op(): OperatorToken = if(opIndex == -1) throw Exception("op not available") else nodes[opIndex] as OperatorToken } @Serializable data class BinaryExpressionP1(override val nodes: List<Ast>, override val errors: CortecsErrors, override val lhsIndex: Int, override val opIndex: Int, override val rhsIndex: Int): BinaryExpression() @Serializable data class BinaryExpressionP2(override val nodes: List<Ast>, override val errors: CortecsErrors, override val lhsIndex: Int, override val opIndex: Int, override val rhsIndex: Int): BinaryExpression() @Serializable data class BinaryExpressionP3(override val nodes: List<Ast>, override val errors: CortecsErrors, override val lhsIndex: Int, override val opIndex: Int, override val rhsIndex: Int): BinaryExpression() @Serializable data class BinaryExpressionP4(override val nodes: List<Ast>, override val errors: CortecsErrors, override val lhsIndex: Int, override val opIndex: Int, override val rhsIndex: Int): BinaryExpression() @Serializable data class BinaryExpressionP5(override val nodes: List<Ast>, override val errors: CortecsErrors, override val lhsIndex: Int, override val opIndex: Int, override val rhsIndex: Int): BinaryExpression() @Serializable data class BinaryExpressionP6(override val nodes: List<Ast>, override val errors: CortecsErrors, override val lhsIndex: Int, override val opIndex: Int, override val rhsIndex: Int): BinaryExpression() @Serializable data class BinaryExpressionP7(override val nodes: List<Ast>, override val errors: CortecsErrors, override val lhsIndex: Int, override val opIndex: Int, override val rhsIndex: Int): BinaryExpression()
7
Kotlin
0
0
740f60309da3e612e2e505424db98f554ea65e3b
14,398
cortecs
MIT License
domain/src/main/kotlin/com/github/websocket/message/WebServiceRequest.kt
fengzhizi715
422,455,347
false
null
package com.github.websocket.message class WebServiceRequest private constructor(private val builder: Builder) { private var header: RequestHeaderVO?=null private var body: Map<String,Any>?=null init { header = builder.header body = builder.body } fun getHeader() = header fun getBody() = body class Builder private constructor() { var header: RequestHeaderVO?=null var body: Map<String,Any>?=null constructor(init: Builder.() -> Unit): this() { init() } fun header(init: Builder.() -> RequestHeaderVO) = apply { header = init() } fun body(init: Builder.() -> Map<String,Any>?) = apply { body = init() } fun build(): WebServiceRequest = WebServiceRequest(this) } }
0
Kotlin
0
1
b696971f0b77902eb0a970308539e340728e077a
772
websocket-demo
Apache License 2.0
scope/src/test/kotlin/dev/tcheng/common/scope/manager/ObjectManagerTest.kt
nesboy
593,404,458
false
null
package dev.tcheng.common.scope.manager import dev.tcheng.common.easyRandom.nextString import dev.tcheng.common.model.exception.InternalException import dev.tcheng.common.scope.model.Context import io.mockk.every import io.mockk.mockk import io.mockk.mockkObject import org.jeasy.random.EasyRandom import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertDoesNotThrow import org.junit.jupiter.api.assertThrows import kotlin.test.assertEquals import kotlin.test.assertNull class ObjectManagerTest { private lateinit var random: EasyRandom @BeforeEach fun setUp() { random = EasyRandom() } @Nested inner class AddObject { @BeforeEach fun setUp() { mockkObject(ContextStorageManager) } @Test fun `WHEN key is absent THEN add it context`() { // prepare val key = random.nextString() val expectedInstance = random.nextString() val context = Context() every { ContextStorageManager.peek() } returns context // execute ObjectManager.addObject(key, expectedInstance) // verify assertEquals(expected = expectedInstance, actual = context.objects[key]) } @Test fun `WHEN key is present but object is different THEN throw InternalException`() { // prepare val key = random.nextString() val instance = random.nextInt() val context = Context(objects = mutableMapOf(key to random.nextDouble())) every { ContextStorageManager.peek() } returns context // execute and verify assertThrows<InternalException> { ObjectManager.addObject(key, instance) } } @Test fun `WHEN key is present and object is same THEN no-op`() { // prepare val key = random.nextString() val instance = random.nextInt() val context = Context(objects = mutableMapOf(key to instance)) every { ContextStorageManager.peek() } returns context // execute assertDoesNotThrow { ObjectManager.addObject(key, instance) } } } @Nested inner class GetObjectOrNull { @BeforeEach fun setUp() { mockkObject(ContextStorageManager) } @Test fun `WHEN key is present and type matches THEN return object`() { // prepare val key = random.nextString() val expectedInstance = random.nextDouble() val context = Context(objects = mutableMapOf(key to expectedInstance)) every { ContextStorageManager.peek() } returns context // execute val actualInstance = ObjectManager.getObjectOrNull<Double>(key) // verify assertEquals(expected = expectedInstance, actual = actualInstance) } @Test fun `WHEN key is absent THEN return null`() { // prepare val key = random.nextString() val context = Context() every { ContextStorageManager.peek() } returns context // execute val instance = ObjectManager.getObjectOrNull<Double>(key) // verify assertNull(instance) } @Test fun `WHEN key is present but type mismatches THEN throw InternalException`() { // prepare val key = random.nextString() val instance = random.nextDouble() val context = Context(objects = mutableMapOf(key to instance)) every { ContextStorageManager.peek() } returns context // execute adn verify assertThrows<InternalException> { ObjectManager.getObjectOrNull<Int>(key) } } } @Nested inner class GetObject { @Test fun `WHEN key is present and type matches THEN return object`() { // prepare val key = random.nextString() val instanceType = String::class.java val underTest = mockk<ObjectManager>() val expectedInstance = random.nextString() every { underTest.getObject<String>(key) } answers { callOriginal() } every { underTest.getObject(key, instanceType) } answers { callOriginal() } every { underTest.getObjectOrNull(key, instanceType) } returns expectedInstance // execute val actualInstance = underTest.getObject<String>(key) // verify assertEquals(expected = expectedInstance, actual = actualInstance) } @Test fun `WHEN key is absent THEN throw InternalException`() { // prepare val key = random.nextString() val instanceType = String::class.java val underTest = mockk<ObjectManager>() every { underTest.getObject<String>(key) } answers { callOriginal() } every { underTest.getObject(key, instanceType) } answers { callOriginal() } every { underTest.getObjectOrNull(key, instanceType) } returns null // execute and verify assertThrows<InternalException> { underTest.getObject<String>(key) } } } @Nested inner class GetAllObjects { @Test fun `WHEN called THEN return all objects`() { // prepare val expectedInstances = mutableMapOf<String, Any>( random.nextString() to random.nextInt(), random.nextString() to random.nextString() ) val context = Context(objects = expectedInstances) mockkObject(ContextStorageManager) every { ContextStorageManager.peek() } returns context // execute val actualInstances = ObjectManager.getAllObjects() // verify assertEquals(expected = expectedInstances, actual = actualInstances) } } }
0
Kotlin
0
0
56ad78037f8ffbc12cfb3691059bb5d6d39272f6
6,068
common
MIT License
src/main/kotlin/hii/thing/api/vital/link/JwtLink.kt
hii-in-th
190,712,805
false
null
/* * Copyright (c) 2019 NSTDA * National Science and Technology Development Agency, Thailand * * 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 hii.thing.api.vital.link import com.auth0.jwt.JWT import com.auth0.jwt.algorithms.Algorithm import hii.thing.api.security.JwtConst import java.security.interfaces.RSAPrivateKey import java.security.interfaces.RSAPublicKey import java.util.Date import java.util.UUID /** * ตัวจัดการ Link token ในรูปแบบ JWT */ class JwtLink : Link { override fun create(refId: String): String { val jwtId = UUID.randomUUID().toString() val publicKey: RSAPublicKey = JwtConst.keyPair.publicKey val privateKey: RSAPrivateKey = JwtConst.keyPair.privateKey val algorithm = Algorithm.RSA512(publicKey, privateKey) val date = Date() val tokenAgeDay = 30 return JWT.create() .withIssuer(JwtConst.issuer) .withIssuedAt(date) .withExpiresAt(Date((tokenAgeDay * 86400000L) + date.time)) .withAudience(JwtConst.audience) .withJWTId(jwtId) .withArrayClaim("role", arrayOf("report")) .withArrayClaim("scope", arrayOf("/lresult")) .withClaim("ref", refId) .withSubject("Anonymous") .withNotBefore(date) .sign(algorithm) } override fun getRefId(link: String): String? { return JwtConst.decode(link).getClaim("ref").asString() } }
0
Kotlin
0
0
02fc485731329edfaf3ce7c4b0d5e0e98e9b9d36
1,984
thing-api
Apache License 2.0
composer/src/main/java/com/patrykkosieradzki/composer/dialog/DialogManagerImpl.kt
k0siara
391,273,596
false
null
/* * Copyright (C) 2022 Patryk Kosieradzki * * 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.patrykkosieradzki.composer.dialog import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.receiveAsFlow internal class DialogManagerImpl : DialogManager { private val channel: Channel<ComposerDialog?> = Channel(Channel.UNLIMITED) override val dialogFlow: Flow<ComposerDialog?> get() = channel.receiveAsFlow() override fun showDialog(composerDialog: ComposerDialog) { channel.trySend(composerDialog) } override fun closeDialog() { channel.trySend(null) } }
0
Kotlin
0
1
1393f26c14183041f7882e58fb2897c04a0a4b59
1,176
composer
Apache License 2.0
src/main/java/robTheSpire/powers/RarePower.kt
MillerIsa
272,558,280
false
null
package robTheSpire.powers import basemod.interfaces.CloneablePowerInterface import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion import com.megacrit.cardcrawl.actions.utility.QueueCardAction import com.megacrit.cardcrawl.cards.AbstractCard import com.megacrit.cardcrawl.core.AbstractCreature import com.megacrit.cardcrawl.core.CardCrawlGame import com.megacrit.cardcrawl.dungeons.AbstractDungeon import com.megacrit.cardcrawl.powers.AbstractPower import robTheSpire.DefaultMod.Companion.makeID import robTheSpire.cards.defaultExampleCards.DefaultRareAttack import robTheSpire.util.TextureLoader class RarePower(owner: AbstractCreature?, source: AbstractCreature, amount: Int) : AbstractPower(), CloneablePowerInterface { var source: AbstractCreature override fun atStartOfTurn() { // At the start of your turn val playCard: AbstractCard = DefaultRareAttack() // Declare Card - the DefaultRareAttack card. We will name it 'playCard'. val targetMonster = AbstractDungeon.getRandomMonster() // Declare Target - Random Monster. We will name the monster 'targetMonster'. playCard.freeToPlayOnce = true //Self Explanatory if (playCard.type != AbstractCard.CardType.POWER) { playCard.purgeOnUse = true } // Remove completely on use (Not Exhaust). A note - you don't need the '{}' in this if statement, // as it's just 1 line directly under. You can remove them, if you want. In fact, you can even put it all on 1 line: // if (playCard.type != AbstractCard.CardType.POWER) playCard.purgeOnUse = true; - works identically AbstractDungeon.actionManager.addToBottom(QueueCardAction(playCard, targetMonster)) // Play the card on the target. } override fun updateDescription() { if (amount == 1) { description = DESCRIPTIONS[0] + amount + DESCRIPTIONS[1] } else if (amount > 1) { description = DESCRIPTIONS[0] + amount + DESCRIPTIONS[2] } } override fun makeCopy(): AbstractPower { return RarePower(owner, source, amount) } companion object { val POWER_ID = makeID("RarePower") private val powerStrings = CardCrawlGame.languagePack.getPowerStrings(POWER_ID) val NAME = powerStrings.NAME val DESCRIPTIONS = powerStrings.DESCRIPTIONS // We create 2 new textures *Using This Specific Texture Loader* - an 84x84 image and a 32x32 one. private val tex84 = TextureLoader.getTexture("robTheSpireResources/images/powers/placeholder_power84.png") private val tex32 = TextureLoader.getTexture("robTheSpireResources/images/powers/placeholder_power32.png") } init { name = NAME ID = POWER_ID this.owner = owner this.amount = amount this.source = source type = PowerType.DEBUFF isTurnBased = false // We load those textures here. region128 = AtlasRegion(tex84, 0, 0, 84, 84) region48 = AtlasRegion(tex32, 0, 0, 32, 32) updateDescription() } }
0
Kotlin
0
0
4e51a202508f0d0779d303bea378107a947dbc00
3,064
Rob-the-Spire
Apache License 2.0
src/main/kotlin/no/nav/klage/oppgave/service/VedtakKafkaProducer.kt
navikt
297,650,936
false
null
package no.nav.klage.oppgave.service import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule import no.nav.klage.oppgave.domain.kafka.KlagevedtakFattet import no.nav.klage.oppgave.util.getLogger import no.nav.klage.oppgave.util.getSecureLogger import org.springframework.beans.factory.annotation.Value import org.springframework.kafka.core.KafkaTemplate import org.springframework.stereotype.Service @Service class VedtakKafkaProducer( private val aivenKafkaTemplate: KafkaTemplate<String, String> ) { @Value("\${VEDTAK_FATTET_TOPIC}") lateinit var topic: String companion object { @Suppress("JAVA_CLASS_ON_COMPANION") private val logger = getLogger(javaClass.enclosingClass) private val secureLogger = getSecureLogger() private val objectMapper = ObjectMapper().registerModule(JavaTimeModule()) } fun sendVedtak(vedtak: KlagevedtakFattet) { logger.debug("Sending to Kafka topic: {}", topic) secureLogger.debug("Sending to Kafka topic: {}\nVedtak: {}", topic, vedtak) runCatching { val result = aivenKafkaTemplate.send(topic, vedtak.kabalReferanse, vedtak.toJson()).get() logger.info("Vedtak sent to Kafka.") secureLogger.debug("Vedtak $vedtak sent to kafka ($result)") }.onFailure { val errorMessage = "Could not send vedtak to Kafka. Check secure logs for more information." logger.error(errorMessage) secureLogger.error("Could not send vedtak to Kafka", it) throw RuntimeException(errorMessage) } } private fun Any.toJson(): String = objectMapper.writeValueAsString(this) }
2
Kotlin
1
1
7255f8d9a5b0c23e4a22b5bd736d3b656790dfb7
1,725
kabal-api
MIT License
composeApp/src/commonMain/kotlin/org/example/project/App.kt
KStateMachine
625,936,057
false
{"Kotlin": 25898, "Swift": 621}
package org.example.project import androidx.compose.material.MaterialTheme import androidx.compose.runtime.* import cafe.adriel.voyager.navigator.Navigator import com.sample.kstatemachine_compose_sample.StickManGameScreen import org.jetbrains.compose.ui.tooling.preview.Preview //import cafe.adriel.voyager.jetpack.ProvideNavigatorLifecycleKMPSupport //@OptIn(ExperimentalVoyagerApi::class) @Composable @Preview fun App() { MaterialTheme { // ProvideNavigatorLifecycleKMPSupport { Navigator(StickManGameScreen()) // } } }
0
Kotlin
1
1
c301a87a7da0014d5eb13d107fe7d7c9d0080d5f
557
compose-kstatemachine-sample
MIT License
src/ressource/template/android-drawer-template/app/src/main/java/MainActivity.kt
mobile-generator
200,253,005
false
{"TypeScript": 67616, "Kotlin": 13051, "Swift": 9313, "JavaScript": 140, "Batchfile": 31}
package {{app_id}} import android.content.Intent import android.os.Bundle import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.snackbar.Snackbar import androidx.core.view.GravityCompat import androidx.appcompat.app.ActionBarDrawerToggle import android.view.MenuItem import androidx.drawerlayout.widget.DrawerLayout import com.google.android.material.navigation.NavigationView import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import android.view.Menu import kotlinx.android.synthetic.main.content_main.* class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar: Toolbar = findViewById(R.id.toolbar) setSupportActionBar(toolbar) val fab: FloatingActionButton = findViewById(R.id.fab) fab.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout) val navView: NavigationView = findViewById(R.id.nav_view) val toggle = ActionBarDrawerToggle( this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) drawerLayout.addDrawerListener(toggle) toggle.syncState() navView.setNavigationItemSelectedListener(this) setupViews() } override fun onBackPressed() { val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout) if (drawerLayout.isDrawerOpen(GravityCompat.START)) { drawerLayout.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. return when (item.itemId) { R.id.action_settings -> true else -> super.onOptionsItemSelected(item) } } override fun onNavigationItemSelected(item: MenuItem): Boolean { // Handle navigation view item clicks here. when (item.itemId) { R.id.nav_home -> { // Handle the camera action } R.id.nav_layout_guide -> { val layoutGuideIntent = Intent(this@MainActivity, LayoutGuideActivity::class.java) startActivity(layoutGuideIntent) } R.id.nav_gallery -> { } R.id.nav_slideshow -> { } R.id.nav_tools -> { } R.id.nav_share -> { } R.id.nav_send -> { } } val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout) drawerLayout.closeDrawer(GravityCompat.START) return true } private fun setupViews() { tvWelcomeMessage.text = getString(R.string.welcomeMessage) tvApplicationId.text = getString(R.string.appId, BuildConfig.APPLICATION_ID) tvApplicationVersion.text = getString(R.string.applicationVersion, BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE) tvApplicationTemplate.text = getString(R.string.template) } }
9
TypeScript
2
1
82f9e7280df336f67e464a799cf18d6931fff808
3,811
mobile-generator
MIT License
columbiad-express-domain/src/test/kotlin/org/craftsrecords/columbiadexpress/domain/search/criteria/JourneyParameterResolver.kt
ArjunDahal864
680,370,067
false
null
package org.craftsrecords.columbiadexpress.domain.search.criteria import org.craftsrecords.TypedParameterResolver import org.craftsrecords.columbiadexpress.domain.Random import org.craftsrecords.columbiadexpress.domain.search.Inbound import org.craftsrecords.columbiadexpress.domain.search.Outbound import org.craftsrecords.columbiadexpress.domain.search.RoundTrip class JourneyParameterResolver : TypedParameterResolver<Journey>({ parameterContext, _ -> when { parameterContext.isAnnotated(Random::class.java) -> { randomJourney() } parameterContext.isAnnotated(Outbound::class.java) -> { outboundJourney() } parameterContext.isAnnotated(Inbound::class.java) -> { inboundJourney() } else -> journey() } }) class JourneysParameterResolver : TypedParameterResolver<Journeys>({ parameterContext, _ -> when { parameterContext.isAnnotated(Random::class.java) -> { listOf(randomJourney()) } parameterContext.isAnnotated(RoundTrip::class.java) -> { listOf(journey(), inboundOf(journey())) } else -> listOf(journey()) } })
0
Kotlin
0
0
b06fcef38e8fa258184b91fe52e66100c518c1c1
1,191
hyperlink_based_api
MIT License
app/src/main/java/com/badger/familyorgfe/base/BaseResponse.kt
Artem-Yakovlev
435,967,282
false
{"Kotlin": 264356}
package com.badger.familyorgfe.base enum class ResponseError { NONE, FAMILY_MEMBER_DOES_NOT_EXIST, INVALID_SCANNING_CODE, FAMILY_DOES_NOT_EXISTS, USER_ALREADY_IN_FAMILY, USER_ALREADY_INVITED } data class BaseResponse<T>( val error: ResponseError = ResponseError.NONE, val data: T ) { fun hasNoErrors() = error == ResponseError.NONE }
0
Kotlin
0
1
3aa4ff1bd05efb2c9d16fd0fae0e907674817c5c
371
FamilyOrganizerAndroid
MIT License
wear/src/main/java/io/homeassistant/companion/android/onboarding/viewHolders/ManualSetupViewHolder.kt
Eff4real
415,904,592
true
{"Kotlin": 951267}
package io.homeassistant.companion.android.onboarding.viewHolders import android.view.View import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import io.homeassistant.companion.android.R class ManualSetupViewHolder(v: View, val onClick: () -> Unit) : RecyclerView.ViewHolder(v) { val text: TextView = v.findViewById(R.id.name) init { // Set onclick listener v.setOnClickListener { onClick() } } }
0
null
0
1
2edc63c062a8bb1b9c0c57ce9601043e04d8d9af
481
android-3
Apache License 2.0
src/main/kotlin/com/patronusstudio/BottleFlip/enums/AchievementEnum.kt
Patronus-Studio
506,114,514
false
{"Kotlin": 112407, "Procfile": 85}
package com.patronusstudio.BottleFlip.enums enum class AchievementEnum { REACHED,NOT_REACHED }
0
Kotlin
0
0
66330a2aa108cdd432bd2782485b5dc2d00572e5
99
Sise-Backend
Apache License 2.0
src/main/kotlin/io/github/breninsul/simpleimageconvertor/service/reader/ImageIOReader.kt
BreninSul
843,824,335
false
{"Kotlin": 82143}
package io.github.breninsul.simpleimageconvertor.service.reader import com.sksamuel.scrimage.ImmutableImage import io.github.breninsul.simpleimageconvertor.dto.ImageOrAnimation import io.github.breninsul.simpleimageconvertor.dto.Settings import java.awt.image.BufferedImage import java.io.InputStream import java.util.function.Supplier import javax.imageio.ImageIO open class ImageIOReader(private val order:Int=Int.MAX_VALUE) : ImageReader { protected open val supportedImageTypes =ImageIO.getReaderFormatNames().map { it.lowercase() }.toSet()+ setOf("svg+xml") override fun supportedTypes()=supportedImageTypes override fun read(fileStream: Supplier<InputStream>,settings: List<Settings>): ImageOrAnimation { val bufferedImage: BufferedImage = fileStream.get().use { ImageIO.read(it) } val originalImage = ImmutableImage.fromAwt(bufferedImage) return ImageOrAnimation(null,originalImage) } override fun getOrder(): Int { return order } }
0
Kotlin
0
0
3ea01775b1151bbf60a1fe3f861de394fc967ba3
1,000
simple-image-converter
MIT License
androidApp/src/main/java/org/mifos/pisp/android/old/notifications/NotificationsFragment.kt
openMF
665,697,141
false
{"Kotlin": 84180, "Swift": 343}
package org.mifos.pisp.android.old.notifications //import android.os.Bundle //import android.view.LayoutInflater //import android.view.View //import android.view.ViewGroup //import android.widget.TextView //import androidx.fragment.app.Fragment //import androidx.lifecycle.Observer //import androidx.lifecycle.ViewModelProviders //import org.mifos.openbanking.R // //class NotificationsFragment : Fragment() { // // private lateinit var notificationsViewModel: NotificationsViewModel // // override fun onCreateView( // inflater: LayoutInflater, // container: ViewGroup?, // savedInstanceState: Bundle? // ): View? { // notificationsViewModel = // ViewModelProviders.of(this).get(NotificationsViewModel::class.java) // val root = inflater.inflate(R.layout.fragment_notifications, container, false) // val textView: TextView = root.findViewById(R.id.text_notifications) // notificationsViewModel.text.observe(viewLifecycleOwner, Observer { // textView.text = it // }) // return root // } //}
1
Kotlin
2
2
6b45d62c23bbe2f7672b38a1d6952b883bcd190b
1,089
pisp-app
Apache License 2.0
domain/src/main/java/com/hxl/domain/usecase/prefs/SavePositive.kt
hexley21
507,946,022
false
{"Kotlin": 87163}
package com.hxl.domain.usecase.prefs import com.hxl.domain.repository.PreferenceRepository /** * Preference use-case that provides Positive-field save method. */ class SavePositive(private val preferenceRepository: PreferenceRepository) { operator fun invoke(value: Boolean) { preferenceRepository.savePositive(value) } }
0
Kotlin
0
1
d0f9a19c28e3646966d0c66d192109a20fc0a293
341
ArithMathics
Apache License 2.0
finance-backend/src/main/kotlin/dev/zrdzn/finance/backend/authentication/api/AuthenticationDetailsResponse.kt
zrdzn
740,479,724
false
{"Kotlin": 148135, "TypeScript": 145149, "Dockerfile": 1373, "Shell": 429, "JavaScript": 157}
package dev.zrdzn.finance.backend.authentication.api data class AuthenticationDetailsResponse( val email: String, val username: String )
13
Kotlin
0
0
22e3c57227398f89cb5ca1921a8c601837896fc8
146
finance
MIT License
app/src/main/java/im/fdx/v2ex/ui/BaseFragment.kt
fan123199
40,707,106
false
{"Markdown": 4, "Gradle Kotlin DSL": 3, "Java Properties": 2, "Text": 10, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "YAML": 2, "JSON": 1, "Proguard": 2, "XML": 166, "Kotlin": 87, "Java": 4, "Ruby": 1, "Gradle": 1}
package im.fdx.v2ex.ui import androidx.fragment.app.Fragment /** * Create by fandongxiao on 2019/5/16 */ open class BaseFragment : Fragment() { }
3
Kotlin
4
64
c0778b6aae99b19567671fd5fc858ea007f26820
149
v2ex-simple
Apache License 2.0
app/src/main/java/app/nexd/android/ui/common/Constants.kt
NexdApp
248,949,675
false
null
package app.nexd.android.ui.common abstract class Constants { companion object { const val USER_ME = "me" const val PRIVACY_POLICY_URL = "https://www.nexd.app/privacypage" } }
35
null
4
12
8c24048adc38a886447c69c7e6b4cedb2168a9a0
201
nexd-android
MIT License
src/test/kotlin/br/com/zupacademy/shared/enums/TipoDeChaveRequestTest.kt
CharlesRodrigues-01
395,076,592
true
{"Kotlin": 36191, "Smarty": 1872, "Dockerfile": 183}
package br.com.zupacademy.shared.enums import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test internal class TipoDeChaveRequestTest{ @Nested inner class CPF{ @Test fun `deve ser valido quando cpf for valido`(){ with(TipoDeChaveRequest.CPF) { assertTrue(valida("00000000000")) } } @Test fun `nao deve ser valido quando cpf for invalido`(){ with(TipoDeChaveRequest.CPF){ assertFalse(valida("000000")) } } @Test fun `nao deve ser valido quando cpf nao for passado`(){ with(TipoDeChaveRequest.CPF){ assertFalse(valida("")) } } @Test fun `nao deve ser valido quando cpf possuir letras`(){ with(TipoDeChaveRequest.CPF){ assertFalse(valida("00000Aa0000")) } } } @Nested inner class CELULAR{ @Test fun `deve ser valido quando celular for valido`(){ with(TipoDeChaveRequest.CELULAR){ assertTrue(valida("+5585988714077")) } } @Test fun `nao deve ser valido quando celular nao for valido`(){ with(TipoDeChaveRequest.CELULAR) { assertFalse(valida("5585988714077")) assertFalse(valida("+558598871407a")) } } @Test fun `nao deve ser valido quando celular nao for passado`(){ with(TipoDeChaveRequest.CELULAR){ assertFalse(valida("")) assertFalse(valida(null)) } } } @Nested inner class EMAIL{ @Test fun `deve ser valido se o email for valido`(){ with(TipoDeChaveRequest.EMAIL){ assertTrue(valida("<EMAIL>")) } } @Test fun `nao deve ser valido quando email nao for valido`(){ with(TipoDeChaveRequest.EMAIL) { assertFalse(valida("test<EMAIL>")) assertFalse(valida("<EMAIL> } } @Test fun `nao deve ser valido quando email nao for passado`(){ with(TipoDeChaveRequest.EMAIL){ assertFalse(valida("")) assertFalse(valida(null)) } } } @Nested inner class ALEATORIA{ @Test fun `deve ser valido quando chave for nula ou vazia`(){ with(TipoDeChaveRequest.ALEATORIA){ assertTrue(valida(null)) assertTrue((valida(""))) } } @Test fun `nao deve ser valido quando a chave tiver um valor`(){ with(TipoDeChaveRequest.ALEATORIA){ assertFalse(valida("teste")) } } } }
0
Kotlin
0
0
6088a94a68ec987b108aac2ff39d7c5edb448d4a
2,904
orange-talents-06-template-pix-keymanager-rest
Apache License 2.0
compiler/fir/checkers/checkers.jvm/src/org/jetbrains/kotlin/fir/analysis/jvm/checkers/JvmExpressionCheckers.kt
krzema12
312,049,057
false
null
/* * Copyright 2010-2021 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.fir.analysis.jvm.checkers import org.jetbrains.kotlin.fir.analysis.checkers.expression.ExpressionCheckers import org.jetbrains.kotlin.fir.analysis.checkers.expression.FirAnnotationCallChecker import org.jetbrains.kotlin.fir.analysis.checkers.expression.FirFunctionCallChecker import org.jetbrains.kotlin.fir.analysis.jvm.checkers.expression.FirDeprecatedJavaAnnotationsChecker import org.jetbrains.kotlin.fir.analysis.jvm.checkers.expression.FirJavaGenericVarianceViolationTypeChecker import org.jetbrains.kotlin.fir.analysis.jvm.checkers.expression.FirJvmPackageNameAnnotationsChecker import org.jetbrains.kotlin.fir.analysis.jvm.checkers.expression.FirSuperCallWithDefaultsChecker object JvmExpressionCheckers : ExpressionCheckers() { override val functionCallCheckers: Set<FirFunctionCallChecker> get() = setOf( FirJavaGenericVarianceViolationTypeChecker, FirSuperCallWithDefaultsChecker, ) override val annotationCallCheckers: Set<FirAnnotationCallChecker> get() = setOf( FirDeprecatedJavaAnnotationsChecker, FirJvmPackageNameAnnotationsChecker, ) }
34
null
2
24
af0c7cfbacc9fa1cc9bec5c8e68847b3946dc33a
1,384
kotlin-python
Apache License 2.0
couchbase-lite/src/jvmCommonMain/kotlin/kotbase/ReplicatorProgress.jvmCommon.kt
jeffdgr8
518,984,559
false
{"Kotlin": 2289925, "Python": 294}
/* * Copyright 2022-2023 Jeff Lockhart * * 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 kotbase import kotbase.internal.DelegatedClass import com.couchbase.lite.ReplicatorProgress as CBLReplicatorProgress public actual class ReplicatorProgress internal constructor(actual: CBLReplicatorProgress) : DelegatedClass<CBLReplicatorProgress>(actual) { public actual val completed: Long get() = actual.completed public actual val total: Long get() = actual.total }
0
Kotlin
0
7
188723bf0c4609b649d157988de44ac140e431dd
1,008
kotbase
Apache License 2.0
app/src/main/java/com/example/iwatchedthis/presentation/screens/home/composable/CustomSearchBarViewModel.kt
asGenn
836,220,356
false
{"Kotlin": 97097}
package com.example.iwatchedthis.presentation.screens.home.composable import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.iwatchedthis.data.Result import com.example.iwatchedthis.data.source.network.model.Movies import com.example.iwatchedthis.data.source.network.repository.MoviesRepository import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class CustomSearchBarViewModel( private val moviesRepository: MoviesRepository ) : ViewModel() { private val _queryText = MutableStateFlow<String>("") val queryText = _queryText.asStateFlow() private val active = MutableStateFlow<Boolean>(false) val isActive = active.asStateFlow() private val _movies = MutableStateFlow(Movies(emptyList(), false)) val movies = _movies.asStateFlow() fun onQueryChange(query: String) { _queryText.value = query } fun onActiveChange(isActive: Boolean) { active.value = isActive } fun getMoviesList(movieName: String) { viewModelScope.launch { moviesRepository.getMoviesList(movieName).collectLatest { result -> when (result) { is Result.Error -> active.emit(false) is Result.Success -> result.data?.let { movies -> _movies.update { movies } } } } } } }
0
Kotlin
0
0
0e4f8837068a8276c63284e317e658b349020dd3
1,560
iwatchedthis
MIT License
common/src/main/kotlin/dev/teogor/winds/common/utils/ProjectPluginUtils.kt
teogor
713,830,828
false
{"Kotlin": 243916}
/* * Copyright 2023 teogor (<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 dev.teogor.winds.common.utils import org.gradle.api.Project /** * A list of Gradle plugins that are considered publishing plugins. * These plugins are typically used to publish libraries or other artifacts to a repository. */ private val publishPlugins = listOf( "com.android.library", "com.gradle.plugin-publish", "org.jetbrains.kotlin.multiplatform", "org.jetbrains.kotlin.jvm", "org.jetbrains.kotlin.js", "java", "java-library", "java-platform", "java-gradle-plugin", "version-catalog", ) /** * Checks whether the project has the Android library plugin applied. * * @return `true` if the project has the Android library plugin applied, `false` otherwise. */ fun Project.hasAndroidLibraryPlugin(): Boolean { return plugins.hasPlugin("com.android.library") } /** * Checks whether the project has the Kotlin Multiplatform plugin applied. * * @return `true` if the project has the Kotlin Multiplatform plugin applied, `false` otherwise. */ fun Project.hasKotlinMultiplatformPlugin(): Boolean { return plugins.hasPlugin("org.jetbrains.kotlin.multiplatform") } /** * Checks whether the project has the Kotlin DSL plugin applied. * * @return `true` if the project has the Kotlin DSL plugin applied, `false` otherwise. */ fun Project.hasKotlinDslPlugin(): Boolean { return plugins.hasPlugin("org.gradle.kotlin.kotlin-dsl") } /** * Checks whether the project has any of the publishing plugins applied. * * @return `true` if the project has any of the publishing plugins applied, `false` otherwise. */ fun Project.hasPublishPlugin(): Boolean { return publishPlugins.any { plugins.hasPlugin(it) } } /** * Checks whether the project has the Winds plugin applied. * * @return `true` if the project has the Winds plugin applied, `false` otherwise. */ fun Project.hasWindsPlugin(): Boolean { return project.plugins.hasPlugin("dev.teogor.winds") } /** * Applies a given action to all child projects that have the Winds plugin applied. * * @param action The action to apply to each Wind-enabled child project. */ inline fun Project.processWindsChildProjects( crossinline action: Project.() -> Unit, ) { childProjects.values .toList() .filter { hasWindsPlugin() } .forEach { it.action() } }
0
Kotlin
0
4
71cf37d06289def68684450a7825b255ef2d97fe
2,876
winds
Apache License 2.0
WKChart/src/main/java/com/wk/view/indexSetting/IndexChildNode.kt
LLWenke
170,989,352
false
null
package com.wk.view.indexSetting import androidx.annotation.DrawableRes import com.chad.library.adapter.base.entity.node.BaseNode import com.wk.chart.enumeration.IndexType class IndexChildNode(@get:IndexType @param:IndexType val indexType: Int, val name: String, var flag: Int, val color: Int, @param:DrawableRes private val checkedImageRes: Int?, @param:DrawableRes private val unCheckedImageRes: Int?, private var enable: Boolean) : BaseNode() { @get:DrawableRes val imageRes: Int? get() = if (isEnable()) checkedImageRes else unCheckedImageRes fun isEnable(): Boolean { return enable && 0 != flag } fun setEnable(enable: Boolean) { this.enable = enable } override val childNode: MutableList<BaseNode>? get() = null }
3
null
35
84
ec4728e40beca81ef20a0f4a3b8458279595201d
1,000
InteractiveChart
Apache License 2.0
shared/src/commonMain/kotlin/util/DebugJsonHelper.kt
ChromeSD22159
825,951,465
false
{"Kotlin": 762084, "Swift": 234835}
package util import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.lighthousegames.logging.logging inline fun <reified T> debugJsonHelper(entity: T) { val jsonFormatter = Json { prettyPrint = true // For easier readability encodeDefaults = true // Encode default values } val jsonData = jsonFormatter.encodeToString(entity) logging().info { "JSON Data: $jsonData" } }
2
Kotlin
0
1
9f6048bb4321f9459bf1710176ad8691a4ffe59a
441
BauchGlueck
Apache License 2.0
domain/src/test/kotlin/no/nav/su/se/bakover/domain/revurdering/OpphørsdatoForUtbetalingerTest.kt
navikt
227,366,088
false
null
package no.nav.su.se.bakover.domain.revurdering import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldContain import io.kotest.matchers.types.beOfType import no.nav.su.se.bakover.common.desember import no.nav.su.se.bakover.common.januar import no.nav.su.se.bakover.common.mars import no.nav.su.se.bakover.common.periode.Periode import no.nav.su.se.bakover.common.startOfMonth import no.nav.su.se.bakover.domain.avkorting.AvkortingVedRevurdering import no.nav.su.se.bakover.test.nåtidForSimuleringStub import no.nav.su.se.bakover.test.simulertRevurderingOpphørtPgaVilkårFraInnvilgetSøknadsbehandlingsVedtak import no.nav.su.se.bakover.test.simulertRevurderingOpphørtUføreFraInnvilgetSøknadsbehandlingsVedtak import no.nav.su.se.bakover.test.vilkår.utenlandsoppholdAvslag import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import java.time.LocalDate internal class OpphørsdatoForUtbetalingerTest { @Test fun `opphørsdato er lik revurdering fra og med hvis ingen avkortingsvarsel`() { val revurderingsperiode = Periode.create(LocalDate.now(nåtidForSimuleringStub).startOfMonth(), 31.desember(2021)) val simulert = simulertRevurderingOpphørtUføreFraInnvilgetSøknadsbehandlingsVedtak( revurderingsperiode = revurderingsperiode, ).second OpphørsdatoForUtbetalinger(simulert).value shouldBe revurderingsperiode.fraOgMed simulert.avkorting shouldBe beOfType<AvkortingVedRevurdering.Håndtert.IngenNyEllerUtestående>() } @Test fun `opphørsdato er lik første måned uten utbetalte beløp hvis feilutbetalinger kan avkortes`() { val tidligsteFraOgMedSomIkkeErUtbetalt = LocalDate.now(nåtidForSimuleringStub).startOfMonth() val simulert = simulertRevurderingOpphørtPgaVilkårFraInnvilgetSøknadsbehandlingsVedtak( vilkårSomFørerTilOpphør = utenlandsoppholdAvslag(), ).second OpphørsdatoForUtbetalinger(simulert).value shouldBe tidligsteFraOgMedSomIkkeErUtbetalt simulert.avkorting shouldBe beOfType<AvkortingVedRevurdering.Håndtert.OpprettNyttAvkortingsvarsel>() } @Test fun `kaster exception hvis opphørsdato for utbetalinger er utenfor revurderingsperioden`() { assertThrows<IllegalStateException> { simulertRevurderingOpphørtPgaVilkårFraInnvilgetSøknadsbehandlingsVedtak( revurderingsperiode = Periode.create(1.januar(2021), 31.mars(2021)), vilkårSomFørerTilOpphør = utenlandsoppholdAvslag(periode = Periode.create(1.januar(2021), 31.mars(2021))), ).second }.also { it.message shouldContain "Opphørsdato er utenfor revurderingsperioden" } } }
4
Kotlin
0
0
d23e2f58306b48f4fe21a1c74c38085f4f4ab115
2,723
su-se-bakover
MIT License
wow-spring-boot-starter/src/main/kotlin/me/ahoo/wow/spring/boot/starter/query/QueryAutoConfiguration.kt
Ahoo-Wang
628,167,080
false
{"Kotlin": 2172043, "TypeScript": 46163, "Java": 37656, "HTML": 12915, "Lua": 3978, "JavaScript": 2288, "Dockerfile": 820, "SCSS": 500, "Less": 413}
/* * Copyright [2021-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 me.ahoo.wow.spring.boot.starter.query import me.ahoo.wow.spring.boot.starter.ConditionalOnWowEnabled import me.ahoo.wow.spring.query.SnapshotQueryServiceRegistrar import org.springframework.boot.autoconfigure.AutoConfiguration import org.springframework.context.annotation.Import /** * Query AutoConfiguration . * * @author ahoo wang */ @AutoConfiguration @Import(SnapshotQueryServiceRegistrar::class) @ConditionalOnWowEnabled class QueryAutoConfiguration
6
Kotlin
13
133
4d0e9fb736f08e002f2426f5609c0e0130ea9f2c
1,117
Wow
Apache License 2.0
runtime/src/commonMain/kotlin/space/jetbrains/api/runtime/JsonValue.kt
JetBrains
239,972,147
false
{"Kotlin": 199812}
package space.jetbrains.api.runtime public expect abstract class JsonValue public expect fun parseJson(json: String): JsonValue? /** * Must return `null` if [json] is not a valid JSON */ public expect fun tryParseJson(json: String): JsonValue? public expect fun JsonValue.print(): String internal expect fun jsonNumber(number: Number): JsonValue internal expect fun JsonValue.asNumberOrNull(): Number? internal fun JsonValue.asNumber(link: ReferenceChainLink) = asNumberOrNull() ?: deserializationError("Value is expected to be a number: " + link.referenceChain()) public expect fun jsonString(string: String): JsonValue public expect fun JsonValue.asStringOrNull(): String? internal fun JsonValue.asString(link: ReferenceChainLink): String = asStringOrNull() ?: deserializationError("Value is expected to be a string: " + link.referenceChain()) internal expect fun jsonBoolean(boolean: Boolean): JsonValue internal expect fun JsonValue.asBooleanOrNull(): Boolean? internal fun JsonValue.asBoolean(link: ReferenceChainLink): Boolean = asBooleanOrNull() ?: deserializationError("Value is expected to be a boolean: " + link.referenceChain()) internal expect fun jsonNull(): JsonValue internal expect fun JsonValue.isNull(): Boolean public expect fun jsonObject(properties: Iterable<Pair<String, JsonValue>>): JsonValue internal fun jsonObject(vararg properties: Pair<String, JsonValue>): JsonValue = jsonObject(properties.asIterable()) internal expect fun jsonObject(properties: Map<String, JsonValue>): JsonValue internal expect fun JsonValue.getField(key: String): JsonValue? /** * Must return `null` when receiver [JsonValue] is not an object. */ internal expect fun JsonValue.getFieldOrNull(key: String): JsonValue? internal expect operator fun JsonValue.set(property: String, value: JsonValue) internal expect fun JsonValue.getFieldsOrNull(): Iterable<Map.Entry<String, JsonValue>>? internal fun JsonValue.getFields(link: ReferenceChainLink): Iterable<Map.Entry<String, JsonValue>> = getFieldsOrNull() ?: deserializationError("Value is expected to be an object: " + link.referenceChain()) internal expect fun jsonArray(vararg elements: JsonValue): JsonValue internal expect fun JsonValue.arrayElementsOrNull(): Iterable<JsonValue>? internal fun JsonValue.arrayElements(link: ReferenceChainLink): Iterable<JsonValue> = arrayElementsOrNull() ?: deserializationError("Value is expected to be an array: " + link.referenceChain())
2
Kotlin
3
46
a366a1da23e7f04a070a6ace3f0b98692a4f4cf0
2,464
space-kotlin-sdk
Apache License 2.0
kord-extensions/src/main/kotlin/com/kotlindiscord/kord/extensions/annotations/BotBuilderDSL.kt
Kord-Extensions
262,018,456
false
null
package com.kotlindiscord.kord.extensions.annotations /** Marks a class or function that's part of the bot builder DSLs. **/ @DslMarker public annotation class BotBuilderDSL
15
Kotlin
14
53
c4a5a8cc8a65c0bd0928a4dcc6c05e3fc4fd75cf
175
kord-extensions
MIT License
src/boj_1969/Kotlin.kt
devetude
70,114,524
false
{"Java": 564034, "Kotlin": 80457}
package boj_1969 import java.util.StringTokenizer fun main() { val st = StringTokenizer(readln()) val n = st.nextToken().toInt() val m = st.nextToken().toInt() val dnas = Array(n) { "" } val frequencies = Array(m) { IntArray(size = 4) } repeat(n) { row -> val dna = readln() dnas[row] = dna repeat(m) { col -> when (dna[col]) { 'A' -> ++frequencies[col][0] 'C' -> ++frequencies[col][1] 'G' -> ++frequencies[col][2] else -> ++frequencies[col][3] } } } val result = buildString { var hammingDistance = 0 repeat(m) { col -> var maxFrequency = 0 var maxFrequencyIdx = 0 var frequencySum = 0 frequencies[col].forEachIndexed { idx, frequency -> if (maxFrequency < frequency) { maxFrequency = frequency maxFrequencyIdx = idx } frequencySum += frequency } hammingDistance += frequencySum - maxFrequency val nucleotide = when (maxFrequencyIdx) { 0 -> 'A' 1 -> 'C' 2 -> 'G' else -> 'T' } append(nucleotide) } appendLine() append(hammingDistance) } System.out.bufferedWriter().use { it.write(result) it.flush() } }
0
Java
7
20
4c6acff4654c49d15827ef87c8e41f972ff47222
1,490
BOJ-PSJ
Apache License 2.0
app/src/main/java/me/stayplus/paypaytest/presentation/main/MainAdapter.kt
yusufabd
318,946,158
false
null
package me.stayplus.paypaytest.presentation.main import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import me.stayplus.paypaytest.databinding.ItemQuoteBinding import me.stayplus.paypaytest.domain.entities.Quote import me.stayplus.paypaytest.extensions.formatDecimal class MainAdapter : RecyclerView.Adapter<MainAdapter.QuoteHolder>(){ private val list = ArrayList<Quote>() fun setData(newList: List<Quote>) { list.clear() list.addAll(newList) notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QuoteHolder { val itemBinding = ItemQuoteBinding.inflate(LayoutInflater.from(parent.context), parent, false) return QuoteHolder(itemBinding) } override fun onBindViewHolder(holder: QuoteHolder, position: Int) { holder.bind(list[position]) } override fun getItemCount(): Int { return list.size } inner class QuoteHolder(private val binding: ItemQuoteBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(quote: Quote) { val from = "${quote.amount.formatDecimal()} ${quote.currencyFrom}" val to = "${quote.calculateQuote().formatDecimal()} ${quote.currencyTo}" val rate = "1 ${quote.currencyFrom} = ${String.format("%2f", quote.rate)} ${quote.currencyTo}" binding.from.text = from binding.to.text = to binding.rate.text = rate } } }
0
Kotlin
0
0
c5fb5c2d14805c63eef150c0183ddb86a88aea71
1,557
paypaytest
MIT License
local_libs/lib-cloud-proxy/src/main/kotlin/gov/cdc/dex/cloud/messaging/CloudMessage.kt
CDCgov
510,836,864
false
{"Kotlin": 746627, "Scala": 208820, "Python": 44391, "Java": 18075, "Batchfile": 11894, "Go": 8661, "JavaScript": 7609, "Groovy": 4230, "HTML": 2177, "Shell": 1362, "CSS": 979}
package gov.cdc.dex.cloud.messaging abstract class CloudMessage( val id: String, val recipientHandle: String, val body: String, val queue: String ) { abstract fun key(): String override fun toString(): String { return """CloudMessage( | id='$id', | recipientHandle='$recipientHandle', | body='$body', | key='${key()}', | queue='$queue' |)""".trimMargin() } }
118
Kotlin
14
9
e859ed7c4d5feb3a97acd6e3faef1382487a689f
477
data-exchange-hl7
Apache License 2.0
android/AndroidAutoCompanion/connectionservice/src/com/google/android/libraries/car/connectionservice/PhoneSyncReceiver.kt
JoelDreaver
407,282,189
true
{"Swift": 933403, "Kotlin": 823763, "Java": 243210, "Objective-C": 9962, "Objective-C++": 8509}
// Copyright 2021 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.android.libraries.car.connectionservice import android.app.PendingIntent import android.bluetooth.le.BluetoothLeScanner import android.bluetooth.le.ScanResult import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import androidx.annotation.VisibleForTesting import com.google.android.libraries.car.trustagent.AssociationManager import com.google.android.libraries.car.trustagent.ConnectionManager import com.google.android.libraries.car.trustagent.api.PublicApi import com.google.android.libraries.car.trustagent.util.loge import com.google.android.libraries.car.trustagent.util.logi import kotlinx.coroutines.runBlocking /** A receiver that is notified for scan results matching the filters. */ @PublicApi open class PhoneSyncReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { logi(TAG, "New devices found") // Ignore the results if there is nothing to forward to. val receiverIntent = intent.getParcelableExtra(EXTRA_RECEIVER_INTENT) as? Intent if (receiverIntent == null) { loge(TAG, "Intent extra $EXTRA_RECEIVER_INTENT not set. Ignoring scan results.") return } // default value is 0 because BluetoothScanner errors are all positive. val errorCode = intent.getIntExtra(BluetoothLeScanner.EXTRA_ERROR_CODE, 0) if (errorCode != 0) { loge(TAG, "Received scanner $errorCode from $intent.") return } val results = intent.getParcelableArrayListExtra<ScanResult>(BluetoothLeScanner.EXTRA_LIST_SCAN_RESULT) if (results == null) { loge(TAG, "Received null results in intent. Ignoring.") return } logi(TAG, "Received ${results.size} scan results from $intent.") // When Bluetooth is turned off, we stop scanning. But occasionally the BluetoothAdapter // would return a null scanner since Bluetooth is turned off, thus the BLE scanning could not be // stopped. // Ignore the scan results so the experience is consistent. if (!AssociationManager.getInstance(context).isBluetoothEnabled) { logi(TAG, "Received ScanResult when Bluetooth is off. Ignored.") return } val filteredResults = ArrayList( runBlocking { ConnectionManager.getInstance(context).filterForConnectableCars(results) } ) if (filteredResults.isEmpty()) { logi(TAG, "No suitable devices in results.") return } context.startForegroundService( receiverIntent .putExtra(BluetoothLeScanner.EXTRA_ERROR_CODE, errorCode) .putParcelableArrayListExtra(PhoneSyncBaseService.EXTRA_SCAN_DEVICES, filteredResults) ) } @PublicApi companion object { const val TAG = "PhoneSyncReceiver" const val SERVICE_REQUEST_CODE = 1 const val ACTION_DEVICE_FOUND = "com.google.android.libraries.car.connectionservice.DEVICE_FOUND" @VisibleForTesting internal const val EXTRA_RECEIVER_INTENT = "com.google.android.libraries.car.connectionservice.RECEIVER_INTENT" /** * Creates a PendingIntent to this broadcast receiver. * * [receiverIntent] will be used to start the service when filtered result is available. The * service will be passed a list of devices as an `ArrayList` extra that is retrievable via the * name [PhoneSyncBaseService.EXTRA_SCAN_DEVICES]. * * If there was a scanner error, results will be ignored. Otherwise the code is retrievable via * the name [BluetoothLeScanner.EXTRA_ERROR_CODE], with a value that matches the constant in * [BluetoothLeScanner]. */ // Specify return type because // - kotlin cannot infer type properly from framework API call; // - getBroadcast() only returns null when FLAG_NO_CREATE is supplied (not nullable here). @JvmStatic fun createPendingIntent(context: Context, receiverIntent: Intent): PendingIntent = PendingIntent.getBroadcast( context, SERVICE_REQUEST_CODE, createBroadcastIntent(context, receiverIntent), PendingIntent.FLAG_UPDATE_CURRENT ) @JvmStatic fun createBroadcastIntent(context: Context, receiverIntent: Intent) = Intent(context, PhoneSyncReceiver::class.java) .setAction(ACTION_DEVICE_FOUND) .putExtra(EXTRA_RECEIVER_INTENT, receiverIntent) } }
0
null
0
0
bfb5508c818a7682ba1bec8a0744755026e3698a
4,947
android-auto-companion
Apache License 2.0
app/src/main/java/com/wrbug/developerhelper/base/BaseFragment.kt
WrBug
159,928,379
false
{"Kotlin": 261119, "Java": 8681}
package com.wrbug.developerhelper.base import androidx.fragment.app.Fragment open class BaseFragment : Fragment() { }
18
Kotlin
249
1,321
0435b0467631babfef0418692913ba74674a7c89
121
DeveloperHelper
MIT License