path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/main/kotlin/astminer/parse/antlr/python/AntlrPythonFunctionInfo.kt
JetBrains-Research
161,813,380
false
null
package astminer.parse.antlr.python import astminer.common.model.* import astminer.parse.antlr.* import astminer.parse.findEnclosingElementBy import mu.KotlinLogging private val logger = KotlinLogging.logger("Antlr-python-function-info") class AntlrPythonFunctionInfo(override val root: AntlrNode, override val filePath: String) : FunctionInfo<AntlrNode> { override val nameNode: AntlrNode? = collectNameNode() override val enclosingElement: EnclosingElement<AntlrNode>? = collectEnclosingElement() override val parameters: List<FunctionInfoParameter>? = try { collectParameters() } catch (e: IllegalStateException) { logger.warn { e.message } null } private fun collectNameNode(): AntlrNode? = root.getChildOfType(FUNCTION_NAME_NODE) private fun collectParameters(): List<FunctionInfoParameter> { val parametersRoot = root.getChildOfType(METHOD_PARAMETER_NODE) val innerParametersRoot = parametersRoot?.getChildOfType(METHOD_PARAMETER_INNER_NODE) ?: return emptyList() val methodHaveOnlyOneParameter = innerParametersRoot.lastLabelIn(listOf(METHOD_SINGLE_PARAMETER_NODE, PARAMETER_NAME_NODE)) if (methodHaveOnlyOneParameter) { return listOf(assembleMethodInfoParameter(innerParametersRoot)) } return innerParametersRoot.getChildrenOfType(METHOD_SINGLE_PARAMETER_NODE).map { node -> assembleMethodInfoParameter(node) } } private fun assembleMethodInfoParameter(parameterNode: AntlrNode): FunctionInfoParameter { val parameterHaveNoDefaultOrType = parameterNode.hasLastLabel(PARAMETER_NAME_NODE) val parameterNameNode = if (parameterHaveNoDefaultOrType) parameterNode else parameterNode.getChildOfType(PARAMETER_NAME_NODE) val parameterName = parameterNameNode?.originalToken require(parameterName != null) { "Method name was not found" } val parameterType = parameterNode.getChildOfType(PARAMETER_TYPE_NODE)?.getTokensFromSubtree() return FunctionInfoParameter( name = parameterName, type = parameterType ) } // TODO: refactor remove nested whens private fun collectEnclosingElement(): EnclosingElement<AntlrNode>? { val enclosingNode = root.findEnclosingElementBy { it.lastLabelIn(POSSIBLE_ENCLOSING_ELEMENTS) } ?: return null val type = when { enclosingNode.hasLastLabel(CLASS_DECLARATION_NODE) -> EnclosingElementType.Class enclosingNode.hasLastLabel(FUNCTION_NODE) -> if (enclosingNode.isMethod()) EnclosingElementType.Method else EnclosingElementType.Function else -> error("Enclosing node can only be function or class") } val name = when (type) { EnclosingElementType.Class -> enclosingNode.getChildOfType(CLASS_NAME_NODE) EnclosingElementType.Method, EnclosingElementType.Function -> enclosingNode.getChildOfType(FUNCTION_NAME_NODE) else -> error("Enclosing node can only be function or class") }?.originalToken return EnclosingElement( type = type, name = name, root = enclosingNode ) } private fun Node.isMethod(): Boolean { val outerBody = parent if (outerBody?.typeLabel != BODY) return false val enclosingNode = outerBody.parent require(enclosingNode != null) { "Found body without enclosing element" } val lastLabel = decompressTypeLabel(enclosingNode.typeLabel).last() return lastLabel == CLASS_DECLARATION_NODE } companion object { private const val FUNCTION_NODE = "funcdef" private const val FUNCTION_NAME_NODE = "NAME" private const val CLASS_DECLARATION_NODE = "classdef" private const val CLASS_NAME_NODE = "NAME" private const val METHOD_PARAMETER_NODE = "parameters" private const val METHOD_PARAMETER_INNER_NODE = "typedargslist" private const val METHOD_SINGLE_PARAMETER_NODE = "tfpdef" private const val PARAMETER_NAME_NODE = "NAME" private const val PARAMETER_TYPE_NODE = "test" // It's seems strange but it works because actual type label will be // test|or_test|and_test|not_test|comparison|expr|xor_expr... // ..|and_expr|shift_expr|arith_expr|term|factor|power|atom_expr|atom|NAME private val POSSIBLE_ENCLOSING_ELEMENTS = listOf(CLASS_DECLARATION_NODE, FUNCTION_NODE) private const val BODY = "suite" } }
2
null
66
192
c0bb987ac7adba3fe96a2df206160b06da73c793
4,595
astminer
MIT License
core/src/commonMain/kotlin/com/xebia/functional/xef/prompt/templates/templates.kt
xebia-functional
629,411,216
false
{"Kotlin": 4213138, "TypeScript": 67083, "Mustache": 17787, "CSS": 7836, "Java": 6473, "JavaScript": 4293, "Python": 2757, "HTML": 679}
package com.xebia.functional.xef.prompt.templates import com.xebia.functional.xef.llm.models.chat.Message import com.xebia.functional.xef.llm.models.chat.Role import com.xebia.functional.xef.prompt.message fun system(context: String): Message = context.message(Role.SYSTEM) fun assistant(context: String): Message = context.message(Role.ASSISTANT) fun user(context: String): Message = context.message(Role.USER) inline fun <reified A> system(data: A): Message = data.message(Role.SYSTEM) inline fun <reified A> assistant(data: A): Message = data.message(Role.ASSISTANT) inline fun <reified A> user(data: A): Message = data.message(Role.USER) fun steps(role: Role, content: () -> List<String>): Message = content().mapIndexed { ix, elt -> "${ix + 1} - $elt" }.joinToString("\n").message(role) fun systemSteps(content: () -> List<String>): Message = steps(Role.SYSTEM, content) fun assistantSteps(content: () -> List<String>): Message = steps(Role.ASSISTANT, content) fun userSteps(content: () -> List<String>): Message = steps(Role.USER, content) fun writeSequenceOf( content: String, prefix: String = "Step", role: Role = Role.ASSISTANT ): Message = """ Write a sequence of $content in the following format: $prefix 1 - ... $prefix 2 - ... ... $prefix N - ... """ .trimIndent() .message(role) fun code( code: String, delimiter: Delimiter?, name: String? = null, role: Role = Role.ASSISTANT ): Message = """ ${name ?: "" } ${delimiter?.start() ?: ""} $code ${delimiter?.end() ?: ""} """ .trimIndent() .message(role) enum class Delimiter { ThreeBackticks, ThreeQuotes; fun text(): String = when (this) { ThreeBackticks -> "triple backticks" ThreeQuotes -> "triple quotes" } fun start() = when (this) { ThreeBackticks -> "```" ThreeQuotes -> "\"\"\"" } fun end() = when (this) { ThreeBackticks -> "```" ThreeQuotes -> "\"\"\"" } }
39
Kotlin
11
119
0db20cf0c61a718d3c85ef6c3d49d5e5925ec145
2,039
xef
Apache License 2.0
solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAtomic.kt
tuProlog
230,784,338
false
null
package it.unibo.tuprolog.solve.streams.systemtest import it.unibo.tuprolog.solve.SolverFactory import it.unibo.tuprolog.solve.TestAtomic import it.unibo.tuprolog.solve.streams.StreamsSolverFactory import kotlin.test.Test class TestStreamsAtomic : TestAtomic, SolverFactory by StreamsSolverFactory { private val prototype = TestAtomic.prototype(this) @Test override fun testAtomicAtom() { prototype.testAtomicAtom() } @Test override fun testAtomicAofB() { prototype.testAtomicAofB() } @Test override fun testAtomicVar() { prototype.testAtomicVar() } @Test override fun testAtomicEmptyList() { prototype.testAtomicEmptyList() } @Test override fun testAtomicNum() { prototype.testAtomicNum() } @Test override fun testAtomicNumDec() { prototype.testAtomicNumDec() } }
92
null
14
93
3223ffc302e5da0efe2b254045fa1b6a1a122519
898
2p-kt
Apache License 2.0
couchbase-lite-ee/src/commonMain/ee/kotbase/ConnectionStatus.kt
jeffdgr8
518,984,559
false
null
/* * 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 /** * **ENTERPRISE EDITION API** * * Connection Status */ public expect class ConnectionStatus { /** * The count of clients currently connected to this listener. */ public val connectionCount: Int /** * The count of clients that are currently actively transferring data. * Note: this number is highly volatile. The actual number of active connections * may have changed by the time the call returns. */ public val activeConnectionCount: Int }
1
null
1
7
188723bf0c4609b649d157988de44ac140e431dd
1,115
kotbase
Apache License 2.0
services/csm.cloud.reset/src/main/kotlin/com/bosch/pt/iot/smartsite/dataimport/project/model/WorkArea.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: <NAME> Power Tools GmbH, 2018 - 2021 * * ************************************************************************ */ package com.bosch.pt.iot.smartsite.dataimport.project.model import com.bosch.pt.iot.smartsite.dataimport.common.model.ImportObject import com.bosch.pt.iot.smartsite.dataimport.common.model.UserBasedImport data class WorkArea( override val id: String, val version: Long? = null, val projectId: String, val name: String, val position: Int? = null, val etag: String, override val createWithUserId: String ) : UserBasedImport(), ImportObject
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
691
bosch-pt-refinemysite-backend
Apache License 2.0
ctp-validators/src/main/kotlin/com/commercetools/rmf/validators/TypesRule.kt
commercetools
136,635,215
false
null
package com.commercetools.rmf.validators import io.vrap.rmf.raml.model.types.util.TypesSwitch import org.eclipse.emf.common.util.Diagnostic import org.eclipse.emf.ecore.EObject abstract class TypesRule(override val severity: RuleSeverity = RuleSeverity.ERROR, val options: List<RuleOption>? = null) : TypesSwitch<List<Diagnostic>>(), DiagnosticsAware, Validator<TypesValidator> { override fun defaultCase(`object`: EObject?): List<Diagnostic> { return emptyList() } override fun ValidatorType() = TypesValidator::class.java }
21
null
6
14
1d93054f2117374f2f9384947c9d93a51f53f5ab
550
rmf-codegen
Apache License 2.0
dapp/src/main/kotlin/jp/co/soramitsu/dapp/config/DappContextConfiguration.kt
d3ledger
183,171,401
false
null
/* * Copyright D3 Ledger, Inc. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package jp.co.soramitsu.dapp.config import com.d3.commons.config.RMQConfig import com.d3.commons.config.loadRawLocalConfigs import com.d3.commons.healthcheck.HealthCheckEndpoint import com.d3.commons.sidechain.iroha.ReliableIrohaChainListener import com.d3.commons.util.createPrettySingleThreadPool import jp.co.soramitsu.iroha.java.IrohaAPI import jp.co.soramitsu.iroha.java.QueryAPI import jp.co.soramitsu.iroha.java.Utils import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import java.net.URI @Configuration class DappContextConfiguration { private val dappConfig = loadRawLocalConfigs(DAPP_NAME, DappConfig::class.java, "dapp.properties") private val rmqConfig = loadRawLocalConfigs(DAPP_NAME, RMQConfig::class.java, "rmq.properties") @Bean fun dappKeyPair() = Utils.parseHexKeypair( dappConfig.pubKey, dappConfig.privKey ) @Bean fun irohaApi() = IrohaAPI(URI(dappConfig.irohaUrl)) @Bean fun dAppAccountId() = dappConfig.accountId @Bean fun queryApi(): QueryAPI { return QueryAPI(irohaApi(), dAppAccountId(), dappKeyPair()) } @Bean fun chainListener() = ReliableIrohaChainListener( rmqConfig, dappConfig.queue, createPrettySingleThreadPool(DAPP_NAME, "chain-listener") ) @Bean fun repositoryAccountId() = dappConfig.repository @Bean fun repositorySetterId() = dappConfig.repositorySetter @Bean fun healthCheckEndpoint()=HealthCheckEndpoint(dappConfig.healthCheckPort) }
1
Kotlin
1
2
e3c0701897721030bb3faf678b197297120cc6e3
1,675
iroha-dapp
Apache License 2.0
sample-app/src/main/java/com/binbo/glvideo/sample_app/ui/advanced/activity/VideoCutSelectActivity.kt
bigbugbb
590,505,224
false
{"C": 7685938, "C++": 4393829, "Kotlin": 644772, "Java": 564403, "GLSL": 23970, "Objective-C": 7449, "CMake": 3326}
package com.binbo.glvideo.sample_app.ui.advanced.activity import android.content.pm.ActivityInfo import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.binbo.glvideo.sample_app.R import com.binbo.glvideo.sample_app.ui.advanced.fragment.VideoCutSelectFragment import com.binbo.glvideo.sample_app.ui.base.BaseActivity import com.binbo.glvideo.sample_app.utils.replaceViewWithFragment class VideoCutSelectActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_common_container) requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT replaceViewWithFragment(R.id.viewContainer, VideoCutSelectFragment::class.java) } }
0
C
0
10
e7384ea4f23ab8cc89d5701dcedaf8cdd6ecaf17
787
glvideo
MIT License
app/src/main/java/com/example/dentalapp/model/DokterGigi.kt
bilalfauzy
783,091,256
false
{"Kotlin": 160751}
package com.example.dentalapp.model import com.google.firebase.firestore.IgnoreExtraProperties @IgnoreExtraProperties data class DokterGigi( var id: String? = null, var nama: String? = null, var gender: String? = null, var spesialis: String? = null, var umur: String? = null, var fotoDokterUrl: String? = null, var rating: String? = null, )
0
Kotlin
0
0
f8bc8e672291d45fbaec325431e8f3d12a9a5067
371
Android-DentistReservation
MIT License
src/main/kotlin/org/myteer/novel/gui/volume/VolumeToolBar.kt
myteer
435,773,999
false
{"Kotlin": 631442, "CSS": 50750}
/* * Copyright (c) 2021 MTSoftware * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.myteer.novel.gui.volume import javafx.beans.binding.Bindings import javafx.collections.ObservableList import javafx.geometry.Insets import javafx.scene.control.* import org.myteer.novel.db.data.Chapter import org.myteer.novel.gui.api.Context import org.myteer.novel.gui.control.BiToolBar import org.myteer.novel.gui.utils.icon import org.myteer.novel.gui.utils.typeEquals import org.myteer.novel.i18n.i18n class VolumeToolBar( private val context: Context, private val volumeView: VolumeView, private val baseItems: ObservableList<Chapter> ) : BiToolBar() { init { buildUI() } private fun buildUI() { leftItems.addAll( buildRefreshItem(), Separator(), buildCacheInfoLabel() ) rightItems.addAll( buildSyncItem(), buildCacheItem(), buildCleanItem() ) } private fun buildRefreshItem() = Button().apply { contentDisplay = ContentDisplay.GRAPHIC_ONLY graphic = icon("reload-icon") tooltip = Tooltip(i18n("page.reload")) setOnAction { volumeView.refresh() } } private fun buildCacheInfoLabel() = Label().apply { padding = Insets(5.0) textProperty().bind(Bindings.createStringBinding({ val cachedSize = baseItems.filter { true == it.contentCached }.size i18n("chapters.cache.info", cachedSize, baseItems.size) }, baseItems)) } private fun buildSyncItem() = Button().apply { contentDisplay = ContentDisplay.GRAPHIC_ONLY graphic = icon("cloud-sync-icon") tooltip = Tooltip(i18n("chapters.cloud.sync")) setOnAction { volumeView.syncChapterListFromCloud() } } private fun buildCacheItem() = Button().apply { contentDisplay = ContentDisplay.GRAPHIC_ONLY graphic = icon("download-icon") tooltip = Tooltip(i18n("chapters.cache.all")) setOnAction { context.showConfirmationDialog( i18n("chapters.cache.all.title"), i18n("chapters.cache.all.message") ) { btn -> if (btn.typeEquals(ButtonType.YES)) { volumeView.cacheAll() } } } } private fun buildCleanItem() = Button().apply { contentDisplay = ContentDisplay.GRAPHIC_ONLY graphic = icon("clean-icon") tooltip = Tooltip(i18n("chapters.cache.clear")) setOnAction { context.showConfirmationDialog( i18n("chapters.cache.clear.title"), i18n("chapters.cache.clear.message") ) { btn -> if (btn.typeEquals(ButtonType.YES)) { volumeView.clearCache() } } } } }
0
Kotlin
0
0
6bea86cbc2b2408303175f0558262092a9562bb2
3,452
novel
Apache License 2.0
core-web-starter/src/main/kotlin/com/labijie/application/web/interceptor/HumanVerifyInterceptor.kt
hongque-pro
309,874,586
false
null
package com.labijie.application.web.interceptor import com.labijie.application.ApplicationErrors import com.labijie.application.component.IHumanChecker import com.labijie.application.web.annotation.HumanVerify import com.labijie.application.web.getRealIp import com.labijie.application.web.handler.ErrorResponse import com.labijie.infra.json.JacksonHelper import jakarta.servlet.http.HttpServletRequest import jakarta.servlet.http.HttpServletResponse import org.springframework.http.HttpStatus import org.springframework.web.method.HandlerMethod import org.springframework.web.servlet.HandlerInterceptor /** * Created with IntelliJ IDEA. * @author <NAME> * @date 2019-11-24 */ class HumanVerifyInterceptor(private val checker: IHumanChecker) : HandlerInterceptor { companion object { const val TOKEN_HTTP_NAME = "captcha" const val TOKEN_HTTP_STAMP_NAME = "captchaStamp" } override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean { val method = (handler as? HandlerMethod); if (method != null) { val anno = method.getMethodAnnotation(HumanVerify::class.java) if (anno != null) { val token = request.getHeader(TOKEN_HTTP_NAME) ?: request.getParameter(TOKEN_HTTP_NAME).orEmpty() val tokenStamp = request.getHeader(TOKEN_HTTP_STAMP_NAME) ?: request.getParameter(TOKEN_HTTP_STAMP_NAME).orEmpty() val valid = checker.check(token, tokenStamp, request.getRealIp()) if(!valid) { response.status = HttpStatus.FORBIDDEN.value() val resp = ErrorResponse( ApplicationErrors.RobotDetected, "robot detected." ) response.writer.write(JacksonHelper.serializeAsString(resp)) response.writer.flush() response.writer.close() return false } } } return true } }
0
null
0
8
9e2b1f76bbb239ae9029bd27cda2d17f96b13326
2,064
application-framework
Apache License 2.0
app/src/main/java/com/example/memoryexplorer/ui/screens/settings/SettingsScreen.kt
NiccoloBert0zzi
788,964,132
false
{"Kotlin": 100143}
package com.example.memoryexplorer.ui.screens.settings import android.widget.Toast import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Image import androidx.compose.material3.Button import androidx.compose.material3.Divider import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExposedDropdownMenuBox import androidx.compose.material3.ExposedDropdownMenuDefaults import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.graphics.Color import androidx.navigation.NavHostController import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.example.memoryexplorer.R @OptIn(ExperimentalMaterial3Api::class) @Composable fun SettingsScreen( navController: NavHostController, settingsViewModel: SettingsViewModel, ) { val theme = arrayOf(R.string.theme_system, R.string.theme_light, R.string.theme_dark) .map { stringResource(it) } .toTypedArray() val language = R.string::class.java.fields .filter { it.name.startsWith("language_") } .mapNotNull { it.getInt(it) } .map { navController.context.getString(it) } .toTypedArray() var expanded by remember { mutableStateOf(false) } var selectedText by remember { mutableStateOf(theme[0]) } Scaffold( modifier = Modifier .fillMaxSize() .padding(32.dp) ) { contentPadding -> Column( modifier = Modifier .padding(contentPadding) .fillMaxSize(), ) { Row( modifier = Modifier .fillMaxWidth() .padding(bottom = 16.dp), ) { Text( text = stringResource(R.string.select_theme) ) } Row( modifier = Modifier .fillMaxWidth() .padding(bottom = 16.dp), ) { Box( modifier = Modifier.fillMaxWidth() ) { ExposedDropdownMenuBox( expanded = expanded, onExpandedChange = { expanded = !expanded } ) { TextField( colors = TextFieldDefaults.colors( focusedContainerColor = MaterialTheme.colorScheme.secondary, unfocusedContainerColor = MaterialTheme.colorScheme.secondary, ), value = selectedText, onValueChange = { settingsViewModel.onThemeChange(selectedText) }, readOnly = true, trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) }, modifier = Modifier .menuAnchor() .fillMaxWidth() ) ExposedDropdownMenu( expanded = expanded, onDismissRequest = { expanded = false } ) { theme.forEach { item -> DropdownMenuItem( text = { Text(text = item) }, onClick = { selectedText = item expanded = false Toast.makeText(navController.context, item, Toast.LENGTH_LONG).show() } ) } } } } } Divider(color = Color.Gray, thickness = 1.dp) Row( modifier = Modifier .fillMaxWidth() .padding(top = 16.dp, bottom = 16.dp) ) { Text(text = stringResource(R.string.select_language)) } language.forEach { item -> Row( modifier = Modifier .fillMaxWidth() .padding(bottom = 16.dp), ) { Button( onClick = { Toast.makeText(navController.context, item, Toast.LENGTH_LONG).show() }, modifier = Modifier.fillMaxWidth() ) { // TODO add icon flag Icon( Icons.Filled.Image, contentDescription = "Flag icon" ) Text(text = item) } } } Divider(color = Color.Gray, thickness = 1.dp) Row( modifier = Modifier .fillMaxWidth() .padding(top = 16.dp) ) { Button( onClick = { settingsViewModel.onLogout(navController) }, modifier = Modifier.fillMaxWidth() ) { Text(text = stringResource(R.string.logout)) } } } } }
0
Kotlin
0
1
e1620dd968fc101a3152ba50d27880f158d2bbc5
6,295
MemoryExplorer
MIT License
src/main/java/morefirework/mod/block/entity/GunpowderBarrelBlockEntity.kt
Sparkierkan7
617,247,442
false
null
package morefirework.mod.block.entity import morefirework.mod.MorefireworkMod import net.minecraft.block.BlockState import net.minecraft.block.entity.BlockEntity import net.minecraft.nbt.NbtCompound import net.minecraft.network.Packet import net.minecraft.network.listener.ClientPlayPacketListener import net.minecraft.network.packet.s2c.play.BlockEntityUpdateS2CPacket import net.minecraft.util.math.BlockPos //this is useless just ignore. class GunpowderBarrelBlockEntity(pos: BlockPos?, state: BlockState?) : BlockEntity(MorefireworkMod.GUNPOWDER_BARREL_BLOCK_ENTITY, pos, state) { var fuse = 125 var primed = false // Serialize the BlockEntity public override fun writeNbt(nbt: NbtCompound) { // Save the current value of the number to the nbt nbt.putInt("fuse", fuse) nbt.putBoolean("primed", primed) super.writeNbt(nbt) } override fun readNbt(nbt: NbtCompound?) { super.readNbt(nbt) fuse = nbt!!.getInt("fuse") primed = nbt.getBoolean("primed") } override fun toUpdatePacket(): Packet<ClientPlayPacketListener?>? { return BlockEntityUpdateS2CPacket.create(this) } override fun toInitialChunkDataNbt(): NbtCompound? { return createNbt() } }
0
Kotlin
0
0
298d3b06c408b2c93ef379b4ab693905d07270a7
1,279
more_explosives_mod
MIT License
service/src/main/java/com/tink/service/statistics/StatisticsService.kt
tink-ab
245,144,086
false
null
package com.tink.service.statistics import com.tink.model.misc.Amount import com.tink.model.misc.ExactNumber import com.tink.model.statistics.Statistics import com.tink.model.time.Period import com.tink.model.user.UserProfile import com.tink.rest.apis.StatisticsApi import com.tink.rest.models.StatisticQuery import com.tink.service.time.PeriodService import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import javax.inject.Inject import com.tink.rest.models.Statistics as StatisticsDto private const val EXPENSES_IDENTIFIER = "expenses-by-category" private const val INCOME_IDENTIFIER = "income-by-category" interface StatisticsService { suspend fun query(queryDescriptor: StatisticsQueryDescriptor): List<Statistics> } data class StatisticsQueryDescriptor(val periodMode: UserProfile.PeriodMode, val currencyCode: String) internal class StatisticsServiceImpl @Inject constructor( private val api: StatisticsApi, private val periodService: PeriodService ) : StatisticsService { override suspend fun query(queryDescriptor: StatisticsQueryDescriptor): List<Statistics> { val resolution = when (queryDescriptor.periodMode) { is UserProfile.PeriodMode.Monthly -> StatisticQuery.ResolutionEnum.MONTHLY is UserProfile.PeriodMode.MonthlyAdjusted -> StatisticQuery.ResolutionEnum.MONTHLY_ADJUSTED } val statisticDtos = api.query( StatisticQuery( resolution = resolution, types = listOf( Statistics.Type.EXPENSES_BY_CATEGORY.value, Statistics.Type.INCOME_BY_CATEGORY.value ) ) ) val periodDescriptions = statisticDtos.map { it.period }.toSet() val periodsAsync = coroutineScope { periodDescriptions.map { async { periodService.getPeriod(it) } } } val periods: Map<String, Period> = periodsAsync .awaitAll() .flatten() .mapNotNull { period -> period.identifier.takeUnless { it.isBlank() }?.let { it to period } } .toMap() return statisticDtos.map { Statistics( identifier = it.description, type = it.getType(), period = periods.getValue(it.period), value = Amount(ExactNumber(it.value), queryDescriptor.currencyCode) ) } } private fun StatisticsDto.getType(): Statistics.Type = when (type) { EXPENSES_IDENTIFIER -> Statistics.Type.EXPENSES_BY_CATEGORY INCOME_IDENTIFIER -> Statistics.Type.INCOME_BY_CATEGORY else -> Statistics.Type.UNKNOWN } }
1
null
6
1
e2202bb6892e5310feaf5fa51a35714302ddb7b0
2,830
tink-core-android
MIT License
app/src/main/java/ir/android/filimo/api/RetrofitClient.kt
mahsasa71
666,846,099
false
null
package ir.android.filimo.api import retrofit2.Retrofit object RetrofitClient { var retrofit=Retrofit.Builder() .baseUrl("http://mobilemasters.ir/apps/filimo-android/") .build() }
0
Kotlin
0
0
e1ce42b484e95102194248a2a07d2efc125c4465
201
filimo
MIT License
app/src/main/java/com/transcodium/wirepurse/classes/AppAlert.kt
iagyei
165,226,708
false
null
/** # Copyright 2018 - Transcodium Ltd. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License v2.0 which accompanies this distribution. # # The Apache License v2.0 is available at # http://www.opensource.org/licenses/apache2.0.php # # You are required to redistribute this code under the same licenses. # # Project TNSMoney # @author <NAME> <<EMAIL>> # https://transcodium.com # created_at 09/08/2018 **/ package com.transcodium.wirepurse.classes import android.app.Activity import com.tapadoo.alerter.Alerter import com.transcodium.wirepurse.R import com.transcodium.wirepurse.UI import com.transcodium.wirepurse.vibrate import kotlinx.coroutines.launch class AppAlert(val activity: Activity) { private val duration = 8000L private fun alertObj(): Alerter { if(Alerter.isShowing){ Alerter.hide() } return Alerter.create(activity) .enableVibration(false) .enableIconPulse(true) .setDismissable(true) .enableSwipeToDismiss() .enableInfiniteDuration(true) } /** * error */ fun error(message: Any,autoClose : Boolean = false) = UI.launch{ activity.runOnUiThread { val alertObj = alertObj() val messageStr = if (message is Int) { activity.getString(message) } else { message.toString() } alertObj.setBackgroundColorRes(R.color.colorAccent) .setText(messageStr) .setIcon(R.drawable.ic_error_outline_pink_24dp) if (autoClose) { alertObj.enableInfiniteDuration(false) .setDuration(duration) } activity.vibrate() alertObj.show() } } /** * success */ fun success(message: Any,autoClose : Boolean = true) = UI.launch { activity.runOnUiThread { val alertObj = alertObj() val messageStr = if (message is Int) { activity.getString(message) } else { message.toString() } alertObj.setBackgroundColorRes(R.color.green) .setText(messageStr) .setIcon(R.drawable.ic_done_all_black_24dp) if (autoClose) { alertObj.enableInfiniteDuration(false) .setDuration(duration) } alertObj.show() } }//end if /** * showStatus */ fun showStatus(status: Status){ activity.runOnUiThread { if (Alerter.isShowing) { Alerter.hide() } if (status.isError()) { error(status.message(activity)) } else if (status.isSuccess()) { success(status.getMessage(activity)) } } }//end fun }//end class
1
null
1
1
a4074defab03573dce30226cbb309eb1d7ea70c1
3,018
WirePurse-Android
Apache License 2.0
src/main/kotlin/reactor/kotlin/core/publisher/FluxExtensions.kt
reactor
185,153,235
false
null
/* * Copyright (c) 2011-2018 Pivotal Software Inc, All Rights Reserved. * * 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 reactor.kotlin.core.publisher import org.reactivestreams.Publisher import reactor.core.publisher.Flux import java.util.stream.Stream import kotlin.reflect.KClass /** * Extension to convert any [Publisher] of [T] to a [Flux]. * * Note this extension doesn't make much sense on a [Flux] but it won't be converted so it * doesn't hurt. * * @author <NAME> * @since 3.1.1 */ fun <T : Any> Publisher<T>.toFlux(): Flux<T> = Flux.from(this) /** * Extension for transforming an [Iterator] to a [Flux]. * * @author <NAME> * @since 3.1 */ fun <T : Any> Iterator<T>.toFlux(): Flux<T> = toIterable().toFlux() /** * Extension for transforming an [Iterable] to a [Flux]. * * @author <NAME> * @since 3.1 */ fun <T : Any> Iterable<T>.toFlux(): Flux<T> = Flux.fromIterable(this) /** * Extension for transforming a [Sequence] to a [Flux]. * * @author <NAME> * @since 3.1 */ fun <T : Any> Sequence<T>.toFlux(): Flux<T> = Flux.fromIterable(object : Iterable<T> { override fun iterator(): Iterator<T> = [email protected]() }) /** * Extension for transforming a [Stream] to a [Flux]. * * @author <NAME> * @since 3.1 */ fun <T : Any> Stream<T>.toFlux(): Flux<T> = Flux.fromStream(this) /** * Extension for transforming a [BooleanArray] to a [Flux]. * * @author <NAME> * @since 3.1 */ fun BooleanArray.toFlux(): Flux<Boolean> = this.toList().toFlux() /** * Extension for transforming a [ByteArray] to a [Flux]. * * @author <NAME> * @since 3.1 */ fun ByteArray.toFlux(): Flux<Byte> = this.toList().toFlux() /** * Extension for transforming a [ShortArray] to a [Flux]. * * @author <NAME> * @since 3.1 */ fun ShortArray.toFlux(): Flux<Short> = this.toList().toFlux() /** * Extension for transforming a [IntArray] to a [Flux]. * * @author <NAME> * @since 3.1 */ fun IntArray.toFlux(): Flux<Int> = this.toList().toFlux() /** * Extension for transforming a [LongArray] to a [Flux]. * * @author <NAME> * @since 3.1 */ fun LongArray.toFlux(): Flux<Long> = this.toList().toFlux() /** * Extension for transforming a [FloatArray] to a [Flux]. * * @author <NAME> * @since 3.1 */ fun FloatArray.toFlux(): Flux<Float> = this.toList().toFlux() /** * Extension for transforming a [DoubleArray] to a [Flux]. * * @author <NAME> * @since 3.1 */ fun DoubleArray.toFlux(): Flux<Double> = this.toList().toFlux() /** * Extension for transforming an [Array] to a [Flux]. * * @author <NAME> * @since 3.1 */ fun <T> Array<out T>.toFlux(): Flux<T> = Flux.fromArray(this) private fun <T> Iterator<T>.toIterable() = object : Iterable<T> { override fun iterator(): Iterator<T> = this@toIterable } /** * Extension for transforming an exception to a [Flux] that completes with the specified error. * * @author <NAME> * @since 3.1 */ fun <T> Throwable.toFlux(): Flux<T> = Flux.error(this) /** * Extension for [Flux.cast] providing a `cast<Foo>()` variant. * * @author <NAME> * @since 3.1 */ inline fun <reified T : Any> Flux<*>.cast(): Flux<T> = cast(T::class.java) /** * Extension for [Flux.doOnError] providing a [KClass] based variant. * * @author <NAME> * @since 3.1 */ fun <T, E : Throwable> Flux<T>.doOnError(exceptionType: KClass<E>, onError: (E) -> Unit): Flux<T> = doOnError(exceptionType.java) { onError(it) } /** * Extension for [Flux.onErrorMap] providing a [KClass] based variant. * * @author <NAME> * @since 3.1 */ fun <T, E : Throwable> Flux<T>.onErrorMap(exceptionType: KClass<E>, mapper: (E) -> Throwable): Flux<T> = onErrorMap(exceptionType.java) { mapper(it) } /** * Extension for [Flux.ofType] providing a `ofType<Foo>()` variant. * * @author <NAME> * @since 3.1 */ inline fun <reified T : Any> Flux<*>.ofType(): Flux<T> = ofType(T::class.java) /** * Extension for [Flux.onErrorResume] providing a [KClass] based variant. * * @author <NAME> * @since 3.1 */ fun <T : Any, E : Throwable> Flux<T>.onErrorResume(exceptionType: KClass<E>, fallback: (E) -> Publisher<T>): Flux<T> = onErrorResume(exceptionType.java) { fallback(it) } /** * Extension for [Flux.onErrorReturn] providing a [KClass] based variant. * * @author <NAME> * @since 3.1 */ fun <T : Any, E : Throwable> Flux<T>.onErrorReturn(exceptionType: KClass<E>, value: T): Flux<T> = onErrorReturn(exceptionType.java, value) /** * Extension for flattening [Flux] of [Iterable] * * @author <NAME> * @since 3.1 */ fun <T : Any> Flux<out Iterable<T>>.split(): Flux<T> = this.flatMapIterable { it } /** * Extension for [Flux.switchIfEmpty] accepting a function providing a Publisher. This allows having a deferred execution with * the [switchIfEmpty] operator * * @author <NAME> * @since 3.2 */ fun <T> Flux<T>.switchIfEmpty(s: () -> Publisher<T>): Flux<T> = this.switchIfEmpty(Flux.defer { s() })
82
null
960
91
f885aef3e1914cb42ee6a8ca9d9f0d6bd8f2e829
5,439
reactor-kotlin-extensions
Apache License 2.0
remote-robot/src/main/kotlin/com/intellij/remoterobot/fixtures/dataExtractor/server/textCellRenderers/JComboBoxTextCellReader.kt
JetBrains
301,411,608
false
null
package com.intellij.remoterobot.fixtures.dataExtractor.server.textCellRenderers import com.intellij.remoterobot.fixtures.dataExtractor.server.TextParser import org.assertj.swing.cell.JComboBoxCellReader import java.awt.Dimension import javax.swing.JComboBox import javax.swing.JList import javax.swing.ListCellRenderer class JComboBoxTextCellReader : JComboBoxCellReader { override fun valueAt(comboBox: JComboBox<*>, index: Int): String? { return computeOnEdt { @Suppress("UNCHECKED_CAST") val renderer = comboBox.renderer as ListCellRenderer<Any> val c = renderer.getListCellRendererComponent(JList(), comboBox.getItemAt(index), index, true, true) c.size = Dimension(comboBox.width, 100) TextParser.parseCellRenderer(c).joinToString(" ") { it.trim() } } } }
7
null
27
98
f89c6eb1976a10dbb9feff72fcb778716649c8f5
834
intellij-ui-test-robot
Apache License 2.0
src/io/File.kt
q-lang
128,704,097
false
null
package io import kotlin.coroutines.experimental.buildSequence private fun lines(filename: String) = buildSequence { java.io.File(filename).useLines { yieldAll(it) } } data class File(val filename: String) { fun lines(): Sequence<String> { return lines(filename) } }
0
Kotlin
1
0
2d8a8b4d32ae8ec5b8ed9cce099bd58f37838833
281
q-lang
MIT License
wallet/src/main/java/com/fzm/chat/wallet/ui/coins/CoinViewModel.kt
txchat
507,831,442
false
{"Kotlin": 2234450, "Java": 384844}
package com.fzm.chat.wallet.ui.coins import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.asLiveData import com.fzm.chat.biz.base.AppConst import com.fzm.chat.core.session.LoginDelegate import com.fzm.wallet.sdk.BWallet import com.fzm.wallet.sdk.db.entity.AddCoinTabBean import com.fzm.wallet.sdk.db.entity.Coin import com.zjy.architecture.data.Result import com.zjy.architecture.mvvm.LoadingViewModel import com.zjy.architecture.mvvm.request import kotlinx.coroutines.flow.onEach /** * @author zhengjy * @since 2022/02/28 * Description: */ class CoinViewModel(private val delegate: LoginDelegate) : LoadingViewModel() { private val _chainAssets by lazy { MutableLiveData<List<AddCoinTabBean>>() } val chainAssets: LiveData<List<AddCoinTabBean>> get() = _chainAssets private val _searchResult by lazy { MutableLiveData<List<Coin>>() } val searchResult: LiveData<List<Coin>> get() = _searchResult val homeCoins by lazy { BWallet.get().getCoinsFlow().onEach { coins -> netCoinsMap.putAll( coins.filter { it.netId != null } .associateBy { it.netId } ) }.asLiveData(coroutineContext) } val netCoinsMap = HashMap<String, Coin>() fun hasPassword() = delegate.preference.hasChatPassword() fun searchCoins(page: Int, keywords: String, chain: String, platform: String) { request<List<Coin>> { onRequest { try { val coins = BWallet.get() .searchCoins(page, AppConst.PAGE_SIZE, keywords, chain, platform) Result.Success(coins) } catch (e: Exception) { Result.Error(e) } } onSuccess { _searchResult.value = it } } } fun addCoin(coin: Coin, index: Int, password: suspend () -> String) { request<Unit>(loading = false) { onRequest { Result.Success(BWallet.get().addCoins(listOf(coin), password)) } } } fun removeCoin(coin: Coin, index: Int) { request<Unit>(loading = false) { onRequest { Result.Success(BWallet.get().deleteCoins(listOf(coin))) } } } fun getChainAssets() { request<List<AddCoinTabBean>> { onRequest { Result.Success(BWallet.get().getChainAssets()) } onSuccess { _chainAssets.value = it } } } }
0
Kotlin
1
1
6a3c6edf6ae341199764d4d08dffd8146877678b
2,636
ChatPro-Android
MIT License
kzmq-cio/src/commonMain/kotlin/org/zeromq/internal/InvalidReadFrame.kt
ptitjes
386,722,015
false
null
/* * Copyright (c) 2021-2024 <NAME> and Kzmq contributors. * Use of this source code is governed by the Apache 2.0 license. */ package org.zeromq.internal internal class InvalidReadFrame( override val message: String, override val cause: Throwable? = null ) : ProtocolError(message, cause) internal fun invalidFrame(message: String): Nothing = throw InvalidReadFrame(message)
21
null
1
6
1e6c7a35b7dc93b34a8f6da9d56fd5b3335dd790
390
kzmq
Apache License 2.0
springboot-flutter/springboot/src/main/kotlin/com/ghrcosta/planningpoker/controller/TaskController.kt
ghrcosta
463,750,399
false
{"Kotlin": 100515, "Dart": 41347, "HTML": 1838}
package com.ghrcosta.planningpoker.controller import com.ghrcosta.planningpoker.service.RoomService import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.responses.ApiResponse import io.swagger.v3.oas.annotations.tags.Tag import kotlinx.coroutines.runBlocking import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("/task") @Tag(name = "taskApi", description = "API used internally by GCP App Engine Cron Jobs") class TaskController(private val roomService: RoomService) { /** * Endpoint called by a GAE Cron Job. */ @GetMapping("/cleanup") // Must be GET because it's called automatically by GCP @ResponseStatus(HttpStatus.NO_CONTENT) @Operation( summary = "Clear database", description = "Called periodically by a GCP App Engine Cron Job to remove all rooms from the database.") @ApiResponse( responseCode = "204", description = "Database cleared") fun cleanStorage() = runBlocking { roomService.deleteAllRooms() } }
0
Kotlin
0
0
98b7f3dae0ede6fa4ee1a050bd7bad0672667099
1,294
planning-poker
MIT License
app/src/main/java/com/raheemjnr/jr_music/ui/components/BottomNavBar.kt
RaheemJnr
489,742,823
false
{"Kotlin": 153287}
package com.raheemjnr.jr_music.ui.components import MainScreen import android.annotation.SuppressLint import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.animation.animateContentSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material.BottomNavigation import androidx.compose.material.BottomNavigationItem import androidx.compose.material.Icon import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.navigation.NavController import androidx.navigation.NavGraph.Companion.findStartDestination import androidx.navigation.compose.currentBackStackEntryAsState @SuppressLint("MutableCollectionMutableState") @ExperimentalAnimationApi @Composable fun BottomNav(navController: NavController) { // val dimension by remember { mutableStateOf(arrayListOf(35, 35)) } HomeBottomItem(dimension, navController) } @Composable private fun HomeBottomItem( dimension: ArrayList<Int>, navController: NavController ) { val navBackStackEntry by navController.currentBackStackEntryAsState() val currentRoute = navBackStackEntry?.destination?.route BottomNavigation( modifier = Modifier .padding(40.dp, 0.dp, 30.dp, 0.dp) .height(100.dp), backgroundColor = Color.White, elevation = 0.dp ) { items.forEach { BottomNavigationItem( alwaysShowLabel = true, modifier = Modifier, icon = { it.icon?.let { icon -> Icon( painter = painterResource(id = icon), contentDescription = "", modifier = Modifier .width(dimension[it.index!!].dp) .height(dimension[it.index].dp) .animateContentSize(), ) } }, label = { it.title?.let { labelValue -> Text( text = labelValue, color = Color.LightGray ) } }, // selected = currentRoute == it.route, onClick = { it.route?.let { destination -> navController.navigate(destination) { // Pop up to the start destination of the graph to // avoid building up a large stack of destinations // on the back stack as users select items popUpTo(navController.graph.findStartDestination().id) { saveState = true } // Avoid multiple copies of the same destination when // reSelecting the same item launchSingleTop = true // Restore state when reSelecting a previously selected item restoreState = true } } dimension.forEachIndexed { index, _ -> if (index == it.index) dimension[index] = 36 else dimension[index] = 35 } }, selectedContentColor = Color.Black, unselectedContentColor = Color.Green, ) } } } val items = listOf(MainScreen.Local, MainScreen.Gap, MainScreen.Online)
0
Kotlin
0
0
43a64f07137c6b3be5b5a381c31ee9a6a57a7be5
4,151
Jr-Music-Player
MIT License
domain/client/src/main/kotlin/io/github/siyual_park/client/domain/auth/ClientPrincipal.kt
siyul-park
403,557,925
false
null
package io.github.siyual_park.client.domain.auth import io.github.siyual_park.auth.domain.Principal import io.github.siyual_park.auth.domain.scope_token.ScopeToken import io.github.siyual_park.client.entity.ClientAssociable import io.github.siyual_park.ulid.ULID data class ClientPrincipal( override val id: ULID = ULID.randomULID(), override val clientId: ULID, override var scope: Set<ScopeToken>, ) : Principal, ClientAssociable
10
Kotlin
0
18
9e01acd48ed3d47b43b0126482ea160e18b88099
446
spring-webflux-multi-module-boilerplate
MIT License
codebase/android/feature/accounts/src/main/java/com/makeappssimple/abhimanyu/financemanager/android/feature/accounts/edit_account/viewmodel/EditAccountScreenViewModel.kt
Abhimanyu14
429,663,688
false
{"Kotlin": 1907509}
package com.makeappssimple.abhimanyu.financemanager.android.feature.accounts.edit_account.viewmodel import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.input.TextFieldValue import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.viewModelScope import com.makeappssimple.abhimanyu.financemanager.android.core.common.coroutines.di.ApplicationScope import com.makeappssimple.abhimanyu.financemanager.android.core.common.datetime.DateTimeUtil import com.makeappssimple.abhimanyu.financemanager.android.core.common.extensions.combineAndCollectLatest import com.makeappssimple.abhimanyu.financemanager.android.core.common.extensions.map import com.makeappssimple.abhimanyu.financemanager.android.core.common.extensions.orZero import com.makeappssimple.abhimanyu.financemanager.android.core.data.usecase.account.GetAccountUseCase import com.makeappssimple.abhimanyu.financemanager.android.core.data.usecase.account.GetAllAccountsUseCase import com.makeappssimple.abhimanyu.financemanager.android.core.data.usecase.account.UpdateAccountsUseCase import com.makeappssimple.abhimanyu.financemanager.android.core.data.usecase.transaction.InsertTransactionsUseCase import com.makeappssimple.abhimanyu.financemanager.android.core.model.Account import com.makeappssimple.abhimanyu.financemanager.android.core.model.AccountType import com.makeappssimple.abhimanyu.financemanager.android.core.navigation.Navigator import com.makeappssimple.abhimanyu.financemanager.android.core.ui.base.ScreenViewModel import com.makeappssimple.abhimanyu.financemanager.android.core.ui.component.chip.ChipUIData import com.makeappssimple.abhimanyu.financemanager.android.core.ui.extensions.icon import com.makeappssimple.abhimanyu.financemanager.android.feature.accounts.edit_account.screen.EditAccountScreenUIVisibilityData import com.makeappssimple.abhimanyu.financemanager.android.feature.accounts.edit_account.state.EditAccountScreenNameError import com.makeappssimple.abhimanyu.financemanager.android.feature.accounts.edit_account.state.EditAccountScreenUIState import com.makeappssimple.abhimanyu.financemanager.android.feature.accounts.edit_account.state.EditAccountScreenUIStateEvents import com.makeappssimple.abhimanyu.financemanager.android.feature.accounts.edit_account.usecase.EditAccountScreenDataValidationUseCase import com.makeappssimple.abhimanyu.financemanager.android.feature.accounts.navigation.EditAccountScreenArgs import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel public class EditAccountScreenViewModel @Inject constructor( @ApplicationScope coroutineScope: CoroutineScope, savedStateHandle: SavedStateHandle, private val dateTimeUtil: DateTimeUtil, private val editAccountScreenDataValidationUseCase: EditAccountScreenDataValidationUseCase, private val getAllAccountsUseCase: GetAllAccountsUseCase, private val getAccountUseCase: GetAccountUseCase, private val insertTransactionsUseCase: InsertTransactionsUseCase, private val navigator: Navigator, private val updateAccountsUseCase: UpdateAccountsUseCase, ) : ScreenViewModel( viewModelScope = coroutineScope, ), EditAccountScreenUIStateDelegate by EditAccountScreenUIStateDelegateImpl( coroutineScope = coroutineScope, dateTimeUtil = dateTimeUtil, insertTransactionsUseCase = insertTransactionsUseCase, navigator = navigator, updateAccountsUseCase = updateAccountsUseCase, ) { // region screen args private val screenArgs = EditAccountScreenArgs( savedStateHandle = savedStateHandle, ) // endregion // region initial data private var allAccounts: ImmutableList<Account> = persistentListOf() // endregion // region uiStateAndStateEvents internal val uiState: MutableStateFlow<EditAccountScreenUIState> = MutableStateFlow( value = EditAccountScreenUIState(), ) internal val uiStateEvents: EditAccountScreenUIStateEvents = EditAccountScreenUIStateEvents( clearBalanceAmountValue = ::clearBalanceAmountValue, clearMinimumAccountBalanceAmountValue = ::clearMinimumAccountBalanceAmountValue, clearName = ::clearName, navigateUp = ::navigateUp, resetScreenBottomSheetType = ::resetScreenBottomSheetType, setMinimumAccountBalanceAmountValue = ::setMinimumAccountBalanceAmountValue, setName = ::setName, setBalanceAmountValue = ::setBalanceAmountValue, setScreenBottomSheetType = ::setScreenBottomSheetType, setScreenSnackbarType = ::setScreenSnackbarType, setSelectedAccountTypeIndex = ::setSelectedAccountTypeIndex, updateAccount = ::updateAccount, ) // endregion // region initViewModel internal fun initViewModel() { fetchData() observeData() } private fun fetchData() { viewModelScope.launch { withLoadingSuspend { getAllAccounts() getCurrentAccount() } } } private fun observeData() { observeForUiStateAndStateEvents() } // endregion // region getAllAccounts private suspend fun getAllAccounts() { allAccounts = getAllAccountsUseCase() } // endregion // region getCurrentAccount private fun getCurrentAccount() { val currentAccountId = screenArgs.accountId ?: return // TODO(Abhi): Throw exception here viewModelScope.launch { currentAccount = getAccountUseCase( id = currentAccountId, ) currentAccount?.let { currentAccount -> setSelectedAccountTypeIndex( validAccountTypesForNewAccount.indexOf( element = currentAccount.type, ) ) setName( name.value .copy( text = currentAccount.name, ) ) setBalanceAmountValue( TextFieldValue( text = currentAccount.balanceAmount.value.toString(), selection = TextRange(currentAccount.balanceAmount.value.toString().length), ) ) currentAccount.minimumAccountBalanceAmount?.let { minimumAccountBalanceAmount -> setMinimumAccountBalanceAmountValue( TextFieldValue( text = minimumAccountBalanceAmount.value.toString(), selection = TextRange(minimumAccountBalanceAmount.value.toString().length), ) ) } } } } // endregion // region observeForUiStateAndStateEvents private fun observeForUiStateAndStateEvents() { viewModelScope.launch { combineAndCollectLatest( isLoading, screenBottomSheetType, name, selectedAccountTypeIndex, minimumAccountBalanceAmountValue, balanceAmountValue, ) { ( isLoading, screenBottomSheetType, name, selectedAccountTypeIndex, minimumAccountBalanceAmountValue, balanceAmountValue, ), -> val selectedAccountType = validAccountTypesForNewAccount.getOrNull( selectedAccountTypeIndex ) val validationState = editAccountScreenDataValidationUseCase( allAccounts = allAccounts, enteredName = name.text.trim(), currentAccount = currentAccount, ) uiState.update { EditAccountScreenUIState( screenBottomSheetType = screenBottomSheetType, isLoading = isLoading, isCtaButtonEnabled = validationState.isCtaButtonEnabled, nameError = validationState.nameError, selectedAccountTypeIndex = selectedAccountTypeIndex.orZero(), accountTypesChipUIDataList = validAccountTypesForNewAccount .map { accountType -> ChipUIData( text = accountType.title, icon = accountType.icon, ) }, balanceAmountValue = balanceAmountValue, minimumBalanceAmountValue = minimumAccountBalanceAmountValue, name = name, visibilityData = EditAccountScreenUIVisibilityData( balanceAmountTextField = true, minimumBalanceAmountTextField = selectedAccountType == AccountType.BANK, nameTextField = validationState.isCashAccount.not(), nameTextFieldErrorText = validationState.nameError != EditAccountScreenNameError.None, accountTypesRadioGroup = validationState.isCashAccount.not(), ), ) } } } } // endregion }
12
Kotlin
0
3
e71d6e6f959dfbf2bcf555a13a115d83c796b11b
9,807
finance-manager
Apache License 2.0
core/src/main/kotlin/io/rover/campaigns/core/tracking/Interfaces.kt
RoverPlatform
177,201,916
false
null
package io.rover.campaigns.core.tracking import io.rover.campaigns.core.data.domain.Attributes import java.util.UUID interface SessionStoreInterface { /** * Enters a session. * * Returns the new session's UUID, or, if a session is already active, null. */ fun enterSession(sessionKey: Any, sessionEventName: String, attributes: Attributes) fun leaveSession(sessionKey: Any) /** * Returns the soonest time that a session is going to expire. */ fun soonestExpiryInSeconds(keepAliveSeconds: Int): Int? /** * Returns the sessions that are expired and should have their event emitted. * * Such sessions will only be returned once; they are deleted. */ fun collectExpiredSessions(keepAliveSeconds: Int): List<ExpiredSession> data class ExpiredSession( val sessionKey: Any, val uuid: UUID, val eventName: String, val attributes: Attributes, val durationSeconds: Int ) } interface SessionTrackerInterface { /** * Indicate a session is opening for the given session key. The Session Key should be a value * object (a Kotlin data class, a string, etc.) that properly implements hashcode, equals, and * an exhaustive version of toString(). This value object should describe the given semantic * item the user is looking at (a given experience, a given view, etc.). * * Note that the values need to be unique amongst the different event sources in the app, so be * particularly careful with string values or data class class names. * * A [sessionEventName] must be provided so that the Session Tracker can emit session viewed * after the timeout completes. */ fun enterSession( sessionKey: Any, sessionStartEventName: String, sessionEventName: String, attributes: Attributes ) /** * Indicate a session is being left. See [enterSession] for an explanation of session key. */ fun leaveSession( sessionKey: Any, sessionEndEventName: String, attributes: Attributes ) }
1
null
1
1
5f06b8393a7848c6f038819f84db772faa3ccb6c
2,134
rover-campaigns-android
Apache License 2.0
longan/src/main/java/com/dylanc/longan/SystemBars.kt
DylanCaiCoding
299,663,353
false
{"Kotlin": 234095}
/* * Copyright (c) 2021. Dylan Cai * * 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. */ @file:Suppress("unused") package com.dylanc.longan import android.app.Activity import android.graphics.Color import android.view.View import android.view.ViewGroup import androidx.annotation.ColorInt import androidx.core.view.WindowInsetsCompat.Type import androidx.core.view.WindowInsetsControllerCompat import androidx.core.view.updateLayoutParams import androidx.core.view.updateMargins import androidx.core.view.updatePadding import androidx.fragment.app.Fragment fun Fragment.immerseStatusBar(lightMode: Boolean = true) { activity?.immerseStatusBar(lightMode) } fun Activity.immerseStatusBar(lightMode: Boolean = true) { decorFitsSystemWindows = false window.decorView.windowInsetsControllerCompat?.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE transparentStatusBar() isLightStatusBar = lightMode contentView.addNavigationBarHeightToMarginBottom() } inline var Fragment.isLightStatusBar: Boolean get() = activity?.isLightStatusBar == true set(value) { view?.post { activity?.isLightStatusBar = value } } inline var Activity.isLightStatusBar: Boolean get() = window.decorView.windowInsetsControllerCompat?.isAppearanceLightStatusBars == true set(value) { window.decorView.windowInsetsControllerCompat?.isAppearanceLightStatusBars = value } inline var Fragment.statusBarColor: Int get() = activity?.statusBarColor ?: -1 set(value) { activity?.statusBarColor = value } @setparam:ColorInt inline var Activity.statusBarColor: Int get() = window.statusBarColor set(value) { window.statusBarColor = value } fun Fragment.transparentStatusBar() { activity?.transparentStatusBar() } fun Activity.transparentStatusBar() { statusBarColor = Color.TRANSPARENT } inline var Fragment.isStatusBarVisible: Boolean get() = activity?.isStatusBarVisible == true set(value) { activity?.isStatusBarVisible = value } inline var Activity.isStatusBarVisible: Boolean get() = window.decorView.isStatusBarVisible set(value) { window.decorView.isStatusBarVisible = value } inline var View.isStatusBarVisible: Boolean get() = rootWindowInsetsCompat?.isVisible(Type.statusBars()) == true set(value) { windowInsetsControllerCompat?.run { if (value) show(Type.statusBars()) else hide(Type.statusBars()) } } val statusBarHeight: Int get() = topActivity.window.decorView.rootWindowInsetsCompat?.getInsets(Type.statusBars())?.top ?: application.resources.getIdentifier("status_bar_height", "dimen", "android") .let { if (it > 0) application.resources.getDimensionPixelSize(it) else 0 } fun View.addStatusBarHeightToMarginTop() = post { if (isStatusBarVisible && isAddedMarginTop != true) { updateLayoutParams<ViewGroup.MarginLayoutParams> { updateMargins(top = topMargin + statusBarHeight) isAddedMarginTop = true } } } fun View.subtractStatusBarHeightToMarginTop() = post { if (isStatusBarVisible && isAddedMarginTop == true) { updateLayoutParams<ViewGroup.MarginLayoutParams> { updateMargins(top = topMargin - statusBarHeight) isAddedMarginTop = false } } } fun View.addStatusBarHeightToPaddingTop() = post { if (isAddedPaddingTop != true) { updatePadding(top = paddingTop + statusBarHeight) updateLayoutParams { height = measuredHeight + statusBarHeight } isAddedPaddingTop = true } } fun View.subtractStatusBarHeightToPaddingTop() = post { if (isAddedPaddingTop == true) { updatePadding(top = paddingTop - statusBarHeight) updateLayoutParams { height = measuredHeight - statusBarHeight } isAddedPaddingTop = false } } inline var Fragment.isLightNavigationBar: Boolean get() = activity?.isLightNavigationBar == true set(value) { activity?.isLightNavigationBar = value } inline var Activity.isLightNavigationBar: Boolean get() = window.decorView.windowInsetsControllerCompat?.isAppearanceLightNavigationBars == true set(value) { window.decorView.windowInsetsControllerCompat?.isAppearanceLightNavigationBars = value } fun Fragment.transparentNavigationBar() { activity?.transparentNavigationBar() } fun Activity.transparentNavigationBar() { navigationBarColor = Color.TRANSPARENT } inline var Fragment.navigationBarColor: Int get() = activity?.navigationBarColor ?: -1 set(value) { activity?.navigationBarColor = value } inline var Activity.navigationBarColor: Int get() = window.navigationBarColor set(value) { window.navigationBarColor = value } inline var Fragment.isNavigationBarVisible: Boolean get() = activity?.isNavigationBarVisible == true set(value) { activity?.isNavigationBarVisible = value } inline var Activity.isNavigationBarVisible: Boolean get() = window.decorView.isNavigationBarVisible set(value) { window.decorView.isNavigationBarVisible = value } inline var View.isNavigationBarVisible: Boolean get() = rootWindowInsetsCompat?.isVisible(Type.navigationBars()) == true set(value) { windowInsetsControllerCompat?.run { if (value) show(Type.navigationBars()) else hide(Type.navigationBars()) } } val navigationBarHeight: Int get() = topActivity.window.decorView.rootWindowInsetsCompat?.getInsets(Type.navigationBars())?.bottom ?: application.resources.getIdentifier("navigation_bar_height", "dimen", "android") .let { if (it > 0) application.resources.getDimensionPixelSize(it) else 0 } fun View.addNavigationBarHeightToMarginBottom() = post { if (isNavigationBarVisible && isAddedMarginBottom != true) { updateLayoutParams<ViewGroup.MarginLayoutParams> { updateMargins(bottom = bottomMargin + navigationBarHeight) isAddedMarginBottom = true } } } fun View.subtractNavigationBarHeightToMarginBottom() = post { if (isNavigationBarVisible && isAddedMarginBottom == true) { updateLayoutParams<ViewGroup.MarginLayoutParams> { updateMargins(bottom = bottomMargin - navigationBarHeight) isAddedMarginBottom = false } } }
9
Kotlin
66
539
c21dd7e9b84e4fd65c424e9cfc524dbf35f9761b
6,631
Longan
Apache License 2.0
src/main/kotlin/com/github/poolParty/pullPartyBot/handler/message/PullPartyMessages.kt
pool-party
276,690,235
false
null
package com.github.poolParty.pullPartyBot.handler.message object PullPartyMessages { val empty = """ I could call up all parties, but it doesn't sound like a good idea. 🤪 Perhaps you forgot to enter the party names Follow the /party command with the names of existing parties Type `/help party` for more information """.trimIndent() val requestFail = """ I am not aware of this party. You didn't invite me? 🤔 Perhaps you wanted to /create the party or misspelled its name Follow the /party command with the names of existing parties Type `/help party` or `/help create` for more information """.trimIndent() val requestFails = """ I'm not that impudent to call up the parties I don't know. 😅 Perhaps you misspelled some names Follow the /party command with the names of existing parties Type `/help party` for more information """.trimIndent() }
2
Kotlin
0
8
1815ce56b70e5ba6b9d708c00099969fc026d8a6
1,012
pull-party-bot
MIT License
app/src/main/java/com/jinesh/mpokket/modules/repodetail/viewmodel/OwnerViewModel.kt
babashaik17
281,186,737
true
{"Kotlin": 48703}
package com.jinesh.mpokket.modules.repodetail.viewmodel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.jinesh.mpokket.entity.Repo import com.jinesh.mpokket.entity.Owner import com.jinesh.mpokket.repo.OwnerRepo import kotlinx.coroutines.launch import javax.inject.Inject class OwnerViewModel @Inject constructor(var repo: OwnerRepo) : ViewModel() { private val contributor = MutableLiveData<ArrayList<Owner>>() var repoObject:Repo? = null private val isContributorNotFound = MutableLiveData<Boolean>() fun getRepoContributor() { viewModelScope.launch { repoObject?.let { repo.getContributers(repoObject!!.name!!,repoObject!!.owner!!.login!!,success = { contributor.postValue(it) },failure = { isContributorNotFound.postValue(true) }) } } } fun observePostsLiveData(): MutableLiveData<ArrayList<Owner>> { return contributor } fun observeContributorNotFound(): MutableLiveData<Boolean> { return isContributorNotFound } }
0
null
0
0
4008b9d4c2f0a1aaadb96456ce659b51ebfbc211
1,194
MVVM-offline-cache-demo
Apache License 2.0
nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/definitions/implementations/Dropout.kt
kgoderis
450,799,656
true
{"Text": 21, "Shell": 31, "Groovy": 1, "Batchfile": 1, "Maven POM": 95, "Markdown": 65, "Ignore List": 4, "Kotlin": 247, "Java": 4946, "XML": 32, "Java Properties": 29, "Protocol Buffer Text Format": 8, "PureBasic": 121, "Python": 25, "Protocol Buffer": 123, "C++": 1816, "C": 14, "JavaScript": 33, "Ruby": 5, "Starlark": 1, "JSON": 9, "YAML": 35, "Dockerfile": 2, "Fluent": 8, "Scala": 1, "JSON with Comments": 1, "CSS": 3, "HTML": 3, "CMake": 24, "Cuda": 207, "Smarty": 1, "Cython": 1, "Diff": 1}
package org.nd4j.samediff.frameworkimport.onnx.definitions.implementations import org.nd4j.autodiff.samediff.SDVariable import org.nd4j.autodiff.samediff.SameDiff import org.nd4j.autodiff.samediff.internal.SameDiffOp import org.nd4j.samediff.frameworkimport.ImportGraph import org.nd4j.samediff.frameworkimport.hooks.PreImportHook import org.nd4j.samediff.frameworkimport.hooks.annotations.PreHookRule import org.nd4j.samediff.frameworkimport.registry.OpMappingRegistry import org.nd4j.shade.protobuf.GeneratedMessageV3 import org.nd4j.shade.protobuf.ProtocolMessageEnum /** * Maps dropout * @author <NAME> */ @PreHookRule(nodeNames = [],opNames = ["Dropout"],frameworkName = "onnx") class Dropout : PreImportHook { override fun doImport( sd: SameDiff, attributes: Map<String, Any>, outputNames: List<String>, op: SameDiffOp, mappingRegistry: OpMappingRegistry<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum, GeneratedMessageV3, GeneratedMessageV3>, importGraph: ImportGraph<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum> ): Map<String, List<SDVariable>> { var inputVariable = sd.getVariable(op.inputsToOp[0]) val p = if(attributes.containsKey("ratio")) { val fVal = attributes["ratio"] as Float fVal.toDouble() } else if(op.inputsToOp.size > 1) { val dropoutVar = sd.getVariable(op.inputsToOp[1]).arr.getDouble(0) dropoutVar } else { 0.5 } val outputVar = sd.nn().dropoutInverted(outputNames[0],inputVariable,p) return mapOf(outputVar.name() to listOf(outputVar)) } }
634
null
5
3
15cbb3133c967681a831819630bd6f07e0dbeba2
1,804
deeplearning4j
Apache License 2.0
app/src/test/kotlin/no/nav/arbeidssokerregisteret/arena/adapter/VerifiserSlettingTopologyTest.kt
navikt
739,364,491
false
{"Kotlin": 57570}
package no.nav.arbeidssokerregisteret.arena.adapter import io.kotest.core.spec.style.FreeSpec import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import no.nav.arbeidssokerregisteret.arena.adapter.utils.* import no.nav.paw.arbeidssokerregisteret.arena.adapter.compoundKey import no.nav.paw.arbeidssokerregisteret.arena.adapter.topology import java.time.Duration.ofDays import java.time.Instant import java.time.Instant.now import java.util.concurrent.atomic.AtomicLong class VerifiserSlettingTopologyTest : FreeSpec({ with(testScope()) { val keySequence = AtomicLong(0) "Når vi har sendt, periode, opplysninger" - { val periode = keySequence.incrementAndGet() to periode(identietsnummer = "12345678901") "Når bare perioden er sendt inn skal vi ikke få noe ut på arena topic" { periodeTopic.pipeInput(periode.key, periode.melding) arenaTopic.isEmpty shouldBe true } val opplysninger = periode.key to opplysninger(periode = periode.melding.id) "Når opplysningene blir tilgjengelig sammen med perioden skal vi få noe ut på arena topic" { opplysningerTopic.pipeInput(opplysninger.key, opplysninger.melding ) arenaTopic.isEmpty shouldBe true } "Join store skal inneholde periode og opplysninger" { val topicsJoin = joinStore.get(compoundKey(periode.key, periode.melding.id)) topicsJoin.shouldNotBeNull() } "stream time settes flere dager frem i tid " { val ubruktePeriode = keySequence.incrementAndGet() to periode( identietsnummer = "12345678902", startet = metadata(now() + ofDays(30)) ) periodeTopic.pipeInput(ubruktePeriode.key, ubruktePeriode.melding, ubruktePeriode.melding.startet.tidspunkt) } "join store skal ikke lenger inneholde topics joind for periode: ${periode.melding.id}" { joinStore.get(compoundKey(periode.key, periode.melding.id)) shouldBe null } } } })
0
Kotlin
0
0
363a08f77da1839ef575b6b4a534a9895b36107e
2,217
paw-arbeidssokerregisteret-arena-adapter
MIT License
tl/src/main/kotlin/com/github/badoualy/telegram/tl/api/request/TLRequestAuthBindTempAuthKey.kt
Miha-x64
436,587,061
true
{"Kotlin": 3919807, "Java": 75352}
package com.github.badoualy.telegram.tl.api.request import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT32 import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT64 import com.github.badoualy.telegram.tl.TLObjectUtils.computeTLBytesSerializedSize import com.github.badoualy.telegram.tl.core.TLBool import com.github.badoualy.telegram.tl.core.TLBytes import com.github.badoualy.telegram.tl.core.TLMethod import com.github.badoualy.telegram.tl.serialization.TLDeserializer import com.github.badoualy.telegram.tl.serialization.TLSerializer import java.io.IOException /** * @author <NAME> <EMAIL> * @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a> */ class TLRequestAuthBindTempAuthKey() : TLMethod<TLBool>() { var permAuthKeyId: Long = 0L var nonce: Long = 0L var expiresAt: Int = 0 var encryptedMessage: TLBytes = TLBytes.EMPTY private val _constructor: String = "auth.bindTempAuthKey#cdd42a05" override val constructorId: Int = CONSTRUCTOR_ID constructor( permAuthKeyId: Long, nonce: Long, expiresAt: Int, encryptedMessage: TLBytes ) : this() { this.permAuthKeyId = permAuthKeyId this.nonce = nonce this.expiresAt = expiresAt this.encryptedMessage = encryptedMessage } @Throws(IOException::class) override fun serializeBody(tlSerializer: TLSerializer) = with (tlSerializer) { writeLong(permAuthKeyId) writeLong(nonce) writeInt(expiresAt) writeTLBytes(encryptedMessage) } @Throws(IOException::class) override fun deserializeBody(tlDeserializer: TLDeserializer) = with (tlDeserializer) { permAuthKeyId = readLong() nonce = readLong() expiresAt = readInt() encryptedMessage = readTLBytes() } override fun computeSerializedSize(): Int { var size = SIZE_CONSTRUCTOR_ID size += SIZE_INT64 size += SIZE_INT64 size += SIZE_INT32 size += computeTLBytesSerializedSize(encryptedMessage) return size } override fun toString() = _constructor override fun equals(other: Any?): Boolean { if (other !is TLRequestAuthBindTempAuthKey) return false if (other === this) return true return permAuthKeyId == other.permAuthKeyId && nonce == other.nonce && expiresAt == other.expiresAt && encryptedMessage == other.encryptedMessage } companion object { const val CONSTRUCTOR_ID: Int = 0xcdd42a05.toInt() } }
1
Kotlin
2
3
1a8963dce921c1e9ef05b9d1e56d8fbcb1ea1c4b
2,695
kotlogram-resurrected
MIT License
src/main/kotlin/com/github/keelar/exprk/internal/Token.kt
Keelar
115,964,472
false
null
package com.github.keelar.exprk.internal internal class Token(val type: TokenType, val lexeme: String, val literal: Any?) { override fun toString(): String { return type.toString() + " " + lexeme + " " + literal } }
2
null
30
98
30c00415a87a53b4bb5e4a2eb7ded20ed1f64b86
276
ExprK
MIT License
compiler/testData/codegen/box/inlineClasses/callableReferences/inlineClassPrivatePrimaryValGeneric.kt
JetBrains
3,432,266
false
null
// WITH_STDLIB // WORKS_WHEN_VALUE_CLASS // LANGUAGE: +ValueClasses, +GenericInlineClassParameter import kotlin.test.assertEquals OPTIONAL_JVM_INLINE_ANNOTATION value class Z<T: Int>(private val x: T) { companion object { val xref = Z<Int>::x } } OPTIONAL_JVM_INLINE_ANNOTATION value class L<T: Long>(private val x: T) { companion object { val xref = L<Long>::x } } OPTIONAL_JVM_INLINE_ANNOTATION value class S<T: String>(private val x: T) { companion object { val xref = S<String>::x } } fun box(): String { assertEquals(42, Z.xref.get(Z(42))) assertEquals(1234L, L.xref.get(L(1234L))) assertEquals("abc", S.xref.get(S("abc"))) assertEquals(42, Z.xref.invoke(Z(42))) assertEquals(1234L, L.xref.invoke(L(1234L))) assertEquals("abc", S.xref.invoke(S("abc"))) return "OK" }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
854
kotlin
Apache License 2.0
app/src/main/java/com/faldez/shachi/ui/search/SearchSuggestionAdapter.kt
faldez
457,580,136
false
null
package com.faldez.shachi.ui.search import android.content.res.ColorStateList import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.faldez.shachi.R import com.faldez.shachi.data.model.Category import com.faldez.shachi.data.model.TagDetail import com.faldez.shachi.databinding.SearchSuggestionTagListItemBinding class SearchSuggestionAdapter( val setTextColor: (Int) -> ColorStateList, val onClick: (TagDetail) -> Unit, ) : ListAdapter<TagDetail, SearchSugestionViewHolder>(COMPARATOR) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchSugestionViewHolder { val inflater = LayoutInflater.from(parent.context) val view = SearchSuggestionTagListItemBinding.inflate(inflater, parent, false) return SearchSugestionViewHolder(view) } override fun onBindViewHolder(holder: SearchSugestionViewHolder, position: Int) { val tag = getItem(position) val textColor = when (tag.type) { Category.General -> R.color.tag_general Category.Artist -> R.color.tag_artist Category.Copyright -> R.color.tag_copyright Category.Character -> R.color.tag_character Category.Metadata -> R.color.tag_metadata else -> null } textColor?.let { holder.binding.sugestionTagTextView.setTextColor(setTextColor(it)) } holder.binding.sugestionTagTextView.text = "# ${tag.name}" holder.binding.root.setOnClickListener { onClick(tag) } } companion object { private val COMPARATOR = object : DiffUtil.ItemCallback<TagDetail>() { override fun areItemsTheSame( oldItem: TagDetail, newItem: TagDetail, ): Boolean = oldItem.name == newItem.name override fun areContentsTheSame( oldItem: TagDetail, newItem: TagDetail, ): Boolean = oldItem == newItem } } } class SearchSugestionViewHolder(val binding: SearchSuggestionTagListItemBinding) : RecyclerView.ViewHolder(binding.root)
8
null
1
20
6491f53f06ae2aeb6cd786fb9f4fe7cb21958540
2,294
shachi
Apache License 2.0
app/src/main/java/com/faldez/shachi/ui/search/SearchSuggestionAdapter.kt
faldez
457,580,136
false
null
package com.faldez.shachi.ui.search import android.content.res.ColorStateList import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.faldez.shachi.R import com.faldez.shachi.data.model.Category import com.faldez.shachi.data.model.TagDetail import com.faldez.shachi.databinding.SearchSuggestionTagListItemBinding class SearchSuggestionAdapter( val setTextColor: (Int) -> ColorStateList, val onClick: (TagDetail) -> Unit, ) : ListAdapter<TagDetail, SearchSugestionViewHolder>(COMPARATOR) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchSugestionViewHolder { val inflater = LayoutInflater.from(parent.context) val view = SearchSuggestionTagListItemBinding.inflate(inflater, parent, false) return SearchSugestionViewHolder(view) } override fun onBindViewHolder(holder: SearchSugestionViewHolder, position: Int) { val tag = getItem(position) val textColor = when (tag.type) { Category.General -> R.color.tag_general Category.Artist -> R.color.tag_artist Category.Copyright -> R.color.tag_copyright Category.Character -> R.color.tag_character Category.Metadata -> R.color.tag_metadata else -> null } textColor?.let { holder.binding.sugestionTagTextView.setTextColor(setTextColor(it)) } holder.binding.sugestionTagTextView.text = "# ${tag.name}" holder.binding.root.setOnClickListener { onClick(tag) } } companion object { private val COMPARATOR = object : DiffUtil.ItemCallback<TagDetail>() { override fun areItemsTheSame( oldItem: TagDetail, newItem: TagDetail, ): Boolean = oldItem.name == newItem.name override fun areContentsTheSame( oldItem: TagDetail, newItem: TagDetail, ): Boolean = oldItem == newItem } } } class SearchSugestionViewHolder(val binding: SearchSuggestionTagListItemBinding) : RecyclerView.ViewHolder(binding.root)
8
null
1
20
6491f53f06ae2aeb6cd786fb9f4fe7cb21958540
2,294
shachi
Apache License 2.0
src/app/src/main/java/com/cunyn/android/financesystem/ResultActivity.kt
hottech-jxd
150,100,491
false
null
package com.cunyn.android.financesystem import android.app.Activity import android.os.AsyncTask import android.os.Bundle import android.os.Handler import android.os.Message import android.text.method.ScrollingMovementMethod import android.util.Log import android.view.View import android.widget.ProgressBar import android.widget.TextView import com.cunyn.android.financesystem.bean.XinYanData import com.cunyn.android.financesystem.bean.XinYan_CHANNEL import com.xinyan.bigdata.bean.XinyanCallBackData import kotlinx.android.synthetic.main.layout_header.* import java.io.BufferedReader import java.io.InputStreamReader import java.net.HttpURLConnection import java.net.URL /** * Created by creedon.dong on 2016/10/27. */ class ResultActivity : Activity() { private var tvResult: TextView? = null private var stringBuffer: StringBuffer? = null private var progressBar: ProgressBar? = null private val handler = object : Handler() { override fun handleMessage(msg: Message) { LoadTask().execute() } } private var url = "" private var baseResulturl: String? = null private//https://api.xinyan.com/data/carrier/v2/mobile/201805222136590131070693?mobile= //https://api.xinyan.com/data/qq/v1/alldata/{tradeNo} //data/chsi/v1/all/{tradeNO} ///data/chsi/v1/all/{tradeNO} ///data/chsi/v1/all/{tradeNO} val resulturl: String get() { if ( XinYan_CHANNEL.FUNCTION_TAOBAO.equals(XinYanData.type)) { url = baseResulturl!! + XinYanData.UrlManager.TAOBAO_RESULT_URL } else if ( XinYan_CHANNEL.FUNCTION_ALIPAY.equals(XinYanData.type)) { url = baseResulturl!! + XinYanData.UrlManager.ALIPAY_RESULT_URL } else if ( XinYan_CHANNEL.FUNCTION_JINGDONG.equals(XinYanData.type)) { url = baseResulturl!! + XinYanData.UrlManager.JINGDONG_RESULT_URL } else if (XinYan_CHANNEL.FUNCTION_CARRIER.equals(XinYanData.type)) { url = baseResulturl!! + XinYanData.UrlManager.CARRIER_RESULT_URL } else if (XinYan_CHANNEL.FUNCTION_QQ.equals(XinYanData.type)) { url = baseResulturl!! + XinYanData.UrlManager.QQ_RESULT_URL } else if (XinYan_CHANNEL.FUNCTION_FUND.equals(XinYanData.type)) { url = baseResulturl!! + XinYanData.UrlManager.FUND_RESULT_URL } else if (XinYan_CHANNEL.FUNCTION_CHSI.equals(XinYanData.type)) { url = baseResulturl!! + XinYanData.UrlManager.CHIS_RESULT_URL } else if (XinYan_CHANNEL.FUNCTION_DIDI.equals(XinYanData.type)) { url = baseResulturl!! + XinYanData.UrlManager.DIDI_RESULT_URL } else if (XinYan_CHANNEL.FUNCTION_MAIL.equals(XinYanData.type)) { url = baseResulturl!! + XinYanData.UrlManager.MAIL_RESULT_URL } else if (XinYan_CHANNEL.FUNCTION_SECURITY.equals(XinYanData.type)) { url = baseResulturl!! + XinYanData.UrlManager.SECURITY_RESULT_URL } else if (XinYan_CHANNEL.FUNCTION_ONLINE_BANK.equals(XinYanData.type)) { url = baseResulturl!! + XinYanData.UrlManager.BANK_RESULT_URL } else if (XinYan_CHANNEL.FUNCTION_TAOBAOPAY.equals(XinYanData.type)) { url = baseResulturl!! + XinYanData.UrlManager.TAOBAOPAY_RESULT_URL } url = url.replace("\\{[^}]*\\}".toRegex(), XinYanData.tradeNo!!) return url } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_result) tvResult = findViewById(R.id.tvResult) progressBar = findViewById(R.id.pb) tvResult!!.movementMethod = ScrollingMovementMethod() header_left_image.setImageResource(R.mipmap.arrow_left) header_left_image.setOnClickListener(View.OnClickListener { finish() }) initData() } private fun initData() { try { if ("test" == XinYanData.environment) { baseResulturl = "https://test.xinyan.com/data/" } if ("product" == XinYanData.environment) { baseResulturl = "https://api.xinyan.com/data/" } val xinyanCallBackData = intent.extras!!.get("data") as XinyanCallBackData stringBuffer = StringBuffer() stringBuffer!!.append("订单ID:" + XinYanData.tradeNo + "\n") stringBuffer!!.append("任务ID:" + xinyanCallBackData.taskId + "\n") stringBuffer!!.append("任务消息:" + xinyanCallBackData.message + "\n") tvResult!!.text = stringBuffer!!.toString() if ("YES" == XinYanData.titleConfig.getLoginSuccessQuit()) {//登录退出模式,结果需要自己轮询解析的状态,然后再获取结果 handler.sendEmptyMessageDelayed(1, 5000) } else { handler.sendEmptyMessageDelayed(1, 500) } } catch (e: Exception) { e.printStackTrace() } } internal inner class LoadTask : AsyncTask<String, String, String>() { override fun onPreExecute() {} // 支付宝: // 1、查询用户支付宝基本信息 ///data/alipay/v3/info/{orderNo} // //2、查询用户的支付宝交易记录信息 ///data/alipay/v3/tradeInfo/{orderNo} // //3、查询用户的支付宝资产状况 ///data/alipay/v3/wealth/{orderNo} // //4、查询用户花呗消费记录和银行卡消费记录 ///data/alipay/v3/assetinfo/{orderNo} // //5、查询用户所有数据 ///data/alipay/v3/data/{orderNo} // //6、查询支付宝芝麻信用分信息 ///data/alipay/v3/zmscore/{orderNo} // // 京东: // 1、查询用户的基本信息 ///data/jingdong/v3/userinfo/{orderNo} //2、查询用户的收货地址信息 ///data/jingdong/v2/deliverAddress/{orderNo} //3. 查询用户的资产信息 ///data/jingdong/v3/wealth/{orderNo} //4、查询用户的交易信息(不含商品) ///data/jingdong/v3/trade/info/{orderNo}?page=&pageSize= // 5、根据订单号分页查询用户交易记录(含商品信息) ///data/jingdong/v3/trade/details/{orderNo}?page=&pageSize= // 6、查询用户的全部信息 ///data/jingdong/v3/userdata/{orderNo} //7、查询用户的白条账单信息 ///data/jingdong/v3/btdata/{orderNo} //8、查询用户的金条借款记录 ///data/jingdong/v3/jtdata/{orderNo} // // // 淘宝: // 1、 查询用户的基本信息 ///data/taobao/v3/user/{orderNo} //2、查询用户的淘宝收货地址 ///data/taobao/v3/deliveraddress/{orderNo} //3、查询用户的最近几笔订单的收货地址 override fun doInBackground(params: Array<String>): String { resulturl Log.i("tag", "url == $url") val orderinfo = loadOrderInFo(url) Log.i("tag", "orderinfo == $orderinfo") return orderinfo } override fun onPostExecute(orderinfo: String) { stringBuffer!!.append(orderinfo) runOnUiThread { if (!isFinishing) { tvResult!!.text = stringBuffer!!.toString() progressBar!!.visibility = View.GONE } } } } fun loadOrderInFo( url: String?): String { var urlex = url if(url==null) urlex ="" //Log.i(ResultActivity::class.simpleName ,"loadOrderInFo url = $urlex") val json = StringBuilder() val inReader : BufferedReader try { val urlObject = URL(urlex) val uc = urlObject.openConnection() as HttpURLConnection uc.addRequestProperty("memberId", XinYanData.memberId) inReader = BufferedReader(InputStreamReader(uc.inputStream)) var inputLine: String? = null inputLine = inReader.readLine() while (inputLine != null) { json.append(inputLine) inputLine = inReader.readLine() } inReader.close() } catch (e: Exception) { e.printStackTrace() } return json.toString() } }
0
Kotlin
0
1
ce4ed7ad9f6391401e3ce94ccb055c2fe660bf75
8,040
financesystem
Apache License 2.0
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/fragment/impl/DefaultSelector.kt
Xanik
282,687,897
false
null
package org.hexworks.zircon.internal.fragment.impl import org.hexworks.cobalt.databinding.api.binding.bindTransform import org.hexworks.cobalt.databinding.api.collection.ListProperty import org.hexworks.cobalt.databinding.api.extension.createPropertyFrom import org.hexworks.cobalt.databinding.api.extension.toProperty import org.hexworks.cobalt.databinding.api.value.ObservableValue import org.hexworks.zircon.api.Components import org.hexworks.zircon.api.behavior.TextHolder import org.hexworks.zircon.api.component.HBox import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.api.fragment.Selector import org.hexworks.zircon.api.graphics.Symbols import org.hexworks.zircon.api.uievent.ComponentEventType class DefaultSelector<T : Any>( parent: HBox, defaultSelected: T, initialValues: Iterable<T>, private val centeredText: Boolean = true, private val toStringMethod: (T) -> String = Any::toString, clickable: Boolean = false ) : Selector<T> { override val valuesProperty = initialValues.toProperty() override val values: List<T> by valuesProperty.asDelegate() private val indexProperty = createPropertyFrom(values.indexOf(defaultSelected)) override val selectedValue: ObservableValue<T> = indexProperty.bindTransform { values[it] } override val selected: T get() = selectedValue.value private val rightButton = Components.button().withText(Symbols.ARROW_RIGHT.toString()).withDecorations().build().apply { processComponentEvents(ComponentEventType.ACTIVATED) { showNextValue() } } private val leftButton = Components.button().withText(Symbols.ARROW_LEFT.toString()).withDecorations().build().apply { processComponentEvents(ComponentEventType.ACTIVATED) { showPrevValue() } } private val labelSize = Size.create(parent.contentSize.width - (leftButton.width + rightButton.width), 1) override val root = parent.apply { addComponent(leftButton) if (clickable) { addComponent(Components.button().withDecorations().withSize(labelSize).build().apply { initLabel() processComponentEvents(ComponentEventType.ACTIVATED) { showNextValue() } }) } else { addComponent(Components.label() .withSize(labelSize) .build().apply { initLabel() }) } addComponent(rightButton) } private fun TextHolder.initLabel() { text = fetchLabelBy(0) textProperty.updateFrom(indexProperty) { i -> fetchLabelBy(i) } } private fun setValue(from: Int, to: Int) { indexProperty.value = to } private fun showNextValue() { val oldIndex = indexProperty.value var nextIndex = oldIndex + 1 if (nextIndex >= values.size) { nextIndex = 0 } setValue(oldIndex, nextIndex) } private fun showPrevValue() { val oldIndex = indexProperty.value var prevIndex = oldIndex - 1 if (prevIndex < 0) { prevIndex = values.size - 1 } setValue(oldIndex, prevIndex) } private fun fetchLabelBy(index: Int) = toStringMethod.invoke(values[index]).centered() private fun String.centered(): String { val maxWidth = labelSize.width return if (centeredText && length < maxWidth) { val spacesCount = (maxWidth - length) / 2 this.padStart(spacesCount + length).padEnd(maxWidth) } else { this.substring(0, kotlin.math.min(length, maxWidth)) } } }
1
null
1
2
bf435cddeb55f7c3a9da5dd5c29be13af8354d0f
3,707
zircon
Apache License 2.0
src/main/kotlin/ru/kontur/cdp4k/protocol/network/MonotonicTime.kt
kinfra
758,916,083
false
{"Kotlin": 93843}
package ru.kontur.cdp4k.protocol.network /** * Monotonically increasing time in seconds since an arbitrary point in the past. */ class MonotonicTime(val value: Double) : Comparable<MonotonicTime> { init { require(value.isFinite()) { "Value must be a finite number: $value" } } override fun compareTo(other: MonotonicTime): Int { return value.compareTo(other.value) } override fun equals(other: Any?): Boolean { return other is MonotonicTime && other.value == value } override fun hashCode(): Int { return value.hashCode() } override fun toString(): String { return "MonotonicTime($value)" } }
0
Kotlin
0
0
0b7a7a3072a918e49588df4b7843e7c6dc7c350a
681
cdp4k
MIT License
kotlin_new_backend/src/main/kotlin/query/MultipleResultQueryWithParser.kt
capgadsx
306,060,415
true
{"Kotlin": 264698, "Jupyter Notebook": 155496, "Python": 30773, "Go": 27219, "Shell": 329}
package query import org.apache.lucene.document.Document import org.apache.lucene.index.DirectoryReader import org.apache.lucene.queries.function.FunctionScoreQuery import org.apache.lucene.queryparser.classic.QueryParser import org.apache.lucene.search.DoubleValuesSource import org.apache.lucene.search.IndexSearcher import org.apache.lucene.store.Directory import shared.StringConstants open class MultipleResultQueryWithParser(val parser: QueryParser, open val index: Directory) { fun query(term: String): Collection<Document> { val query = parser.parse(term) val boostedQuery = FunctionScoreQuery.boostByValue( query, DoubleValuesSource.fromDoubleField(StringConstants.LUCENE_DOC_PROP_RANK) ) val reader = DirectoryReader.open(index) val searcher = IndexSearcher(reader) return if (reader.maxDoc() > 0) { val docs = searcher.search(boostedQuery, reader.maxDoc()) val hits = docs.scoreDocs val result = hits.map { hit -> searcher.doc(hit.doc) } reader.close() result.filterNotNull() } else { listOf() } } }
0
Kotlin
0
0
725b60b9a7a8878e9c529b4d8210e8f5ec6c1ec4
1,180
SPARQLforHumans
Apache License 2.0
app/src/main/java/dev/kingbond/moveon/ui/packageandmovers/fragMov/itemList/ItemList.kt
Kingbond470
422,909,035
false
{"Kotlin": 129863, "Java": 9137}
package dev.kingbond.moveon.ui.packageandmovers.fragMov.itemList import android.content.Context import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.CheckBox import android.widget.Toast import androidx.navigation.Navigation import dev.kingbond.moveon.R import dev.kingbond.moveon.ui.packageandmovers.fragMov.cost.CoastPage import dev.kingbond.moveon.ui.packageandmovers.spref.GlobalV import dev.kingbond.moveon.ui.packageandmovers.spref.SharedPref import kotlinx.android.synthetic.main.fragment_house_size.* import kotlinx.android.synthetic.main.fragment_item_list.* class ItemList : Fragment(), View.OnClickListener { val sharedPref = SharedPref() var sum = 0 override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_item_list, container, false) view.findViewById<Button>(R.id.itemBtn).setOnClickListener { Navigation.findNavController(view).navigate(R.id.action_itemList_to_coastPage) sharedPref.insertIntData(requireContext(), "sum", sum) } setData(view) // HouseCat_data(view) return view } fun setData(v: View) { val mat = v.findViewById<CheckBox>(R.id.Matress) val Almirah = v.findViewById<CheckBox>(R.id.Almirah) val chair = v.findViewById<CheckBox>(R.id.Chair) val Sofa = v.findViewById<CheckBox>(R.id.Sofa) val Table = v.findViewById<CheckBox>(R.id.Table) val Purifier = v.findViewById<CheckBox>(R.id.Purifier) val Shoe = v.findViewById<CheckBox>(R.id.Shoe) val Fridge = v.findViewById<CheckBox>(R.id.Fridge) val TV = v.findViewById<CheckBox>(R.id.WashingMachine) val GasStove = v.findViewById<CheckBox>(R.id.GasStove) val Cylinder = v.findViewById<CheckBox>(R.id.Cyclinder) val Bed = v.findViewById<CheckBox>(R.id.bed) val Specific = v.findViewById<CheckBox>(R.id.specific) mat.setOnClickListener(this) Almirah.setOnClickListener(this) chair.setOnClickListener(this) Sofa.setOnClickListener(this) Table.setOnClickListener(this) Purifier.setOnClickListener(this) Shoe.setOnClickListener(this) Fridge.setOnClickListener(this) TV.setOnClickListener(this) GasStove.setOnClickListener(this) Cylinder.setOnClickListener(this) Bed.setOnClickListener(this) Specific.setOnClickListener(this) } override fun onClick(v: View) { when (v.id) { R.id.Matress -> { if (Matress.isChecked) { // Toast.makeText(requireActivity(), "Maitress", Toast.LENGTH_SHORT).show() // sharedPref.insertIntData(requireContext(), "Maitress", sum+100) sum += 100 } } R.id.Almirah -> { if (Almirah.isChecked) { // Toast.makeText(requireActivity(), "Almirah", Toast.LENGTH_SHORT).show() // sharedPref.insertIntData(requireContext(), "Almirah", sum+200) sum += 200 } } R.id.Chair -> { if (Chair.isChecked) { // Toast.makeText(requireActivity(), "Chair", Toast.LENGTH_SHORT).show() // sharedPref.insertIntData(requireContext(), "Chair", sum + 300) sum += 300 } } R.id.Sofa -> { if (Sofa.isChecked) { // Toast.makeText(requireActivity(), "Sofa", Toast.LENGTH_SHORT).show() // sharedPref.insertIntData(requireContext(), "Sofa", sum+400) sum += 400 } } R.id.Table -> { if (Table.isChecked) { // Toast.makeText(requireActivity(), "Table", Toast.LENGTH_SHORT).show() // sharedPref.insertIntData(requireContext(), "Table", sum+500) sum += 500 } } R.id.Purifier -> { if (Purifier.isChecked) { // Toast.makeText(requireActivity(), "Table", Toast.LENGTH_SHORT).show() // sharedPref.insertIntData(requireContext(), "Table", sum+600) sum += 600 } } R.id.Shoe -> { if (Shoe.isChecked) { // Toast.makeText(requireActivity(), "Shoe", Toast.LENGTH_SHORT).show() // sharedPref.insertIntData(requireContext(), "Shoe", sum+700) sum += 700 } } R.id.Fridge -> { if (Fridge.isChecked) { // Toast.makeText(requireActivity(), "Fridge", Toast.LENGTH_SHORT).show() // sharedPref.insertIntData(requireContext(), "Fridge", sum+800) sum += 800 } } R.id.WashingMachine -> { if (WashingMachine.isChecked) { // Toast.makeText(requireActivity(), "TV", Toast.LENGTH_SHORT).show() // sharedPref.insertIntData(requireContext(), "washingMachine", sum+900) sum += 900 } } R.id.GasStove -> { if (GasStove.isChecked) { // Toast.makeText(requireActivity(), "GasStove", Toast.LENGTH_SHORT).show() // sharedPref.insertIntData(requireContext(), "GasStove", sum+500) sum += 500 } } R.id.Cyclinder -> { if (Cyclinder.isChecked) { // Toast.makeText(requireActivity(), "Cyclinder", Toast.LENGTH_SHORT).show() // sharedPref.insertIntData(requireContext(), "Cyclinder", sum+500) sum += 500 } } R.id.bed -> { if (bed.isChecked) { // Toast.makeText(requireActivity(), "Bed", Toast.LENGTH_SHORT).show() // sharedPref.insertIntData(requireContext(), "Bed", sum+500) sum += 300 } } R.id.specific -> { if (specific.isChecked) { // Toast.makeText(requireActivity(), "specific", Toast.LENGTH_SHORT).show() // sharedPref.insertIntData(requireContext(), "specific", sum+1000) sum += 1000 } } } } }
0
Kotlin
0
5
b1f790c6cf43354857f1f98e217fe68bdb3e9e3a
6,927
Move-On
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/pecs/jpc/service/SpreadsheetService.kt
uk-gov-mirror
356,783,334
true
{"Kotlin": 428549, "HTML": 83335, "CSS": 12598, "Shell": 6092, "Mustache": 4485, "Dockerfile": 945}
package uk.gov.justice.digital.hmpps.pecs.jpc.service import org.slf4j.LoggerFactory import org.springframework.security.core.Authentication import org.springframework.stereotype.Service import uk.gov.justice.digital.hmpps.pecs.jpc.auditing.AuditableEvent import uk.gov.justice.digital.hmpps.pecs.jpc.price.Supplier import uk.gov.justice.digital.hmpps.pecs.jpc.spreadsheet.PricesSpreadsheetGenerator import java.io.File import java.time.LocalDate @Service class SpreadsheetService( private val pricesSpreadsheetGenerator: PricesSpreadsheetGenerator, private val auditService: AuditService ) { private val logger = LoggerFactory.getLogger(javaClass) fun spreadsheet(authentication: Authentication, supplier: Supplier, startDate: LocalDate): File? { logger.info("Generating spreadsheet for supplier '$supplier', moves from '$startDate''") return pricesSpreadsheetGenerator.generate(supplier, startDate).also { auditService.create(AuditableEvent.downloadSpreadsheetEvent(startDate, supplier, authentication)) } } }
0
Kotlin
0
0
448660ac4b18cc4c8cf3c137a902ed7a99a9fff4
1,045
ministryofjustice.calculate-journey-variable-payments
MIT License
compose/foundation/foundation-layout/src/commonMain/kotlin/androidx/compose/foundation/layout/Column.kt
androidx
256,589,781
false
{"Kotlin": 102794437, "Java": 64412412, "C++": 9138104, "AIDL": 617598, "Python": 310931, "Shell": 189529, "TypeScript": 40586, "HTML": 35176, "Groovy": 27482, "ANTLR": 26700, "Svelte": 20307, "CMake": 18033, "C": 16982, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.layout import androidx.annotation.FloatRange import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import androidx.compose.runtime.Stable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.IntrinsicMeasurable import androidx.compose.ui.layout.IntrinsicMeasureScope import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.Measurable import androidx.compose.ui.layout.MeasurePolicy import androidx.compose.ui.layout.MeasureResult import androidx.compose.ui.layout.MeasureScope import androidx.compose.ui.layout.Measured import androidx.compose.ui.layout.Placeable import androidx.compose.ui.layout.VerticalAlignmentLine import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.LayoutDirection /** * A layout composable that places its children in a vertical sequence. For a layout composable * that places its children in a horizontal sequence, see [Row]. Note that by default items do * not scroll; see `Modifier.verticalScroll` to add this behavior. For a vertically * scrollable list that only composes and lays out the currently visible items see `LazyColumn`. * * The [Column] layout is able to assign children heights according to their weights provided * using the [ColumnScope.weight] modifier. If a child is not provided a weight, it will be * asked for its preferred height before the sizes of the children with weights are calculated * proportionally to their weight based on the remaining available space. Note that if the * [Column] is vertically scrollable or part of a vertically scrollable container, any provided * weights will be disregarded as the remaining available space will be infinite. * * When none of its children have weights, a [Column] will be as small as possible to fit its * children one on top of the other. In order to change the height of the [Column], use the * [Modifier.height] modifiers; e.g. to make it fill the available height [Modifier.fillMaxHeight] * can be used. If at least one child of a [Column] has a [weight][ColumnScope.weight], the [Column] * will fill the available height, so there is no need for [Modifier.fillMaxHeight]. However, if * [Column]'s size should be limited, the [Modifier.height] or [Modifier.size] layout modifiers * should be applied. * * When the size of the [Column] is larger than the sum of its children sizes, a * [verticalArrangement] can be specified to define the positioning of the children inside the * [Column]. See [Arrangement] for available positioning behaviors; a custom arrangement can also * be defined using the constructor of [Arrangement]. Below is an illustration of different * vertical arrangements: * * ![Column arrangements](https://developer.android.com/images/reference/androidx/compose/foundation/layout/column_arrangement_visualization.gif) * * Example usage: * * @sample androidx.compose.foundation.layout.samples.SimpleColumn * * @param modifier The modifier to be applied to the Column. * @param verticalArrangement The vertical arrangement of the layout's children. * @param horizontalAlignment The horizontal alignment of the layout's children. * * @see Row * @see [androidx.compose.foundation.lazy.LazyColumn] */ @Composable inline fun Column( modifier: Modifier = Modifier, verticalArrangement: Arrangement.Vertical = Arrangement.Top, horizontalAlignment: Alignment.Horizontal = Alignment.Start, content: @Composable ColumnScope.() -> Unit ) { val measurePolicy = columnMeasurePolicy(verticalArrangement, horizontalAlignment) Layout( content = { ColumnScopeInstance.content() }, measurePolicy = measurePolicy, modifier = modifier ) } @PublishedApi internal val DefaultColumnMeasurePolicy: MeasurePolicy = ColumnMeasurePolicy( verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.Start, ) @PublishedApi @Composable internal fun columnMeasurePolicy( verticalArrangement: Arrangement.Vertical, horizontalAlignment: Alignment.Horizontal ): MeasurePolicy = if (verticalArrangement == Arrangement.Top && horizontalAlignment == Alignment.Start) { DefaultColumnMeasurePolicy } else { remember(verticalArrangement, horizontalAlignment) { ColumnMeasurePolicy( verticalArrangement = verticalArrangement, horizontalAlignment = horizontalAlignment, ) } } internal data class ColumnMeasurePolicy( private val verticalArrangement: Arrangement.Vertical, private val horizontalAlignment: Alignment.Horizontal ) : MeasurePolicy, RowColumnMeasurePolicy { override fun Placeable.mainAxisSize(): Int = height override fun Placeable.crossAxisSize(): Int = width override fun populateMainAxisPositions( mainAxisLayoutSize: Int, childrenMainAxisSize: IntArray, mainAxisPositions: IntArray, measureScope: MeasureScope ) { with(verticalArrangement) { measureScope.arrange( mainAxisLayoutSize, childrenMainAxisSize, mainAxisPositions ) } } override fun placeHelper( placeables: Array<Placeable?>, measureScope: MeasureScope, beforeCrossAxisAlignmentLine: Int, mainAxisPositions: IntArray, mainAxisLayoutSize: Int, crossAxisLayoutSize: Int, crossAxisOffset: IntArray?, currentLineIndex: Int, startIndex: Int, endIndex: Int ): MeasureResult { return with(measureScope) { layout(crossAxisLayoutSize, mainAxisLayoutSize) { placeables.forEachIndexed { i, placeable -> val crossAxisPosition = getCrossAxisPosition( placeable!!, placeable.rowColumnParentData, crossAxisLayoutSize, beforeCrossAxisAlignmentLine, measureScope.layoutDirection ) placeable.place( crossAxisPosition, mainAxisPositions[i], ) } } } } private fun getCrossAxisPosition( placeable: Placeable, parentData: RowColumnParentData?, crossAxisLayoutSize: Int, beforeCrossAxisAlignmentLine: Int, layoutDirection: LayoutDirection ): Int { val childCrossAlignment = parentData?.crossAxisAlignment return childCrossAlignment?.align( size = crossAxisLayoutSize - placeable.width, layoutDirection = layoutDirection, placeable = placeable, beforeCrossAxisAlignmentLine = beforeCrossAxisAlignmentLine ) ?: horizontalAlignment.align(0, crossAxisLayoutSize - placeable.width, layoutDirection) } override fun createConstraints( mainAxisMin: Int, crossAxisMin: Int, mainAxisMax: Int, crossAxisMax: Int, isPrioritizing: Boolean ): Constraints { return createColumnConstraints( isPrioritizing, mainAxisMin, crossAxisMin, mainAxisMax, crossAxisMax ) } override fun MeasureScope.measure( measurables: List<Measurable>, constraints: Constraints ): MeasureResult { return measure( constraints.minHeight, constraints.minWidth, constraints.maxHeight, constraints.maxWidth, verticalArrangement.spacing.roundToPx(), this, measurables, arrayOfNulls(measurables.size), 0, measurables.size ) } override fun IntrinsicMeasureScope.minIntrinsicWidth( measurables: List<IntrinsicMeasurable>, height: Int ) = IntrinsicMeasureBlocks.VerticalMinWidth( measurables, height, verticalArrangement.spacing.roundToPx(), ) override fun IntrinsicMeasureScope.minIntrinsicHeight( measurables: List<IntrinsicMeasurable>, width: Int ) = IntrinsicMeasureBlocks.VerticalMinHeight( measurables, width, verticalArrangement.spacing.roundToPx(), ) override fun IntrinsicMeasureScope.maxIntrinsicWidth( measurables: List<IntrinsicMeasurable>, height: Int ) = IntrinsicMeasureBlocks.VerticalMaxWidth( measurables, height, verticalArrangement.spacing.roundToPx(), ) override fun IntrinsicMeasureScope.maxIntrinsicHeight( measurables: List<IntrinsicMeasurable>, width: Int ) = IntrinsicMeasureBlocks.VerticalMaxHeight( measurables, width, verticalArrangement.spacing.roundToPx(), ) } internal fun createColumnConstraints( isPrioritizing: Boolean, mainAxisMin: Int, crossAxisMin: Int, mainAxisMax: Int, crossAxisMax: Int, ): Constraints { return if (!isPrioritizing) { Constraints( minHeight = mainAxisMin, minWidth = crossAxisMin, maxHeight = mainAxisMax, maxWidth = crossAxisMax ) } else { Constraints.fitPrioritizingHeight( minHeight = mainAxisMin, minWidth = crossAxisMin, maxHeight = mainAxisMax, maxWidth = crossAxisMax ) } } /** * Scope for the children of [Column]. */ @LayoutScopeMarker @Immutable @JvmDefaultWithCompatibility interface ColumnScope { /** * Size the element's height proportional to its [weight] relative to other weighted sibling * elements in the [Column]. The parent will divide the vertical space remaining after measuring * unweighted child elements and distribute it according to this weight. * When [fill] is true, the element will be forced to occupy the whole height allocated to it. * Otherwise, the element is allowed to be smaller - this will result in [Column] being smaller, * as the unused allocated height will not be redistributed to other siblings. * * In a [FlowColumn], when a weight is applied to an item, the item is scaled based on * the number of weighted items that fall on the column it was placed in. * * @param weight The proportional height to give to this element, as related to the total of * all weighted siblings. Must be positive. * @param fill When `true`, the element will occupy the whole height allocated. * * @sample androidx.compose.foundation.layout.samples.SimpleColumn */ @Stable fun Modifier.weight( @FloatRange(from = 0.0, fromInclusive = false) weight: Float, fill: Boolean = true ): Modifier /** * Align the element horizontally within the [Column]. This alignment will have priority over * the [Column]'s `horizontalAlignment` parameter. * * Example usage: * @sample androidx.compose.foundation.layout.samples.SimpleAlignInColumn */ @Stable fun Modifier.align(alignment: Alignment.Horizontal): Modifier /** * Position the element horizontally such that its [alignmentLine] aligns with sibling elements * also configured to [alignBy]. [alignBy] is a form of [align], * so both modifiers will not work together if specified for the same layout. * Within a [Column], all components with [alignBy] will align horizontally using * the specified [VerticalAlignmentLine]s or values provided using the other * [alignBy] overload, forming a sibling group. * At least one element of the sibling group will be placed as it had [Alignment.Start] align * in [Column], and the alignment of the other siblings will be then determined such that * the alignment lines coincide. Note that if only one element in a [Column] has the * [alignBy] modifier specified the element will be positioned * as if it had [Alignment.Start] align. * * Example usage: * @sample androidx.compose.foundation.layout.samples.SimpleRelativeToSiblingsInColumn */ @Stable fun Modifier.alignBy(alignmentLine: VerticalAlignmentLine): Modifier /** * Position the element horizontally such that the alignment line for the content as * determined by [alignmentLineBlock] aligns with sibling elements also configured to * [alignBy]. [alignBy] is a form of [align], so both modifiers * will not work together if specified for the same layout. * Within a [Column], all components with [alignBy] will align horizontally using * the specified [VerticalAlignmentLine]s or values obtained from [alignmentLineBlock], * forming a sibling group. * At least one element of the sibling group will be placed as it had [Alignment.Start] align * in [Column], and the alignment of the other siblings will be then determined such that * the alignment lines coincide. Note that if only one element in a [Column] has the * [alignBy] modifier specified the element will be positioned * as if it had [Alignment.Start] align. * * Example usage: * @sample androidx.compose.foundation.layout.samples.SimpleRelativeToSiblings */ @Stable fun Modifier.alignBy(alignmentLineBlock: (Measured) -> Int): Modifier } internal object ColumnScopeInstance : ColumnScope { @Stable override fun Modifier.weight(weight: Float, fill: Boolean): Modifier { require(weight > 0.0) { "invalid weight $weight; must be greater than zero" } return this.then( LayoutWeightElement( // Coerce Float.POSITIVE_INFINITY to Float.MAX_VALUE to avoid errors weight = weight.coerceAtMost(Float.MAX_VALUE), fill = fill ) ) } @Stable override fun Modifier.align(alignment: Alignment.Horizontal) = this.then( HorizontalAlignElement( horizontal = alignment ) ) @Stable override fun Modifier.alignBy(alignmentLine: VerticalAlignmentLine) = this.then( WithAlignmentLineElement( alignmentLine = alignmentLine ) ) @Stable override fun Modifier.alignBy(alignmentLineBlock: (Measured) -> Int) = this.then( WithAlignmentLineBlockElement( block = alignmentLineBlock ) ) }
28
Kotlin
937
5,108
89ec14e39cf771106a8719337062572717cbad31
15,197
androidx
Apache License 2.0
CRM/src/test/kotlin/org/example/crm/integrationTest/services/MessageServiceIntegrationTest.kt
M4tT3d
874,249,564
false
{"Kotlin": 354206, "TypeScript": 180680, "JavaScript": 3610, "Dockerfile": 2844, "CSS": 2078, "HTML": 302}
package org.example.crm.integrationTest.services import jakarta.persistence.EntityNotFoundException import org.example.crm.dtos.request.create.CMessageDTO import org.example.crm.dtos.request.filters.MessageParams import org.example.crm.dtos.request.filters.PaginationParams import org.example.crm.integrationTest.controllers.IntegrationTest import org.example.crm.services.MessageService import org.example.crm.utils.enums.Channel import org.example.crm.utils.enums.Priority import org.example.crm.utils.enums.State import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.ContextConfiguration import java.text.SimpleDateFormat import java.util.* @SpringBootTest @ContextConfiguration(initializers = [IntegrationTest.Initializer::class]) class MessageServiceIntegrationTest : IntegrationTest() { @Autowired private lateinit var messageService: MessageService @Test fun testCreateNewMessage() { // Arrange val createMessageDTO = CMessageDTO( sender = "1234567891", date = stringToDate("2022-01-01"), subject = "Test subject", body = "Test body", channel = Channel.TEXT_MESSAGE, priority = Priority.HIGH, state = State.RECEIVED, comment = "Test comment", ) // Act val createdMessage = messageService.create(createMessageDTO) // Assert Assertions.assertNotNull(createdMessage) Assertions.assertEquals(createMessageDTO.sender, createdMessage.sender) Assertions.assertEquals(createMessageDTO.date, createdMessage.date) Assertions.assertEquals(createMessageDTO.subject, createdMessage.subject) Assertions.assertEquals(createMessageDTO.body, createdMessage.body) Assertions.assertEquals(createMessageDTO.channel, createdMessage.channel) Assertions.assertEquals(createMessageDTO.priority, createdMessage.priority) Assertions.assertEquals(createMessageDTO.state, createdMessage.state) Assertions.assertEquals(createMessageDTO.comment, createdMessage.comment) } @Test fun testUpdateMessageState() { // Arrange val createMessageDTO = CMessageDTO( sender = "1234567891", date = stringToDate("2022-01-01"), subject = "Test subject", body = "Test body", channel = Channel.TEXT_MESSAGE, priority = Priority.HIGH, state = State.RECEIVED, comment = "Test comment", ) val createdMessage = messageService.create(createMessageDTO) val newState = State.READ // Act val updatedMessage = messageService.updateState(createdMessage.id, createMessageDTO.copy(state = newState), "State updated") // Assert Assertions.assertNotNull(updatedMessage) Assertions.assertEquals(newState, updatedMessage.state) } @Test fun testUpdateMessagePriority() { // Arrange val createMessageDTO = CMessageDTO( sender = "1234567891", date = stringToDate("2022-01-01"), subject = "Test subject", body = "Test body", channel = Channel.TEXT_MESSAGE, priority = Priority.HIGH, state = State.RECEIVED, comment = "Test comment", ) val createdMessage = messageService.create(createMessageDTO) val newPriority = Priority.LOW // Act val updatedMessage = messageService.updatePriority(createdMessage.id, newPriority) // Assert Assertions.assertNotNull(updatedMessage) Assertions.assertEquals(newPriority, updatedMessage.priority) } @Test fun testListAllMessages() { // Arrange val createMessageDTO = CMessageDTO( sender = "1234567891", date = stringToDate("2022-01-01"), subject = "Test subject", body = "Test body", channel = Channel.TEXT_MESSAGE, priority = Priority.HIGH, state = State.RECEIVED, comment = "Test comment", ) messageService.create(createMessageDTO) val paginationParams = PaginationParams() val params = MessageParams("asc", "asc") // Act val messages = messageService.listAll(paginationParams, params) // Assert Assertions.assertTrue(messages.isNotEmpty()) } @Test fun testFindMessageById() { // Arrange val createMessageDTO = CMessageDTO( sender = "1234567891", date = stringToDate("2022-01-01"), subject = "Test subject", body = "Test body", channel = Channel.TEXT_MESSAGE, priority = Priority.HIGH, state = State.RECEIVED, comment = "Test comment", ) val createdMessage = messageService.create(createMessageDTO) // Act val foundMessage = messageService.findById(createdMessage.id) // Assert Assertions.assertNotNull(foundMessage) Assertions.assertEquals(createdMessage.id, foundMessage.id) } @Test fun testFindMessageByNonExistentId() { // Arrange val nonExistentId = 9999L // Assumiamo che questo ID non esista nel database // Act and Assert assertThrows<EntityNotFoundException> { messageService.findById(nonExistentId) } } } fun stringToDate(dateString: String, format: String = "yyyy-MM-dd"): Date { val formatter = SimpleDateFormat(format) return formatter.parse(dateString) }
0
Kotlin
0
0
26ff03cc3863e278d0ec6b87ced384122cf66c98
5,855
wa2-project-job-placement
MIT License
f2-client/f2-client-ktor/f2-client-ktor-http/src/jvmTest/kotlin/f2/client/ktor/http/server/command/ServerConsumeCommand.kt
komune-io
746,765,045
false
{"Kotlin": 221432, "Java": 155444, "Gherkin": 24181, "Makefile": 1677, "JavaScript": 1459, "Dockerfile": 963, "CSS": 102}
package f2.client.ktor.http.server.command import f2.dsl.fnc.F2Function import kotlinx.serialization.Serializable typealias ServerConsumeFunction = F2Function<ServerConsumeCommand, ServerConsumedEvent> @Serializable data class ServerConsumeCommand( val stuff: String ) typealias ServerConsumedEvent = ServerConsumeCommand
1
Kotlin
0
0
72b43ee5a40e0167556cb4657cc518614f44a108
330
fixers-f2
Apache License 2.0
app/src/main/java/com/my/homecloud/ui/watercounter/WaterCounter.kt
valientinx
604,223,619
false
{"Kotlin": 28916}
package com.my.homecloud.ui.watercounter import android.annotation.SuppressLint import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue @Composable fun WaterCounter(modifier: Modifier = Modifier) { Column(modifier = modifier.padding(16.dp)) { var count by rememberSaveable {mutableStateOf(0)} if (count > 3) { Text( text = "You've had ${count} glasses.", modifier = modifier.padding(16.dp) ) } Button(onClick = { count++ }, Modifier.padding(top = 8.dp), enabled = count < 10) { Text("Add one") } } } @Composable fun StatelessCounter(title: String, count: Int, onIncrement: () -> Unit, modifier: Modifier = Modifier) { Column(modifier = modifier.padding(16.dp)) { if (count > 0) { Text("You've had $count glasses of $title") } Button(onClick = onIncrement, Modifier.padding(top = 8.dp), enabled = count < 10) { Text("Add one") } } } @Composable fun StatefullCounter(modifier: Modifier = Modifier) { var count by rememberSaveable { mutableIntStateOf(0) } var juiceCount by remember { mutableStateOf(0) } StatelessCounter(title = "water", count = count, onIncrement = { count++ }, modifier.padding(0.dp,0.dp,0.dp,0.dp)) StatelessCounter(title = "juice", count = juiceCount, onIncrement = { juiceCount++ }, modifier.padding(0.dp,0.dp,0.dp,0.dp)) } @Composable fun WellnessScreen(modifier: Modifier = Modifier) { Column(modifier = modifier.padding(16.dp)) { // WaterCounter(modifier) StatefullCounter(modifier) } }
1
Kotlin
0
3
aeb50a30967f358f0db61b81328041a0b3866d76
2,195
LocalMediaStoreSync
Apache License 2.0
app/src/main/java/io/plaidapp/ui/PlaidApplication.kt
hzsweers
47,207,521
false
null
/* * Copyright 2018 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 io.plaidapp.ui import android.app.Activity import android.app.Application import android.content.Context import androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY import androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM import androidx.appcompat.app.AppCompatDelegate.setDefaultNightMode import androidx.core.os.BuildCompat import io.plaidapp.core.dagger.CoreComponent import io.plaidapp.core.dagger.DaggerCoreComponent /** * Io and Behold */ class PlaidApplication : Application() { override fun onCreate() { super.onCreate() val nightMode = if (BuildCompat.isAtLeastQ()) { MODE_NIGHT_FOLLOW_SYSTEM } else { MODE_NIGHT_AUTO_BATTERY } setDefaultNightMode(nightMode) } private val coreComponent: CoreComponent by lazy { DaggerCoreComponent.create() } companion object { @JvmStatic fun coreComponent(context: Context) = (context.applicationContext as PlaidApplication).coreComponent } } fun Activity.coreComponent() = PlaidApplication.coreComponent(this)
1
null
6
42
9aa03c4c1db0c364bbfcd32b17c09a24d31e9361
1,719
plaid
Apache License 2.0
rx-validation-errors/src/main/java/by/shostko/rxvalidation/StringValidator.kt
shostko
212,552,006
false
null
@file:Suppress("unused") package by.shostko.rxvalidation import android.text.TextUtils import by.shostko.errors.ErrorCode import by.shostko.rxvalidation.errors.BaseValidationErrorCode import by.shostko.rxvalidation.errors.ValidationError private class StringValidationException(code: ErrorCode) : ValidationError(code) class NotEmptyValidator<T : CharSequence>(private val code: ErrorCode? = null) : Validator<T>() { override fun validate(value: T) { if (value.isEmpty()) { throw StringValidationException(code ?: BaseValidationErrorCode(this, "Value should not be empty")) } } } class EmptyValidator<T : CharSequence>(private val code: ErrorCode? = null) : Validator<T>() { override fun validate(value: T) { if (value.isNotEmpty()) { throw StringValidationException(code ?: BaseValidationErrorCode(this, "Value should be empty")) } } } class NotBlankValidator<T : CharSequence>(private val code: ErrorCode? = null) : Validator<T>() { override fun validate(value: T) { if (value.isBlank()) { throw StringValidationException(code ?: BaseValidationErrorCode(this, "Value should not be blank")) } } } class BlankValidator<T : CharSequence>(private val code: ErrorCode? = null) : Validator<T>() { override fun validate(value: T) { if (value.isNotBlank()) { throw StringValidationException(code ?: BaseValidationErrorCode(this, "Value should be blank")) } } } class LengthValidator<T : CharSequence>(private val expectedLength: Int, private val code: ErrorCode? = null) : Validator<T>() { override fun validate(value: T) { if (value.length != expectedLength) { throw StringValidationException(code ?: BaseValidationErrorCode(this, "Value length should be $expectedLength")) } } } class LengthLessValidator<T : CharSequence>(private val limit: Int, private val code: ErrorCode? = null) : Validator<T>() { override fun validate(value: T) { if (value.length >= limit) { throw StringValidationException(code ?: BaseValidationErrorCode(this, "Value length should be less than $limit")) } } } class LengthLessOrEqualValidator<T : CharSequence>(private val limit: Int, private val code: ErrorCode? = null) : Validator<T>() { override fun validate(value: T) { if (value.length > limit) { throw StringValidationException(code ?: BaseValidationErrorCode(this, "Value length should be less or equal than $limit")) } } } class LengthOverValidator<T : CharSequence>(private val limit: Int, private val code: ErrorCode? = null) : Validator<T>() { override fun validate(value: T) { if (value.length <= limit) { throw StringValidationException(code ?: BaseValidationErrorCode(this, "Value length should be over than $limit")) } } } class LengthOverOrEqualValidator<T : CharSequence>(private val limit: Int, private val code: ErrorCode? = null) : Validator<T>() { override fun validate(value: T) { if (value.length < limit) { throw StringValidationException(code ?: BaseValidationErrorCode(this, "Value length should be over or equal than $limit")) } } } class SingleCharValidator<T : CharSequence>(private val code: ErrorCode? = null) : Validator<T>() { override fun validate(value: T) { if (value.length != 1) { throw StringValidationException(code ?: BaseValidationErrorCode(this, "Value should contain only one char")) } } } class NumericValidator<T : CharSequence>(private val code: ErrorCode? = null) : Validator<T>() { override fun validate(value: T) { if (!TextUtils.isDigitsOnly(value)) { throw StringValidationException(code ?: BaseValidationErrorCode(this, "Value should contain only digits")) } } } class GraphicValidator<T : CharSequence>(private val code: ErrorCode? = null) : Validator<T>() { override fun validate(value: T) { if (!TextUtils.isGraphic(value)) { throw StringValidationException(code ?: BaseValidationErrorCode(this, "Value should contain at least one printable char")) } } }
0
Kotlin
0
0
da47331f5eb62cd7dec9ba84b23dca2df196f9bb
4,230
rx-validation
Apache License 2.0
permission-flow/src/main/java/dev/shreyaspatil/permissionFlow/internal/ApplicationStateMonitor.kt
PatilShreyas
504,894,810
false
{"Kotlin": 120505}
/** * Copyright 2022 Shreyas Patil * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shreyaspatil.permissionFlow.internal import android.app.Activity import android.app.Application import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import androidx.annotation.RequiresApi import androidx.annotation.VisibleForTesting import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import dev.shreyaspatil.permissionFlow.PermissionState import java.lang.ref.WeakReference import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.callbackFlow /** * Monitors the state of the application and provides information about the info and state of * application. */ internal class ApplicationStateMonitor(private val application: Application) { private var currentActivity: WeakReference<Activity>? = null /** Returns the current state of the permission. */ fun getPermissionState(permission: String): PermissionState { val isGranted = isPermissionGranted(permission) val isRationaleRequired = shouldShowPermissionRationale(permission) return PermissionState(permission, isGranted, isRationaleRequired) } /** Returns whether the permission should show rationale or not. */ private fun shouldShowPermissionRationale(permission: String): Boolean? { val activity = currentActivity?.get() ?: return null return ActivityCompat.shouldShowRequestPermissionRationale(activity, permission) } /** Returns whether the permission is granted or not. */ private fun isPermissionGranted(permission: String): Boolean { return ContextCompat.checkSelfPermission( application, permission, ) == PackageManager.PERMISSION_GRANTED } /** * A flow which gives callback whenever any activity is started withing application (without * configuration change) or any activity is resumed after being in multi-window or * picture-in-picture mode. */ val activityForegroundEvents get() = callbackFlow { val callback = object : Application.ActivityLifecycleCallbacks { private var isActivityChangingConfigurations: Boolean? = null private var wasInMultiWindowMode: Boolean? = null private var wasInPictureInPictureMode: Boolean? = null override fun onActivityPreCreated( activity: Activity, savedInstanceState: Bundle?, ) { currentActivity = WeakReference(activity) } override fun onActivityCreated( activity: Activity, savedInstanceState: Bundle?, ) { if (currentActivity?.get() != activity) { currentActivity = WeakReference(activity) } } /** * Whenever activity receives onStart() lifecycle callback, emit foreground * event only when activity hasn't changed configurations. */ override fun onActivityStarted(activity: Activity) { if (isActivityChangingConfigurations == false) { trySend(Unit) } } override fun onActivityStopped(activity: Activity) { isActivityChangingConfigurations = activity.isChangingConfigurations } /** * Whenever application is resized after being in in PiP or multi-window mode, * or exits from these modes, onResumed() lifecycle callback is triggered. * * Here we assume that user has changed permission from app settings after being * in PiP or multi-window mode. So whenever these modes are exited, emit * foreground event. */ override fun onActivityResumed(activity: Activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { if (isActivityResumedAfterMultiWindowOrPiPMode(activity)) { trySend(Unit) } wasInMultiWindowMode = activity.isInMultiWindowMode wasInPictureInPictureMode = activity.isInPictureInPictureMode } } /** * Whenever application is launched in PiP or multi-window mode, onPaused() * lifecycle callback is triggered. */ override fun onActivityPaused(activity: Activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { wasInMultiWindowMode = activity.isInMultiWindowMode wasInPictureInPictureMode = activity.isInPictureInPictureMode } } override fun onActivitySaveInstanceState( activity: Activity, outState: Bundle, ) {} override fun onActivityDestroyed(activity: Activity) { if (activity == currentActivity?.get()) { currentActivity?.clear() } } /** * Returns whether [activity] was previously in multi-window mode or PiP mode. */ @RequiresApi(Build.VERSION_CODES.N) private fun isActivityResumedAfterMultiWindowOrPiPMode(activity: Activity) = (wasInMultiWindowMode == true && !activity.isInMultiWindowMode) || (wasInPictureInPictureMode == true && !activity.isInPictureInPictureMode) } application.registerActivityLifecycleCallbacks(callback) awaitClose { // Cleanup application.unregisterActivityLifecycleCallbacks(callback) } } @VisibleForTesting fun getCurrentActivityReference() = currentActivity }
6
Kotlin
21
557
016837505eb08a388ba15365312636479a4f708e
7,080
permission-flow-android
Apache License 2.0
app/src/main/java/com/thiha/efficientweatherapp/model/WeatherObject.kt
sheldonTest
846,962,649
false
{"Kotlin": 30990}
package com.example.jetweatherforecast.model data class WeatherObject( val description: String, val icon: String, val id: Int, val main: String)
0
Kotlin
0
0
fe2f31a4be98d5e99403ce225c7a58bff7957dc5
161
u-pd-android-jetpack-compose-comprehensive-bootcamp-2022
MIT License
one.irradia.opds1_2.parser.extension.spi/src/main/java/one.irradia.opds1_2.parser.extension.spi/OPDS12FeedExtensionParserProviderType.kt
irradia
177,828,518
false
{"Gradle": 12, "INI": 12, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 1, "YAML": 1, "Markdown": 1, "XML": 36, "Kotlin": 61, "Java": 8}
package one.irradia.opds1_2.parser.extension.spi /** * A provider of extension parsers. */ interface OPDS12FeedExtensionParserProviderType { /** * @param context The parser context * * Create a parser. */ fun createParser( context: OPDS12FeedExtensionParserContextType) : OPDS12FeedExtensionParserType }
1
null
1
1
78596ee9c5e528ec4810472f1252d844abdf7fe3
335
one.irradia.opds1_2
BSD Zero Clause License
app/src/main/java/com/fitken/lanchat/thread/SendMessageAsync.kt
nmhung
115,481,934
false
null
package com.fitken.lanchat.thread import android.os.AsyncTask import com.fitken.lanchat.MyApplication import java.io.BufferedWriter import java.io.IOException import java.io.OutputStreamWriter import java.io.PrintWriter import java.net.Socket import java.net.UnknownHostException /** * Created by ken on 12/28/17. */ class SendMessageAsync(socket: Socket) : AsyncTask<String, Void, Void>() { private var mSocket: Socket = socket override fun doInBackground(vararg params: String): Void? { sendMessage(params[0]) return null } private fun sendMessage(message: String) { try { val out = PrintWriter(BufferedWriter( OutputStreamWriter(mSocket.getOutputStream())), true) out.println(message) val threads = MyApplication.instance.getThreads() for (i in 0 until threads!!.size) { if (threads[i] != null && !threads[i]!!.mClientSocket.inetAddress.toString().equals(mSocket.inetAddress.toString())) { val out = PrintWriter(BufferedWriter( OutputStreamWriter(threads[i]!!.mClientSocket.getOutputStream())), true) out.println(message) } } } catch (e: UnknownHostException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } catch (e: Exception) { e.printStackTrace() } } }
1
Kotlin
1
3
97df05546b9e0b2b454ffb039762ff5a705284e2
1,531
chat-in-LAN-android-ios
MIT License
src/main/kotlin/de/bdr/servko/keycloak/gematik/idp/model/AuthenticationFlowType.kt
Bundesdruckerei-GmbH
588,222,404
false
{"Kotlin": 349718, "HTML": 17285, "JavaScript": 6324, "FreeMarker": 4218, "Dockerfile": 1465}
/* * Copyright 2023 Bundesdruckerei GmbH and/or its affiliates * and other contributors. * * 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 de.bdr.servko.keycloak.gematik.idp.model enum class AuthenticationFlowType(var typeName: String) { LEGACY("legacy"), MULTI("multi"), HBA("HBA"), SMCB("SMC-B"); }
2
Kotlin
1
8
86fb3e67dd4492d01c2e66db068820b7109f24f3
848
Gematik-IDP
Apache License 2.0
src/main/kotlin/com/github/poolParty/pullPartyBot/handler/interaction/command/ClearCommand.kt
pool-party
276,690,235
false
null
package com.github.poolParty.pullPartyBot.handler.interaction.command import com.elbekd.bot.Bot import com.elbekd.bot.types.Message import com.github.poolParty.pullPartyBot.Configuration import com.github.poolParty.pullPartyBot.handler.Button import com.github.poolParty.pullPartyBot.handler.deleteMessageLogging import com.github.poolParty.pullPartyBot.handler.interaction.callback.ClearConfirmationCallback import com.github.poolParty.pullPartyBot.handler.message.DeleteMessages import com.github.poolParty.pullPartyBot.handler.message.HelpMessages import com.github.poolParty.pullPartyBot.handler.sendMessageLogging import kotlinx.coroutines.delay class ClearCommand() : AdministratorCommand("clear", "shut down all the parties ever existed", HelpMessages.clear) { override suspend fun Bot.administratorAction(message: Message, args: List<String>) { val chatId = message.chat.id val sentMessage = sendMessageLogging( chatId, DeleteMessages.clearConfirmation, buttons = listOf( Button("No, I changed my mind", ClearConfirmationCallback(chatId, message.from?.id, false)), Button("Yes, I am pretty sure", ClearConfirmationCallback(chatId, message.from?.id, true)), ), ) delay(Configuration.STALE_PING_SECONDS * 1_000L) deleteMessageLogging(chatId, sentMessage.messageId) } }
2
Kotlin
0
8
1815ce56b70e5ba6b9d708c00099969fc026d8a6
1,413
pull-party-bot
MIT License
src/se/clau/yang/psi/YangElementType.kt
geddings-bsn
621,946,905
true
{"Kotlin": 26715, "Lex": 9588, "Java": 1609}
/* * Copyright 2014 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package se.clau.yang.psi import se.clau.yang.YangLanguage import com.intellij.psi.tree.IElementType import org.jetbrains.annotations.NonNls class YangElementType(@NonNls debugName: String) : IElementType(debugName, YangLanguage.INSTANCE)
0
null
0
0
f627632b194fca15c54626ba6eeeaa0f82b02900
840
yang-plugin
Apache License 2.0
app/src/main/java/app/odapplications/bitstashwallet/modules/settings/basecurrency/BaseCurrencySettingsView.kt
bitstashco
220,133,996
false
null
package app.odapplications.bitstashwallet.modules.settings.basecurrency import androidx.lifecycle.MutableLiveData class BaseCurrencySettingsView : BaseCurrencySettingsModule.IView { val currencyItems = MutableLiveData<List<CurrencyViewItem>>() override fun show(items: List<CurrencyViewItem>) { currencyItems.value = items } }
4
null
3
11
64c242dbbcb6b4df475a608b1edb43f87e5091fd
350
BitStash-Android-Wallet
MIT License
test-suite-kotlin/src/test/kotlin/io/micronaut/mqtt/docs/publisher/qos/ProductClient.kt
micronaut-projects
304,407,403
false
null
package io.micronaut.mqtt.docs.publisher.qos // tag::imports[] import io.micronaut.mqtt.annotation.Qos import io.micronaut.mqtt.annotation.Topic import io.micronaut.mqtt.annotation.v5.MqttPublisher // end::imports[] import io.micronaut.context.annotation.Requires; @Requires(property = "spec.name", value = "PublisherQosSpec") // tag::clazz[] @MqttPublisher interface ProductClient { @Topic(value = "product", qos = 2) // <1> fun send(data: ByteArray?) @Topic("product") fun send(data: ByteArray?, @Qos qos: Int) // <2> } // end:clazz[]
5
null
9
13
b5bc2728a30b3df0cb9c1f1aa0b38c992d63baf0
558
micronaut-mqtt
Apache License 2.0
kplotandroidlib/src/androidTest/java/dev/curlybraces/kplot/UiUtilsTests.kt
PravSonawane
223,865,951
false
null
package dev.curlybraces.kplot import android.content.Context import android.util.TypedValue import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.rule.ActivityTestRule import org.junit.Assert.* import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class UiUtilsTests { lateinit var context: Context @get:Rule var activityRule: ActivityTestRule<TestActivity> = ActivityTestRule(TestActivity::class.java) @Before fun setup() { context = InstrumentationRegistry.getInstrumentation().context } @Test fun given_dp_when_converted_to_pixels_then_should_get_pixels() { val dp = 80 val expectedPixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp.toFloat(), context.resources.displayMetrics).toInt() assertEquals(expectedPixels, dpToPx(context, dp)) } }
1
Kotlin
0
0
516e35f3fc7679a59d01b113cbb3305f9de6da40
988
kplot
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/Star.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.outline 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.Outline.Star: ImageVector get() { if (_star != null) { return _star!! } _star = Builder(name = "Star", 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(23.836f, 8.794f) arcToRelative(3.179f, 3.179f, 0.0f, false, false, -3.067f, -2.226f) lineTo(16.4f, 6.568f) lineTo(15.073f, 2.432f) arcToRelative(3.227f, 3.227f, 0.0f, false, false, -6.146f, 0.0f) lineTo(7.6f, 6.568f) lineTo(3.231f, 6.568f) arcToRelative(3.227f, 3.227f, 0.0f, false, false, -1.9f, 5.832f) lineTo(4.887f, 15.0f) lineTo(3.535f, 19.187f) arcTo(3.178f, 3.178f, 0.0f, false, false, 4.719f, 22.8f) arcToRelative(3.177f, 3.177f, 0.0f, false, false, 3.8f, -0.019f) lineTo(12.0f, 20.219f) lineToRelative(3.482f, 2.559f) arcToRelative(3.227f, 3.227f, 0.0f, false, false, 4.983f, -3.591f) lineTo(19.113f, 15.0f) lineToRelative(3.56f, -2.6f) arcTo(3.177f, 3.177f, 0.0f, false, false, 23.836f, 8.794f) close() moveTo(21.493f, 10.785f) lineTo(17.349f, 13.814f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, -0.362f, 1.116f) lineTo(18.562f, 19.8f) arcToRelative(1.227f, 1.227f, 0.0f, false, true, -1.895f, 1.365f) lineToRelative(-4.075f, -3.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, -1.184f, 0.0f) lineToRelative(-4.075f, 3.0f) arcToRelative(1.227f, 1.227f, 0.0f, false, true, -1.9f, -1.365f) lineTo(7.013f, 14.93f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, -0.362f, -1.116f) lineTo(2.507f, 10.785f) arcToRelative(1.227f, 1.227f, 0.0f, false, true, 0.724f, -2.217f) horizontalLineToRelative(5.1f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.952f, -0.694f) lineToRelative(1.55f, -4.831f) arcToRelative(1.227f, 1.227f, 0.0f, false, true, 2.336f, 0.0f) lineToRelative(1.55f, 4.831f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.952f, 0.694f) horizontalLineToRelative(5.1f) arcToRelative(1.227f, 1.227f, 0.0f, false, true, 0.724f, 2.217f) close() } } .build() return _star!! } private var _star: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,508
icons
MIT License
app/src/main/java/com/kerite/pokedex/model/enums/MovePattern.kt
Kerite
535,721,279
false
{"Kotlin": 187667, "CMake": 1639, "C++": 342}
package com.kerite.pokedex.model.enums enum class MovePattern { LEVEL, TM_MACHINE, BREED, TEACH; companion object { fun fromIndex(index: Int): MovePattern { for (value in values()) { if (value.ordinal == index) { return value } } throw IndexOutOfBoundsException() } } }
0
Kotlin
0
2
98758205bdf25480bab8d19d92a0daa839a0e7e2
399
PokeDex-android
Apache License 2.0
app/src/main/java/com/example/Tapatan/ui/GameViewModel.kt
PatrickLyonsISD
709,221,895
false
{"Kotlin": 27739}
package com.example.Tapatan.ui import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel class GameViewModel : ViewModel() { var buttons = Array(3) { arrayOfNulls<String>(3) } var currentPlayer = mutableStateOf("Black") var roundCount = 0 var gameEnded = mutableStateOf(false) var winner = mutableStateOf<String?>(null) var gamePhase = mutableStateOf("placing") var selectedPiece = mutableStateOf<Pair<Int, Int>?>(null) var blackScore = mutableStateOf(0) var whiteScore = mutableStateOf(0) fun onButtonClick(row: Int, col: Int) { when (gamePhase.value) { "placing" -> handlePlacingPhase(row, col) "moving" -> handleMovingPhase(row, col) } } private fun handlePlacingPhase(row: Int, col: Int) { if (buttons[row][col] == null && !gameEnded.value) { buttons[row][col] = currentPlayer.value roundCount++ if (checkForWin(row, col)) { gameEnded.value = true winner.value = currentPlayer.value } else if (roundCount == 6) { gamePhase.value = "moving" } changePlayer() } } private fun handleMovingPhase(row: Int, col: Int) { selectedPiece.value?.let { (selectedRow, selectedCol) -> if (buttons[row][col] == null && isAdjacent(selectedRow, selectedCol, row, col)) { buttons[selectedRow][selectedCol] = null buttons[row][col] = currentPlayer.value if (checkForWin(row, col)) { gameEnded.value = true winner.value = currentPlayer.value } selectedPiece.value = null changePlayer() } } ?: run { if (buttons[row][col] == currentPlayer.value) { selectedPiece.value = Pair(row, col) } } } private fun isAdjacent(row1: Int, col1: Int, row2: Int, col2: Int): Boolean { return Math.abs(row1 - row2) <= 1 && Math.abs(col1 - col2) <= 1 && !(row1 == row2 && col1 == col2) } private fun changePlayer() { if (!gameEnded.value) { currentPlayer.value = if (currentPlayer.value == "Black") "White" else "Black" } } private fun checkForWin(row: Int, col: Int): Boolean { val player = buttons[row][col] // Function to update the score fun updateScore() { if (player == "Black") { blackScore.value += 1 } else if (player == "White") { whiteScore.value += 1 } } // Check for horizontal win for (i in 0 until 3) { if (buttons[row][i] != player) { break } if (i == 2) { updateScore() return true } } // Check for vertical win for (i in 0 until 3) { if (buttons[i][col] != player) { break } if (i == 2) { updateScore() return true } } // Check for diagonal win (top-left to bottom-right) if (row == col) { for (i in 0 until 3) { if (buttons[i][i] != player) { break } if (i == 2) { updateScore() return true } } } // Check for diagonal win (top-right to bottom-left) if (row + col == 2) { for (i in 0 until 3) { if (buttons[i][2 - i] != player) { break } if (i == 2) { updateScore() return true } } } return false } fun resetGame() { buttons = Array(3) { arrayOfNulls<String>(3) } currentPlayer.value = "Black" roundCount = 0 gameEnded.value = false winner.value = null gamePhase.value = "placing" selectedPiece.value = null } fun newGame() { resetGame() blackScore.value = 0 whiteScore.value = 0 } }
0
Kotlin
0
0
5c4ee9d3e42b02a538f73f7176077e72099a918f
4,319
Tapatan
Apache License 2.0
cinescout/database/src/commonMain/kotlin/cinescout/database/model/DatabaseGenre.kt
4face-studi0
280,630,732
false
null
package cinescout.database.model typealias DatabaseGenre = cinescout.database.Genre
19
Kotlin
2
3
d64398507d60a20a445db1451bdd8be23d65c9aa
85
CineScout
Apache License 2.0
buildSrc/src/main/kotlin/com/spark/review/wizard/IWizard.kt
ZuYun
402,787,726
false
{"Gradle": 3, "Kotlin": 55, "Gradle Kotlin DSL": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "YAML": 1, "Proguard": 3, "XML": 90, "Java": 3, "Groovy": 9}
package com.spark.review.wizard import java.io.File import java.util.jar.JarEntry /** * @author yun. * @date 2021/7/22 * @des [一句话描述] * @since [https://github.com/ZuYun] * <p><a href="https://github.com/ZuYun">github</a> */ abstract class IWizard { fun enable(): Boolean = true abstract fun transformStart() open fun checkIfJarMatches(srcJarFile: File, destJarFile: File): Boolean { return true } open fun checkIfJarEntryMatches(srcJarEntry: JarEntry, srcJarFile: File, destJarFile: File): Boolean { return true } open fun transformJarEntry(classFileByte: ByteArray): ByteArray { return classFileByte } open fun checkIfFileMatches(srcFile: File, destFile: File, srcDirectory: File): Boolean { return true } open fun transformFile(classFileByte: ByteArray): ByteArray { return classFileByte } abstract fun transformEnd() }
1
null
1
1
53460de3f8192ed958a4351243c7c7762c4aac7a
931
sparkj
Apache License 2.0
buildSrc/src/main/kotlin/com/spark/review/wizard/IWizard.kt
ZuYun
402,787,726
false
{"Gradle": 3, "Kotlin": 55, "Gradle Kotlin DSL": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "YAML": 1, "Proguard": 3, "XML": 90, "Java": 3, "Groovy": 9}
package com.spark.review.wizard import java.io.File import java.util.jar.JarEntry /** * @author yun. * @date 2021/7/22 * @des [一句话描述] * @since [https://github.com/ZuYun] * <p><a href="https://github.com/ZuYun">github</a> */ abstract class IWizard { fun enable(): Boolean = true abstract fun transformStart() open fun checkIfJarMatches(srcJarFile: File, destJarFile: File): Boolean { return true } open fun checkIfJarEntryMatches(srcJarEntry: JarEntry, srcJarFile: File, destJarFile: File): Boolean { return true } open fun transformJarEntry(classFileByte: ByteArray): ByteArray { return classFileByte } open fun checkIfFileMatches(srcFile: File, destFile: File, srcDirectory: File): Boolean { return true } open fun transformFile(classFileByte: ByteArray): ByteArray { return classFileByte } abstract fun transformEnd() }
1
null
1
1
53460de3f8192ed958a4351243c7c7762c4aac7a
931
sparkj
Apache License 2.0
app/src/main/java/com/example/rollcall/navigation/DeepLinkFragment.kt
kimonkremizas
488,979,396
false
{"Kotlin": 44951}
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.rollcall.navigation 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.lifecycleScope import com.example.rollcall.appLogic.AppState import com.example.rollcall.databinding.DeeplinkFragmentBinding import com.example.rollcall.helpers.HelperFunctions import kotlinx.android.synthetic.main.deeplink_fragment.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.datetime.* import kotlinx.datetime.TimeZone import com.example.rollcall.models.Lesson import com.example.rollcall.services.LessonService import java.time.YearMonth /** * Fragment used to show how to deep link to a destination */ class DeepLinkFragment : Fragment() { private var _binding: DeeplinkFragmentBinding? = null private val binding get() = _binding!! private var selectedMonth: Int = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).monthNumber override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = DeeplinkFragmentBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) twMonthName?.text = HelperFunctions.GetMonthName(selectedMonth) + " 2022" AssignDayNumbers(LocalDateTime(2022, selectedMonth,1, 12, 30, 0, 0)) GetLessons(selectedMonth) minusMonth?.setOnClickListener { if(selectedMonth == 1) selectedMonth = 12 else selectedMonth-- twMonthName?.text = HelperFunctions.GetMonthName(selectedMonth) + " 2022" AssignDayNumbers(LocalDateTime(2022, selectedMonth,1, 12, 30, 0, 0)) GetLessons(selectedMonth) } plusMonth?.setOnClickListener { if(selectedMonth == 12) selectedMonth = 1 else selectedMonth++ twMonthName?.text = HelperFunctions.GetMonthName(selectedMonth) + " 2022" AssignDayNumbers(LocalDateTime(2022, selectedMonth,1, 12, 30, 0, 0)) GetLessons(selectedMonth) } } private fun GetLessons(month: Int) { lifecycleScope.launch(Dispatchers.IO) { val service: LessonService = LessonService() val lessons: List<Lesson> = service.GetLessonsByMonth(AppState.CurrentUser, selectedMonth) if(lessons.isEmpty()) { return@launch } lifecycleScope.launch(Dispatchers.Main) { AssignDayNumbersAndLessons(LocalDateTime(lessons[0].StartTime.year, lessons[0].StartTime.month, 1, 1, 0, 0, 0), lessons.sortedBy { x -> x.StartTime }) } } } private fun AssignDayNumbers(firstDate: LocalDateTime) { FlushCalendar() val yearMonthObject: YearMonth = YearMonth.of(firstDate.year, firstDate.month) val daysInMonth: Int = yearMonthObject.lengthOfMonth() var i:Int = 1 var k:Int = 1 if(firstDate.dayOfWeek.value != 6 && firstDate.dayOfWeek.value != 7 ){ k = firstDate.dayOfWeek.value } while(i <= daysInMonth) { val day:Int = LocalDateTime(firstDate.year, firstDate.month,i, 1, 0, 0, 0).dayOfWeek.value if(day != 6 && day != 7) { GetCalendarBlock(k).text = i.toString() i++ k++ } else { i++ } } } private fun AssignDayNumbersAndLessons(firstDate: LocalDateTime, lessons:List<Lesson>) { FlushCalendar() val yearMonthObject: YearMonth = YearMonth.of(firstDate.year, firstDate.month) val daysInMonth: Int = yearMonthObject.lengthOfMonth() var i:Int = 1 var k:Int = 1 while(i <= daysInMonth) { val day:Int = LocalDateTime(firstDate.year, firstDate.month,i, 1, 0, 0, 0).dayOfWeek.value if(day != 6 && day != 7) { GetCalendarBlock(k).text = i.toString() var lastDay: Int = 0 var beginning: String = "" for(l in lessons.filter { x -> x.StartTime.dayOfMonth == i }){ if(l.StartTime.dayOfMonth == i) { if(lastDay != l.StartTime.dayOfMonth) { GetCalendarBlock(k).text = GetCalendarBlock(k).text.toString() + "\n${l.StartTime.hour}:${l.StartTime.minute}" beginning = GetCalendarBlock(k).text.toString() lastDay = l.StartTime.dayOfMonth } val endTime = HelperFunctions.GetDatePlusMinutes(45, l.StartTime) if(lastDay != l.StartTime.dayOfMonth) { GetCalendarBlock(k).text = GetCalendarBlock(k).text.toString() + "\n-\n${endTime.hour}:${endTime.minute}" } else { GetCalendarBlock(k).text = beginning + "\n-\n${endTime.hour}:${endTime.minute}" } } } i++ k++ } else { i++ } } } private fun FlushCalendar() { var i:Int = 0 while (i < 26) { GetCalendarBlock(i).text = "" i++ } } private fun GetCalendarBlock(id: Int): TextView { when(id) { 1 -> return day1 2 -> return day2 3 -> return day3 4 -> return day4 5 -> return day5 6 -> return day6 7 -> return day7 8 -> return day8 9 -> return day9 10 -> return day10 11 -> return day11 12 -> return day12 13 -> return day13 14 -> return day14 15 -> return day15 16 -> return day16 17 -> return day17 18 -> return day18 19 -> return day19 20 -> return day20 21 -> return day21 22 -> return day22 23 -> return day23 24 -> return day24 25 -> return day25 else -> return day1 } } }
0
Kotlin
0
2
cd051564c70584f253f498272c0e6fd0451c5de3
7,160
roll-call-android
Apache License 2.0
Corona-Warn-App/src/test/java/de/rki/coronawarnapp/datadonation/analytics/modules/keysubmission/AnalyticsKeySubmissionCollectorTest.kt
corona-warn-app
268,027,139
false
null
package de.rki.coronawarnapp.datadonation.analytics.modules.keysubmission import de.rki.coronawarnapp.coronatest.type.BaseCoronaTest.Type.PCR import de.rki.coronawarnapp.coronatest.type.BaseCoronaTest.Type.RAPID_ANTIGEN import de.rki.coronawarnapp.datadonation.analytics.storage.AnalyticsSettings import de.rki.coronawarnapp.presencetracing.risk.PtRiskLevelResult import de.rki.coronawarnapp.risk.CombinedEwPtRiskLevelResult import de.rki.coronawarnapp.risk.EwRiskLevelResult import de.rki.coronawarnapp.risk.LastCombinedRiskResults import de.rki.coronawarnapp.risk.RiskState import de.rki.coronawarnapp.risk.storage.RiskLevelStorage import de.rki.coronawarnapp.util.TimeStamper import de.rki.coronawarnapp.util.toLocalDateUtc import io.mockk.MockKAnnotations import io.mockk.Runs import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.impl.annotations.MockK import io.mockk.just import io.mockk.verify import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.flowOf import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import testhelpers.BaseTest import testhelpers.coroutines.runTest2 import java.time.Duration import java.time.Instant class AnalyticsKeySubmissionCollectorTest : BaseTest() { @MockK lateinit var timeStamper: TimeStamper @MockK lateinit var analyticsSettings: AnalyticsSettings @MockK lateinit var analyticsPcrKeySubmissionStorage: AnalyticsPCRKeySubmissionStorage @MockK lateinit var analyticsRaKeySubmissionStorage: AnalyticsRAKeySubmissionStorage @MockK lateinit var riskLevelStorage: RiskLevelStorage @MockK lateinit var ewRiskLevelResult: EwRiskLevelResult @MockK lateinit var ptRiskLevelResult: PtRiskLevelResult private val now = Instant.now() @BeforeEach fun setup() { MockKAnnotations.init(this) every { timeStamper.nowUTC } returns now every { analyticsSettings.analyticsEnabled } returns flowOf(true) } @Test fun `save test registered`() = runTest2 { val combinedEwPtRiskLevelResult = CombinedEwPtRiskLevelResult(ptRiskLevelResult, ewRiskLevelResult) coEvery { analyticsPcrKeySubmissionStorage.updateTestRegisteredAt(any()) } just Runs coEvery { analyticsPcrKeySubmissionStorage.updateEwHoursSinceHighRiskWarningAtTestRegistration(any()) } just Runs coEvery { analyticsPcrKeySubmissionStorage.updateEwDaysSinceMostRecentDateAtRiskLevelAtTestRegistration(any()) } just Runs coEvery { analyticsPcrKeySubmissionStorage.updatePtDaysSinceMostRecentDateAtRiskLevelAtTestRegistration(any()) } just Runs coEvery { analyticsRaKeySubmissionStorage.updateTestRegisteredAt(any()) } just Runs coEvery { analyticsRaKeySubmissionStorage.updateEwHoursSinceHighRiskWarningAtTestRegistration(any()) } just Runs coEvery { analyticsRaKeySubmissionStorage.updateEwDaysSinceMostRecentDateAtRiskLevelAtTestRegistration(any()) } just Runs coEvery { analyticsRaKeySubmissionStorage.updatePtDaysSinceMostRecentDateAtRiskLevelAtTestRegistration(any()) } just Runs every { ewRiskLevelResult.riskState } returns RiskState.INCREASED_RISK every { ptRiskLevelResult.riskState } returns RiskState.LOW_RISK every { ewRiskLevelResult.calculatedAt } returns now every { ptRiskLevelResult.calculatedAt } returns now every { ewRiskLevelResult.wasSuccessfullyCalculated } returns true every { ptRiskLevelResult.wasSuccessfullyCalculated } returns true coEvery { riskLevelStorage.latestAndLastSuccessfulCombinedEwPtRiskLevelResult } returns flowOf(LastCombinedRiskResults(combinedEwPtRiskLevelResult, RiskState.INCREASED_RISK)) coEvery { riskLevelStorage.allEwRiskLevelResultsWithExposureWindows } returns flowOf(listOf(ewRiskLevelResult)) coEvery { riskLevelStorage.allEwRiskLevelResults } returns flowOf(listOf(ewRiskLevelResult)) coEvery { riskLevelStorage.allPtRiskLevelResults } returns flowOf(listOf(ptRiskLevelResult)) coEvery { analyticsPcrKeySubmissionStorage.testRegisteredAt } returns flowOf(now.toEpochMilli()) coEvery { analyticsRaKeySubmissionStorage.testRegisteredAt } returns flowOf(now.toEpochMilli()) every { ewRiskLevelResult.wasSuccessfullyCalculated } returns true every { analyticsPcrKeySubmissionStorage.ewHoursSinceHighRiskWarningAtTestRegistration } returns flowOf(-1) every { analyticsRaKeySubmissionStorage.ewHoursSinceHighRiskWarningAtTestRegistration } returns flowOf(-1) every { analyticsPcrKeySubmissionStorage.ewDaysSinceMostRecentDateAtRiskLevelAtTestRegistration } returns flowOf(0) every { analyticsRaKeySubmissionStorage.ewDaysSinceMostRecentDateAtRiskLevelAtTestRegistration } returns flowOf(0) every { analyticsPcrKeySubmissionStorage.ptDaysSinceMostRecentDateAtRiskLevelAtTestRegistration } returns flowOf(0) every { analyticsRaKeySubmissionStorage.ptDaysSinceMostRecentDateAtRiskLevelAtTestRegistration } returns flowOf(0) coEvery { analyticsPcrKeySubmissionStorage.clear() } just Runs coEvery { analyticsRaKeySubmissionStorage.clear() } just Runs every { ewRiskLevelResult.mostRecentDateAtRiskState } returns now.minus(Duration.ofDays(2)) every { ptRiskLevelResult.mostRecentDateAtRiskState } returns now.minus(Duration.ofDays(2)).toLocalDateUtc() val collector = createInstance(this) collector.reportTestRegistered(PCR) coVerify { analyticsPcrKeySubmissionStorage.updateTestRegisteredAt(any()) analyticsPcrKeySubmissionStorage.updateEwHoursSinceHighRiskWarningAtTestRegistration(any()) analyticsPcrKeySubmissionStorage.updatePtDaysSinceMostRecentDateAtRiskLevelAtTestRegistration(any()) analyticsPcrKeySubmissionStorage.updateEwDaysSinceMostRecentDateAtRiskLevelAtTestRegistration(any()) } val collector2 = createInstance(this) collector2.reportTestRegistered(RAPID_ANTIGEN) coVerify { analyticsRaKeySubmissionStorage.updateTestRegisteredAt(any()) analyticsRaKeySubmissionStorage.updateEwHoursSinceHighRiskWarningAtTestRegistration(any()) analyticsRaKeySubmissionStorage.updatePtDaysSinceMostRecentDateAtRiskLevelAtTestRegistration(any()) } } @Test fun `PCR save keys submitted`() = runTest2 { coEvery { analyticsPcrKeySubmissionStorage.updateSubmitted(any()) } just Runs coEvery { analyticsPcrKeySubmissionStorage.updateSubmittedAt(any()) } just Runs every { analyticsPcrKeySubmissionStorage.submitted } returns flowOf(false) every { analyticsPcrKeySubmissionStorage.submittedAt } returns flowOf(now.toEpochMilli()) val collector = createInstance(this) collector.reportSubmitted(PCR) coVerify { analyticsPcrKeySubmissionStorage.updateSubmitted(any()) analyticsPcrKeySubmissionStorage.updateSubmittedAt(any()) } } @Test fun `PCR save keys submitted after cancel`() = runTest2 { every { analyticsPcrKeySubmissionStorage.submittedAfterCancel } returns flowOf(false) coEvery { analyticsPcrKeySubmissionStorage.updateSubmittedAfterCancel(any()) } just Runs val collector = createInstance(this) collector.reportSubmittedAfterCancel(PCR) coVerify { analyticsPcrKeySubmissionStorage.updateSubmittedAfterCancel(any()) } } @Test fun `PCR save keys submitted in background`() = runTest2 { every { analyticsPcrKeySubmissionStorage.submittedInBackground } returns flowOf(false) coEvery { analyticsPcrKeySubmissionStorage.updateSubmittedInBackground(any()) } just Runs val collector = createInstance(this) collector.reportSubmittedInBackground(PCR) coVerify { analyticsPcrKeySubmissionStorage.updateSubmittedInBackground(any()) } } @Test fun `PCR save keys submitted after symptom flow`() = runTest2 { every { analyticsPcrKeySubmissionStorage.submittedAfterSymptomFlow } returns flowOf(false) coEvery { analyticsPcrKeySubmissionStorage.updateSubmittedAfterSymptomFlow(any()) } just Runs val collector = createInstance(this) collector.reportSubmittedAfterSymptomFlow(PCR) coVerify { analyticsPcrKeySubmissionStorage.updateSubmittedAfterSymptomFlow(any()) } } @Test fun `PCR save positive test result received`() = runTest2 { every { analyticsPcrKeySubmissionStorage.testResultReceivedAt } returns flowOf(-1L) coEvery { analyticsPcrKeySubmissionStorage.updateTestResultReceivedAt(any()) } just Runs val collector = createInstance(this) collector.reportPositiveTestResultReceived(PCR) coVerify { analyticsPcrKeySubmissionStorage.updateTestResultReceivedAt(any()) } } @Test fun `PCR positive test result received is not overwritten`() = runTest2 { every { analyticsPcrKeySubmissionStorage.testResultReceivedAt } returns flowOf(now.toEpochMilli()) val collector = createInstance(this) collector.reportPositiveTestResultReceived(PCR) coVerify(exactly = 0) { analyticsPcrKeySubmissionStorage.updateTestResultReceivedAt(any()) } } @Test fun `PCR save advanced consent given`() = runTest2 { every { analyticsPcrKeySubmissionStorage.advancedConsentGiven } returns flowOf(false) coEvery { analyticsPcrKeySubmissionStorage.updateAdvancedConsentGiven(any()) } just Runs val collector = createInstance(this) collector.reportAdvancedConsentGiven(PCR) coVerify { analyticsPcrKeySubmissionStorage.updateAdvancedConsentGiven(any()) } } @Test fun `PCR save consent withdrawn`() = runTest2 { every { analyticsPcrKeySubmissionStorage.advancedConsentGiven } returns flowOf(false) coEvery { analyticsPcrKeySubmissionStorage.updateAdvancedConsentGiven(any()) } just Runs val collector = createInstance(this) collector.reportConsentWithdrawn(PCR) coVerify { analyticsPcrKeySubmissionStorage.updateAdvancedConsentGiven(any()) } } @Test fun `save registered with tele tan`() = runTest2 { every { analyticsPcrKeySubmissionStorage.registeredWithTeleTAN } returns flowOf(false) coEvery { analyticsPcrKeySubmissionStorage.updateRegisteredWithTeleTAN(any()) } just Runs val collector = createInstance(this) collector.reportRegisteredWithTeleTAN() coVerify { analyticsPcrKeySubmissionStorage.updateRegisteredWithTeleTAN(any()) } } @Test fun `PCR save last submission flow screen`() = runTest2 { coEvery { analyticsPcrKeySubmissionStorage.updateLastSubmissionFlowScreen(any()) } just Runs every { analyticsPcrKeySubmissionStorage.lastSubmissionFlowScreen } returns flowOf(0) val collector = createInstance(this) collector.reportLastSubmissionFlowScreen(Screen.WARN_OTHERS, PCR) coVerify { analyticsPcrKeySubmissionStorage.updateLastSubmissionFlowScreen(any()) } } @Test fun `PCR no data collection if disabled`() = runTest2 { every { analyticsSettings.analyticsEnabled } returns flowOf(false) val collector = createInstance(this) collector.reportTestRegistered(PCR) verify(exactly = 0) { analyticsPcrKeySubmissionStorage.testRegisteredAt analyticsPcrKeySubmissionStorage.ewHoursSinceHighRiskWarningAtTestRegistration } collector.reportSubmitted(PCR) verify(exactly = 0) { analyticsPcrKeySubmissionStorage.submitted } collector.reportSubmittedInBackground(PCR) verify(exactly = 0) { analyticsPcrKeySubmissionStorage.submittedInBackground } collector.reportAdvancedConsentGiven(PCR) verify(exactly = 0) { analyticsPcrKeySubmissionStorage.advancedConsentGiven } collector.reportConsentWithdrawn(PCR) verify(exactly = 0) { analyticsPcrKeySubmissionStorage.advancedConsentGiven } collector.reportLastSubmissionFlowScreen(Screen.UNKNOWN, PCR) verify(exactly = 0) { analyticsPcrKeySubmissionStorage.lastSubmissionFlowScreen } collector.reportPositiveTestResultReceived(PCR) verify(exactly = 0) { analyticsPcrKeySubmissionStorage.testResultReceivedAt } collector.reportSubmittedAfterCancel(PCR) verify(exactly = 0) { analyticsPcrKeySubmissionStorage.submittedAfterCancel } } fun createInstance(scope: CoroutineScope) = AnalyticsKeySubmissionCollector( timeStamper, analyticsSettings, analyticsPcrKeySubmissionStorage, analyticsRaKeySubmissionStorage, riskLevelStorage, scope ) }
6
null
504
2,486
7b0eee8d53a090ee0ca585c6a90c4cec570e51d6
12,979
cwa-app-android
Apache License 2.0
app/src/main/java/app/runchallenge/view/fragment/preferences/PreferenceFragment.kt
afTrolle
186,638,043
false
null
package app.runchallenge.view.fragment.preferences import android.content.Context import android.os.Bundle import com.takisoft.preferencex.PreferenceFragmentCompat import android.view.View import androidx.navigation.fragment.findNavController import androidx.preference.ListPreference import androidx.preference.SwitchPreference import app.runchallenge.dagger.DaggerFragmentComponent import app.runchallenge.dagger.FragmentModule import app.runchallenge.model.data.settings.ApplicationSettings import app.runchallenge.model.data.settings.Setting import app.runchallenge.model.data.settings.UnitMeasurement import app.runchallenge.controller.repository.SettingsRepository import app.runchallenge.controller.repository.UserRepository import app.runchallenge.model.data.toolbar.MyToolbarSettings import app.runchallenge.view.fragment.base.mainActivity import app.runchallenge.view.fragment.base.updateToolbar import com.pavelsikun.seekbarpreference.SeekBarPreferenceCompat import javax.inject.Inject import android.util.TypedValue import app.runchallenge.R class PreferenceFragment : PreferenceFragmentCompat() { @Inject lateinit var settingsRepository: SettingsRepository @Inject lateinit var userRepository: UserRepository private val myToolbarSettings = MyToolbarSettings( title = R.string.toolbar_menu_settings_text, showBackButton = true ) override fun onCreatePreferencesFix(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.preferences, rootKey) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mainActivity?.let { val fragmentComponent = DaggerFragmentComponent.builder().fragmentModule(FragmentModule(this)) .activityComponent(it.activityComponent).build() fragmentComponent.inject(this) } findPreference("pref_eula").setOnPreferenceClickListener { findNavController().navigate(R.id.action_PreferenceFragment_to_EULAFragment) true // True if the click was handled. } findPreference("pref_about").setOnPreferenceClickListener { findNavController().navigate(R.id.action_PreferenceFragment_to_aboutFragment) true // True if the click was handled. } updateToolbar(myToolbarSettings) } fun dpToPx(dps: Float): Float { return TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, dps, resources.displayMetrics ) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) settingsRepository.observer(this, { response: Setting -> setUi(response.appSettings) // setTheme(response.appSettings.themeMode) }, { error -> }) findPreference("pref_sign_out").setOnPreferenceClickListener { userRepository.signOut() findNavController().popBackStack() return@setOnPreferenceClickListener true } findPreference("pref_auto_manage_theme").setOnPreferenceChangeListener { preference, newValue -> return@setOnPreferenceChangeListener true } findPreference("pref_always_dark_theme").setOnPreferenceChangeListener { preference, newValue -> return@setOnPreferenceChangeListener true } val autoTheme = findPreference("pref_auto_manage_theme") as SwitchPreference val darkThemeAlways = findPreference("pref_always_dark_theme") as SwitchPreference darkThemeAlways.isEnabled = !autoTheme.isChecked } // fun setTheme(currentMode: Int) { // val mActivity = activity?.let { it as MainActivity } // // AppCompatDelegate.setDefaultNightMode(themeMode) // val defaultMode = AppCompatDelegate.getDefaultNightMode() // if (currentMode != defaultMode) { // AppCompatDelegate.setDefaultNightMode(currentMode) // mActivity?.recreate() // } // // mActivity?.delegate?.setLocalNightMode(themeMode) // } override fun onResume() { super.onResume() updateToolbar(myToolbarSettings) } private fun setUi(applicationSettings: ApplicationSettings) { val findPreference: ListPreference = findPreference("pref_speed_or_pace") as ListPreference val thisContext: Context? = context if (thisContext != null && applicationSettings.measurementType == UnitMeasurement.Imperial) { //imperial setDistanceFeedBackMeasureUnit(R.string.pref_distance_beep_measure_unit_imperial) findPreference.setEntryValues(R.array.preferences_speed_imperial_values) findPreference.setEntries(R.array.preferences_speed_imperial) } else { //metric setDistanceFeedBackMeasureUnit(R.string.pref_distance_beep_measure_unit_metric) findPreference.setEntryValues(R.array.preferences_speed_metric_values) findPreference.setEntries(R.array.preferences_speed_metric) } val index = findPreference.entryValues.indexOf(applicationSettings.speedPacingRepresentation.value.toString()) if (index == -1) { findPreference.setValueIndex(0) } else { findPreference.setValueIndex(index) } //enable disable audio controller val volumeSlider: SeekBarPreferenceCompat = findPreference("pref_audio_volume") as SeekBarPreferenceCompat volumeSlider.isEnabled = applicationSettings.isAudioOn val distanceFeedbackSeekBar = findPreference("pref_distance_feedback") as SeekBarPreferenceCompat distanceFeedbackSeekBar.isEnabled = applicationSettings.isAudioOn if (distanceFeedbackSeekBar.currentValue == 0) { distanceFeedbackSeekBar.setSummary(R.string.pref_distance_feedback_summary_disabled) } else { distanceFeedbackSeekBar.summary = getString(R.string.pref_distance_feedback_summary) + " " + distanceFeedbackSeekBar.currentValue + " " + distanceFeedbackSeekBar.measurementUnit } val autoTheme = findPreference("pref_auto_manage_theme") as SwitchPreference val darkThemeAlways = findPreference("pref_always_dark_theme") as SwitchPreference darkThemeAlways.isEnabled = !autoTheme.isChecked } private fun setDistanceFeedBackMeasureUnit(id: Int) { val distanceFeedbackSeekBar = findPreference("pref_distance_feedback") as SeekBarPreferenceCompat distanceFeedbackSeekBar.measurementUnit = getString(id) } }
1
null
1
1
9e34724edd53a1c6248d03d7939070b9ac8bd791
6,741
Run-Challenge-Public
MIT License
buildSrc/src/main/java/com/hi/dhl/plugin/DependencyManager.kt
hi-dhl
391,529,628
false
null
package com.hi.dhl.plugin /** * <pre> * author: dhl * date : 2020/7/3 * desc : 如果数量少的话,放在一个类里面就可以,如果数量多的话,可以拆分为多个类 * </pre> */ object Versions { const val retrofit = "2.9.0" const val okhttpLogging = "4.9.0" const val appcompat = "1.2.0" const val coreKtx = "1.3.2" const val constraintlayout = "2.0.4" const val paging = "3.0.0-alpha02" const val timber = "4.7.1" const val kotlin = "1.4.20" const val kotlinCoroutinesCore = "1.3.7" const val kotlinCoroutinesAndrid = "1.3.6" const val koin = "2.1.5" const val work = "2.2.0" const val room = "2.3.0-alpha01" const val cardview = "1.0.0" const val recyclerview = "1.0.0" const val fragment = "1.3.0-alpha06" const val anko = "0.10.8" const val swiperefreshlayout = "1.1.0" const val junit = "4.13.1" const val junitExt = "1.1.2" const val espressoCore = "3.3.0" const val jDatabinding = "1.0.4" const val progressview = "1.0.2" const val runtime = "1.1.0" const val hit = "2.28-alpha" const val hitViewModule = "1.0.0-alpha01" const val appStartup = "1.0.0" const val material = "1.2.1" } object AndroidX { const val appcompat = "androidx.appcompat:appcompat:${Versions.appcompat}" const val coreKtx = "androidx.core:core-ktx:${Versions.coreKtx}" const val constraintlayout = "androidx.constraintlayout:constraintlayout:${Versions.constraintlayout}" const val pagingRuntime = "androidx.paging:paging-runtime:${Versions.paging}" const val workRuntime = "androidx.work:work-runtime:${Versions.work}" const val workTesting = "androidx.work:work-testing:${Versions.work}" const val cardview = "androidx.cardview:cardview:${Versions.cardview}" const val recyclerview = "androidx.recyclerview:recyclerview:${Versions.recyclerview}" const val swiperefreshlayout = "androidx.swiperefreshlayout:swiperefreshlayout:${Versions.swiperefreshlayout}" const val appStartup = "androidx.startup:startup-runtime:${Versions.appStartup}" } object Android { const val meteria = "com.google.android.material:material:${Versions.material}" } object Hilt { const val daggerRuntime = "com.google.dagger:hilt-android:${Versions.hit}" const val daggerCompiler = "com.google.dagger:hilt-android-compiler:${Versions.hit}" const val viewModule = "androidx.hilt:hilt-lifecycle-viewmodel:${Versions.hitViewModule}" const val compiler = "androidx.hilt:hilt-compiler:${Versions.hitViewModule}" } object Coil { const val runtime = "io.coil-kt:coil:${Versions.runtime}" } object Room { const val runtime = "androidx.room:room-runtime:${Versions.room}" const val compiler = "androidx.room:room-compiler:${Versions.room}" const val ktx = "androidx.room:room-ktx:${Versions.room}" const val rxjava2 = "androidx.room:room-rxjava2:${Versions.room}" const val testing = "androidx.room:room-testing:${Versions.room}" } object Fragment { const val runtime = "androidx.fragment:fragment:${Versions.fragment}" const val runtimeKtx = "androidx.fragment:fragment-ktx:${Versions.fragment}" const val testing = "androidx.fragment:fragment-testing:${Versions.fragment}" } object Kt { const val stdlibJdk7 = "org.jetbrains.kotlin:kotlin-stdlib-jdk7:${Versions.kotlin}" const val stdlibJdk8 = "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${Versions.kotlin}" const val coroutinesCore = "org.jetbrains.kotlinx:kotlinx-coroutines-core:${Versions.kotlinCoroutinesCore}" const val coroutinesAndroid = "org.jetbrains.kotlinx:kotlinx-coroutines-android:${Versions.kotlinCoroutinesAndrid}" const val test = "org.jetbrains.kotlin:kotlin-test-junit:${Versions.kotlin}" const val plugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:${Versions.kotlin}" } object Koin { const val core = "org.koin:koin-core:${Versions.koin}" const val androidCore = "org.koin:koin-android:${Versions.koin}" const val viewmodel = "org.koin:koin-androidx-viewmodel:${Versions.koin}" const val androidScope = "org.koin:koin-android-scope:$${Versions.koin}" } object Anko { const val common = "org.jetbrains.anko:anko-common:${Versions.anko}" const val sqlite = "org.jetbrains.anko:anko-sqlite:${Versions.anko}" const val coroutines = "org.jetbrains.anko:anko-coroutines:${Versions.anko}" const val design = "org.jetbrains.anko:anko-design:${Versions.anko}" // For SnackBars } object Retrofit { const val runtime = "com.squareup.retrofit2:retrofit:${Versions.retrofit}" const val gson = "com.squareup.retrofit2:converter-gson:${Versions.retrofit}" const val mock = "com.squareup.retrofit2:retrofit-mock:${Versions.retrofit}" const val logging = "com.squareup.okhttp3:logging-interceptor:${Versions.okhttpLogging}" } object Depend { const val junit = "junit:junit:${Versions.junit}" const val androidTestJunit = "androidx.test.ext:junit:${Versions.junitExt}" const val espressoCore = "androidx.test.espresso:espresso-core:${Versions.espressoCore}" const val jDatabinding = "com.hi-dhl:jdatabinding:${Versions.jDatabinding}" const val progressview = "com.hi-dhl:progressview:${Versions.progressview}" const val timber = "com.jakewharton.timber:timber:${Versions.timber}" }
2
null
9
94
138c05ce19904b554a777154be8504238668b273
5,302
KtKit
Apache License 2.0
src/main/kotlin/br/com/zup/academy/shared/validation/exceptions/ClienteNaoEncontradoException.kt
christian-moura
411,306,523
true
{"Kotlin": 40119}
package br.com.zup.edu.pix class ClienteNaoEncontradoException(message: String) : RuntimeException(message)
0
Kotlin
0
0
7b87a56598523c5bdd13a4c65667941b1b4e4fa8
108
orange-talents-07-template-pix-keymanager-grpc
Apache License 2.0
client/app/src/main/java/com/example/healthc/data/source/local/user/UpdateLocalUserInfoDataSourceImpl.kt
Solution-Challenge-HealthC
601,915,784
false
null
package com.example.healthc.data.source.local.user import com.example.healthc.data.local.UserInfoDao import com.example.healthc.data.local.entity.UserInfoEntity import com.example.healthc.domain.utils.Resource import javax.inject.Inject class UpdateLocalUserInfoDataSourceImpl @Inject constructor( private val dao : UserInfoDao ) : UpdateLocalUserInfoDataSource{ override suspend fun updateUserInfo(userInfo: UserInfoEntity) : Resource<Unit>{ return try{ dao.deleteUserInfo(userInfo) dao.insertUserInfo(userInfo) Resource.Success(Unit) } catch (e : Exception){ e.printStackTrace() Resource.Failure(e) } } }
2
Kotlin
0
2
21c45b6fd672074616945e45f0807e0ce43b06b8
713
HealthC_Android
MIT License
lib/src/main/kotlin/org/hravemzdy/procezor/interfaces/IConceptSpec.kt
hravemzdy
486,632,661
false
null
package org.hravemzdy.procezor.interfaces import org.hravemzdy.legalios.interfaces.IBundleProps import org.hravemzdy.legalios.interfaces.IPeriod import org.hravemzdy.procezor.service.types.ArticleCode import org.hravemzdy.procezor.service.types.BuilderResultList import org.hravemzdy.procezor.service.types.MonthCode import org.hravemzdy.procezor.service.types.VariantCode typealias ResultFunc = (ITermTarget, IArticleSpec?, IPeriod, IBundleProps, BuilderResultList) -> BuilderResultList interface IConceptSpec : IConceptDefine { val path : Iterable<ArticleCode> val resultDelegate : ResultFunc? fun defaultTargetList(article: ArticleCode, period: IPeriod, ruleset: IBundleProps, month: MonthCode, contractTerms: Iterable<IContractTerm>, positionTerms: Iterable<IPositionTerm>, targets: ITermTargetList, vars: VariantCode) : ITermTargetList }
0
Kotlin
0
0
345d489c83901ca501a46c055e9733b51ad8581f
911
kotlin-procezor
The Unlicense
designer/src/com/android/tools/idea/uibuilder/actions/MorphComponentAction.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.uibuilder.actions import com.android.tools.idea.common.command.NlWriteCommandActionUtil import com.android.tools.idea.common.model.NlComponent import com.android.tools.idea.common.model.NlDependencyManager import com.android.tools.idea.common.util.XmlTagUtil import com.android.tools.idea.uibuilder.model.NlComponentHelper import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbService import com.intellij.openapi.ui.popup.JBPopup import com.intellij.openapi.ui.popup.JBPopupFactory import org.jetbrains.android.facet.AndroidFacet /** * Action that shows a dialog to change the tag name of a component */ class MorphComponentAction(component: NlComponent) : AnAction("Convert view...") { private val myFacet: AndroidFacet = component.model.facet private val myProject = component.model.project private val myNlComponent = component private var myNewName = component.tagName init { templatePresentation.isEnabled = true templatePresentation.isVisible = true } /** * Apply the provided tag name to the component in the model */ private fun applyTagEdit(newTagName: String) { val dependencyManager = NlDependencyManager.getInstance() val component = NlComponent(myNlComponent.model, XmlTagUtil.createTag(myNlComponent.model.project, "<$newTagName/>")) NlComponentHelper.registerComponent(component) val newTag = listOf(component) if (dependencyManager.checkIfUserWantsToAddDependencies(newTag, myFacet)) { val callback = Runnable { editTagNameAndAttributes(newTagName) } dependencyManager.addDependenciesAsync(newTag, myFacet, "Converting Component...", callback) } } /** * Edit the tag name and remove the attributes that are not needed anymore. */ private fun editTagNameAndAttributes(newTagName: String) { DumbService.getInstance(myProject).runWhenSmart { NlWriteCommandActionUtil.run(myNlComponent, "Convert " + myNlComponent.tagName + " to ${newTagName.split(".").last()}") { myNlComponent.tagDeprecated.name = newTagName myNlComponent.removeObsoleteAttributes() myNlComponent.children.forEach(NlComponent::removeObsoleteAttributes) } } } private fun createMorphPopup(morphPanel: MorphPanel): JBPopup { val popup = JBPopupFactory.getInstance() .createComponentPopupBuilder(morphPanel, morphPanel.preferredFocusComponent) .setMovable(true) .setFocusable(true) .setRequestFocus(true) .setShowShadow(true) .setCancelOnClickOutside(true) .setAdText("Set the new type for the selected View") .createPopup() morphPanel.setOkAction { applyTagEdit(myNewName) popup.closeOk(null) } return popup } private fun showMorphPopup() { val oldTagName = myNlComponent.tagName val morphSuggestion = MorphManager.getMorphSuggestion(myNlComponent) val morphDialog = MorphPanel(myFacet, myProject, oldTagName, morphSuggestion) morphDialog.setTagNameChangeConsumer { newName -> myNewName = newName } createMorphPopup(morphDialog).showCenteredInCurrentWindow(myProject) } override fun actionPerformed(e: AnActionEvent) = showMorphPopup() }
0
null
220
857
8d22f48a9233679e85e42e8a7ed78bbff2c82ddb
3,915
android
Apache License 2.0
app/src/test/java/com/example/calculadoraimc/HistoryViewModelTest.kt
victorashino
750,024,332
false
{"Kotlin": 19065}
package com.example.calculadoraimc import com.example.calculadoraimc.data.HistoryDao import com.example.calculadoraimc.domain.IMC import com.example.calculadoraimc.view.HistoryViewModel import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import org.junit.Rule import org.junit.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify class HistoryViewModelTest { @get:Rule val mainDispatcherRule = MainDispatcherRule() private val historyDao: HistoryDao = mock() private val underTest: HistoryViewModel by lazy { HistoryViewModel(historyDao) } @Test fun deleteItem() = runTest { val imc = IMC( id = 1, weight = "60.0", height = "1.77", classification = "NORMAL", imc = "19.2" ) underTest.deleteItem(imc.id) verify(historyDao).delete(imc.id) } }
0
Kotlin
0
0
9aacf18bf5058b7e7500ba9a7947e337f885b500
936
Calculadora_IMC
MIT License
notifications/core/src/main/kotlin/org/opensearch/notifications/core/client/DestinationSnsClient.kt
opensearch-project
354,080,507
false
null
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. * * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ package org.opensearch.notifications.core.client import com.amazonaws.AmazonServiceException import com.amazonaws.SdkBaseException import com.amazonaws.services.sns.AmazonSNS import com.amazonaws.services.sns.model.AmazonSNSException import com.amazonaws.services.sns.model.AuthorizationErrorException import com.amazonaws.services.sns.model.EndpointDisabledException import com.amazonaws.services.sns.model.InternalErrorException import com.amazonaws.services.sns.model.InvalidParameterException import com.amazonaws.services.sns.model.InvalidParameterValueException import com.amazonaws.services.sns.model.InvalidSecurityException import com.amazonaws.services.sns.model.KMSAccessDeniedException import com.amazonaws.services.sns.model.KMSDisabledException import com.amazonaws.services.sns.model.KMSInvalidStateException import com.amazonaws.services.sns.model.KMSNotFoundException import com.amazonaws.services.sns.model.KMSOptInRequiredException import com.amazonaws.services.sns.model.KMSThrottlingException import com.amazonaws.services.sns.model.NotFoundException import com.amazonaws.services.sns.model.PlatformApplicationDisabledException import com.amazonaws.services.sns.model.PublishResult import org.opensearch.notifications.core.NotificationCorePlugin.Companion.LOG_PREFIX import org.opensearch.notifications.core.credentials.SnsClientFactory import org.opensearch.notifications.core.utils.logger import org.opensearch.notifications.spi.model.DestinationMessageResponse import org.opensearch.notifications.spi.model.MessageContent import org.opensearch.notifications.spi.model.destination.SnsDestination import org.opensearch.rest.RestStatus /** * This class handles the SNS connections to the given Destination. */ class DestinationSnsClient(private val snsClientFactory: SnsClientFactory) { companion object { private val log by logger(DestinationSnsClient::class.java) } fun execute(destination: SnsDestination, message: MessageContent, referenceId: String): DestinationMessageResponse { val amazonSNS: AmazonSNS = snsClientFactory.createSnsClient(destination.region, destination.roleArn) return try { val result = sendMessage(amazonSNS, destination, message) DestinationMessageResponse(RestStatus.OK.status, "Success, message id: ${result.messageId}") } catch (exception: InvalidParameterException) { DestinationMessageResponse(RestStatus.BAD_REQUEST.status, getSnsExceptionText(exception)) } catch (exception: InvalidParameterValueException) { DestinationMessageResponse(RestStatus.BAD_REQUEST.status, getSnsExceptionText(exception)) } catch (exception: InternalErrorException) { DestinationMessageResponse(RestStatus.INTERNAL_SERVER_ERROR.status, getSnsExceptionText(exception)) } catch (exception: NotFoundException) { DestinationMessageResponse(RestStatus.NOT_FOUND.status, getSnsExceptionText(exception)) } catch (exception: EndpointDisabledException) { DestinationMessageResponse(RestStatus.LOCKED.status, getSnsExceptionText(exception)) } catch (exception: PlatformApplicationDisabledException) { DestinationMessageResponse(RestStatus.SERVICE_UNAVAILABLE.status, getSnsExceptionText(exception)) } catch (exception: AuthorizationErrorException) { DestinationMessageResponse(RestStatus.UNAUTHORIZED.status, getSnsExceptionText(exception)) } catch (exception: KMSDisabledException) { DestinationMessageResponse(RestStatus.PRECONDITION_FAILED.status, getSnsExceptionText(exception)) } catch (exception: KMSInvalidStateException) { DestinationMessageResponse(RestStatus.PRECONDITION_FAILED.status, getSnsExceptionText(exception)) } catch (exception: KMSNotFoundException) { DestinationMessageResponse(RestStatus.PRECONDITION_FAILED.status, getSnsExceptionText(exception)) } catch (exception: KMSOptInRequiredException) { DestinationMessageResponse(RestStatus.PRECONDITION_FAILED.status, getSnsExceptionText(exception)) } catch (exception: KMSThrottlingException) { DestinationMessageResponse(RestStatus.TOO_MANY_REQUESTS.status, getSnsExceptionText(exception)) } catch (exception: KMSAccessDeniedException) { DestinationMessageResponse(RestStatus.UNAUTHORIZED.status, getSnsExceptionText(exception)) } catch (exception: InvalidSecurityException) { DestinationMessageResponse(RestStatus.UNAUTHORIZED.status, getSnsExceptionText(exception)) } catch (exception: AmazonSNSException) { DestinationMessageResponse(RestStatus.FAILED_DEPENDENCY.status, getSnsExceptionText(exception)) } catch (exception: AmazonServiceException) { DestinationMessageResponse(RestStatus.FAILED_DEPENDENCY.status, getServiceExceptionText(exception)) } catch (exception: SdkBaseException) { DestinationMessageResponse(RestStatus.FAILED_DEPENDENCY.status, getSdkExceptionText(exception)) } } /** * Create error string from Amazon SNS Exceptions * @param exception SNS Exception * @return generated error string */ private fun getSnsExceptionText(exception: AmazonSNSException): String { log.info("$LOG_PREFIX:SnsException $exception") return "SNS Send Error(${exception.statusCode}), SNS status:(${exception.errorType.name})${exception.errorCode}:${exception.errorMessage}" } /** * Create error string from Amazon Service Exceptions * @param exception Amazon Service Exception * @return generated error string */ private fun getServiceExceptionText(exception: AmazonServiceException): String { log.info("$LOG_PREFIX:SnsException $exception") return "SNS service Error(${exception.statusCode}), Service status:(${exception.errorType.name})${exception.errorCode}:${exception.errorMessage}" } /** * Create error string from Amazon SDK Exceptions * @param exception SDK Exception * @return generated error string */ private fun getSdkExceptionText(exception: SdkBaseException): String { log.info("$LOG_PREFIX:SdkException $exception") return "SNS sdk Error, SDK status:${exception.message}" } /* * This method is useful for mocking the client */ @Throws(Exception::class) fun sendMessage(amazonSNS: AmazonSNS, destination: SnsDestination, message: MessageContent): PublishResult { return amazonSNS.publish(destination.topicArn, message.textDescription, message.title) } }
62
null
64
8
ded1a4ccc574e0042457d388a9d91d87be64228e
6,961
notifications
Apache License 2.0
codebase/android/core/common/src/main/java/com/makeappssimple/abhimanyu/financemanager/android/core/common/stringencoder/StringEncoder.kt
Abhimanyu14
429,663,688
false
{"Kotlin": 1459939, "Dart": 102426}
package com.makeappssimple.abhimanyu.financemanager.android.core.common.stringencoder interface StringEncoder { fun encodeString( string: String, ): String }
11
Kotlin
0
1
433728cb7a9003e38ea9f579d561e4e27b47ef76
175
finance-manager
Apache License 2.0
sykepenger-model/src/main/kotlin/no/nav/helse/serde/migration/V78VedtaksperiodeListeOverUtbetalinger.kt
navikt
193,907,367
false
null
package no.nav.helse.serde.migration import com.fasterxml.jackson.databind.node.ArrayNode import com.fasterxml.jackson.databind.node.ObjectNode internal class V78VedtaksperiodeListeOverUtbetalinger : JsonMigration(version = 78) { override val description: String = "Lager liste over utbetalinger på Vedtaksperiode" override fun doMigration(jsonNode: ObjectNode, meldingerSupplier: MeldingerSupplier) { jsonNode.path("arbeidsgivere").forEach { arbeidsgiver -> arbeidsgiver.path("vedtaksperioder").forEach { vedtaksperiode -> migrateVedtaksperiode(vedtaksperiode as ObjectNode) } arbeidsgiver.path("forkastede").forEach { forkastet -> migrateVedtaksperiode(forkastet.path("vedtaksperiode") as ObjectNode) } } } private fun migrateVedtaksperiode(element: ObjectNode) { element.putArray("utbetalinger") if (element.hasNonNull("utbetalingId")) (element.path("utbetalinger") as ArrayNode).add(element.path("utbetalingId").asText()) } }
2
null
6
5
2f940cad2bc6a756033a4e19edc5236a0648c971
1,079
helse-spleis
MIT License
sandbox/src/jsMain/showcases/MDCFormField.kt
mpetuska
430,798,310
false
null
package showcases import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import dev.petuska.katalog.runtime.Showcase import dev.petuska.katalog.runtime.layout.InteractiveShowcase import dev.petuska.kmdc.checkbox.MDCCheckbox import dev.petuska.kmdc.form.field.MDCFormField import dev.petuska.kmdc.form.field.MDCFormFieldAlign import dev.petuska.kmdc.radio.MDCRadio import sandbox.control.BooleanControl import sandbox.control.ChoiceControl private class MDCFormFieldVM { var align by mutableStateOf(MDCFormFieldAlign.Start) var noWrap by mutableStateOf(false) var checked by mutableStateOf(false) } @Composable @Showcase(id = "MDCFormField") fun MDCFormField() = InteractiveShowcase( viewModel = { MDCFormFieldVM() }, controls = { ChoiceControl("Align", MDCFormFieldAlign.values().associateBy(MDCFormFieldAlign::name), ::align) BooleanControl("No Wrap", ::noWrap) }, ) { MDCFormField( align = align, noWrap = noWrap, ) { MDCCheckbox( checked = checked, label = "Sample Checkbox", attrs = { onInput { checked = !checked } }, ) } MDCFormField( align = align, noWrap = noWrap, ) { MDCRadio( checked = checked, label = "Sample Radio", attrs = { onInput { checked = !checked } }, ) } }
9
Kotlin
13
99
c1ba9cf15d091916f1e253c4c37cc9f9c643f5e3
1,401
kmdc
Apache License 2.0
text-library-service/src/test/kotlin/de/roamingthings/tracing/textlibrary/ports/driving/RetrieveParagraphControllerTest.kt
roamingthings
214,773,818
false
null
package de.roamingthings.tracing.author.ports.driving import com.nhaarman.mockitokotlin2.doReturn import de.roamingthings.tracing.novelai.test.mockTracingLenientUsingMock import de.roamingthings.tracing.textlibrary.ports.driving.PARAGRAPH import de.roamingthings.tracing.textlibrary.ports.driving.RetrieveParagraphController import de.roamingthings.tracing.textlibrary.usecases.retrieve.RetrieveParagraphService import io.opentracing.Tracer import org.assertj.core.api.SoftAssertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.InjectMocks import org.mockito.Mock import org.mockito.junit.jupiter.MockitoExtension import org.springframework.http.HttpStatus.OK @ExtendWith(MockitoExtension::class) class RetrieveParagraphControllerTest { @Mock lateinit var tracer: Tracer; @Mock lateinit var retrieveParagraphService: RetrieveParagraphService @InjectMocks lateinit var retrieveParagraphController: RetrieveParagraphController @BeforeEach fun mockTracing() { mockTracingLenientUsingMock(tracer) } @Test fun `should return response with paragraph as plain text`() { serviceReturnsContent() val response = retrieveParagraphController.retrieveRandomParagraph() SoftAssertions.assertSoftly {softly -> softly.assertThat(response.statusCode).isEqualTo(OK) softly.assertThat(response.body).isEqualTo(PARAGRAPH) } } private fun serviceReturnsContent() { doReturn(PARAGRAPH) .`when`(retrieveParagraphService).retrieveParagraph() } }
8
null
1
1
ee264dba66268763e761fb5d731f57fc3fc248d4
1,674
workbench-tracing
Apache License 2.0
modulecheck-project/api/src/main/kotlin/modulecheck/project/McProject.kt
RBusarow
316,627,145
false
null
/* * Copyright (C) 2021-2023 <NAME> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package modulecheck.project import modulecheck.model.dependency.Configurations import modulecheck.model.dependency.ExternalDependencies import modulecheck.model.dependency.HasConfigurations import modulecheck.model.dependency.HasDependencies import modulecheck.model.dependency.HasProjectPath import modulecheck.model.dependency.HasSourceSets import modulecheck.model.dependency.ProjectDependencies import modulecheck.model.dependency.ProjectPath.StringProjectPath import modulecheck.model.dependency.SourceSets import modulecheck.model.dependency.isAndroid import modulecheck.model.sourceset.SourceSetName import modulecheck.parsing.gradle.dsl.HasBuildFile import modulecheck.parsing.gradle.dsl.HasDependencyDeclarations import modulecheck.parsing.gradle.dsl.InvokesConfigurationNames import modulecheck.parsing.gradle.model.HasPlatformPlugin import modulecheck.parsing.gradle.model.PluginAware import modulecheck.parsing.source.AnvilGradlePlugin import modulecheck.parsing.source.QualifiedDeclaredName import modulecheck.parsing.source.ResolvableMcName import modulecheck.reporting.logging.McLogger import org.jetbrains.kotlin.config.JvmTarget import java.io.File @Suppress("TooManyFunctions") interface McProject : ProjectContext, Comparable<McProject>, HasProjectPath, HasProjectCache, HasBuildFile, HasConfigurations, HasDependencies, HasSourceSets, HasDependencyDeclarations, InvokesConfigurationNames, HasPlatformPlugin, PluginAware { override val projectPath: StringProjectPath override val configurations: Configurations get() = platformPlugin.configurations override val sourceSets: SourceSets get() = platformPlugin.sourceSets val projectDir: File override val projectDependencies: ProjectDependencies override val externalDependencies: ExternalDependencies val anvilGradlePlugin: AnvilGradlePlugin? override val hasAnvil: Boolean get() = anvilGradlePlugin != null override val hasAGP: Boolean get() = platformPlugin.isAndroid() val logger: McLogger val jvmFileProviderFactory: JvmFileProvider.Factory /** * The Java version used to compile this project * * @since 0.12.0 */ val jvmTarget: JvmTarget /** * @return a [QualifiedDeclaredName] if one can be found * for the given [resolvableMcName] and [sourceSetName] * @since 0.12.0 */ suspend fun resolvedNameOrNull( resolvableMcName: ResolvableMcName, sourceSetName: SourceSetName ): QualifiedDeclaredName? } fun McProject.isAndroid(): Boolean = platformPlugin.isAndroid()
76
Kotlin
7
95
24e7c7667490630d30cf8b59cd504cd863cd1fba
3,151
ModuleCheck
Apache License 2.0
app/src/main/java/com/example/mymovie/presentation/utils/Genre.kt
didikk
829,815,819
false
{"Kotlin": 12601}
package com.example.mymovie.presentation.utils val genres = mapOf( 28 to "Action", 12 to "Adventure", 16 to "Animation", 35 to "Comedy", 80 to "Crime", 99 to "Documentary", 18 to "Drama", 10751 to "Family", 14 to "Fantasy", 36 to "History", 27 to "Horror", 10402 to "Music", 9648 to "Mystery", 10749 to "Romance", 878 to "Science Fiction", 10770 to "TV Movie", 53 to "Thriller", 10752 to "War", 37 to "Western" ) fun getGenreString(genreIds: List<Int>): String { for (genreId in genreIds) { if (genres.containsKey(genreId)) { return genres[genreId] ?: "" } } return "" }
0
Kotlin
0
0
e0d0f0e0a7e3a7e96994a144d24b56526a185324
691
compose-movie-app
MIT License
kvision-modules/kvision-maps/src/main/kotlin/io/kvision/maps/externals/leaflet/layer/vector/SVG.kt
rjaros
120,835,750
false
null
/* * Copyright (c) 2017-present <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ @file:JsModule("leaflet") @file:JsNonModule package io.kvision.maps.externals.leaflet.layer.vector import io.kvision.maps.externals.leaflet.geometry.Point import org.w3c.dom.svg.SVGElement open external class SVG( options: RendererOptions = definedExternally ) : Renderer<Renderer.RendererOptions> { companion object { /** @param[name] The name of an [SVG element](https://developer.mozilla.org/en-US/docs/Web/SVG/Element), * for example `line` or `circle` */ fun create(name: String): SVGElement /** * Generates an SVG path string for multiple rings, with each ring turning into `M..L..L..` * instructions. */ fun pointsToPath( rings: Array<Point>, closed: Boolean ): String } }
22
null
65
882
bde30bbfd3c1a837eeff58a0a81bf7a5d677c72f
1,918
kvision
MIT License
app/src/main/java/ru/sshex/exchange/di/app/component/AppComponent.kt
ShadyRover
182,038,832
false
null
package ru.sshex.exchange.di.app.component import dagger.Component import ru.sshex.exchange.ExchangeApp import ru.sshex.exchange.di.app.module.AppModule import javax.inject.Singleton @Singleton @Component(modules = [AppModule::class]) interface AppComponent { fun inject(application: ExchangeApp) }
0
Kotlin
0
0
d050e45e413ea60057f3103bf249603b51b8cebe
304
Exchange
Apache License 2.0
reactive/kotlinx-coroutines-rx2/src/RxCancellable.kt
objcode
159,731,828
false
null
/* * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.rx2 import io.reactivex.functions.* import kotlinx.coroutines.* internal class RxCancellable(private val job: Job) : Cancellable { override fun cancel() { job.cancel() } }
1
null
2
5
46741db4b0c2863475d5cc6fc75eafadd8e6199d
327
kotlinx.coroutines
Apache License 2.0
library/src/main/java/ru/yandex/money/android/sdk/impl/secure/BcKeyStorage.kt
GorshkovNikita
144,304,854
false
null
/* * The MIT License (MIT) * Copyright © 2018 NBCO Yandex.Money LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the “Software”), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package ru.yandex.money.android.sdk.impl.secure import android.content.Context import java.io.FileNotFoundException import java.security.Key import java.security.KeyStore import javax.crypto.KeyGenerator private const val KEYSTORE_TYPE = "BouncyCastle" internal class BcKeyStorage(private val context: Context, private val path: String, password: String) : Storage<Key> { private val password = <PASSWORD>() private val store = loadKeyStore(context, path, this.password) override fun get(key: String): Key? = store.getKey(key, null) override fun getOrCreate(key: String): Key = get(key) ?: generateKey().also { generatedKey -> store.setKeyEntry(key, generatedKey, null, null) saveStore() } override fun remove(key: String) { store.deleteEntry(key) saveStore() } private fun saveStore() { context.openFileOutput(path, Context.MODE_PRIVATE).use { file -> store.store(file, password) } } } private fun loadKeyStore(context: Context, path: String, password: CharArray): KeyStore { return KeyStore.getInstance(KEYSTORE_TYPE).apply { try { context.openFileInput(path).use { file -> load(file, password) } } catch (e: FileNotFoundException) { load(null) } } } private fun generateKey() = KeyGenerator.getInstance("AES", "BC").generateKey()
1
null
1
1
fa44a3b0a3872d9f1ede52ebbf90fc1d68dcf386
2,539
yandex-checkout-android-sdk
MIT License
src/pt/mundowebtoon/src/eu/kanade/tachiyomi/extension/pt/mundowebtoon/ObsoleteExtensionInterceptor.kt
tachiyomiorg
79,658,844
false
{"Kotlin": 5275963}
package eu.kanade.tachiyomi.extension.pt.mundowebtoon import eu.kanade.tachiyomi.network.GET import kotlinx.serialization.Serializable import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import okhttp3.Interceptor import okhttp3.Response import uy.kohesive.injekt.injectLazy import java.io.IOException class ObsoleteExtensionInterceptor : Interceptor { private val json: Json by injectLazy() private var isObsolete: Boolean? = null override fun intercept(chain: Interceptor.Chain): Response { if (isObsolete == null) { val extRepoResponse = chain.proceed(GET(REPO_URL)) val extRepo = json.decodeFromString<List<ExtensionJsonObject>>(extRepoResponse.body.string()) isObsolete = !extRepo.any { ext -> ext.pkg == this.javaClass.`package`?.name && ext.lang == "pt-BR" } } if (isObsolete == true) { throw IOException("Extensão obsoleta. Desinstale e migre para outras fontes.") } return chain.proceed(chain.request()) } @Serializable private data class ExtensionJsonObject( val pkg: String, val lang: String, ) companion object { private const val REPO_URL = "https://raw.githubusercontent.com/tachiyomiorg/tachiyomi-extensions/repo/index.min.json" } }
584
Kotlin
1234
2,850
3d5b6cf9d1294bf42bfdb0f6534c4852b68cedd4
1,366
tachiyomi-extensions
Apache License 2.0
src/test/kotlin/no/nav/helse/flex/syketilfelle/kafka/TestKafkaConfig.kt
navikt
440,416,678
false
null
package no.nav.helse.flex.syketilfelle.kafka import org.apache.kafka.clients.consumer.ConsumerConfig import org.apache.kafka.clients.consumer.KafkaConsumer import org.apache.kafka.clients.producer.KafkaProducer import org.apache.kafka.clients.producer.ProducerConfig import org.apache.kafka.common.serialization.StringDeserializer import org.apache.kafka.common.serialization.StringSerializer import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import java.util.* @Configuration class TestKafkaConfig( private val aivenKafkaConfig: AivenKafkaConfig ) { @Bean fun kafkaProducer(): KafkaProducer<String, String> { val config = mapOf( ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG to StringSerializer::class.java, ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG to StringSerializer::class.java, ProducerConfig.ACKS_CONFIG to "all", ProducerConfig.RETRIES_CONFIG to 10, ProducerConfig.RETRY_BACKOFF_MS_CONFIG to 100 ) + aivenKafkaConfig.commonConfig() return KafkaProducer(config) } @Bean fun syketilfelleBitConsumer() = KafkaConsumer<String, String>(consumerConfig("bit-group-id")) @Bean fun juridiskVurderingKafkaConsumer() = KafkaConsumer<String, String>(consumerConfig("juridisk-group-id")) private fun consumerConfig(groupId: String) = mapOf( ConsumerConfig.GROUP_ID_CONFIG to groupId, ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG to false, ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG to StringDeserializer::class.java, ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG to StringDeserializer::class.java, ConsumerConfig.AUTO_OFFSET_RESET_CONFIG to "earliest" ) + aivenKafkaConfig.commonConfig() }
4
Kotlin
0
1
ad110512ab2c59883df6e6ca9594d4d7cfb56144
1,816
flex-syketilfelle
MIT License
app/src/main/java/quick/sms/quicksms/backend/RuntimePermissions.kt
mahbubiftekhar
130,412,702
false
null
package quick.sms.quicksms.backend import android.app.Activity import android.content.pm.PackageManager import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat fun getPermissions(activity: Activity, permissions: Array<String>): Boolean { val requiredPermissions = permissions.filter { val permissionGranted = ContextCompat.checkSelfPermission(activity, it) permissionGranted != PackageManager.PERMISSION_GRANTED }.toTypedArray() if (!requiredPermissions.isEmpty()) { ActivityCompat.requestPermissions(activity, requiredPermissions, 1) return false } return true }
0
Kotlin
3
2
4b2f7ca0c15d340952260072a54306f133e2ba6f
654
quickSMS
MIT License
src/main/java/uos/dev/restcli/parser/RequestMethod.kt
restcli
276,395,595
false
null
package uos.dev.restcli.parser enum class RequestMethod { GET, HEAD, POST, PUT, DELETE, CONNECT, PATCH, OPTIONS, TRACE; companion object { fun from(value: String?, ignoreCase: Boolean = true): RequestMethod = values().firstOrNull { it.name.equals(value, ignoreCase) } ?: GET } }
35
Kotlin
35
272
cc9087d883742b0c468b0b2874208f6827d210b5
345
restcli
MIT License
models/src/main/java/lt/markmerkk/IDataStorage.kt
marius-m
67,072,115
false
null
package lt.markmerkk /** * Represents the exposed methods for handling simple events on the database. */ interface IDataStorage<T> { /** * Registers to the event reporter * @param listener */ fun register(listener: IDataListener<T>) /** * Unregisters from the reporter * @param listener */ fun unregister(listener: IDataListener<T>) /** * Inserts a data entity * @param dataEntity provided data entity * @return inserted new log id, otherwise [Const.NO_ID] */ fun insert(dataEntity: T): Long /** * Deletes a data entity * @param dataEntity provided data entity * @return deleted entry id, or [Const.NO_ID] */ fun delete(dataEntity: T): Long /** * Updates a data entity * @param dataEntity provided data entity * @return updated entry id or [Const.NO_ID] */ fun update(dataEntity: T): Long /** * Notifies logs have changed and needs a refresh */ fun notifyDataChange() /** * Finds item by id or null */ fun findByIdOrNull(id: Long): T? /** * Get currently loaded logs */ val data: List<T> }
1
null
1
26
6632d6bfd53de4760dbc3764c361f2dcd5b5ebce
1,186
wt4
Apache License 2.0
app/src/main/java/com/herdal/mealdb/data/remote/service/MealService.kt
herdal06
600,210,877
false
null
package com.herdal.mealdb.data.remote.service import com.herdal.mealdb.data.remote.dto.meal.MealResponse import com.herdal.mealdb.data.remote.dto.meal_detail.MealDetailResponse import com.herdal.mealdb.data.remote.utils.ApiConstants import retrofit2.http.GET import retrofit2.http.Query interface MealService { @GET(ApiConstants.Endpoints.MEALS) suspend fun getMeals( @Query("c") category: String = "Beef" ): MealResponse @GET(ApiConstants.Endpoints.SEARCH_MEALS) suspend fun searchMeals( @Query("s") query: String ): MealResponse @GET(ApiConstants.Endpoints.MEAL_DETAILS) suspend fun getMealDetails( @Query("i") id: Int ): MealDetailResponse }
0
Kotlin
0
2
01f6a072a2668490d94ed390b077729d77a9ae13
709
MealDB
Apache License 2.0
tonapi-tl/src/liteserver/config/LiteServerConfigLocal.kt
ton-community
448,983,229
false
{"Kotlin": 1194581}
package org.ton.api.liteserver.config import kotlinx.serialization.Polymorphic import kotlinx.serialization.Serializable import kotlinx.serialization.json.JsonClassDiscriminator @Serializable @Polymorphic @JsonClassDiscriminator("@type") public sealed interface LiteServerConfigLocal
21
Kotlin
24
80
7eb82e9b04a2e518182ebfc56c165fbfcc916be9
286
ton-kotlin
Apache License 2.0
kotlin/src/main/java/app/rive/runtime/kotlin/core/Renderer.kt
rive-app
299,578,948
false
null
package app.rive.runtime.kotlin.core import android.graphics.Canvas import android.graphics.Matrix import android.graphics.Paint import android.graphics.Path /** * A [Renderer] is used to help draw an [Artboard] to a [Canvas] * * This object has a counterpart in c++, which implements a lot of functionality. * The [cppPointer] keeps track of this relationship. * * Most of the functions implemented here are called from the c++ layer when artboards are * rendered. */ class Renderer(antialias: Boolean = true) { var cppPointer: Long lateinit var canvas: Canvas init { cppPointer = constructor(antialias) } private external fun cppAlign( cppPointer: Long, fit: Fit, alignment: Alignment, targetBoundsPointer: Long, srcBoundsPointer: Long ) private external fun constructor(antialias: Boolean): Long private external fun cleanupJNI(cppPointer: Long) /** * Passthrough to apply [matrix] to the [canvas] * * This function is used by the c++ layer. */ fun setMatrix(matrix: Matrix) { canvas.concat(matrix) } /** * Instruct the cpp renderer how to align the artboard in the available space [targetBounds]. * * Use [fit] and [alignment] to instruct how the [sourceBounds] should be matched into [targetBounds]. * * typically it is expected to use an [Artboard]s bounds as [sourceBounds]. */ fun align(fit: Fit, alignment: Alignment, targetBounds: AABB, sourceBounds: AABB) { cppAlign( cppPointer, fit, alignment, targetBounds.cppPointer, sourceBounds.cppPointer ) } /** * Remove the [Renderer] object from memory. */ fun cleanup() { cleanupJNI(cppPointer) cppPointer = 0 } /** * Passthrough to apply [save] to the [canvas] * * This function is used by the c++ layer. */ fun save(): Int { return canvas.save() } /** * Passthrough to apply [restore] to the [canvas] * * This function is used by the c++ layer. */ fun restore() { return canvas.restore() } /** * Passthrough to apply [translate] to the [canvas] * * This function is used by the c++ layer. */ fun translate(dx: Float, dy: Float) { return canvas.translate(dx, dy) } /** * Passthrough to apply [drawPath] to the [canvas] * * This function is used by the c++ layer. */ fun drawPath(path: Path, paint: Paint) { return canvas.drawPath(path, paint) } /** * Passthrough to apply [clipPath] to the [canvas] * * This function is used by the c++ layer. */ fun clipPath(path: Path): Boolean { return canvas.clipPath(path) } }
7
Kotlin
15
98
f7f2389eb11a080e18c8f15d82f35bc25bf998b4
2,869
rive-android
MIT License
kotlin/src/main/java/app/rive/runtime/kotlin/core/Renderer.kt
rive-app
299,578,948
false
null
package app.rive.runtime.kotlin.core import android.graphics.Canvas import android.graphics.Matrix import android.graphics.Paint import android.graphics.Path /** * A [Renderer] is used to help draw an [Artboard] to a [Canvas] * * This object has a counterpart in c++, which implements a lot of functionality. * The [cppPointer] keeps track of this relationship. * * Most of the functions implemented here are called from the c++ layer when artboards are * rendered. */ class Renderer(antialias: Boolean = true) { var cppPointer: Long lateinit var canvas: Canvas init { cppPointer = constructor(antialias) } private external fun cppAlign( cppPointer: Long, fit: Fit, alignment: Alignment, targetBoundsPointer: Long, srcBoundsPointer: Long ) private external fun constructor(antialias: Boolean): Long private external fun cleanupJNI(cppPointer: Long) /** * Passthrough to apply [matrix] to the [canvas] * * This function is used by the c++ layer. */ fun setMatrix(matrix: Matrix) { canvas.concat(matrix) } /** * Instruct the cpp renderer how to align the artboard in the available space [targetBounds]. * * Use [fit] and [alignment] to instruct how the [sourceBounds] should be matched into [targetBounds]. * * typically it is expected to use an [Artboard]s bounds as [sourceBounds]. */ fun align(fit: Fit, alignment: Alignment, targetBounds: AABB, sourceBounds: AABB) { cppAlign( cppPointer, fit, alignment, targetBounds.cppPointer, sourceBounds.cppPointer ) } /** * Remove the [Renderer] object from memory. */ fun cleanup() { cleanupJNI(cppPointer) cppPointer = 0 } /** * Passthrough to apply [save] to the [canvas] * * This function is used by the c++ layer. */ fun save(): Int { return canvas.save() } /** * Passthrough to apply [restore] to the [canvas] * * This function is used by the c++ layer. */ fun restore() { return canvas.restore() } /** * Passthrough to apply [translate] to the [canvas] * * This function is used by the c++ layer. */ fun translate(dx: Float, dy: Float) { return canvas.translate(dx, dy) } /** * Passthrough to apply [drawPath] to the [canvas] * * This function is used by the c++ layer. */ fun drawPath(path: Path, paint: Paint) { return canvas.drawPath(path, paint) } /** * Passthrough to apply [clipPath] to the [canvas] * * This function is used by the c++ layer. */ fun clipPath(path: Path): Boolean { return canvas.clipPath(path) } }
7
Kotlin
15
98
f7f2389eb11a080e18c8f15d82f35bc25bf998b4
2,869
rive-android
MIT License
implementation/src/main/kotlin/com/aoc/intcode/droid/spring/register/read/ReadOnlyRegister.kt
TomPlum
227,887,094
false
null
package com.aoc.intcode.droid.spring.register.read import com.aoc.intcode.droid.spring.register.Register /** * A [Register] that once instantiated, its value cannot be changed and only read from. */ interface ReadOnlyRegister : Register
7
Kotlin
1
2
12d47cc9c50aeb9e20bcf110f53d097d8dc3762f
240
advent-of-code-2019
Apache License 2.0
app/src/main/java/io/horizontalsystems/bankwallet/core/storage/BlockchainSettingsStorage.kt
horizontalsystems
142,825,178
false
null
package io.horizontalsystems.bankwallet.core.storage import io.horizontalsystems.bankwallet.entities.BlockchainSettingRecord import io.horizontalsystems.bankwallet.entities.BtcRestoreMode import io.horizontalsystems.bankwallet.entities.TransactionDataSortMode import io.horizontalsystems.marketkit.models.BlockchainType class BlockchainSettingsStorage(appDatabase: AppDatabase) { companion object { const val keyBtcRestore: String = "btc-restore" const val keyBtcTransactionSort: String = "btc-transaction-sort" const val keyEvmSyncSource: String = "evm-sync-source" } private val dao = appDatabase.blockchainSettingDao() fun btcRestoreMode(blockchainType: BlockchainType): BtcRestoreMode? { return dao.getBlockchainSetting(blockchainType.uid, keyBtcRestore)?.let { storedSetting -> BtcRestoreMode.values().firstOrNull { it.raw == storedSetting.value } } } fun save(btcRestoreMode: BtcRestoreMode, blockchainType: BlockchainType) { dao.insert( BlockchainSettingRecord( blockchainUid = blockchainType.uid, key = keyBtcRestore, value = btcRestoreMode.raw ) ) } fun btcTransactionSortMode(blockchainType: BlockchainType): TransactionDataSortMode? { return dao.getBlockchainSetting(blockchainType.uid, keyBtcTransactionSort) ?.let { sortSetting -> TransactionDataSortMode.values().firstOrNull { it.raw == sortSetting.value } } } fun save(transactionDataSortMode: TransactionDataSortMode, blockchainType: BlockchainType) { dao.insert( BlockchainSettingRecord( blockchainUid = blockchainType.uid, key = keyBtcTransactionSort, value = transactionDataSortMode.raw ) ) } fun evmSyncSourceName(blockchainType: BlockchainType): String? { return dao.getBlockchainSetting(blockchainType.uid, keyEvmSyncSource)?.value } fun save(evmSyncSourceName: String, blockchainType: BlockchainType) { dao.insert( BlockchainSettingRecord( blockchainUid = blockchainType.uid, key = keyEvmSyncSource, value = evmSyncSourceName ) ) } }
131
Kotlin
288
551
c48fdb4463a1245418edd0ace4d1e7d029bc4d70
2,350
unstoppable-wallet-android
MIT License
compiler/testData/codegen/box/unsignedTypes/unsignedLongDivide.kt
JetBrains
3,432,266
false
null
// JVM_TARGET: 1.8 // WITH_RUNTIME // IGNORE_BACKEND: JVM_IR val ua = 1234UL val ub = 5678UL val uai = ua.toUInt() val u = ua * ub fun box(): String { val div = u / ua if (div != ub) throw AssertionError("$div") val divInt = u / uai if (div != ub) throw AssertionError("$div") return "OK" }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
314
kotlin
Apache License 2.0
src/main/kotlin/com/charleskorn/shokunin/gameofpawns/model/Board.kt
charleskorn
179,935,036
false
null
package com.charleskorn.shokunin.gameofpawns.model class Board private constructor(val ranks: List<List<BoardSquare>>) { constructor() : this(List(8) { List(8) { EmptySquare } }) fun withPiece(rank: Int, file: Int, player: Player, piece: Piece): Board { val newSquare = OccupiedSquare(player, piece) val newRank = ranks[rank].replaceAt(file, newSquare) val newRanks = ranks.replaceAt(rank, newRank) return Board(newRanks) } private fun <T> List<T>.replaceAt(index: Int, newValue: T): List<T> { return this.mapIndexed { i, existingValue -> if (i == index) { newValue } else { existingValue } } } }
0
Kotlin
0
0
e265918abaca5a85d8f59ba434d5e4e0f6456509
749
game-of-pawns
Apache License 2.0
app-backend/src/main/kotlin/jooq/main/tables/Kotliner.kt
Heapy
40,936,978
false
{"Kotlin": 3311624, "TypeScript": 19032, "Less": 5146, "HTML": 4493, "JavaScript": 2299, "CSS": 2174, "Dockerfile": 243}
/* * This file is generated by jOOQ. */ package jooq.main.tables import java.time.OffsetDateTime import jooq.main.Public import jooq.main.enums.KotlinerStatusEnum import jooq.main.keys.ARTICLE_AUTHOR__ARTICLE_AUTHOR_KOTLINER_ID_FKEY import jooq.main.keys.ARTICLE__ARTICLE_CREATED_BY_FKEY import jooq.main.keys.ARTICLE__ARTICLE_UPDATED_BY_FKEY import jooq.main.keys.BOOK_SPEAKER__BOOK_SPEAKER_KOTLINER_ID_FKEY import jooq.main.keys.COMMENT__COMMENT_KOTLINER_ID_FKEY import jooq.main.keys.COURSE_SPEAKER__COURSE_SPEAKER_KOTLINER_ID_FKEY import jooq.main.keys.KOTLINER_LIKE_ENTITY_STATE__KOTLINER_LIKE_ENTITY_STATE_KOTLINER_ID_FKEY import jooq.main.keys.KOTLINER_PKEY import jooq.main.keys.KOTLINER_READ_ENTITY_STATE__KOTLINER_READ_ENTITY_STATE_KOTLINER_ID_FKEY import jooq.main.keys.KUG_EVENT__KUG_EVENT_UPDATED_BY_FKEY import jooq.main.keys.KUG_MEMBER__KUG_MEMBER_KOTLINER_ID_FKEY import jooq.main.keys.KUG__KUG_CREATED_BY_FKEY import jooq.main.keys.KUG__KUG_UPDATED_BY_FKEY import jooq.main.keys.UNIQUE_KOTLINER_EMAIL import jooq.main.keys.UNIQUE_KOTLINER_NICKNAME import jooq.main.keys.VACANCY__VACANCY_KOTLINER_ID_FKEY import jooq.main.keys.VIDEO_SPEAKER__VIDEO_SPEAKER_KOTLINER_ID_FKEY import jooq.main.tables.Article.ArticlePath import jooq.main.tables.ArticleAuthor.ArticleAuthorPath import jooq.main.tables.Book.BookPath import jooq.main.tables.BookSpeaker.BookSpeakerPath import jooq.main.tables.Comment.CommentPath import jooq.main.tables.Course.CoursePath import jooq.main.tables.CourseSpeaker.CourseSpeakerPath import jooq.main.tables.KotlinerLikeEntityState.KotlinerLikeEntityStatePath import jooq.main.tables.KotlinerReadEntityState.KotlinerReadEntityStatePath import jooq.main.tables.Kug.KugPath import jooq.main.tables.KugEvent.KugEventPath import jooq.main.tables.KugMember.KugMemberPath import jooq.main.tables.Vacancy.VacancyPath import jooq.main.tables.Video.VideoPath import jooq.main.tables.VideoSpeaker.VideoSpeakerPath import jooq.main.tables.records.KotlinerRecord import kotlin.collections.Collection import kotlin.collections.List import org.jooq.Condition import org.jooq.Field import org.jooq.ForeignKey import org.jooq.Identity import org.jooq.InverseForeignKey import org.jooq.JSONB import org.jooq.Name import org.jooq.Path import org.jooq.PlainSQL import org.jooq.QueryPart import org.jooq.Record import org.jooq.SQL import org.jooq.Schema import org.jooq.Select import org.jooq.Stringly import org.jooq.Table import org.jooq.TableField import org.jooq.TableOptions import org.jooq.UniqueKey import org.jooq.impl.DSL import org.jooq.impl.Internal import org.jooq.impl.SQLDataType import org.jooq.impl.TableImpl /** * This class is generated by jOOQ. */ @Suppress("UNCHECKED_CAST") open class Kotliner( alias: Name, path: Table<out Record>?, childPath: ForeignKey<out Record, KotlinerRecord>?, parentPath: InverseForeignKey<out Record, KotlinerRecord>?, aliased: Table<KotlinerRecord>?, parameters: Array<Field<*>?>?, where: Condition? ): TableImpl<KotlinerRecord>( alias, Public.PUBLIC, path, childPath, parentPath, aliased, parameters, DSL.comment(""), TableOptions.table(), where, ) { companion object { /** * The reference instance of <code>public.kotliner</code> */ val KOTLINER: Kotliner = Kotliner() } /** * The class holding records for this type */ override fun getRecordType(): Class<KotlinerRecord> = KotlinerRecord::class.java /** * The column <code>public.kotliner.id</code>. */ val ID: TableField<KotlinerRecord, Long?> = createField(DSL.name("id"), SQLDataType.BIGINT.nullable(false).identity(true), this, "") /** * The column <code>public.kotliner.created</code>. */ val CREATED: TableField<KotlinerRecord, OffsetDateTime?> = createField(DSL.name("created"), SQLDataType.TIMESTAMPWITHTIMEZONE(6).nullable(false), this, "") /** * The column <code>public.kotliner.updated</code>. */ val UPDATED: TableField<KotlinerRecord, OffsetDateTime?> = createField(DSL.name("updated"), SQLDataType.TIMESTAMPWITHTIMEZONE(6).nullable(false), this, "") /** * The column <code>public.kotliner.status</code>. */ val STATUS: TableField<KotlinerRecord, KotlinerStatusEnum?> = createField(DSL.name("status"), SQLDataType.VARCHAR.nullable(false).asEnumDataType(KotlinerStatusEnum::class.java), this, "") /** * The column <code>public.kotliner.avatar</code>. */ val AVATAR: TableField<KotlinerRecord, String?> = createField(DSL.name("avatar"), SQLDataType.VARCHAR(500), this, "") /** * The column <code>public.kotliner.description</code>. */ val DESCRIPTION: TableField<KotlinerRecord, String?> = createField(DSL.name("description"), SQLDataType.CLOB.nullable(false), this, "") /** * The column <code>public.kotliner.normalized_email</code>. */ val NORMALIZED_EMAIL: TableField<KotlinerRecord, String?> = createField(DSL.name("normalized_email"), SQLDataType.VARCHAR(500).nullable(false), this, "") /** * The column <code>public.kotliner.original_email</code>. */ val ORIGINAL_EMAIL: TableField<KotlinerRecord, String?> = createField(DSL.name("original_email"), SQLDataType.VARCHAR(500).nullable(false), this, "") /** * The column <code>public.kotliner.first_name</code>. */ val FIRST_NAME: TableField<KotlinerRecord, String?> = createField(DSL.name("first_name"), SQLDataType.VARCHAR(100), this, "") /** * The column <code>public.kotliner.last_name</code>. */ val LAST_NAME: TableField<KotlinerRecord, String?> = createField(DSL.name("last_name"), SQLDataType.VARCHAR(100), this, "") /** * The column <code>public.kotliner.nickname</code>. */ val NICKNAME: TableField<KotlinerRecord, String?> = createField(DSL.name("nickname"), SQLDataType.VARCHAR(100).nullable(false), this, "") /** * The column <code>public.kotliner.password</code>. */ val PASSWORD: TableField<KotlinerRecord, String?> = createField(DSL.name("password"), SQLDataType.VARCHAR(500).nullable(false), this, "") /** * The column <code>public.kotliner.totp</code>. */ val TOTP: TableField<KotlinerRecord, String?> = createField(DSL.name("totp"), SQLDataType.VARCHAR(500), this, "") /** * The column <code>public.kotliner.meta</code>. */ val META: TableField<KotlinerRecord, JSONB?> = createField(DSL.name("meta"), SQLDataType.JSONB, this, "") /** * The column <code>public.kotliner.version</code>. */ val VERSION: TableField<KotlinerRecord, Long?> = createField(DSL.name("version"), SQLDataType.BIGINT.nullable(false).defaultValue(DSL.field(DSL.raw("0"), SQLDataType.BIGINT)), this, "") private constructor(alias: Name, aliased: Table<KotlinerRecord>?): this(alias, null, null, null, aliased, null, null) private constructor(alias: Name, aliased: Table<KotlinerRecord>?, parameters: Array<Field<*>?>?): this(alias, null, null, null, aliased, parameters, null) private constructor(alias: Name, aliased: Table<KotlinerRecord>?, where: Condition?): this(alias, null, null, null, aliased, null, where) /** * Create an aliased <code>public.kotliner</code> table reference */ constructor(alias: String): this(DSL.name(alias)) /** * Create an aliased <code>public.kotliner</code> table reference */ constructor(alias: Name): this(alias, null) /** * Create a <code>public.kotliner</code> table reference */ constructor(): this(DSL.name("kotliner"), null) constructor(path: Table<out Record>, childPath: ForeignKey<out Record, KotlinerRecord>?, parentPath: InverseForeignKey<out Record, KotlinerRecord>?): this(Internal.createPathAlias(path, childPath, parentPath), path, childPath, parentPath, KOTLINER, null, null) /** * A subtype implementing {@link Path} for simplified path-based joins. */ open class KotlinerPath : Kotliner, Path<KotlinerRecord> { constructor(path: Table<out Record>, childPath: ForeignKey<out Record, KotlinerRecord>?, parentPath: InverseForeignKey<out Record, KotlinerRecord>?): super(path, childPath, parentPath) private constructor(alias: Name, aliased: Table<KotlinerRecord>): super(alias, aliased) override fun `as`(alias: String): KotlinerPath = KotlinerPath(DSL.name(alias), this) override fun `as`(alias: Name): KotlinerPath = KotlinerPath(alias, this) override fun `as`(alias: Table<*>): KotlinerPath = KotlinerPath(alias.qualifiedName, this) } override fun getSchema(): Schema? = if (aliased()) null else Public.PUBLIC override fun getIdentity(): Identity<KotlinerRecord, Long?> = super.getIdentity() as Identity<KotlinerRecord, Long?> override fun getPrimaryKey(): UniqueKey<KotlinerRecord> = KOTLINER_PKEY override fun getUniqueKeys(): List<UniqueKey<KotlinerRecord>> = listOf(UNIQUE_KOTLINER_EMAIL, UNIQUE_KOTLINER_NICKNAME) private lateinit var _articleCreatedByFkey: ArticlePath /** * Get the implicit to-many join path to the <code>public.article</code> * table, via the <code>article_created_by_fkey</code> key */ fun articleCreatedByFkey(): ArticlePath { if (!this::_articleCreatedByFkey.isInitialized) _articleCreatedByFkey = ArticlePath(this, null, ARTICLE__ARTICLE_CREATED_BY_FKEY.inverseKey) return _articleCreatedByFkey; } val articleCreatedByFkey: ArticlePath get(): ArticlePath = articleCreatedByFkey() private lateinit var _articleUpdatedByFkey: ArticlePath /** * Get the implicit to-many join path to the <code>public.article</code> * table, via the <code>article_updated_by_fkey</code> key */ fun articleUpdatedByFkey(): ArticlePath { if (!this::_articleUpdatedByFkey.isInitialized) _articleUpdatedByFkey = ArticlePath(this, null, ARTICLE__ARTICLE_UPDATED_BY_FKEY.inverseKey) return _articleUpdatedByFkey; } val articleUpdatedByFkey: ArticlePath get(): ArticlePath = articleUpdatedByFkey() private lateinit var _articleAuthor: ArticleAuthorPath /** * Get the implicit to-many join path to the * <code>public.article_author</code> table */ fun articleAuthor(): ArticleAuthorPath { if (!this::_articleAuthor.isInitialized) _articleAuthor = ArticleAuthorPath(this, null, ARTICLE_AUTHOR__ARTICLE_AUTHOR_KOTLINER_ID_FKEY.inverseKey) return _articleAuthor; } val articleAuthor: ArticleAuthorPath get(): ArticleAuthorPath = articleAuthor() private lateinit var _bookSpeaker: BookSpeakerPath /** * Get the implicit to-many join path to the * <code>public.book_speaker</code> table */ fun bookSpeaker(): BookSpeakerPath { if (!this::_bookSpeaker.isInitialized) _bookSpeaker = BookSpeakerPath(this, null, BOOK_SPEAKER__BOOK_SPEAKER_KOTLINER_ID_FKEY.inverseKey) return _bookSpeaker; } val bookSpeaker: BookSpeakerPath get(): BookSpeakerPath = bookSpeaker() private lateinit var _comment: CommentPath /** * Get the implicit to-many join path to the <code>public.comment</code> * table */ fun comment(): CommentPath { if (!this::_comment.isInitialized) _comment = CommentPath(this, null, COMMENT__COMMENT_KOTLINER_ID_FKEY.inverseKey) return _comment; } val comment: CommentPath get(): CommentPath = comment() private lateinit var _courseSpeaker: CourseSpeakerPath /** * Get the implicit to-many join path to the * <code>public.course_speaker</code> table */ fun courseSpeaker(): CourseSpeakerPath { if (!this::_courseSpeaker.isInitialized) _courseSpeaker = CourseSpeakerPath(this, null, COURSE_SPEAKER__COURSE_SPEAKER_KOTLINER_ID_FKEY.inverseKey) return _courseSpeaker; } val courseSpeaker: CourseSpeakerPath get(): CourseSpeakerPath = courseSpeaker() private lateinit var _kotlinerLikeEntityState: KotlinerLikeEntityStatePath /** * Get the implicit to-many join path to the * <code>public.kotliner_like_entity_state</code> table */ fun kotlinerLikeEntityState(): KotlinerLikeEntityStatePath { if (!this::_kotlinerLikeEntityState.isInitialized) _kotlinerLikeEntityState = KotlinerLikeEntityStatePath(this, null, KOTLINER_LIKE_ENTITY_STATE__KOTLINER_LIKE_ENTITY_STATE_KOTLINER_ID_FKEY.inverseKey) return _kotlinerLikeEntityState; } val kotlinerLikeEntityState: KotlinerLikeEntityStatePath get(): KotlinerLikeEntityStatePath = kotlinerLikeEntityState() private lateinit var _kotlinerReadEntityState: KotlinerReadEntityStatePath /** * Get the implicit to-many join path to the * <code>public.kotliner_read_entity_state</code> table */ fun kotlinerReadEntityState(): KotlinerReadEntityStatePath { if (!this::_kotlinerReadEntityState.isInitialized) _kotlinerReadEntityState = KotlinerReadEntityStatePath(this, null, KOTLINER_READ_ENTITY_STATE__KOTLINER_READ_ENTITY_STATE_KOTLINER_ID_FKEY.inverseKey) return _kotlinerReadEntityState; } val kotlinerReadEntityState: KotlinerReadEntityStatePath get(): KotlinerReadEntityStatePath = kotlinerReadEntityState() private lateinit var _kugCreatedByFkey: KugPath /** * Get the implicit to-many join path to the <code>public.kug</code> table, * via the <code>kug_created_by_fkey</code> key */ fun kugCreatedByFkey(): KugPath { if (!this::_kugCreatedByFkey.isInitialized) _kugCreatedByFkey = KugPath(this, null, KUG__KUG_CREATED_BY_FKEY.inverseKey) return _kugCreatedByFkey; } val kugCreatedByFkey: KugPath get(): KugPath = kugCreatedByFkey() private lateinit var _kugUpdatedByFkey: KugPath /** * Get the implicit to-many join path to the <code>public.kug</code> table, * via the <code>kug_updated_by_fkey</code> key */ fun kugUpdatedByFkey(): KugPath { if (!this::_kugUpdatedByFkey.isInitialized) _kugUpdatedByFkey = KugPath(this, null, KUG__KUG_UPDATED_BY_FKEY.inverseKey) return _kugUpdatedByFkey; } val kugUpdatedByFkey: KugPath get(): KugPath = kugUpdatedByFkey() private lateinit var _kugEvent: KugEventPath /** * Get the implicit to-many join path to the <code>public.kug_event</code> * table */ fun kugEvent(): KugEventPath { if (!this::_kugEvent.isInitialized) _kugEvent = KugEventPath(this, null, KUG_EVENT__KUG_EVENT_UPDATED_BY_FKEY.inverseKey) return _kugEvent; } val kugEvent: KugEventPath get(): KugEventPath = kugEvent() private lateinit var _kugMember: KugMemberPath /** * Get the implicit to-many join path to the <code>public.kug_member</code> * table */ fun kugMember(): KugMemberPath { if (!this::_kugMember.isInitialized) _kugMember = KugMemberPath(this, null, KUG_MEMBER__KUG_MEMBER_KOTLINER_ID_FKEY.inverseKey) return _kugMember; } val kugMember: KugMemberPath get(): KugMemberPath = kugMember() private lateinit var _vacancy: VacancyPath /** * Get the implicit to-many join path to the <code>public.vacancy</code> * table */ fun vacancy(): VacancyPath { if (!this::_vacancy.isInitialized) _vacancy = VacancyPath(this, null, VACANCY__VACANCY_KOTLINER_ID_FKEY.inverseKey) return _vacancy; } val vacancy: VacancyPath get(): VacancyPath = vacancy() private lateinit var _videoSpeaker: VideoSpeakerPath /** * Get the implicit to-many join path to the * <code>public.video_speaker</code> table */ fun videoSpeaker(): VideoSpeakerPath { if (!this::_videoSpeaker.isInitialized) _videoSpeaker = VideoSpeakerPath(this, null, VIDEO_SPEAKER__VIDEO_SPEAKER_KOTLINER_ID_FKEY.inverseKey) return _videoSpeaker; } val videoSpeaker: VideoSpeakerPath get(): VideoSpeakerPath = videoSpeaker() /** * Get the implicit many-to-many join path to the * <code>public.article</code> table */ val article: ArticlePath get(): ArticlePath = articleAuthor().article() /** * Get the implicit many-to-many join path to the <code>public.book</code> * table */ val book: BookPath get(): BookPath = bookSpeaker().book() /** * Get the implicit many-to-many join path to the <code>public.course</code> * table */ val course: CoursePath get(): CoursePath = courseSpeaker().course() /** * Get the implicit many-to-many join path to the <code>public.kug</code> * table */ val kug: KugPath get(): KugPath = kugMember().kug() /** * Get the implicit many-to-many join path to the <code>public.video</code> * table */ val video: VideoPath get(): VideoPath = videoSpeaker().video() override fun `as`(alias: String): Kotliner = Kotliner(DSL.name(alias), this) override fun `as`(alias: Name): Kotliner = Kotliner(alias, this) override fun `as`(alias: Table<*>): Kotliner = Kotliner(alias.qualifiedName, this) /** * Rename this table */ override fun rename(name: String): Kotliner = Kotliner(DSL.name(name), null) /** * Rename this table */ override fun rename(name: Name): Kotliner = Kotliner(name, null) /** * Rename this table */ override fun rename(name: Table<*>): Kotliner = Kotliner(name.qualifiedName, null) /** * Create an inline derived table from this table */ override fun where(condition: Condition?): Kotliner = Kotliner(qualifiedName, if (aliased()) this else null, condition) /** * Create an inline derived table from this table */ override fun where(conditions: Collection<Condition>): Kotliner = where(DSL.and(conditions)) /** * Create an inline derived table from this table */ override fun where(vararg conditions: Condition?): Kotliner = where(DSL.and(*conditions)) /** * Create an inline derived table from this table */ override fun where(condition: Field<Boolean?>?): Kotliner = where(DSL.condition(condition)) /** * Create an inline derived table from this table */ @PlainSQL override fun where(condition: SQL): Kotliner = where(DSL.condition(condition)) /** * Create an inline derived table from this table */ @PlainSQL override fun where(@Stringly.SQL condition: String): Kotliner = where(DSL.condition(condition)) /** * Create an inline derived table from this table */ @PlainSQL override fun where(@Stringly.SQL condition: String, vararg binds: Any?): Kotliner = where(DSL.condition(condition, *binds)) /** * Create an inline derived table from this table */ @PlainSQL override fun where(@Stringly.SQL condition: String, vararg parts: QueryPart): Kotliner = where(DSL.condition(condition, *parts)) /** * Create an inline derived table from this table */ override fun whereExists(select: Select<*>): Kotliner = where(DSL.exists(select)) /** * Create an inline derived table from this table */ override fun whereNotExists(select: Select<*>): Kotliner = where(DSL.notExists(select)) }
21
Kotlin
1220
11,018
2f4cfa75180e759d91fe238cc3f638beec9286e2
19,587
awesome-kotlin
Apache License 2.0
data/src/main/kotlin/team/duckie/app/android/data/exam/paging/ExamMeFollowingPagingSource.kt
duckie-team
503,869,663
false
{"Kotlin": 1819917}
/* * Designed and developed by Duckie Team, 2022 * * Licensed under the MIT. * Please see full license: https://github.com/duckie-team/duckie-android/blob/develop/LICENSE */ @file:Suppress("TooGenericExceptionCaught") package team.duckie.app.android.data.exam.paging import androidx.paging.PagingSource import androidx.paging.PagingState import team.duckie.app.android.data.exam.repository.ExamRepositoryImpl.Companion.ExamMePagingPage import team.duckie.app.android.domain.exam.model.Exam private const val STARTING_KEY = 1 internal class ExamMeFollowingPagingSource( private val getExamMeFollowing: suspend (Int) -> List<Exam>, ) : PagingSource<Int, Exam>() { override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Exam> { return try { val currentPage = params.key ?: STARTING_KEY val response = getExamMeFollowing(currentPage) LoadResult.Page( data = response, prevKey = if (currentPage == STARTING_KEY) null else currentPage - 1, nextKey = if (response.isEmpty() || response.size < ExamMePagingPage) null else currentPage + 1, ) } catch (e: Exception) { LoadResult.Error(e) } } override fun getRefreshKey(state: PagingState<Int, Exam>): Int { return ((state.anchorPosition ?: 0) - state.config.initialLoadSize / 2) .coerceAtLeast(0) } }
32
Kotlin
1
8
5dbd5b7a42c621931d05a96e66431f67a3a50762
1,439
duckie-android
MIT License
compiler/testData/diagnostics/tests/extensions/contextReceivers/thisWithReceiverLabelsClasses.fir.kt
JetBrains
3,432,266
false
null
// !LANGUAGE: +ContextReceivers class A { val x = 1 } context(A) class B { val prop = <!UNRESOLVED_REFERENCE!>x<!> + this<!UNRESOLVED_LABEL!>@A<!>.x fun f() = <!UNRESOLVED_REFERENCE!>x<!> + this<!UNRESOLVED_LABEL!>@A<!>.x }
135
Kotlin
4980
40,442
817f9f13b71d4957d8eaa734de2ac8369ad64770
238
kotlin
Apache License 2.0