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
sdk/src/main/java/sk/trustpay/api/sdk/methods/Card.kt
TrustPayEU
731,522,955
false
{"Kotlin": 29927}
@file:Suppress("unused") package sk.trustpay.api.sdk.methods import sk.trustpay.api.sdk.common.PaymentRequest import sk.trustpay.api.sdk.common.PaymentResponse import sk.trustpay.api.sdk.dto.CallbackUrls import sk.trustpay.api.sdk.dto.CardTransaction import sk.trustpay.api.sdk.dto.MerchantIdentification import sk.trustpay.api.sdk.dto.PaymentInformation class CardRequest( merchantIdentification: MerchantIdentification, paymentInformation: PaymentInformation, cardTransaction: CardTransaction, callbackUrls: CallbackUrls? = null ) : PaymentRequest<CardRequest>(merchantIdentification, paymentInformation, callbackUrls) { init { this.paymentInformation.cardTransaction = cardTransaction } val paymentMethod: String = "Card" } class CardResponse : PaymentResponse()
0
Kotlin
0
0
9b7faba370e40550f035e87094e1e4c6500d475d
807
android-sdk
MIT License
app/src/main/kotlin/com/krishnaZyala/faceRecognition/ui/screen/home/HomeScreen.kt
MohamedTaher1999
749,859,237
false
{"Kotlin": 45281}
package com.krishnaZyala.faceRecognition.ui.screen.home import android.app.Activity import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.FabPosition import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.contentColorFor import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavHostController import androidx.navigation.compose.rememberNavController import com.krishnaZyala.faceRecognition.data.model.AppState import com.krishnaZyala.faceRecognition.ui.screen.selfie.AddFaceScreen @Composable fun HomeScreen(activity: Activity, vm: HomeViewModel = hiltViewModel()) { val home: NavHostController = rememberNavController() val state: HomeScreenState by remember(vm.state) { vm.state } DisposableEffect( home) { vm.onCompose( home) onDispose { vm.onDispose() } } Scaffold( modifier = Modifier.fillMaxSize(), floatingActionButtonPosition = FabPosition.End, containerColor = MaterialTheme.colorScheme.background, contentColor = contentColorFor(MaterialTheme.colorScheme.background), content = { padding -> Column(modifier = Modifier.padding(padding)) { AddFaceScreen() } } ) state.firstPermission(activity)?.run { state.permissions[this]?.let { isDenied -> invoke(isDenied, onDeny = { vm.onPermissionDeny(this, it) }, onClick = { vm.onPermissionDeny(this, false) }) } } }
0
Kotlin
0
0
b4c079b3fc7c8708a5d52cc1d79de91387bad231
1,858
faceDetectionCapture
MIT License
src/main/kotlin/org/lexem/angmar/parser/descriptive/lexemes/BinarySequenceLexemeNode.kt
lexemlang
184,409,059
false
{"Kotlin": 3049940}
package org.lexem.angmar.parser.descriptive.lexemes import com.google.gson.* import org.lexem.angmar.* import org.lexem.angmar.analyzer.nodes.descriptive.lexemes.* import org.lexem.angmar.parser.* import org.lexem.angmar.parser.functional.expressions.* import org.lexem.angmar.parser.literals.* /** * Parser for binary sequence lexemes. */ internal class BinarySequenceLexemeNode private constructor(parser: LexemParser, parent: ParserNode, parentSignal: Int) : ParserNode(parser, parent, parentSignal) { var isNegated = false var propertyPostfix: LexemPropertyPostfixNode? = null lateinit var bitlist: BitlistNode override fun toString() = StringBuilder().apply { if (isNegated) { append(notOperator) } append(bitlist) if (propertyPostfix != null) { append(propertyPostfix) } }.toString() override fun toTree(): JsonObject { val result = super.toTree() result.addProperty("isNegated", isNegated) result.add("propertyPostfix", propertyPostfix?.toTree()) result.add("bitlist", bitlist.toTree()) return result } override fun analyze(analyzer: LexemAnalyzer, signal: Int) = BinarySequenceLexemAnalyzer.stateMachine(analyzer, signal, this) companion object { const val notOperator = PrefixOperatorNode.notOperator // METHODS ------------------------------------------------------------ /** * Parses a bitlist lexeme. */ fun parse(parser: LexemParser, parent: ParserNode, parentSignal: Int): BinarySequenceLexemeNode? { parser.fromBuffer(parser.reader.currentPosition(), BinarySequenceLexemeNode::class.java)?.let { it.parent = parent it.parentSignal = parentSignal return@parse it } val initCursor = parser.reader.saveCursor() val result = BinarySequenceLexemeNode(parser, parent, parentSignal) result.isNegated = parser.readText(notOperator) val bitlist = BitlistNode.parse(parser, result, BinarySequenceLexemAnalyzer.signalEndBitlist) if (bitlist == null) { initCursor.restore() return null } result.bitlist = bitlist result.propertyPostfix = LexemPropertyPostfixNode.parse(parser, result, BinarySequenceLexemAnalyzer.signalEndPropertyPostfix) return parser.finalizeNode(result, initCursor) } } }
0
Kotlin
0
2
45fb563507a00c3eada89be9ab6e17cfe1701958
2,570
angmar
MIT License
GaiaXAndroidJSAdapter/src/main/java/com/alibaba/gaiax/js/adapter/view/GaiaXCustomDialogView.kt
alibaba
456,772,654
false
{"C": 3164040, "Kotlin": 1554812, "Rust": 1390378, "Objective-C": 919399, "Java": 650270, "JavaScript": 260489, "TypeScript": 230784, "C++": 223843, "CSS": 153571, "HTML": 113541, "MDX": 86833, "Objective-C++": 60116, "Swift": 25131, "Makefile": 12210, "Shell": 9836, "Ruby": 6268, "CMake": 4674, "Batchfile": 3823, "SCSS": 837}
//package com.alibaba.gaiax.js.adapter.view // //import android.app.Dialog //import android.content.Context //import android.graphics.Color //import android.graphics.drawable.ColorDrawable //import android.os.Bundle //import android.view.View //import android.view.Window //import com.alibaba.fastjson.JSONObject //import com.alibaba.gaiax.GXTemplateEngine // ///** // * @author: shisan.lms // * @date: 2023-03-27 // * Description: // */ //class GaiaXCustomDialogView : Dialog { // private val params: JSONObject = JSONObject() // private var mContainer: View? = null // // constructor(context: Context, params: JSONObject?) : super(context) { // if (params != null) { // this.params.putAll(params) // } // } // // override fun onCreate(savedInstanceState: Bundle?) { // super.onCreate(savedInstanceState) // if (params.isEmpty()) { // return // } // initDialogFeature() // val builder: GaiaX.Params.Builder? = initGaiaXBuilder() // val params: GaiaX.Params = builder.build() // GaiaX.Companion.getInstance().bindView(params) // } // // fun getEventDelegate(): GaiaX.IEventDelegate? { // return object : IEventDelegate() { // fun onEvent(@NotNull eventParams: EventParams) { // Log.d("GaiaXCustomDialogView", "onEvent: ") // doEvent(eventParams) // } // } // } // // protected fun doEvent(@NonNull eventParams: EventParams) { // //目前只做点击事件 // if (eventParams.getData() != null) { // val action: Action? = safeToAction(eventParams.getData()) // ActionWrapper.doAction(AppInfoProviderProxy.getAppContext(), action) // } // } // // /** // * 安全转换ACTION // * // * @return 如果失败返回null // */ // fun safeToAction(targetData: JSONObject): Action? { // try { // return targetData.toJavaObject(Action::class.java) // } catch (e: Exception) { // e.printStackTrace() // } // return null // } // // fun getTrackDelegate(): GaiaX.ITrackDelegate3? { // return object : ITrackDelegate3() { // fun onTrack(@NotNull trackParams: TrackParams) { // doTrack(trackParams) // } // } // } // // protected fun doTrack(@NonNull trackParams: TrackParams) { // if (trackParams.getView() != null && trackParams.getData() != null) { // val args = getTrackParams(trackParams.getData()) // if (args != null && TextUtils.isEmpty(args["arg1"])) { // args.put("arg1", args["spm"] + "") // } // YoukuAnalyticsProviderProxy.setTrackerTagParam(trackParams.getView(), args, IContract.ALL_TRACKER) // } // } // // /** // * 获取埋点参数 // */ // fun getTrackParams(@NonNull targetData: JSONObject): Map<String, String>? { // val action: Action? = safeToAction(targetData) // return if (action != null) { // ReportDelegate.generateTrackerMap(action.getReportExtend(), null) // } else HashMap() // } // // // private fun initDialogFeature() { // val dismissWhenTap = if (params.getBoolean("dismissWhenTap") != null) params.getBoolean("dismissWhenTap") else true // requestWindowFeature(Window.FEATURE_NO_TITLE) // setCanceledOnTouchOutside(dismissWhenTap) // this.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) // } // // private fun getWidth(): Int { // val width: Int = params.getIntValue("width") // return if (width != 0) { // width // } else { // DeviceInfoProviderProxy.getWindowWidth() // } // } // // private fun getHeightBuilder(builder: GaiaX.Params.Builder): GaiaX.Params.Builder { // val height: Float = if (params.getFloat("height") == null) 0 else params.getFloat("height") // return if (height != 0f) { // builder.height(height) // } else { // builder // } // } // // private fun getTemplateData(): JSONObject? { // val templateData: JSONObject = params.getJSONObject("templateData") // return if (templateData != null) { // templateData // } else { // JSONObject() // } // } // // private fun initGaiaXBuilder(): GXTemplateEngine.GXTemplateItem { // val templateId: String = params.getString("templateId") // val templateBiz: String = params.getString("bizId") // if (templateBiz == null || templateId == null) { // return null // } // mContainer = LayoutInflater.from(getContext()).inflate(R.layout.custom_dialog_layout, null, false) // setContentView(mContainer) // var builder: GaiaX.Params.Builder = Builder() // .templateId(templateId) // .templateBiz(templateBiz) // .container(mContainer) // .width(getWidth()) // .data(getTemplateData()) // .mode(LoadType.SYNC_NORMAL) // builder = getHeightBuilder(builder) // return builder // } //}
23
C
118
945
81875d09f2bddd307a6203e58ff2f6f13bec9418
5,159
GaiaX
Apache License 2.0
AppJetpackCompose/app/src/main/java/com/example/apptrivial/components/RadioButton.kt
Moromon
712,030,977
false
{"Kotlin": 64386}
package com.example.apptrivial.components import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @Composable fun RadioButton( selected: Boolean, onClick: () -> Unit, text: String ) { Row( modifier = Modifier .clickable(onClick = onClick) .padding(8.dp), verticalAlignment = Alignment.CenterVertically ) { Box( modifier = Modifier .size(24.dp) .border(2.dp, Color.Black, shape = CircleShape) .background(if (selected) Color.Black else Color.Transparent, shape = CircleShape) ) Spacer(modifier = Modifier.width(8.dp)) Text( text = text, fontSize = 16.sp ) } }
0
Kotlin
0
1
74f91965404665a8c6c73819b60ad89542730889
1,434
PregutadosAPP
MIT License
src/main/kotlin/org/shardscript/semantics/prelude/Lang.kt
shardscript
301,230,998
false
{"Kotlin": 1176823, "ANTLR": 8647}
package org.shardscript.semantics.prelude import org.shardscript.semantics.core.* object Lang { val prelude = SymbolTable(NullSymbolTable) val unitId = Identifier(NotInSource, "Unit") val booleanId = Identifier(NotInSource, "Boolean") val intId = Identifier(NotInSource, "Int") val charId = Identifier(NotInSource, "Char") val stringId = Identifier(NotInSource, "String") val stringTypeId = Identifier(NotInSource, "O") val stringInputTypeId = Identifier(NotInSource, "P") val decimalId = Identifier(NotInSource, "Decimal") val decimalTypeId = Identifier(NotInSource, "O") val decimalInputTypeId = Identifier(NotInSource, "P") val listId = Identifier(NotInSource, "List") val listElementTypeId = Identifier(NotInSource, "E") val listFinTypeId = Identifier(NotInSource, "O") val listInputFinTypeId = Identifier(NotInSource, "P") val mutableListId = Identifier(NotInSource, "MutableList") val mutableListElementTypeId = Identifier(NotInSource, "E") val mutableListFinTypeId = Identifier(NotInSource, "O") val mutableListInputFinTypeId = Identifier(NotInSource, "P") val pairId = Identifier(NotInSource, "Pair") private val pairFirstTypeId = Identifier(NotInSource, "A") private val pairSecondTypeId = Identifier(NotInSource, "B") val pairFirstId = Identifier(NotInSource, "first") val pairSecondId = Identifier(NotInSource, "second") val dictionaryId = Identifier(NotInSource, "Dictionary") val dictionaryKeyTypeId = Identifier(NotInSource, "K") val dictionaryValueTypeId = Identifier(NotInSource, "V") val dictionaryFinTypeId = Identifier(NotInSource, "O") val dictionaryInputFinTypeId = Identifier(NotInSource, "P") val mutableDictionaryId = Identifier(NotInSource, "MutableDictionary") val mutableDictionaryKeyTypeId = Identifier(NotInSource, "K") val mutableDictionaryValueTypeId = Identifier(NotInSource, "V") val mutableDictionaryFinTypeId = Identifier(NotInSource, "O") val mutableDictionaryInputFinTypeId = Identifier(NotInSource, "P") val setId = Identifier(NotInSource, "Set") val setElementTypeId = Identifier(NotInSource, "E") val setFinTypeId = Identifier(NotInSource, "O") val setInputFinTypeId = Identifier(NotInSource, "P") val mutableSetId = Identifier(NotInSource, "MutableSet") val mutableSetElementTypeId = Identifier(NotInSource, "E") val mutableSetFinTypeId = Identifier(NotInSource, "O") val mutableSetInputFinTypeId = Identifier(NotInSource, "P") val rangeId = Identifier(NotInSource, "range") val rangeTypeId = Identifier(NotInSource, "O") val randomId = Identifier(NotInSource, "random") val randomTypeId = Identifier(NotInSource, "A") const val INT_FIN: Long = (Int.MIN_VALUE.toString().length).toLong() val unitFin: Long = unitId.name.length.toLong() const val BOOL_FIN: Long = false.toString().length.toLong() const val CHAR_FIN: Long = 1L fun isUnitExactly(type: Type): Boolean = when (generatePath(type as Symbol)) { listOf(unitId.name) -> true else -> false } init { // Unit val unitObject = ObjectSymbol( prelude, unitId, userTypeFeatureSupport ) // Boolean val booleanType = BasicTypeSymbol( prelude, booleanId ) val constantFin = ConstantFinTypeSymbol ValueEqualityOpMembers.members(booleanType, constantFin, booleanType).forEach { (name, plugin) -> booleanType.define(Identifier(NotInSource, name), plugin) } ValueLogicalOpMembers.members(booleanType, constantFin).forEach { (name, plugin) -> booleanType.define(Identifier(NotInSource, name), plugin) } // Integer val intType = intType(intId, booleanType, prelude, setOf()) // Decimal val decimalType = decimalType(decimalId, booleanType, prelude) // Char val charType = BasicTypeSymbol( prelude, charId ) ValueEqualityOpMembers.members(charType, constantFin, charType).forEach { (name, plugin) -> charType.define(Identifier(NotInSource, name), plugin) } // List val listType = listCollectionType(prelude, intType, booleanType) // MutableList val mutableListType = mutableListCollectionType(prelude, intType, unitObject, booleanType, listType) // String val stringType = stringType(booleanType, intType, charType, listType, prelude) // ToString insertIntegerToStringMember(intType, stringType) insertUnitToStringMember(unitObject, stringType) insertBooleanToStringMember(booleanType, stringType) insertDecimalToStringMember(decimalType, stringType) insertCharToStringMember(charType, stringType) insertStringToStringMember(stringType) // Pair val pairType = ParameterizedRecordTypeSymbol( prelude, pairId, userTypeFeatureSupport ) val pairFirstType = StandardTypeParameter(pairType, pairFirstTypeId) val pairSecondType = StandardTypeParameter(pairType, pairSecondTypeId) pairType.typeParams = listOf(pairFirstType, pairSecondType) val pairFirstField = FieldSymbol(pairType, pairFirstId, pairFirstType, mutable = false) val pairSecondField = FieldSymbol(pairType, pairSecondId, pairSecondType, mutable = false) pairType.fields = listOf(pairFirstField, pairSecondField) pairType.define(pairFirstId, pairFirstField) pairType.define(pairSecondId, pairSecondField) // Dictionary val dictionaryType = dictionaryCollectionType(prelude, booleanType, intType, pairType) // MutableDictionary val mutableDictionaryType = mutableDictionaryCollectionType( prelude, booleanType, intType, unitObject, pairType, dictionaryType ) // Set val setType = setCollectionType(prelude, booleanType, intType) // MutableSet val mutableSetType = mutableSetCollectionType(prelude, booleanType, intType, unitObject, setType) // Static val rangePlugin = createRangePlugin(prelude, intType, listType) val randomPlugin = createRandomPlugin(prelude, constantFin) // Compose output prelude.define(unitId, unitObject) prelude.define(booleanId, booleanType) prelude.define(intId, intType) prelude.define(decimalId, decimalType) prelude.define(listId, listType) prelude.define(mutableListId, mutableListType) prelude.define(pairId, pairType) prelude.define(dictionaryId, dictionaryType) prelude.define(mutableDictionaryId, mutableDictionaryType) prelude.define(setId, setType) prelude.define(mutableSetId, mutableSetType) prelude.define(charId, charType) prelude.define(stringId, stringType) prelude.define(rangeId, rangePlugin) prelude.define(randomId, randomPlugin) } }
10
Kotlin
0
6
b3a8ae3fa77031bab40292b489d9c721448bb5d4
7,257
shardscript
MIT License
ProblemSolving/app/src/test/java/com/samiran/problemsolving/leetcode/easy/BestTimeToBuyAndSellStockTest.kt
SamiranKumar
556,658,987
false
{"Kotlin": 7027}
package com.samiran.problemsolving.leetcode.easy import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test /** * @sample * 121. Best Time to Buy and Sell Stock * * */ class BestTimeToBuyAndSellStockTest { /* @Before fun init() { // Log.i("hk", "startup") testMaxProfit1() testMaxProfit2() testMaxProfit3() testMaxProfit4() testMaxProfit5() }*/ @Test fun testMaxProfit1() { val array = intArrayOf(7, 1, 5, 3, 6, 4) assertEquals(5, maxProfit(array)) } @Test fun testMaxProfit2() { val array = intArrayOf(7, 4, 5, 3, 6, 1) assertEquals(3, maxProfit(array)) } @Test fun testMaxProfit3() { val array = intArrayOf(7, 6, 4, 3, 1) assertEquals(0, maxProfit(array)) } @Test fun testMaxProfit4() { val array = intArrayOf(7) assertEquals(0, maxProfit(array)) } @Test fun testMaxProfit5() { val array = intArrayOf(1) assertEquals(0, maxProfit(array)) } /* @After fun teardown() { }*/ }
0
Kotlin
0
0
48a41e64b68375ee67a59962f448a9508deda93f
1,151
ProblemSolving
MIT License
baselineprofile/src/main/kotlin/ru/resodostudios/cashsense/categories/CategoriesActions.kt
f33lnothin9
674,320,726
false
{"Kotlin": 303127}
package ru.resodostudios.cashsense.categories import androidx.benchmark.macro.MacrobenchmarkScope import androidx.test.uiautomator.By import androidx.test.uiautomator.Until import ru.resodostudios.cashsense.waitForObjectOnTopAppBar fun MacrobenchmarkScope.goToCategoriesScreen() { device.findObject(By.text("Categories")).click() waitForObjectOnTopAppBar(By.text("Categories")) // Wait until content is loaded by checking if categories are loaded device.wait(Until.gone(By.res("loadingCircle")), 2_500) }
0
Kotlin
3
33
a246a75e4a67ee55170652e7b16346039c10b427
523
cashsense
Apache License 2.0
kotlin-node/src/jsMain/generated/node/crypto/ED448KeyPairPemPemOptions.kt
JetBrains
93,250,841
false
{"Kotlin": 11411371, "JavaScript": 154302}
package node.crypto external interface ED448KeyPairPemPemOptions : ED448KeyPairOptions<KeyFormat.pem, KeyFormat.pem>
28
Kotlin
173
1,250
9e9dda28cf74f68b42a712c27f2e97d63af17628
119
kotlin-wrappers
Apache License 2.0
src/main/kotlin/com/sourcegraph/cody/agent/protocol_generated/Constants.kt
sourcegraph
702,947,607
false
{"Kotlin": 914689, "Java": 201176, "Shell": 4636, "TypeScript": 2153, "Nix": 1122, "JavaScript": 436, "HTML": 294}
@file:Suppress("unused", "ConstPropertyName") package com.sourcegraph.cody.agent.protocol_generated; object Constants { const val Applied = "Applied" const val Applying = "Applying" const val Automatic = "Automatic" const val Error = "Error" const val Finished = "Finished" const val IDEEXTENSION = "IDEEXTENSION" const val Idle = "Idle" const val Inserting = "Inserting" const val Invoke = "Invoke" const val Pending = "Pending" const val Working = "Working" const val accuracy = "accuracy" const val agentic = "agentic" const val ask = "ask" const val assistant = "assistant" const val autocomplete = "autocomplete" const val balanced = "balanced" const val byok = "byok" const val chat = "chat" const val `class` = "class" const val complete = "complete" const val `create-file` = "create-file" const val default = "default" const val delete = "delete" const val `delete-file` = "delete-file" const val deprecated = "deprecated" const val dev = "dev" const val edit = "edit" const val `edit-file` = "edit-file" const val editor = "editor" const val embeddings = "embeddings" const val enabled = "enabled" const val enterprise = "enterprise" const val error = "error" const val errored = "errored" const val experimental = "experimental" const val fetching = "fetching" const val file = "file" const val free = "free" const val function = "function" const val gateway = "gateway" const val history = "history" const val human = "human" const val ignore = "ignore" const val indentation = "indentation" const val info = "info" const val information = "information" const val initial = "initial" const val insert = "insert" const val isChatErrorGuard = "isChatErrorGuard" const val local = "local" const val method = "method" const val native = "native" const val none = "none" const val notification = "notification" const val `object-encoded` = "object-encoded" const val ollama = "ollama" const val openctx = "openctx" const val paused = "paused" const val pro = "pro" const val `recently used` = "recently used" const val recommended = "recommended" const val `rename-file` = "rename-file" const val replace = "replace" const val repository = "repository" const val request = "request" const val search = "search" const val selection = "selection" const val speed = "speed" const val streaming = "streaming" const val `string-encoded` = "string-encoded" const val suggestion = "suggestion" const val symbol = "symbol" const val system = "system" const val terminal = "terminal" const val tree = "tree" const val `tree-sitter` = "tree-sitter" const val unified = "unified" const val uri = "uri" const val use = "use" const val user = "user" const val warning = "warning" const val workspace = "workspace" }
230
Kotlin
16
55
1eb25809c3e51b64f08e851c8da09778000540c6
2,877
jetbrains
Apache License 2.0
backend/mandalore-express-domain/src/test/kotlin/com/beyondxscratch/mandaloreexpress/domain/booking/spacetrain/SpaceTrainFactory.kt
davidaparicio
761,161,576
false
{"Kotlin": 198124, "JavaScript": 37294, "HTML": 1661, "CSS": 365}
package com.beyondxscratch.mandaloreexpress.domain.booking.spacetrain import com.beyondxscratch.mandaloreexpress.domain.booking.spacetrain.fare.fare import com.beyondxscratch.mandaloreexpress.domain.booking.spacetrain.fare.firstClassFare import com.beyondxscratch.mandaloreexpress.domain.booking.spacetrain.fare.randomFare import com.beyondxscratch.mandaloreexpress.domain.booking.spacetrain.fare.Price import java.time.LocalDateTime import kotlin.random.Random.Default.nextLong fun spaceTrain(): SpaceTrain = SpaceTrain( number = "6127", originId = "CORUSCANT", destinationId = "MANDALORE", schedule = schedule(), fare = fare() ) fun randomSpaceTrain(): SpaceTrain = spaceTrain() .copy( number = nextLong(1, 1000).toString(), schedule = randomSchedule(), fare = randomFare() ) fun SpaceTrain.withFirstClass(): SpaceTrain { return this.copy(fare = firstClassFare()) } fun SpaceTrain.numbered(number: String): SpaceTrain { return this.copy(number = number) } fun SpaceTrain.priced(price: Price): SpaceTrain { return this.copy(fare = fare.copy(price = price)) } fun SpaceTrain.departing(date: LocalDateTime): SpaceTrain { return this.copy(schedule = this.schedule.copy(departure = date, arrival = date.plusDays(7))) }
8
Kotlin
0
0
05dc41e2a5a5ea47ef5d688177631ffa9923fe11
1,290
model-mitosis
Apache License 2.0
api/src/main/kotlin/com/seedcompany/cordtables/components/tables/sc/budget_records/Read.kt
CordField
409,237,733
false
null
package com.seedcompany.cordtables.components.tables.sc.budget_records import com.seedcompany.cordtables.common.ErrorType import com.seedcompany.cordtables.common.Utility import com.seedcompany.cordtables.components.admin.GetSecureListQuery import com.seedcompany.cordtables.components.admin.GetSecureListQueryRequest import org.springframework.beans.factory.annotation.Autowired import org.springframework.jdbc.core.namedparam.MapSqlParameterSource import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.CrossOrigin import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.ResponseBody import java.sql.SQLException import javax.sql.DataSource data class ScBudgetRecordsListRequest( val token: String? ) data class ScBudgetRecordsListResponse( val error: ErrorType, val budget_records: MutableList<BudgetRecord>? ) @CrossOrigin(origins = ["http://localhost:3333", "https://dev.cordtables.com", "https://cordtables.com", "*"]) @Controller("ScBudgetRecordsList") class List( @Autowired val util: Utility, @Autowired val ds: DataSource, @Autowired val secureList: GetSecureListQuery, ) { var jdbcTemplate: NamedParameterJdbcTemplate = NamedParameterJdbcTemplate(ds) @PostMapping("sc/budget-records/list") @ResponseBody fun listHandler(@RequestBody req: ScBudgetRecordsListRequest): ScBudgetRecordsListResponse { var data: MutableList<BudgetRecord> = mutableListOf() if (req.token == null) return ScBudgetRecordsListResponse(ErrorType.TokenNotFound, mutableListOf()) val paramSource = MapSqlParameterSource() paramSource.addValue("token", req.token) val query = secureList.getSecureListQueryHandler( GetSecureListQueryRequest( tableName = "sc.budget_records", filter = "order by id", columns = arrayOf( "id", "budget", "change_to_plan", "active", "amount", "fiscal_year", "organization", "sensitivity", "created_at", "created_by", "modified_at", "modified_by", "owning_person", "owning_group", ) ) ).query try { val jdbcResult = jdbcTemplate.queryForRowSet(query, paramSource) while (jdbcResult.next()) { var id: String? = jdbcResult.getString("id") if (jdbcResult.wasNull()) id = null var budget: String? = jdbcResult.getString("budget") if (jdbcResult.wasNull()) budget = null var change_to_plan: String? = jdbcResult.getString("change_to_plan") if (jdbcResult.wasNull()) change_to_plan = null var active: Boolean? = jdbcResult.getBoolean("active") if (jdbcResult.wasNull()) active = null var amount: Double? = jdbcResult.getDouble("amount") if (jdbcResult.wasNull()) amount = null var fiscal_year: Int? = jdbcResult.getInt("fiscal_year") if (jdbcResult.wasNull()) fiscal_year = null var organization: String? = jdbcResult.getString("organization") if (jdbcResult.wasNull()) organization = null var sensitivity: String? = jdbcResult.getString("sensitivity") if (jdbcResult.wasNull()) sensitivity = null var created_at: String? = jdbcResult.getString("created_at") if (jdbcResult.wasNull()) created_at = null var created_by: String? = jdbcResult.getString("created_by") if (jdbcResult.wasNull()) created_by = null var modified_at: String? = jdbcResult.getString("modified_at") if (jdbcResult.wasNull()) modified_at = null var modified_by: String? = jdbcResult.getString("modified_by") if (jdbcResult.wasNull()) modified_by = null var owning_person: String? = jdbcResult.getString("owning_person") if (jdbcResult.wasNull()) owning_person = null var owning_group: String? = jdbcResult.getString("owning_group") if (jdbcResult.wasNull()) owning_group = null data.add( BudgetRecord( id = id, budget = budget, change_to_plan = change_to_plan, active = active, amount = amount, fiscal_year = fiscal_year, organization = organization, sensitivity = sensitivity, created_at = created_at, created_by = created_by, modified_at = modified_at, modified_by = modified_by, owning_person = owning_person, owning_group = owning_group ) ) } } catch (e: SQLException) { println("error while listing ${e.message}") return ScBudgetRecordsListResponse(ErrorType.SQLReadError, mutableListOf()) } return ScBudgetRecordsListResponse(ErrorType.NoError, data) } }
93
Kotlin
1
3
7e5588a8b3274917f9a5df2ffa12d27db23fb909
5,710
cordtables
MIT License
src/main/kotlin/com/alcosi/nft/apigateway/service/gateway/filter/ControllerGatewayFilter.kt
alcosi
713,491,219
false
{"Kotlin": 582154, "HTML": 4727, "PLpgSQL": 1275, "JavaScript": 1127, "CSS": 824}
/* * Copyright (c) 2023 Alcosi Group Ltd. and affiliates. * * 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.alcosi.nft.apigateway.service.gateway.filter import org.apache.logging.log4j.kotlin.Logging import org.springframework.cloud.gateway.filter.GatewayFilter import org.springframework.core.Ordered import org.springframework.http.server.reactive.ServerHttpRequest /** * Represents the order value for a Controller gateway filter in a Spring Cloud Gateway. * * The CONTROLLER_ORDER constant defines the highest possible order value, which ensures that the Controller gateway filters * are executed last in the filter chain. * * It is typically used in the `getOrder()` method of a ControllerGatewayFilter implementation, to specify the execution order * of the filter. */ const val CONTROLLER_ORDER = Int.MAX_VALUE /** * Represents a Gateway filter for controlling requests to a Controller. */ interface ControllerGatewayFilter : GatewayFilter, Ordered, Logging { /** * Determines if the given `request` matches the criteria for the gateway filter. * * @param request the server HTTP request to be evaluated * @return `true` if the `request` matches the criteria, `false` otherwise */ fun matches(request: ServerHttpRequest): Boolean /** * Gets the order value of this ControllerGatewayFilter. * * This method returns the order value for controlling the execution order of ControllerGatewayFilters. * The order value is used by the GatewayFilterChain to determine the sequence in which filters are applied * to incoming requests. * * @return the order value of this ControllerGatewayFilter */ override fun getOrder(): Int { return CONTROLLER_ORDER } }
0
Kotlin
0
0
3786635735987c8336d02a36f6149c35dd6d1ad2
2,288
alcosi_blockchain_api_gateway
Apache License 2.0
app/src/test/java/com/github/vase4kin/teamcityapp/properties/data/PropertiesDataModelImplTest.kt
TrendingTechnology
203,797,514
true
{"Kotlin": 1130534, "Java": 723425, "HTML": 824}
/* * Copyright 2019 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.vase4kin.teamcityapp.properties.data import com.github.vase4kin.teamcityapp.properties.api.Properties import org.hamcrest.core.Is.`is` import org.hamcrest.core.IsEqual.equalTo import org.junit.Assert.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito.`when` import org.mockito.runners.MockitoJUnitRunner @RunWith(MockitoJUnitRunner::class) class PropertiesDataModelImplTest { @Mock private lateinit var property: Properties.Property private lateinit var dataModel: PropertiesDataModel @Before fun setUp() { val properties = listOf(property) dataModel = PropertiesDataModelImpl(properties) } @Test fun testGetName() { `when`(property.name).thenReturn("name") assertThat(dataModel.getName(0), `is`(equalTo("name"))) } @Test fun testGetValueIfEmpty() { `when`(property.value).thenReturn("") assertThat(dataModel.getValue(0), `is`(equalTo(PropertiesDataModelImpl.EMPTY))) } @Test fun testGetValueIfNotEmpty() { `when`(property.value).thenReturn("value") assertThat(dataModel.getValue(0), `is`(equalTo("value"))) } @Test fun testIsEmpty() { `when`(property.value).thenReturn(PropertiesDataModelImpl.EMPTY) assertThat(dataModel.isEmpty(0), `is`(equalTo(true))) } @Test fun testGetItemCount() { assertThat(dataModel.itemCount, `is`(1)) } }
0
Kotlin
0
0
c26a0a62069ba84804db8d5ed7c58ffba59dce1c
2,112
TeamCityApp
Apache License 2.0
data/src/main/java/org/lotka/xenonx/data/remote/Dto/models/GenreDto.kt
armanqanih
856,154,586
false
{"Kotlin": 105224}
package org.lotka.xenonx.domain.models import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class GenreDto( @SerializedName("id") val id: Int?, @SerializedName("name") val name: String ): Parcelable
0
Kotlin
0
0
e68f154d44e017fa090ca5571d0ada5cce0e7d4f
300
MyWordMovie
Apache License 2.0
app/src/main/java/com/example/bookingapp/app/entities/PeriodForFragment.kt
sv-bubenschikov
511,498,525
false
null
package com.example.bookingapp.app.entities import org.joda.time.DateTime import org.joda.time.format.DateTimeFormat data class PeriodForFragment( val timeStart: DateTime, val timeEnd: DateTime, ) { override fun toString() = DateTimeFormat.forPattern("HH:mm").print(timeStart) + " - " + DateTimeFormat.forPattern("HH:mm").print(timeEnd) }
3
Kotlin
1
0
643699535e4f9aad8cb71c5ce478cdaf4fb4edd1
366
booking
MIT License
src/jsMain/kotlin/components/RgTable.kt
manimaul
711,314,892
false
{"Kotlin": 236503, "Shell": 961, "JavaScript": 547, "HTML": 437, "Dockerfile": 273}
package components import androidx.compose.runtime.Composable import org.jetbrains.compose.web.attributes.Scope import org.jetbrains.compose.web.attributes.colspan import org.jetbrains.compose.web.attributes.scope import org.jetbrains.compose.web.dom.* import org.w3c.dom.HTMLTableCellElement import org.w3c.dom.HTMLTableElement import org.w3c.dom.HTMLTableRowElement import org.w3c.dom.HTMLTableSectionElement enum class TableColor { primary, secondary, success, danger, warning, info, light, dark; } @Composable fun RgTable( caption: String? = null, color: TableColor = TableColor.secondary, stripeColumn: Boolean = false, content: ContentBuilder<HTMLTableElement>? = null ) { Div(attrs = { classes("table-responsive") }) { Table(attrs = { classes( "table", "table-hover", "table-${color.name}", "table-sm", if (stripeColumn) "table-striped-columns" else "table-striped", "caption-top", "table-bordered" ) }) { caption?.let { Caption { Text(it) } } content?.invoke(this) } } } @Composable fun RgTfoot( content: ContentBuilder<HTMLTableSectionElement>? = null ) = Tfoot( attrs = { }, content = content ) @Composable fun RgThead( content: ContentBuilder<HTMLTableSectionElement>? = null ) = Thead( attrs = { }, content = content ) @Composable fun RgTbody( content: ContentBuilder<HTMLTableSectionElement>? = null ) = Tbody( attrs = { }, content = content ) @Composable fun RgTrColor( color: TableColor? = null, content: ContentBuilder<HTMLTableRowElement>? = null ) = RgTr(color?.let { listOf("table-${it.name}") }, content) @Composable fun RgTr( classes: Collection<String>? = null, content: ContentBuilder<HTMLTableRowElement>? = null ) = Tr( attrs = { classes?.let { classes(it) } }, content = content ) @Composable fun RgTh( scope: Scope = Scope.Col, content: ContentBuilder<HTMLTableCellElement>? = null ) = Th( attrs = { scope(scope) }, content = content ) @Composable fun RgTdColor( colSpan: Int? = null, color: TableColor? = null, content: ContentBuilder<HTMLTableCellElement>? = null ) = RgTd(colSpan, color?.let { listOf("table-${it.name}") }, content) @Composable fun RgTd( colSpan: Int? = null, classes: Collection<String>? = null, content: ContentBuilder<HTMLTableCellElement>? = null ) = Td( attrs = { classes?.let { classes(it) } scope(Scope.Row) colSpan?.let { colspan(it) } }, content = content )
0
Kotlin
0
0
052e8e0dfa2f74567415a2c69607ff043a085d72
2,692
regatta
Apache License 2.0
tutorials/kotlin-se/se-syntax/src/main/kotlin/se/syntax/array/_Array.kt
Alice52
589,441,907
false
{"Kotlin": 48216, "Java": 1287, "Shell": 362}
package se.syntax.array class _Array { // 不能存 null 元素 var arr0: IntArray = intArrayOf(1, 2, 3, 4, 5) // [1, 2, 3, 4, 5] // Int? ==> Integer var arr1: Array<Int?> = arrayOf(1, 2, null, 4, 5) // [1, 2, 3, 4, 5] var arr2: Array<Int?> = arrayOfNulls<Int>(5) // [null, null, null, null, null] var arr3: Array<Int> = Array(5) { 0 } // [0, 0, 0, 0, 0] var arr4 = IntArray(5) { i -> i * 2 } // [0, 2, 4, 6, 8] } fun fun3(data: Array<Int>, fn: (Int) -> Int): IntArray { var temp = IntArray(data.size) for (i in data.indices) { temp[i] = fn(data.get(i)) } return temp } fun main() { val array = _Array() println("arr0: ${array.arr0.toList()}") println("arr0: ${array.arr1.toList()}") println("arr0: ${array.arr2.toList()}") println("arr0: ${array.arr3.toList()}") println("arr0: ${array.arr4.toList()}") }
14
Kotlin
0
0
e34f94e0b30c53a600b3e2988ea6d6117fa2d7c0
874
kotlin-tutorial
MIT License
app/src/main/java/com/android/surveysaurus/fragment/ViewPagerFragment.kt
bimser-intern
521,182,311
false
{"Kotlin": 123125, "Java": 2561, "JavaScript": 1892, "HTML": 656}
package com.android.surveysaurus.fragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.android.surveysaurus.activity.MainActivity import com.android.surveysaurus.adapter.SlidePageAdapter import com.android.surveysaurus.databinding.FragmentViewPagerBinding class ViewPagerFragment : Fragment() { private var _binding: FragmentViewPagerBinding? = null private val binding get() = _binding!! private val mainActivity: MainActivity = MainActivity() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment _binding = FragmentViewPagerBinding.inflate(inflater, container, false) val view = binding.root val fragmentList = arrayListOf<Fragment>( HomeFragment(), SurveysFragment() ) val adapter = SlidePageAdapter(fragmentList, requireActivity().supportFragmentManager) val viewPager = binding.viewPager viewPager.adapter = adapter arguments?.let { val index=ViewPagerFragmentArgs.fromBundle(it).index viewPager.setCurrentItem(index) } return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val fragmentList = arrayListOf<Fragment>( HomeFragment(), SurveysFragment() ) val adapter = SlidePageAdapter(fragmentList, requireActivity().supportFragmentManager) val viewPager = binding.viewPager viewPager.adapter = adapter arguments?.let { val index=ViewPagerFragmentArgs.fromBundle(it).index viewPager.setCurrentItem(index) } } override fun onResume() { super.onResume() val fragmentList = arrayListOf<Fragment>( HomeFragment(), SurveysFragment() ) val adapter = SlidePageAdapter(fragmentList, requireActivity().supportFragmentManager) binding.viewPager.adapter = adapter arguments?.let { val index=ViewPagerFragmentArgs.fromBundle(it).index binding.viewPager.setCurrentItem(index) } } override fun onPause() { super.onPause() binding.viewPager.adapter = null //I don't remember why I did this, I gues } override fun onDestroyView() { super.onDestroyView() _binding = null } }
8
Kotlin
2
0
eea81ec33f0c9f94d17a5895c820d54a26b7b133
2,739
surveysaurus-android
MIT License
app/src/main/java/com/sukacolab/app/ui/common/UiState.kt
cahyadiantoni
757,308,387
false
{"Kotlin": 901754}
package com.sukacolab.app.ui.common sealed class UiEvents { data class SnackbarEvent(val message : String) : UiEvents() data class NavigateEvent(val route: String) : UiEvents() }
0
Kotlin
0
0
9fc2f7e0ade163b0089298cafbc2e9fe02883e43
187
sukacolab
MIT License
app/src/main/java/com/example/rushi/common/BaseViewModel.kt
RushiChavan-dev
740,338,383
false
{"Kotlin": 98827}
package com.example.rushi.common import androidx.lifecycle.ViewModel open class BaseViewModel : ViewModel()
0
Kotlin
0
0
648736797c82cd2a4315231e348e92b9bbaa5f51
109
Betting-App-Kotlin
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/BackUp.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Filled.BackUp: ImageVector get() { if (_backUp != null) { return _backUp!! } _backUp = Builder(name = "BackUp", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(8.5f, 16.0f) curveToRelative(3.58f, 0.0f, 6.624f, -0.839f, 8.5f, -2.173f) verticalLineToRelative(1.74f) curveToRelative(0.0f, 1.621f, -3.635f, 3.434f, -8.5f, 3.434f) reflectiveCurveTo(0.0f, 17.188f, 0.0f, 15.566f) verticalLineToRelative(-1.74f) curveToRelative(1.876f, 1.334f, 4.92f, 2.174f, 8.5f, 2.174f) close() moveTo(0.0f, 18.826f) verticalLineToRelative(0.96f) curveToRelative(0.0f, 2.767f, 4.276f, 4.214f, 8.5f, 4.214f) reflectiveCurveToRelative(8.5f, -1.447f, 8.5f, -4.214f) verticalLineToRelative(-0.96f) curveToRelative(-1.876f, 1.334f, -4.92f, 2.174f, -8.5f, 2.174f) reflectiveCurveToRelative(-6.624f, -0.839f, -8.5f, -2.174f) close() moveTo(22.0f, 0.0f) verticalLineToRelative(1.534f) curveToRelative(-1.078f, -0.97f, -2.482f, -1.534f, -4.0f, -1.534f) curveToRelative(-2.967f, 0.0f, -5.431f, 2.167f, -5.91f, 5.0f) horizontalLineToRelative(2.052f) curveToRelative(0.447f, -1.72f, 1.999f, -3.0f, 3.858f, -3.0f) curveToRelative(1.0f, 0.0f, 1.928f, 0.367f, 2.644f, 1.0f) horizontalLineToRelative(-1.644f) verticalLineToRelative(2.0f) horizontalLineToRelative(5.0f) lineTo(24.0f, 0.0f) horizontalLineToRelative(-2.0f) close() moveTo(18.0f, 10.0f) curveToRelative(-0.994f, 0.0f, -1.929f, -0.368f, -2.646f, -1.0f) horizontalLineToRelative(1.646f) verticalLineToRelative(-2.0f) horizontalLineToRelative(-5.0f) verticalLineToRelative(5.0f) horizontalLineToRelative(2.0f) verticalLineToRelative(-1.531f) curveToRelative(1.08f, 0.966f, 2.494f, 1.531f, 4.0f, 1.531f) curveToRelative(2.967f, 0.0f, 5.431f, -2.167f, 5.91f, -5.0f) horizontalLineToRelative(-2.052f) curveToRelative(-0.447f, 1.72f, -1.999f, 3.0f, -3.858f, 3.0f) close() moveTo(8.5f, 9.0f) curveToRelative(0.513f, 0.0f, 1.012f, -0.028f, 1.5f, -0.074f) verticalLineToRelative(-2.926f) curveToRelative(0.0f, -2.151f, 0.854f, -4.1f, 2.235f, -5.538f) curveToRelative(-1.128f, -0.293f, -2.393f, -0.462f, -3.735f, -0.462f) curveTo(3.806f, 0.0f, 0.0f, 2.015f, 0.0f, 4.5f) reflectiveCurveToRelative(3.806f, 4.5f, 8.5f, 4.5f) close() moveTo(8.5f, 14.0f) curveToRelative(0.516f, 0.0f, 1.015f, -0.024f, 1.5f, -0.063f) verticalLineToRelative(-3.003f) curveToRelative(-0.489f, 0.04f, -0.987f, 0.066f, -1.5f, 0.066f) curveToRelative(-3.58f, 0.0f, -6.624f, -1.004f, -8.5f, -2.6f) verticalLineToRelative(2.167f) curveToRelative(0.0f, 1.621f, 3.635f, 3.433f, 8.5f, 3.433f) close() } } .build() return _backUp!! } private var _backUp: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
4,461
icons
MIT License
composeApp/src/desktopMain/kotlin/Gobblet.desktop.kt
joaomanaia
700,458,525
false
{"Kotlin": 63461, "HTML": 373, "Shell": 228}
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Surface import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.window.ApplicationScope import androidx.compose.ui.window.Window import core.presentation.theme.GobbletTheme import di.gameModule import org.koin.compose.KoinApplication import org.koin.compose.koinInject import presentation.game.GameScreen @Composable fun ApplicationScope.GobbletDesktop() { Window(onCloseRequest = ::exitApplication, title = "Gobblet") { KoinApplication( application = { modules(gameModule) } ) { GobbletTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { GameScreen( viewModel = koinInject() ) } } } } }
0
Kotlin
0
1
3ae25a5a4f60e36bccde2357955d7412f437762d
1,072
compose-gobblet
Apache License 2.0
app/src/main/java/io/arjuningole/gpt/output/output.kt
Arjun-Ingole
556,588,324
false
{"Kotlin": 18889}
package io.arjuningole.gpt.output import androidx.compose.foundation.border import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.ArrowBack import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.ClipboardManager import androidx.compose.ui.platform.LocalClipboardManager import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.TextStyle import androidx.compose.ui.unit.dp import androidx.navigation.NavHostController import com.google.accompanist.systemuicontroller.rememberSystemUiController import io.arjuningole.gpt.R import io.arjuningole.gpt.Screen import io.arjuningole.gpt.services.story import io.arjuningole.gpt.ui.theme.Colfax @Composable fun PromptOutput(value : String){ Column() { OutlinedTextField( value = value, onValueChange = {}, maxLines = 50, readOnly = true, textStyle = TextStyle( fontFamily = Colfax ), shape = RoundedCornerShape(5), colors = TextFieldDefaults.outlinedTextFieldColors( focusedBorderColor = Color(0xFF197E63), unfocusedBorderColor = Color(0xFF197E63), textColor = Color(0xFF9197A3) ), modifier = Modifier .height(350.dp) .fillMaxWidth() .border( width = 3.dp, color = Color(0xFF197E63), shape = RoundedCornerShape(5), ) ) } } @Composable fun OutputScreen( navController: NavHostController ){ val systemUiController = rememberSystemUiController() systemUiController.setSystemBarsColor( Color(0xFF197E63)) val clipboardManager: ClipboardManager = LocalClipboardManager.current Column( modifier = Modifier .padding(horizontal = 10.dp) .fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { PromptOutput(value = story) Row(Modifier.fillMaxWidth()) { Button( onClick = { navController.navigate(Screen.Home.route) }, Modifier .fillMaxWidth() .weight(1f) .padding(end = 8.dp, top = 16.dp) .height(75.dp), colors = ButtonDefaults.buttonColors( backgroundColor = Color(0xFF197E63), contentColor = Color.White ) ){ Icon(Icons.Outlined.ArrowBack, "Back") } Button( onClick = { clipboardManager.setText(AnnotatedString(story)) }, Modifier .fillMaxWidth() .weight(1f) .padding(end = 8.dp, top = 16.dp) .height(75.dp), colors = ButtonDefaults.buttonColors( backgroundColor = Color(0xFF197E63), contentColor = Color.White ) ){ Icon(painter = painterResource(id = R.drawable.ic_outline_content_copy_24), "Copy") } } } }
0
Kotlin
0
15
7ace9819d3548ff05d0b8862694c9e4940dccdb2
3,676
GPT-3.kt
The Unlicense
src/marais/graphql/dsl/SchemaBuilder.kt
Gui-Yom
342,984,553
false
null
package marais.graphql.dsl import graphql.Scalars import graphql.schema.* import org.apache.logging.log4j.LogManager import kotlin.reflect.KClass import kotlin.reflect.KType import kotlin.reflect.full.isSubclassOf @SchemaDsl fun GraphQLSchema(spec: SchemaSpec.() -> Unit): GraphQLSchema { return SchemaBuilder(spec).build() } /** * The base object for building a schema. * * @param configure the DSL to create the schema. * * @see SchemaSpec */ class SchemaBuilder(configure: SchemaSpec.() -> Unit) { private val log = LogManager.getLogger("GraphQLDsl") private val schemaSpec = SchemaSpec(log).apply(configure) // A kotlin class to its mapped graphql type private val names = mutableMapOf<KClass<*>, String>() private val inputNames = mutableMapOf<KClass<*>, String>() // Maps kotlin types to graphql types private val scalars = mutableMapOf<KClass<*>, GraphQLScalarType>() private val enums = mutableMapOf<KClass<*>, GraphQLEnumType>() private val inputs = mutableMapOf<KClass<*>, GraphQLInputObjectType>() private val interfaces = mutableMapOf<KClass<*>, GraphQLInterfaceType>() private val types = mutableMapOf<KClass<*>, GraphQLObjectType>() private val codeRegistry = GraphQLCodeRegistry.newCodeRegistry() /** * Build the schema following the spec */ fun build(): GraphQLSchema { // At this step we should know everything in order to build the schema. scalars += schemaSpec.scalars.map { // Probably unnecessary to put scalars since they don't reference anything else and they're mapped first names[it.kclass] = it.name it.kclass to it.createScalar() } log.debug("Registered scalars : $scalars") enums += schemaSpec.enums.map { names[it.kclass] = it.name it.kclass to it.createEnum() } log.debug("Registered enums : $enums") // Early name registration since input objects can refer to each other schemaSpec.inputs.forEach { inputNames[it.kclass] = it.name } inputs += schemaSpec.inputs.map { it.kclass to it.createInputObject() } // Early name registration schemaSpec.interfaces.forEach { names[it.kclass] = it.name } // Early name registration schemaSpec.types.forEach { names[it.kclass] = it.name } // Interfaces interfaces += schemaSpec.interfaces.map { it.kclass to it.createInterface() } log.debug("Registered interfaces : $interfaces") // Any other types types += schemaSpec.types.map { // Add default fields from parent interface if not present for (inter in it.interfaces) { for (field in schemaSpec.interfaces.find { it.kclass == inter }!!.fields) { // We find every field not implemented by the type. if (it.fields.find { it.name == field.name } == null) { it.fields.add(field) } } } it.kclass to it.createOutputObject() } log.debug("Registered types : $types") val query = schemaSpec.query.createOperation() val mutation = schemaSpec.mutation?.createOperation() val subscription = schemaSpec.subscription?.createOperation() return GraphQLSchema.newSchema() .additionalTypes(scalars.values.toSet()) .additionalTypes(enums.values.toSet()) .additionalTypes(inputs.values.toSet()) .additionalTypes(interfaces.values.toSet()) .additionalTypes(types.values.toSet()) .query(query) .mutation(mutation) .subscription(subscription) .codeRegistry(codeRegistry.build()) .build() } private fun resolveOutputType(type: KType): GraphQLOutputType { val kclass = type.classifier as KClass<*> val resolved = resolveInOutType(kclass) as? GraphQLOutputType // Search through what has already been resolved ?: interfaces[kclass] ?: types[kclass] // Fallback to late binding if possible ?: names[kclass]?.let { GraphQLTypeReference(it) } ?: if (kclass.coerceWithList()) { GraphQLList(resolveOutputType(type.unwrap())) } else null ?: if (kclass.isSubclassOf(Map::class)) { GraphQLList(GraphQLNonNull(makeMapEntry(type))) } else null // We won't ever see it ?: throw Exception("Can't resolve $type to a valid graphql type") return if (type.isMarkedNullable) resolved else GraphQLNonNull(resolved) } private fun resolveInputType(type: KType): GraphQLInputType { val kclass = type.classifier as KClass<*> val resolved = resolveInOutType(kclass) as? GraphQLInputType // Search through what has already been resolved ?: inputs[kclass] // Fallback to late binding if possible ?: inputNames[kclass]?.let { GraphQLTypeReference(it) } ?: if (kclass.coerceWithList()) { GraphQLList(resolveInputType(type.unwrap())) } else null // We won't ever see it ?: throw Exception("Can't resolve $type to a valid graphql type") return if (type.isMarkedNullable) resolved else GraphQLNonNull(resolved) } private fun resolveInOutType(kclass: KClass<*>): GraphQLType? { return scalars[kclass] ?: when (kclass) { Byte::class -> Scalars.GraphQLInt // default Short::class -> Scalars.GraphQLInt // default Int::class -> Scalars.GraphQLInt Long::class -> Scalars.GraphQLInt // default Float::class -> Scalars.GraphQLFloat Double::class -> Scalars.GraphQLFloat // default String::class -> Scalars.GraphQLString Char::class -> Scalars.GraphQLString // default Boolean::class -> Scalars.GraphQLBoolean in schemaSpec.idCoercers -> Scalars.GraphQLID else -> null } ?: enums[kclass] } private fun ScalarSpec.createScalar(): GraphQLScalarType { return GraphQLScalarType.newScalar() .name(name) .description(description) .coercing(coercing) .apply(builder) .build() } private fun EnumSpec.createEnum(): GraphQLEnumType { return GraphQLEnumType.newEnum() .name(name) .description(description) .apply { for (enumConstant: Enum<*> in kclass.java.enumConstants as Array<Enum<*>>) { value(enumConstant.name) } } .apply(builder) .build() } private fun InputSpec.createInputObject(): GraphQLInputObjectType { return GraphQLInputObjectType.newInputObject() .name(name) .description(description) .fields(fields.map { (name, type) -> GraphQLInputObjectField.newInputObjectField() .name(name) .type(resolveInputType(type)) .build() }) .apply(builder) .build() } private fun FieldSpec.createField(parentType: String): GraphQLFieldDefinition { // Register the field data fetcher codeRegistry.dataFetcher(FieldCoordinates.coordinates(parentType, name), dataFetcher) return GraphQLFieldDefinition.newFieldDefinition() .name(name) .description(description) .arguments(arguments.filter { it.isShownInSchema }.map { it.createArgument() }) .type(resolveOutputType(outputType)) .build() } private fun Argument.createArgument(): GraphQLArgument { return GraphQLArgument.newArgument() .name(name) .description(description) .type(resolveInputType(type)) .build() } private fun InterfaceSpec<*>.createInterface(): GraphQLInterfaceType { val fields = fields.map { it.createField(name) } codeRegistry.typeResolver(name) { env -> env.schema.getObjectType(names[names.keys.find { it == env.getObject<Any?>()::class }]) } return GraphQLInterfaceType.newInterface() .name(name) .description(description) .fields(fields) .build() } private fun TypeSpec<*>.createOutputObject(): GraphQLObjectType { val fields = fields.map { it.createField(name) } return GraphQLObjectType.newObject() .name(name) .description(description) .fields(fields) .withInterfaces(*interfaces.map { [email protected][it] }.toTypedArray()) .build() } private fun OperationSpec<*>.createOperation(): GraphQLObjectType { val fields = fields.map { it.createField(name) } return GraphQLObjectType.newObject() .name(name) .fields(fields) .build() } private fun makeMapEntry(type: KType): GraphQLObjectType { val name = type.deepName() codeRegistry.dataFetcher( FieldCoordinates.coordinates(name, "key"), DataFetcher { (it.getSource() as Map.Entry<*, *>).key }) codeRegistry.dataFetcher( FieldCoordinates.coordinates(name, "value"), DataFetcher { (it.getSource() as Map.Entry<*, *>).value }) val obj = GraphQLObjectType.newObject() .name(name) .field { it.name("key") .type(resolveOutputType(type.arguments[0].type!!)) } .field { it.name("value") .type(resolveOutputType(type.arguments[1].type!!)) } .build() types[Map::class] = obj return obj } }
1
Kotlin
1
3
f694d569d6895ca68ef84f3678e2bd8f9802acde
10,286
graphql-dsl
Apache License 2.0
atomicfu/src/jvmMain/kotlin/kotlinx/atomicfu/Interceptor.kt
mistletoe5215
321,309,110
true
{"Kotlin": 308813, "Shell": 762}
/* * Copyright 2017-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.atomicfu import java.util.concurrent.locks.ReentrantLock internal var interceptor: AtomicOperationInterceptor = DefaultInterceptor private set private val interceptorLock = ReentrantLock() internal fun lockAndSetInterceptor(impl: AtomicOperationInterceptor) { if (!interceptorLock.tryLock() || interceptor !== DefaultInterceptor) { error("Interceptor is locked by another test: $interceptor") } interceptor = impl } internal fun unlockAndResetInterceptor(impl: AtomicOperationInterceptor) { check(interceptor === impl) { "Unexpected interceptor found: $interceptor" } interceptor = DefaultInterceptor interceptorLock.unlock() } /** * Interceptor for modifications of atomic variables. */ internal open class AtomicOperationInterceptor { open fun <T> beforeUpdate(ref: AtomicRef<T>) {} open fun beforeUpdate(ref: AtomicInt) {} open fun beforeUpdate(ref: AtomicLong) {} open fun beforeUpdate(ref: AtomicBoolean){} open fun <T> afterSet(ref: AtomicRef<T>, newValue: T) {} open fun afterSet(ref: AtomicInt, newValue: Int) {} open fun afterSet(ref: AtomicLong, newValue: Long) {} open fun afterSet(ref: AtomicBoolean, newValue: Boolean) {} open fun <T> afterRMW(ref: AtomicRef<T>, oldValue: T, newValue: T) {} open fun afterRMW(ref: AtomicInt, oldValue: Int, newValue: Int) {} open fun afterRMW(ref: AtomicLong, oldValue: Long, newValue: Long) {} open fun afterRMW(ref: AtomicBoolean, oldValue: Boolean, newValue: Boolean) {} } private object DefaultInterceptor : AtomicOperationInterceptor() { override fun toString(): String = "DefaultInterceptor" }
0
null
0
0
77eda860aae0118453a5d3f59abad16ae338a496
1,770
kotlinx.atomicfu
Apache License 2.0
src/main/kotlin/dev/arbjerg/lavalink/client/loadbalancing/penaltyproviders/VoiceRegionPenaltyProvider.kt
duncte123
642,292,256
false
null
package dev.arbjerg.lavalink.client.loadbalancing.penaltyproviders import dev.arbjerg.lavalink.client.LavalinkNode import dev.arbjerg.lavalink.client.loadbalancing.VoiceRegion class VoiceRegionPenaltyProvider : IPenaltyProvider { override fun getPenalty(node: LavalinkNode, region: VoiceRegion): Int { TODO("Not yet implemented") } }
0
Kotlin
1
1
a87aca321f948993877f544e11c08d61f442ccf9
352
lavalink-client
MIT License
jetbrains-core/src/software/aws/toolkits/jetbrains/services/s3/objectActions/NewFolderAction.kt
vamsikavuru
231,510,408
true
{"Kotlin": 2004686, "Java": 191888, "C#": 117036}
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.services.s3.objectActions import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.ui.Messages import com.intellij.ui.AnActionButton import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import software.aws.toolkits.jetbrains.services.s3.editor.S3TreeTable import software.aws.toolkits.jetbrains.services.s3.editor.getDirectoryKey import software.aws.toolkits.jetbrains.utils.notifyError import software.aws.toolkits.resources.message class NewFolderAction(private val treeTable: S3TreeTable) : AnActionButton(message("s3.new.folder"), null, null) { override fun isDumbAware(): Boolean = true override fun updateButton(e: AnActionEvent) {} override fun isEnabled(): Boolean = treeTable.selectedRows.size <= 1 override fun actionPerformed(e: AnActionEvent) { val node = treeTable.selectedRows.firstOrNull()?.let { treeTable.getNodeForRow(it) } ?: treeTable.getRootNode() Messages.showInputDialog(e.project, message("s3.new.folder.name"), message("s3.new.folder"), null)?.let { key -> GlobalScope.launch { try { treeTable.bucket.newFolder(node.getDirectoryKey() + key) treeTable.invalidateLevel(node) treeTable.refresh() } catch (e: Exception) { e.notifyError() } } } } }
0
null
0
0
ae863f94be81556c914e7b0669757ad6e8b6eebd
1,570
aws-toolkit-jetbrains
Apache License 2.0
app/src/main/java/com/peter/azure/ui/help/HelpCatalogItem.kt
peterdevacc
649,972,321
false
{"Kotlin": 302811}
/* * Copyright (c) 2023 洪振健 All rights reserved. */ package com.peter.azure.ui.help import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.text import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.unit.dp @Composable fun HelpCatalogItem( catalogName: String, catalogIconId: Int, color: Color, modifier: Modifier ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = modifier.clearAndSetSemantics { text = AnnotatedString(catalogName) } ) { Icon( painter = painterResource(catalogIconId), contentDescription = "", modifier = Modifier.size(26.dp), tint = color, ) Spacer(modifier = Modifier.padding(horizontal = 6.dp)) Text( text = catalogName, style = MaterialTheme.typography.titleLarge, color = color, modifier = Modifier.weight(1f) ) } }
0
Kotlin
0
0
eee1d8b81b2a5c1c67aad29bf6889211bb53e517
1,544
Azure
Apache License 2.0
app/src/main/java/com/hypertrack/android/ui/screens/visits_management/tabs/history/HistoryViewModel.kt
hypertrack
241,723,736
false
null
package com.hypertrack.android.ui.screens.visits_management.tabs.history import android.content.Context import android.util.Log import androidx.lifecycle.* import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.model.* import com.google.android.gms.maps.model.Marker import com.google.android.gms.maps.model.Polyline import com.hypertrack.android.interactors.HistoryInteractor import com.hypertrack.android.models.* import com.hypertrack.android.ui.base.BaseViewModel import com.hypertrack.android.ui.base.BaseViewModelDependencies import com.hypertrack.android.ui.base.ErrorHandler import com.hypertrack.android.ui.common.HypertrackMapWrapper import com.hypertrack.android.ui.common.MapParams import com.hypertrack.android.utils.* import com.hypertrack.android.utils.formatters.DatetimeFormatter import com.hypertrack.android.utils.formatters.DistanceFormatter import com.hypertrack.logistics.android.github.R class HistoryViewModel( baseDependencies: BaseViewModelDependencies, private val historyInteractor: HistoryInteractor, private val datetimeFormatter: DatetimeFormatter, private val distanceFormatter: DistanceFormatter, private val deviceLocationProvider: DeviceLocationProvider, ) : BaseViewModel(baseDependencies) { //todo remove legacy private val timeDistanceFormatter = TimeDistanceFormatter( datetimeFormatter, distanceFormatter ) val style = BaseHistoryStyle(MyApplication.context) override val errorHandler = ErrorHandler( osUtilsProvider, crashReportsProvider, historyInteractor.errorFlow.asLiveData() ) //value doesn't represent correct state val bottomSheetOpened = MutableLiveData<Boolean>(false) val tiles = MediatorLiveData<List<HistoryTile>>() private val history = historyInteractor.todayHistory private var userLocation: LatLng? = null private var map: HypertrackMapWrapper? = null private var selectedSegment: Polyline? = null private var viewBounds: LatLngBounds? = null private val activeMarkers = mutableListOf<Marker>() private var firstMovePerformed = false init { loadingState.postValue(true) tiles.addSource(history) { it?.let { if (it.locationTimePoints.isNotEmpty()) { Log.d(TAG, "got new history $it") val asTiles = historyToTiles(it, timeDistanceFormatter) Log.d(TAG, "converted to tiles $asTiles") tiles.postValue(asTiles) } else { Log.d(TAG, "Empty history") tiles.postValue(emptyList()) } } } history.observeManaged { it?.let { loadingState.postValue(false) val map = this.map if (map != null) { displayHistory(map, it) moveMap(map, it, userLocation) } } } deviceLocationProvider.getCurrentLocation { userLocation = it?.toLatLng() history.value?.let { hist -> map?.let { map -> moveMap(map, hist, it?.toLatLng()) } } } } fun onMapReady(context: Context, googleMap: GoogleMap) { firstMovePerformed = false val style = BaseHistoryStyle(MyApplication.context) this.map = HypertrackMapWrapper( googleMap, osUtilsProvider, crashReportsProvider, MapParams( enableScroll = true, enableZoomKeys = true, enableMyLocationButton = true, enableMyLocationIndicator = true ) ) val map = this.map!! map.setPadding(bottom = style.summaryPeekHeight) map.setOnMapClickListener { bottomSheetOpened.postValue(false) } history.value?.let { hist -> displayHistory(map, hist) moveMap(map, hist, userLocation) } } fun onTileSelected(tile: HistoryTile) { try { if (tile.tileType == HistoryTileType.SUMMARY) return selectedSegment?.remove() activeMarkers.forEach { it.remove() } map?.googleMap?.let { googleMap -> selectedSegment = googleMap.addPolyline( tile.locations .map { LatLng(it.latitude, it.longitude) } .fold(PolylineOptions()) { options, loc -> options.add(loc) } .color(style.colorForStatus(tile.status)) .clickable(true) ) tile.locations.firstOrNull()?.let { activeMarkers.add(addMarker(it, googleMap, tile.address, tile.status)) } tile.locations.lastOrNull()?.let { activeMarkers.add(addMarker(it, googleMap, tile.address, tile.status)) } //newLatLngBounds can cause crash if called before layout without map size googleMap.animateCamera( CameraUpdateFactory.newLatLngBounds( tile.locations.boundRect(), style.mapPadding ) ) googleMap.setOnMapClickListener { selectedSegment?.remove() activeMarkers.forEach { it.remove() } activeMarkers.clear() selectedSegment = null viewBounds?.let { bounds -> //newLatLngBounds can cause crash if called before layout without map size googleMap.animateCamera( CameraUpdateFactory.newLatLngBounds( bounds, style.mapPadding ) ) } } } bottomSheetOpened.postValue(false) } catch (e: Exception) { errorHandler.postException(e) } } fun onResume() { historyInteractor.refreshTodayHistory() } private fun displayHistory(map: HypertrackMapWrapper, history: History) { errorHandler.handle { map.showHistory(history, style) } } private fun addMarker( location: Location, map: GoogleMap, address: CharSequence?, status: Status ): Marker { val markerOptions = MarkerOptions().position(LatLng(location.latitude, location.longitude)) .icon(BitmapDescriptorFactory.fromBitmap(style.markerForStatus(status))) address?.let { markerOptions.title(it.toString()) } return map.addMarker(markerOptions) } private fun moveMap(map: HypertrackMapWrapper, history: History, userLocation: LatLng?) { if (!firstMovePerformed) { if (history.locationTimePoints.isEmpty()) { userLocation?.let { map.moveCamera(it) } } else { val viewBounds = history.locationTimePoints.map { it.first }.boundRect().let { if (userLocation != null) { it.including(userLocation) } else it } //newLatLngBounds can cause crash if called before layout without map size try { map.googleMap.animateCamera( CameraUpdateFactory.newLatLngBounds( viewBounds, style.mapPadding ) ) } catch (e: Exception) { userLocation?.let { map.moveCamera(it) } } } firstMovePerformed = true } } private fun historyToTiles( history: History, timeDistanceFormatter: TimeDistanceFormatter ): List<HistoryTile> { with(history) { val result = mutableListOf<HistoryTile>() var startMarker = true var ongoingStatus = Status.UNKNOWN for (marker in markers.sortedBy { it.timestamp }) { when (marker) { is StatusMarker -> { val tile = HistoryTile( marker.status, marker.asDescription(timeDistanceFormatter), if (marker.status == Status.OUTAGE) { mapInactiveReason(marker.reason) } else { marker.address }, marker.timeFrame(timeDistanceFormatter), historyTileType(startMarker, marker.status), filterMarkerLocations( marker.startLocationTimestamp ?: marker.startTimestamp, marker.endLocationTimestamp ?: marker.endTimestamp ?: marker.startTimestamp, locationTimePoints ) ) ongoingStatus = marker.status result.add(tile) } is GeoTagMarker -> { marker.location?.let { geotagLocation -> val tile = HistoryTile( ongoingStatus, marker.asDescription(), null, timeDistanceFormatter.formatTime(marker.timestamp), historyTileType(startMarker, ongoingStatus), listOf(geotagLocation), false ) result.add(tile) } } is GeofenceMarker -> { val tile = HistoryTile( ongoingStatus, marker.asDescription(), null, marker.asTimeFrame(timeDistanceFormatter), historyTileType(startMarker, ongoingStatus), filterMarkerLocations( marker.arrivalTimestamp ?: marker.timestamp, marker.exitTimestamp ?: marker.timestamp, locationTimePoints ), false ) result.add(tile) } } startMarker = result.isEmpty() } val summaryTile = HistoryTile( Status.UNKNOWN, "${formatDuration(summary.totalDuration)} • ${ timeDistanceFormatter.formatDistance( summary.totalDistance ) }", null, "", HistoryTileType.SUMMARY ) return result.apply { add(0, summaryTile) } } } private fun GeofenceMarker.asDescription(): String { //todo string res return (metadata["name"] ?: metadata["address"] ?: metadata ).let { "$it" } } private fun StatusMarker.asDescription(timeDistanceFormatter: TimeDistanceFormatter): String = when (status) { Status.DRIVE -> formatDriveStats(timeDistanceFormatter) Status.WALK -> formatWalkStats() else -> formatDuration(duration) } private fun StatusMarker.formatDriveStats(timeDistanceFormatter: TimeDistanceFormatter) = "${formatDuration(duration)} • ${timeDistanceFormatter.formatDistance(distance ?: 0)}" private fun StatusMarker.formatWalkStats() = "${formatDuration(duration)} • ${stepsCount ?: 0} steps" private fun formatDuration(duration: Int) = when { duration / 3600 < 1 -> "${duration / 60} min" duration / 3600 == 1 -> "1 hour ${duration % 3600 / 60} min" else -> "${duration / 3600} hours ${duration % 3600 / 60} min" } private fun StatusMarker.timeFrame(timeFormatter: TimeDistanceFormatter): String { if (endTimestamp == null) return timeFormatter.formatTime(startTimestamp) return "${timeFormatter.formatTime(startTimestamp)} : ${ timeFormatter.formatTime( endTimestamp ) }" } private fun GeofenceMarker.asTimeFrame(formatter: TimeDistanceFormatter): String { val from = timestamp val upTo = exitTimestamp ?: timestamp return if (from == upTo) formatter.formatTime(timestamp) else "${formatter.formatTime(from)} : ${formatter.formatTime(upTo)}" } private fun historyTileType( startMarker: Boolean, status: Status ): HistoryTileType { return when { startMarker && status in listOf( Status.OUTAGE, Status.INACTIVE ) -> HistoryTileType.OUTAGE_START startMarker -> HistoryTileType.ACTIVE_START status in listOf(Status.OUTAGE, Status.INACTIVE) -> HistoryTileType.OUTAGE else -> HistoryTileType.ACTIVE } } //todo string res private fun GeoTagMarker.asDescription(): String = when { metadata.containsValue(Constants.CLOCK_IN) -> "Clock In" metadata.containsValue(Constants.CLOCK_OUT) -> "Clock Out" metadata.containsValue(Constants.PICK_UP) -> "Pick Up" metadata.containsValue(Constants.VISIT_MARKED_CANCELED) -> "Visit Marked Cancelled" metadata.containsValue(Constants.VISIT_MARKED_COMPLETE) -> "Visit Marked Complete" else -> "Geotag $metadata" } private fun filterMarkerLocations( from: String, upTo: String, locationTimePoints: List<Pair<Location, String>> ): List<Location> { check(locationTimePoints.isNotEmpty()) { "locations should not be empty for the timeline" } val innerLocations = locationTimePoints .filter { (_, time) -> time in from..upTo } .map { (loc, _) -> loc } if (innerLocations.isNotEmpty()) return innerLocations // Snap to adjacent val sorted = locationTimePoints.sortedBy { it.second } Log.v(TAG, "Got sorted $sorted") val startLocation = sorted.lastOrNull { (_, time) -> time < from } val endLocation = sorted.firstOrNull { (_, time) -> time > upTo } Log.v(TAG, "Got start $startLocation, end $endLocation") return listOfNotNull(startLocation?.first, endLocation?.first) } private fun mapInactiveReason(reason: String?): String? { return when (reason) { "location_permissions_denied" -> { osUtilsProvider.getString(R.string.timeline_inactive_reason_location_permissions_denied) } "location_services_disabled" -> { osUtilsProvider.getString(R.string.timeline_inactive_reason_location_services_disabled) } "motion_activity_permissions_denied" -> { osUtilsProvider.getString(R.string.timeline_inactive_reason_motion_activity_permissions_denied) } "motion_activity_services_disabled" -> { osUtilsProvider.getString(R.string.timeline_inactive_reason_motion_activity_services_disabled) } "motion_activity_services_unavailable" -> { osUtilsProvider.getString(R.string.timeline_inactive_reason_motion_activity_services_unavailable) } "tracking_stopped" -> { osUtilsProvider.getString(R.string.timeline_inactive_reason_tracking_stopped) } "tracking_service_terminated" -> { osUtilsProvider.getString(R.string.timeline_inactive_reason_tracking_service_terminated) } "unexpected" -> { osUtilsProvider.getString(R.string.timeline_inactive_reason_unexpected) } else -> reason } } companion object { const val TAG = "HistoryViewModel" } } class TimeDistanceFormatter( val datetimeFormatter: DatetimeFormatter, val distanceFormatter: DistanceFormatter ) { fun formatTime(timestamp: String): String { return datetimeFormatter.formatTime(datetimeFromString(timestamp)) } fun formatDistance(totalDistance: Int): String { return distanceFormatter.formatDistance(totalDistance) } } private fun Iterable<Location>.boundRect(): LatLngBounds { return fold(LatLngBounds.builder()) { builder, point -> builder.include(point.toLatLng()) }.build() }
1
Kotlin
15
28
d418c449cbbbb19eca4f875a3e4f1099614213e4
17,044
logistics-android
MIT License
fluent/src/desktopMain/kotlin/com/konyaco/fluent/component/ContextMenu.desktop.kt
Konyaco
574,321,009
false
{"Kotlin": 11419712, "Java": 256912}
package com.konyaco.fluent.component import androidx.compose.animation.EnterTransition import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.foundation.text.TextContextMenu import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.input.key.* import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLocalization import androidx.compose.ui.unit.* import com.konyaco.fluent.animation.FluentDuration import com.konyaco.fluent.animation.FluentEasing import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.regular.Copy import com.konyaco.fluent.icons.regular.Cut import com.konyaco.fluent.icons.regular.ClipboardPaste internal object FluentContextMenuRepresentation : ContextMenuRepresentation { @Composable override fun Representation(state: ContextMenuState, items: () -> List<ContextMenuItem>) { var rect by remember { mutableStateOf(Rect.Zero) } var visible by remember { mutableStateOf(false) } val status = state.status LaunchedEffect(status) { if (status is ContextMenuState.Status.Open) { rect = status.rect visible = true } else { visible = false } } val density = LocalDensity.current MenuFlyout( visible = visible, onDismissRequest = { state.status = ContextMenuState.Status.Closed }, onKeyEvent = { keyEvent -> items().firstOrNull { val result = it is FluentContextMenuItem && keyEvent.type == KeyEventType.KeyDown && it.keyData != null && it.keyData.isAltPressed == keyEvent.isAltPressed && it.keyData.isCtrlPressed == keyEvent.isCtrlPressed && it.keyData.isShiftPressed == keyEvent.isShiftPressed && it.keyData.key == keyEvent.key if (result) { it.onClick() state.status = ContextMenuState.Status.Closed } result } != null }, positionProvider = remember(rect, density) { ContextMenuFlyoutPositionProvider(rect, density) }, enterPlacementAnimation = { enterAnimation() } ) { val menuItems = items() val shouldPaddingIcon = menuItems.any { it is FluentContextMenuItem && (it.glyph != null || it.vector != null) } menuItems.forEach { if (it is FluentContextMenuItem) { MenuFlyoutItem( text = { Text(it.label, modifier = Modifier) }, icon = if (shouldPaddingIcon) { { if (it.glyph != null && LocalFontIconFontFamily.current != null) { FontIcon(it.glyph, modifier = Modifier) } else if (it.vector != null) { Icon( it.vector, it.label, modifier = Modifier.size(with(LocalDensity.current) { ((FontIconDefaults.fontSizeStandard.value + 2).sp).toDp() }) ) } } } else { null }, training = { it.keyData?.let { keyData -> val keyString = remember(keyData) { buildString { if (keyData.isAltPressed) { append("Alt+") } if (keyData.isCtrlPressed) { append("Ctrl+") } if (keyData.isShiftPressed) { append("Shift+") } append(keyData.key.toString().removePrefix("Key: ")) } } Text( text = keyString, modifier = Modifier.padding(start = 16.dp, end = 8.dp) ) } }, onClick = { it.onClick() state.status = ContextMenuState.Status.Closed } ) } else { MenuFlyoutItem( onClick = { it.onClick() state.status = ContextMenuState.Status.Closed }, text = { Text(it.label) }, icon = if (shouldPaddingIcon) { {} } else { null }, ) } } } } private fun enterAnimation(): EnterTransition { return fadeIn(defaultAnimationSpec()) } private fun <T> defaultAnimationSpec() = tween<T>(FluentDuration.ShortDuration, easing = FluentEasing.FastInvokeEasing) } @OptIn(ExperimentalFoundationApi::class) internal object FluentTextContextMenu : TextContextMenu { @Composable override fun Area( textManager: TextContextMenu.TextManager, state: ContextMenuState, content: @Composable () -> Unit ) { val localization = LocalLocalization.current val items = { listOfNotNull( textManager.cut?.let { FluentContextMenuItem( label = localization.cut, onClick = it, glyph = '\uE8C6', vector = Icons.Default.Cut, keyData = FluentContextMenuItem.KeyData(Key.X, isCtrlPressed = true) ) }, textManager.copy?.let { FluentContextMenuItem( label = localization.copy, onClick = it, glyph = '\uE8C8', vector = Icons.Default.Copy, keyData = FluentContextMenuItem.KeyData(Key.C, isCtrlPressed = true) ) }, textManager.paste?.let { FluentContextMenuItem( label = localization.paste, onClick = it, glyph = '\uE77F', vector = Icons.Default.ClipboardPaste, keyData = FluentContextMenuItem.KeyData(Key.V, isCtrlPressed = true) ) }, textManager.selectAll?.let { FluentContextMenuItem( label = localization.selectAll, onClick = it, keyData = FluentContextMenuItem.KeyData(Key.A, isCtrlPressed = true), ) }, ) } ContextMenuArea(items, state, content = content) } } class FluentContextMenuItem( label: String, onClick: () -> Unit, val vector: ImageVector? = null, val keyData: KeyData? = null, val glyph: Char? = null ) : ContextMenuItem(label, onClick) { data class KeyData( val key: Key, val isAltPressed: Boolean = false, val isCtrlPressed: Boolean = false, val isShiftPressed: Boolean = false ) } private class ContextMenuFlyoutPositionProvider( val rect: Rect, density: Density, ) : FlyoutPositionProvider( density = density, adaptivePlacement = true, initialPlacement = FlyoutPlacement.BottomAlignedStart ) { override fun calculatePosition( anchorBounds: IntRect, windowSize: IntSize, layoutDirection: LayoutDirection, popupContentSize: IntSize ): IntOffset { val targetAnchor = IntRect( offset = rect.center.round() + anchorBounds.topLeft, size = IntSize.Zero ) return super.calculatePosition(targetAnchor, windowSize, layoutDirection, popupContentSize) } }
8
Kotlin
10
262
293d7ab02d80fb9fdd372826fdc0b42b1d6e0019
9,032
compose-fluent-ui
Apache License 2.0
ksp/src/jvmMain/kotlin/eu/vendeli/ksp/ActivityCollectors.kt
vendelieu
496,567,172
false
{"Kotlin": 1041871, "Python": 12809, "Shell": 1249, "CSS": 356}
package eu.vendeli.ksp import com.google.devtools.ksp.symbol.KSClassDeclaration import com.google.devtools.ksp.symbol.KSFunctionDeclaration import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.MAP import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.PropertySpec import com.squareup.kotlinpoet.STRING import com.squareup.kotlinpoet.TypeVariableName import com.squareup.kotlinpoet.asTypeName import com.squareup.kotlinpoet.buildCodeBlock import eu.vendeli.ksp.dto.CollectorsContext import eu.vendeli.ksp.dto.CommonAnnotationData import eu.vendeli.ksp.utils.addMap import eu.vendeli.ksp.utils.addVarStatement import eu.vendeli.ksp.utils.commonMatcherClass import eu.vendeli.ksp.utils.invocableType import eu.vendeli.ksp.utils.parseAsCommandHandler import eu.vendeli.ksp.utils.parseAsInputHandler import eu.vendeli.ksp.utils.parseAsUpdateHandler import eu.vendeli.ksp.utils.toRateLimits import eu.vendeli.tgbot.annotations.CommandHandler import eu.vendeli.tgbot.annotations.CommandHandler.CallbackQuery import eu.vendeli.tgbot.annotations.InputHandler import eu.vendeli.tgbot.annotations.UpdateHandler import eu.vendeli.tgbot.implementations.DefaultArgParser import eu.vendeli.tgbot.implementations.DefaultGuard import eu.vendeli.tgbot.types.internal.UpdateType import eu.vendeli.tgbot.utils.fullName internal fun collectCommandActivities( symbols: Sequence<KSFunctionDeclaration>, ctx: CollectorsContext, ) = ctx.run { logger.info("Collecting commands.") activitiesFile.addMap( "__TG_COMMANDS$idxPostfix", MAP.parameterizedBy( Pair::class.asTypeName().parameterizedBy(STRING, UpdateType::class.asTypeName()), invocableType, ), symbols, ) { function -> var isCallbackQAnnotation = false val annotationData = function.annotations .first { val shortName = it.shortName.asString() when (shortName) { CallbackQuery::class.simpleName -> { isCallbackQAnnotation = true true } CommandHandler::class.simpleName -> true else -> false } }.arguments .parseAsCommandHandler(isCallbackQAnnotation) annotationData.value.forEach { annotationData.scope.forEach { updT -> logger.info("Command: $it UpdateType: ${updT.name} --> ${function.qualifiedName?.asString()}") addVarStatement(postFix = "\n)),") { add("(\"$it\" to %L)" to updT) add( " to (%L to InvocationMeta(\n" to activitiesFile.buildInvocationLambdaCodeBlock( function, injectableTypes, pkg, ), ) add("qualifier = \"%L\"" to function.qualifiedName!!.getQualifier()) add(",\n function = \"%L\"" to function.simpleName.asString()) if (annotationData.rateLimits.first > 0 || annotationData.rateLimits.second > 0) add(",\n rateLimits = %L" to annotationData.rateLimits.toRateLimits()) if (annotationData.guardClass != DefaultGuard::class.fullName) add(",\n guard = %L::class" to annotationData.guardClass) if (annotationData.argParserClass != DefaultArgParser::class.fullName) add(",\n argParser = %L::class" to annotationData.argParserClass) } } } } } internal fun collectInputActivities( symbols: Sequence<KSFunctionDeclaration>, chainSymbols: Sequence<KSClassDeclaration>, ctx: CollectorsContext, ) = ctx.run { logger.info("Collecting inputs.") val tailBlock = collectInputChains(chainSymbols, ctx) activitiesFile.addMap( "__TG_INPUTS$idxPostfix", MAP.parameterizedBy(STRING, invocableType), symbols, tailBlock, ) { function -> val annotationData = function.annotations .first { it.shortName.asString() == InputHandler::class.simpleName!! }.arguments .parseAsInputHandler() annotationData.first.forEach { logger.info("Input: $it --> ${function.qualifiedName?.asString()}") addVarStatement(postFix = "\n)),") { add( "\"$it\" to (%L to InvocationMeta(\n" to activitiesFile.buildInvocationLambdaCodeBlock( function, injectableTypes, pkg, ), ) add("qualifier = \"%L\"" to function.qualifiedName!!.getQualifier()) add(",\n function = \"%L\"" to function.simpleName.asString()) if (annotationData.second.first > 0 || annotationData.second.second > 0) add(",\n rateLimits = %L" to annotationData.second.toRateLimits()) if (annotationData.third != DefaultGuard::class.fullName) add(",\n guard = %L::class" to annotationData.third) } } } } internal fun collectUpdateTypeActivities( symbols: Sequence<KSFunctionDeclaration>, ctx: CollectorsContext, ) = ctx.run { logger.info("Collecting `UpdateType` handlers.") activitiesFile.addMap( "__TG_UPDATE_TYPES$idxPostfix", MAP.parameterizedBy(UpdateType::class.asTypeName(), TypeVariableName("InvocationLambda")), symbols, ) { function -> val annotationData = function.annotations .first { it.shortName.asString() == UpdateHandler::class.simpleName!! }.arguments .parseAsUpdateHandler() annotationData.forEach { logger.info("UpdateType: ${it.name} --> ${function.qualifiedName?.asString()}") addStatement( "%L to %L,", it, activitiesFile.buildInvocationLambdaCodeBlock(function, injectableTypes), ) } } } internal fun collectCommonActivities( data: List<CommonAnnotationData>, ctx: CollectorsContext, ) = ctx.run { logger.info("Collecting common handlers.") activitiesFile.addProperty( PropertySpec .builder( "__TG_COMMONS$idxPostfix", MAP.parameterizedBy(commonMatcherClass, invocableType), KModifier.PRIVATE, ).apply { initializer( CodeBlock .builder() .apply { add("mapOf(\n") data.forEach { addVarStatement(postFix = "\n)),") { add("%L to " to it.value.toCommonMatcher(it.filter, it.scope)) add( "(%L to InvocationMeta(\n" to activitiesFile.buildInvocationLambdaCodeBlock( it.funDeclaration, injectableTypes, pkg, ), ) add("qualifier = \"%L\"" to it.funQualifier) add(",\n function = \"%L\"" to it.funSimpleName) if (it.rateLimits.rate > 0 || it.rateLimits.period > 0) add(",\n rateLimits = %L" to it.rateLimits) if (it.argParser != DefaultArgParser::class.fullName) add(",\n argParser = %L::class" to it.argParser) } } add(")\n") }.build(), ) }.build(), ) } internal fun collectUnprocessed( unprocessedHandlerSymbols: KSFunctionDeclaration?, ctx: CollectorsContext, ) = ctx.run { activitiesFile.addProperty( PropertySpec .builder( "__TG_UNPROCESSED$idxPostfix", TypeVariableName("InvocationLambda").copy(true), KModifier.PRIVATE, ).apply { initializer( buildCodeBlock { add( "%L", unprocessedHandlerSymbols?.let { logger.info("Unprocessed handler --> ${it.qualifiedName?.asString()}") activitiesFile.buildInvocationLambdaCodeBlock(it, injectableTypes) }, ) }, ) }.build(), ) }
2
Kotlin
14
173
d496ae1d783ff155a2f695b0d9ccd4e661ac9488
9,108
telegram-bot
Apache License 2.0
app/src/main/java/org/simple/clinic/monthlyscreeningreports/form/QuestionnaireEntryScreen.kt
simpledotorg
132,515,649
false
null
package org.simple.clinic.monthlyscreeningreports.form import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.compose.ui.platform.ViewCompositionStrategy import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.jakewharton.rxbinding3.view.clicks import com.spotify.mobius.functions.Consumer import io.reactivex.Observable import io.reactivex.rxkotlin.cast import io.reactivex.subjects.PublishSubject import kotlinx.parcelize.Parcelize import org.simple.clinic.R import org.simple.clinic.ReportAnalyticsEvents import org.simple.clinic.databinding.ScreenQuestionnaireEntryFormBinding import org.simple.clinic.di.DateFormatter import org.simple.clinic.di.DateFormatter.Type.MonthAndYear import org.simple.clinic.di.DateFormatter.Type.FormSubmissionDateTime import org.simple.clinic.di.injector import org.simple.clinic.monthlyscreeningreports.complete.MonthlyScreeningReportCompleteScreen import org.simple.clinic.monthlyscreeningreports.form.compose.QuestionnaireFormContainer import org.simple.clinic.monthlyscreeningreports.util.getScreeningMonth import org.simple.clinic.monthlyscreeningreports.util.getScreeningSubmitStatus import org.simple.clinic.questionnaire.QuestionnaireType import org.simple.clinic.questionnaire.component.BaseComponentData import org.simple.clinic.questionnaire.component.ViewGroupComponentData import org.simple.clinic.navigation.v2.HandlesBack import org.simple.clinic.navigation.v2.Router import org.simple.clinic.navigation.v2.ScreenKey import org.simple.clinic.navigation.v2.fragments.BaseScreen import org.simple.clinic.questionnaireresponse.QuestionnaireResponse import org.simple.clinic.util.UserClock import org.simple.clinic.util.scheduler.SchedulersProvider import org.simple.clinic.util.toLocalDateTimeAtZone import org.simple.clinic.widgets.UiEvent import org.simple.clinic.widgets.hideKeyboard import org.simple.clinic.widgets.visibleOrGone import java.time.format.DateTimeFormatter import javax.inject.Inject class QuestionnaireEntryScreen : BaseScreen< QuestionnaireEntryScreen.Key, ScreenQuestionnaireEntryFormBinding, QuestionnaireEntryModel, QuestionnaireEntryEvent, QuestionnaireEntryEffect, QuestionnaireEntryViewEffect>(), QuestionnaireEntryUi, HandlesBack { @Inject lateinit var router: Router @Inject lateinit var userClock: UserClock @Inject @DateFormatter(MonthAndYear) lateinit var monthAndYearDateFormatter: DateTimeFormatter @Inject @DateFormatter(FormSubmissionDateTime) lateinit var formSubmissionDateTimeFormatter: DateTimeFormatter @Inject lateinit var schedulersProvider: SchedulersProvider @Inject lateinit var effectHandlerFactory: QuestionnaireEntryEffectHandler.Factory var content = mutableMapOf<String, Any?>() private val backButton get() = binding.backButton private val monthTextView get() = binding.monthTextView private val facilityTextView get() = binding.facilityTextView private val submittedDateAndTimeContainer get() = binding.submittedDateAndTimeContainer private val submittedDateAndTimeTextView get() = binding.submittedDateAndTimeTextView private val submitButton get() = binding.submitButton private val hotEvents = PublishSubject.create<QuestionnaireEntryEvent>() private val hardwareBackClicks = PublishSubject.create<Unit>() override fun defaultModel() = QuestionnaireEntryModel.from(questionnaireResponse = screenKey.questionnaireResponse) override fun createInit() = QuestionnaireEntryInit(screenKey.questionnaireType) override fun createUpdate() = QuestionnaireEntryUpdate() override fun createEffectHandler(viewEffectsConsumer: Consumer<QuestionnaireEntryViewEffect>) = effectHandlerFactory.create(viewEffectsConsumer = viewEffectsConsumer).build() override fun viewEffectHandler() = QuestionnaireEntryViewEffectHandler(this) override fun events(): Observable<QuestionnaireEntryEvent> { return Observable .mergeArray( backClicks(), submitClicks(), hotEvents ) .compose(ReportAnalyticsEvents()) .cast() } override fun uiRenderer() = QuestionnaireEntryUiRenderer(this) override fun bindView( layoutInflater: LayoutInflater, container: ViewGroup? ) = ScreenQuestionnaireEntryFormBinding.inflate(layoutInflater, container, false) override fun onAttach(context: Context) { super.onAttach(context) context.injector<Injector>().inject(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setToolbarMonth(screenKey.questionnaireResponse) setSubmittedView(screenKey.questionnaireResponse) } @Parcelize data class Key( val questionnaireType: QuestionnaireType, val questionnaireResponse: QuestionnaireResponse, override val analyticsName: String = "$questionnaireType questionnaire entry form" ) : ScreenKey() { override fun instantiateFragment() = QuestionnaireEntryScreen() } override fun setFacility(facilityName: String) { facilityTextView.text = facilityName } private fun setToolbarMonth(response: QuestionnaireResponse) { monthTextView.text = context?.resources?.getString( R.string.monthly_screening_reports_screening_report, getScreeningMonth(response.content, monthAndYearDateFormatter) ) } private fun setSubmittedView(response: QuestionnaireResponse) { val isSubmitted = getScreeningSubmitStatus(response.content) submittedDateAndTimeContainer.visibleOrGone(isSubmitted) if (isSubmitted) { val updatedAt = response.timestamps.updatedAt submittedDateAndTimeTextView.text = context?.resources?.getString( R.string.reports_submitted_with_date_and_time, formSubmissionDateTimeFormatter.format(updatedAt.toLocalDateTimeAtZone(userClock.zone))) } } override fun displayQuestionnaireFormLayout(layout: BaseComponentData) { content = screenKey.questionnaireResponse.content.toMutableMap() if (layout is ViewGroupComponentData) { binding.composeView.apply { setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) setContent { QuestionnaireFormContainer( viewGroupComponentData = layout, content = content ) } } } } private fun backClicks(): Observable<UiEvent> { return backButton.clicks() .mergeWith(hardwareBackClicks) .map { QuestionnaireEntryBackClicked } } private fun submitClicks(): Observable<UiEvent> { return submitButton.clicks() .map { SubmitButtonClicked(content) } } override fun goBack() { binding.root.hideKeyboard() router.pop() } override fun showUnsavedChangesWarningDialog() { MaterialAlertDialogBuilder(requireContext()) .setTitle(R.string.reports_unsaved_changes_title) .setMessage(R.string.reports_unsaved_changes_text) .setPositiveButton(R.string.reports_stay_title, null) .setNegativeButton(R.string.reports_leave_page_title) { _, _ -> hotEvents.onNext(UnsavedChangesWarningLeavePageClicked) } .show() } override fun goToMonthlyScreeningReportsCompleteScreen() { router.push(MonthlyScreeningReportCompleteScreen.Key(screenKey.questionnaireResponse.uuid)) } interface Injector { fun inject(target: QuestionnaireEntryScreen) } override fun onBackPressed(): Boolean { hardwareBackClicks.onNext(Unit) return true } }
4
Kotlin
70
214
17aafda84018751b82e6deef23b1757cb032057d
7,717
simple-android
MIT License
bidon/src/main/java/org/bidon/sdk/regulation/impl/IabConsentImpl.kt
bidon-io
654,165,570
false
null
@file:Suppress("DEPRECATION") package org.bidon.sdk.regulation.impl import android.content.Context import android.content.SharedPreferences import android.preference.PreferenceManager import org.bidon.sdk.regulation.Iab import org.bidon.sdk.regulation.IabConsent internal class IabConsentImpl( private val context: Context ) : IabConsent { private val shared: SharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences(context) } override val iab: Iab get() = Iab( tcfV1 = shared.getString("IABConsent_SubjectToGDPR", null), tcfV2 = shared.getString("IABTCF_gdprApplies", null), usPrivacy = shared.getString("IABUSPrivacy_String", null), ) }
0
Kotlin
0
0
0d87a754b67040e45cd35fa2d5f1f065d59e24ab
737
bidon_sdk_android
Apache License 2.0
lib/src/main/java/com/sd/lib/compose/systemui/SystemUi.kt
zj565061763
568,078,763
false
null
package com.sd.lib.compose.systemui import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.ProvidedValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewmodel.compose.viewModel @Composable fun FSystemUi( content: @Composable () -> Unit ) { val listValue = ArrayList<ProvidedValue<*>>(2) if (LocalStatusBarBrightnessStack.current == null) { viewModel<BrightnessStackViewModel>().statusBarBrightnessStack.let { stack -> ObserverStatusBarBrightnessStack(stack) listValue.add(LocalStatusBarBrightnessStack provides stack) } } if (LocalNavigationBarBrightnessStack.current == null) { viewModel<BrightnessStackViewModel>().navigationBarBrightnessStack.let { stack -> ObserverNavigationBarBrightnessStack(stack) listValue.add(LocalNavigationBarBrightnessStack provides stack) } } if (listValue.isEmpty()) { content() } else { val array = listValue.toTypedArray() CompositionLocalProvider(*array) { content() } } } internal class BrightnessStackViewModel : ViewModel() { val statusBarBrightnessStack = BrightnessStack() val navigationBarBrightnessStack = BrightnessStack() } @Composable private fun ObserverStatusBarBrightnessStack(stack: BrightnessStack) { val statusBarController = rememberStatusBarController() DisposableEffect(statusBarController, stack) { val callback = BrightnessStack.Callback { brightness -> if (brightness != null) { statusBarController.isLight = brightness is Brightness.Light } } stack.registerCallback(callback) onDispose { stack.unregisterCallback(callback) } } } @Composable private fun ObserverNavigationBarBrightnessStack(stack: BrightnessStack) { val navigationBarController = rememberNavigationBarController() DisposableEffect(navigationBarController, stack) { val callback = BrightnessStack.Callback { brightness -> if (brightness != null) { navigationBarController.isLight = brightness is Brightness.Light } } stack.registerCallback(callback) onDispose { stack.unregisterCallback(callback) } } }
0
Kotlin
0
0
c004630a9a0f4057f6523ebad3b3f39c0ea3daf6
2,452
compose-systemui
MIT License
src/main/kotlin/xyz/magentaize/dynamicdata/list/test/ListEx.kt
Magentaize
290,133,754
false
null
package xyz.magentaize.dynamicdata.list.test import xyz.magentaize.dynamicdata.list.ChangeSet import io.reactivex.rxjava3.core.Observable fun <T> Observable<ChangeSet<T>>.asAggregator() = ChangeSetAggregator(this)
0
Kotlin
0
3
dda522f335a6ab3847cc90ff56e8429c15834800
220
dynamicdata-kotlin
MIT License
tezos-rpc/src/main/kotlin/it/airgap/tezos/rpc/shell/ShellSimplifiedRpc.kt
airgap-it
460,351,851
false
null
package it.airgap.tezos.rpc.shell import it.airgap.tezos.core.type.encoded.BlockHash import it.airgap.tezos.core.type.encoded.ChainId import it.airgap.tezos.rpc.http.HttpHeader import it.airgap.tezos.rpc.internal.utils.Constants import it.airgap.tezos.rpc.shell.chains.GetBlocksResponse import it.airgap.tezos.rpc.shell.chains.GetBootstrappedStatusResponse import it.airgap.tezos.rpc.shell.chains.GetChainIdResponse import it.airgap.tezos.rpc.shell.injection.InjectOperationResponse /** * Tezos protocol-independent RPCs. * * See [RPCs - Reference](https://tezos.gitlab.io/shell/rpc.html) for more details. */ public interface ShellSimplifiedRpc { // -- /chains -- /** * Lists block hashes from [chainId], up to the last checkpoint, sorted with decreasing fitness. * Without arguments, it returns the head of the chain. * Optional arguments allow to return the list of predecessors of a given block or of a set of blocks. * * Optional query arguments: * * [length] = `<uint>` : The requested number of predecessors to return (per request; see next argument). * * [head] = `<block_hash>` : An empty argument requests blocks starting with the current head. * A non-empty list allows to request one or more specific fragments of the chain. * * [minDate] = `<date>` : When [minDate] is provided, blocks with a timestamp before [minDate] are filtered out. * However, if the `length` parameter is also provided, then up to that number of predecessors will be returned regardless of their date. * * [`GET /chains/<chain_id>/blocks?[length=<uint>]&(head=<block_hash>)*&[min_date=<date>]`](https://tezos.gitlab.io/shell/rpc.html#get-chains-chain-id-blocks) */ public suspend fun getBlocks( chainId: String = Constants.Chain.MAIN, length: UInt? = null, head: BlockHash? = null, minDate: String? = null, headers: List<HttpHeader> = emptyList(), requestTimeout: Long? = null, connectionTimeout: Long? = null, ): GetBlocksResponse /** * Lists block hashes from [chainId], up to the last checkpoint, sorted with decreasing fitness. * Without arguments, it returns the head of the chain. * Optional arguments allow to return the list of predecessors of a given block or of a set of blocks. * * Optional query arguments: * * [length] = `<uint>` : The requested number of predecessors to return (per request; see next argument). * * [head] = `<block_hash>` : An empty argument requests blocks starting with the current head. * A non-empty list allows to request one or more specific fragments of the chain. * * [minDate] = `<date>` : When [minDate] is provided, blocks with a timestamp before [minDate] are filtered out. * However, if the `length` parameter is also provided, then up to that number of predecessors will be returned regardless of their date. * * [`GET /chains/<chain_id>/blocks?[length=<uint>]&(head=<block_hash>)*&[min_date=<date>]`](https://tezos.gitlab.io/shell/rpc.html#get-chains-chain-id-blocks) */ public suspend fun getBlocks( chainId: ChainId, length: UInt? = null, head: BlockHash? = null, minDate: String? = null, headers: List<HttpHeader> = emptyList(), requestTimeout: Long? = null, connectionTimeout: Long? = null, ): GetBlocksResponse = getBlocks(chainId.base58, length, head, minDate, headers) /** * The chain unique identifier. * * [`GET /chains/<chain_id>/chain_id`](https://tezos.gitlab.io/shell/rpc.html#get-chains-chain-id-chain-id) */ public suspend fun getChainId( chainId: String = Constants.Chain.MAIN, headers: List<HttpHeader> = emptyList(), requestTimeout: Long? = null, connectionTimeout: Long? = null, ): GetChainIdResponse /** * The chain unique identifier. * * [`GET /chains/<chain_id>/chain_id`](https://tezos.gitlab.io/shell/rpc.html#get-chains-chain-id-chain-id) */ public suspend fun getChainId( chainId: ChainId, headers: List<HttpHeader> = emptyList(), requestTimeout: Long? = null, connectionTimeout: Long? = null, ): GetChainIdResponse = getChainId(chainId.base58, headers) /** * The bootstrap status of a chain. * * [`GET /chains/<chain_id>/is_bootstrapped`](https://tezos.gitlab.io/shell/rpc.html#get-chains-chain-id-is-bootstrapped) */ public suspend fun isBootstrapped( chainId: String = Constants.Chain.MAIN, headers: List<HttpHeader> = emptyList(), requestTimeout: Long? = null, connectionTimeout: Long? = null, ): GetBootstrappedStatusResponse /** * The bootstrap status of a chain. * * [`GET /chains/<chain_id>/is_bootstrapped`](https://tezos.gitlab.io/shell/rpc.html#get-chains-chain-id-is-bootstrapped) */ public suspend fun isBootstrapped( chainId: ChainId, headers: List<HttpHeader> = emptyList(), requestTimeout: Long? = null, connectionTimeout: Long? = null, ): GetBootstrappedStatusResponse = isBootstrapped(chainId.base58, headers) // -- /injection -- /** * Inject an operation in node and broadcast it. Returns the ID of the operation. * The `signedOperationContents` should be constructed using contextual RPCs from the latest block and signed by the client. * The injection of the operation will apply it on the current mempool context. * * This context may change at each operation injection or operation reception from peers. * * By default, the RPC will wait for the operation to be (pre-)validated before returning. * However, if ?async is true, the function returns immediately. * The optional ?chain parameter can be used to specify whether to inject on the test chain or the main chain. * * Optional query arguments: * * [async] * * [chain] = `<chain_id> * * [`POST /injection/operation?[async]&[chain=<chain_id>]`](https://tezos.gitlab.io/shell/rpc.html#post-injection-operation) */ public suspend fun injectOperation( data: String, async: Boolean? = null, chain: ChainId? = null, headers: List<HttpHeader> = emptyList(), requestTimeout: Long? = null, connectionTimeout: Long? = null, ): InjectOperationResponse }
0
Kotlin
2
1
c5af5ffdd4940670bd66842580d82c2b9d682d84
6,528
tezos-kotlin-sdk
MIT License
src/main/kotlin/osmpoi/indexer/BasePbfParser.kt
kevintavog
516,472,356
false
{"Kotlin": 232045, "Makefile": 290, "Dockerfile": 214}
package osmpoi.indexer import crosby.binary.BinaryParser abstract class BasePbfParser: BinaryParser() { fun getTags(keysList: List<Int>, valuesList: List<Int>): Map<String,String> { val tags = mutableMapOf<String,String>() for (index in keysList.indices) { tags[getStringById(keysList[index])] = getStringById(valuesList[index]) } return tags } // Packed keys & values are a sequence per id; each key is followed by a value. // Ids are separated by a key of 0 fun getDenseTags(ids: List<Long>, packedKV: List<Int>): List<Map<String,String>> { val allNodeTags = mutableListOf<Map<String,String>>() var lastId = 0L var idIndex = 0 var kvIndex = 0 var tags = mutableMapOf<String,String>() while (kvIndex < packedKV.size && idIndex < ids.size) { if (packedKV[kvIndex] == 0) { allNodeTags.add(tags) tags = mutableMapOf() lastId += ids[idIndex] idIndex += 1 kvIndex += 1 } else { tags[getStringById(packedKV[kvIndex])] = getStringById(packedKV[kvIndex + 1]) // Move past this key & the following value and to the next key kvIndex += 2 } } return allNodeTags } }
0
Kotlin
0
0
48be75b719f51e9bdcc7e6536a62b18aa68bdf86
1,356
osmpoi
MIT License
app/src/main/java/com/example/fitfinder/viewmodel/exercise/ProgressViewModel.kt
OmriGawi
618,447,164
false
{"Kotlin": 233548}
package com.example.fitfinder.viewmodel.exercise import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.fitfinder.data.model.ExerciseProgress import com.example.fitfinder.data.repository.exercise.ProgressRepository class ProgressViewModel(private val repository: ProgressRepository) : ViewModel() { private val _progressData = MutableLiveData<List<ExerciseProgress>>() val progressData: LiveData<List<ExerciseProgress>> = _progressData fun fetchProgressData(userId: String) { repository.fetchUserProgress(userId) { progressList -> _progressData.postValue(progressList) } } }
0
Kotlin
0
0
aaa6f0858ee5d40d2688d3d22d03c92193e7c080
699
FitFinder
MIT License
totp/src/main/java/com/okta/totp/password_generator/PasswordGeneratorModule.kt
okta
162,222,100
false
{"Kotlin": 191339, "Shell": 1016}
/* * Copyright 2022-Present Okta, 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 com.okta.totp.password_generator import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @InstallIn(SingletonComponent::class) @Module interface PasswordGeneratorModule { @Binds fun bindPasswordGenerator( passwordGenerator: PasswordGeneratorImpl ): PasswordGenerator @Binds fun bindPasswordGeneratorFactory( passwordGeneratorFactoryImpl: PasswordGeneratorFactoryImpl ): PasswordGeneratorFactory }
9
Kotlin
52
33
e4ed0cdd3ad0c0decc277eb8426d734450642afb
1,113
samples-android
Apache License 2.0
sample/src/commonMain/kotlin/amaterek/util/ui/navigation/sample/ui/navigation/NavigatorProvider.kt
amaterek
836,737,020
false
{"Kotlin": 87622, "Swift": 671}
package amaterek.util.ui.navigation.sample.ui.navigation import amaterek.util.ui.navigation.Navigator import amaterek.util.ui.navigation.VoyagerNavigationHost import amaterek.util.ui.navigation.VoyagerNavigator import amaterek.util.ui.navigation.annotation.InternalNavigation import amaterek.util.ui.navigation.destination.GraphDestination import amaterek.util.ui.navigation.destination.ScreenDestination import amaterek.util.ui.navigation.rememberVoyagerNavigator import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable internal interface NavigatorProvider { @Stable @Composable operator fun invoke( navigator: Navigator, ) @Composable fun rememberNavigator( startDestination: ScreenDestination, graph: Set<GraphDestination>, parent: Navigator?, ): Navigator } internal class GetDefaultNavigationHost : NavigatorProvider { @OptIn(InternalNavigation::class) @Composable override fun invoke( navigator: Navigator, ) { VoyagerNavigationHost( navigator = navigator as VoyagerNavigator, ) } @Composable override fun rememberNavigator( startDestination: ScreenDestination, graph: Set<GraphDestination>, parent: Navigator?, ): Navigator = rememberVoyagerNavigator(startDestination, graph, parent) }
0
Kotlin
0
0
aabab8fdeac27771b53844fae7348b4293c26caa
1,377
kmp-navigation
Apache License 2.0
app/src/main/java/com/controlevacinacao/extiv/UsuarioDAO.kt
Davi-ChavesN
876,492,166
false
{"Kotlin": 29920}
package com.controlevacinacao.extiv import android.content.ContentValues import android.util.Log class UsuarioDAO(banco: Banco) { var banco: Banco init { this.banco = banco } fun insert(usuario: Usuario) { val db_insert = this.banco.writableDatabase var cv_valores = ContentValues().apply { put("nome", usuario.nome) put("email", usuario.email) put("usuario", usuario.usuario) put("senha", usuario.senha) } val confirmaInsert = db_insert?.insert("usuarios", null, cv_valores) Log.i("Teste Insercao Usuario", "Insercao: ${confirmaInsert}") } fun select(): ArrayList<String> { var listaUsuarios = ArrayList<String>() val db_read = this.banco.readableDatabase var cursor = db_read.rawQuery("SELECT * FROM usuarios", null) with(cursor) { while (moveToNext()) { val codigo = getLong(getColumnIndexOrThrow("codigo")) val nome = getString(getColumnIndexOrThrow("nome")) val email = getString(getColumnIndexOrThrow("email")) val usuario = getString(getColumnIndexOrThrow("usuario")) val senha = getString(getColumnIndexOrThrow("senha")) listaUsuarios.add("${codigo} - ${nome} - ${email} - ${usuario} - ${senha}") } } cursor.close() return (listaUsuarios) } fun selectComWhere(codigo: Long): ArrayList<String> { var listaUsuarios = ArrayList<String>() val db_read = this.banco.readableDatabase var cursor = db_read.rawQuery("SELECT * FROM usuarios WHERE codigo = ${codigo}", null) with(cursor) { while (moveToNext()) { val codigo = getLong(getColumnIndexOrThrow("codigo")) val nome = getString(getColumnIndexOrThrow("nome")) val email = getString(getColumnIndexOrThrow("email")) val usuario = getString(getColumnIndexOrThrow("usuario")) val senha = getString(getColumnIndexOrThrow("senha")) listaUsuarios.add("${codigo} - ${nome} - ${email} - ${usuario} - ${senha}") } } cursor.close() return (listaUsuarios) } fun update(usuario: Usuario) { val db_update = this.banco.writableDatabase var cv_valores = ContentValues().apply { put("nome", usuario.nome) put("email", usuario.email) put("usuario", usuario.usuario) put("senha", usuario.senha) } val condicao = "codigo = ${usuario.codigo}" val confirmaUpdate = db_update.update("usuarios", cv_valores, condicao, null) } fun delete(codigo: Int) { val db_delete = this.banco.writableDatabase val condicao = "codigo = ${codigo}" db_delete.delete("usuarios", condicao, null) } }
0
Kotlin
0
0
7ac74a70de9c13d8c181071d426e5334ba4909b6
2,934
SistemaDeVacinacao
MIT License
bpdm-pool/src/test/kotlin/org/eclipse/tractusx/bpdm/pool/service/TaskStepFetchAndReserveServiceTest.kt
eclipse-tractusx
526,621,398
false
{"Kotlin": 1745671, "Smarty": 19820, "Dockerfile": 4118, "Java": 2019, "Shell": 1136, "Batchfile": 1123}
package org.eclipse.tractusx.bpdm.pool.service import com.neovisionaries.i18n.CountryCode import org.assertj.core.api.Assertions.assertThat import org.eclipse.tractusx.bpdm.pool.Application import org.eclipse.tractusx.bpdm.pool.api.client.PoolClientImpl import org.eclipse.tractusx.bpdm.pool.repository.BpnRequestIdentifierRepository import org.eclipse.tractusx.bpdm.pool.service.TaskStepBuildService.CleaningError import org.eclipse.tractusx.bpdm.pool.util.OpenSearchContextInitializer import org.eclipse.tractusx.bpdm.pool.util.PostgreSQLContextInitializer import org.eclipse.tractusx.bpdm.pool.util.TestHelpers import org.eclipse.tractusx.orchestrator.api.model.* import org.eclipse.tractusx.orchestrator.api.model.BpnReferenceType.BpnRequestIdentifier import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.ActiveProfiles import org.springframework.test.context.ContextConfiguration @SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = [Application::class] ) @ActiveProfiles("test") @ContextConfiguration(initializers = [PostgreSQLContextInitializer::class, OpenSearchContextInitializer::class]) class TaskStepFetchAndReserveServiceTest @Autowired constructor( val cleaningStepService: TaskStepFetchAndReserveService, val bpnRequestIdentifierRepository: BpnRequestIdentifierRepository, val testHelpers: TestHelpers, val poolClient: PoolClientImpl ) { @BeforeEach fun beforeEach() { testHelpers.truncateDbTables() testHelpers.createTestMetadata() } @Test fun `upsert Golden Record into pool with empty legal entity`() { val fullBpWithLegalEntity = minFullBusinessPartner().copy( legalEntity = emptyLegalEntity() ) val result = cleanStep(taskId = "TASK_1", businessPartner = fullBpWithLegalEntity) assertTaskError(result[0], "TASK_1", CleaningError.LEGAL_ENTITY_IS_NULL) } @Test fun `upsert Golden Record into pool with legal entity without legal name to create`() { val fullBpWithLegalEntity = minFullBusinessPartner().copy( legalEntity = emptyLegalEntity().copy( bpnLReference = BpnReferenceDto(referenceValue = "123", referenceType = BpnRequestIdentifier), legalAddress = LogisticAddressDto() ) ) val result = cleanStep(taskId = "TASK_1", businessPartner = fullBpWithLegalEntity) assertTaskError(result[0], "TASK_1", CleaningError.LEGAL_NAME_IS_NULL) } @Test fun `upsert Golden Record into pool with legal entity to create`() { val fullBpWithLegalEntity = minFullBusinessPartner().copy( legalEntity = minValidLegalEntity( BpnReferenceDto(referenceValue = "123", referenceType = BpnRequestIdentifier), BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier) ) ) val resultSteps = cleanStep(taskId = "TASK_1", businessPartner = fullBpWithLegalEntity) assertThat(resultSteps[0].taskId).isEqualTo("TASK_1") assertThat(resultSteps[0].errors.size).isEqualTo(0) val bpnMappings = bpnRequestIdentifierRepository.findDistinctByRequestIdentifierIn(listOf("123","222" )) val createdLegalEntity = poolClient.legalEntities.getLegalEntity(resultSteps[0].businessPartner?.legalEntity?.bpnLReference?.referenceValue!!) assertThat(createdLegalEntity.legalAddress.bpnLegalEntity).isNotNull() assertThat(bpnMappings.size).isEqualTo(2) assertThat(resultSteps[0].businessPartner?.generic?.bpnL).isEqualTo(createdLegalEntity.legalEntity.bpnl) } @Test fun `upsert Golden Record into pool with same legal entity referenceValue to create`() { val fullBpWithLegalEntity = minFullBusinessPartner().copy( legalEntity = minValidLegalEntity( bpnLReference = BpnReferenceDto(referenceValue = "123", referenceType = BpnRequestIdentifier), bpnAReference = BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier) ) ) val resultSteps1 = cleanStep(taskId = "TASK_1", businessPartner = fullBpWithLegalEntity) assertThat(resultSteps1[0].taskId).isEqualTo("TASK_1") assertThat(resultSteps1[0].errors.size).isEqualTo(0) val createdLegalEntity1 = poolClient.legalEntities.getLegalEntity(resultSteps1[0].businessPartner?.legalEntity?.bpnLReference?.referenceValue!!) val resultSteps2 = cleanStep(taskId = "TASK_2", businessPartner = fullBpWithLegalEntity) assertThat(resultSteps2[0].taskId).isEqualTo("TASK_2") assertThat(resultSteps2[0].errors.size).isEqualTo(0) assertThat(createdLegalEntity1.legalEntity.bpnl).isEqualTo(resultSteps2[0].businessPartner?.legalEntity?.bpnLReference?.referenceValue!!) } @Test fun `upsert Golden Record into pool with differrent legal entity referenceValue to create`() { val fullBpWithLegalEntity = minFullBusinessPartner().copy( legalEntity = minValidLegalEntity( bpnLReference = BpnReferenceDto(referenceValue = "123", referenceType = BpnRequestIdentifier), bpnAReference = BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier) ) ) val resultSteps1 = cleanStep(taskId = "TASK_1", businessPartner = fullBpWithLegalEntity) assertThat(resultSteps1[0].taskId).isEqualTo("TASK_1") assertThat(resultSteps1[0].errors.size).isEqualTo(0) val createdLegalEntity1 = poolClient.legalEntities.getLegalEntity(resultSteps1[0].businessPartner?.legalEntity?.bpnLReference?.referenceValue!!) val fullBpWithLegalEntity2 = minFullBusinessPartner().copy( legalEntity = minValidLegalEntity( bpnLReference = BpnReferenceDto(referenceValue = "diffenrentBpnL", referenceType = BpnRequestIdentifier), bpnAReference = BpnReferenceDto(referenceValue = "diffenrentBpnA", referenceType = BpnRequestIdentifier) ) ) val resultSteps2 = cleanStep(taskId = "TASK_2", businessPartner = fullBpWithLegalEntity2) assertThat(resultSteps2[0].taskId).isEqualTo("TASK_2") assertThat(resultSteps2[0].errors.size).isEqualTo(0) assertThat(createdLegalEntity1.legalEntity.bpnl).isNotEqualTo(resultSteps2[0].businessPartner?.legalEntity?.bpnLReference?.referenceValue!!) val createdLegalEntity2 = poolClient.legalEntities.getLegalEntity(resultSteps2[0].businessPartner?.legalEntity?.bpnLReference?.referenceValue!!) assertThat(resultSteps2[0].businessPartner?.generic?.bpnL).isEqualTo(createdLegalEntity2.legalEntity.bpnl) } fun cleanStep(taskId: String, businessPartner: BusinessPartnerFullDto): List<TaskStepResultEntryDto> { val steps = singleTaskStep(taskId = taskId, businessPartner = businessPartner) return cleaningStepService.upsertGoldenRecordIntoPool(steps) } fun singleTaskStep(taskId: String, businessPartner: BusinessPartnerFullDto): List<TaskStepReservationEntryDto> { return listOf( TaskStepReservationEntryDto( taskId = taskId, businessPartner = businessPartner ) ) } fun minFullBusinessPartner(): BusinessPartnerFullDto { return BusinessPartnerFullDto(generic = BusinessPartnerGenericDto()) } fun emptyLegalEntity(): LegalEntityDto { return LegalEntityDto() } fun minValidLegalEntity(bpnLReference: BpnReferenceDto, bpnAReference: BpnReferenceDto): LegalEntityDto { return LegalEntityDto( bpnLReference = bpnLReference, legalName = "legalName_" + bpnLReference.referenceValue, legalAddress = LogisticAddressDto( bpnAReference = bpnAReference, physicalPostalAddress = PhysicalPostalAddressDto( country = CountryCode.DE, city = "City" + bpnLReference.referenceValue ) ) ) } fun assertTaskError(step: TaskStepResultEntryDto, taskId: String, error: CleaningError) { assertThat(step.taskId).isEqualTo(taskId) assertThat(step.errors.size).isEqualTo(1) assertThat(step.errors[0].description).isEqualTo(error.message) } }
47
Kotlin
6
4
e5ce1dae5f342b4c4780f81379c9862d8e8aa158
8,561
bpdm
Apache License 2.0
next/kmp/browser/src/commonMain/kotlin/org/dweb_browser/browser/desk/render/DeskAppIcon.kt
BioforestChain
594,577,896
false
{"Kotlin": 3279967, "TypeScript": 782085, "Swift": 355540, "Vue": 155048, "SCSS": 39016, "Objective-C": 17350, "HTML": 16888, "Shell": 13534, "JavaScript": 4687, "Svelte": 3504, "CSS": 818}
package org.dweb_browser.browser.desk.render import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredSize import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import org.dweb_browser.browser.desk.model.DesktopAppModel import org.dweb_browser.core.module.NativeMicroModule import org.dweb_browser.core.std.file.ext.blobFetchHook import org.dweb_browser.helper.ImageResourcePurposes import org.dweb_browser.helper.StrictImageResource import org.dweb_browser.pure.image.compose.PureImageLoader import org.dweb_browser.pure.image.compose.SmartLoad import org.dweb_browser.sys.window.render.AppIcon @Composable fun DeskAppIcon( icon: StrictImageResource?, microModule: NativeMicroModule.NativeRuntime, width: Dp, height: Dp, containerAlpha: Float? = null, containerColor: Color? = null, modifier: Modifier = Modifier, ) { val imageResult = icon?.let { PureImageLoader.SmartLoad(icon.src, width, height, microModule.blobFetchHook) } AppIcon( icon = imageResult, modifier = modifier.requiredSize(width, height), iconShape = deskSquircleShape(), iconMaskable = icon?.let { icon.purpose.contains(ImageResourcePurposes.Maskable) } ?: false, iconMonochrome = icon?.let { icon.purpose.contains(ImageResourcePurposes.Monochrome) } ?: false, containerAlpha = containerAlpha ?: deskIconAlpha, containerColor = containerColor ) } internal val deskIconAlpha = when { canSupportModifierBlur() -> 0.9f else -> 1f } @Composable internal fun DeskAppIcon( app: DesktopAppModel, microModule: NativeMicroModule.NativeRuntime, containerAlpha: Float? = null, containerColor: Color? = null, modifier: Modifier = Modifier, ) { val iconSize = desktopIconSize() DeskAppIcon( icon = app.icon, microModule = microModule, width = iconSize.width.dp, height = iconSize.height.dp, containerAlpha = containerAlpha, containerColor = containerColor, modifier = modifier.padding(8.dp) ) }
60
Kotlin
4
11
3659481976685b3e566c1080a077e3c1b5c9cece
2,134
dweb_browser
MIT License
AndroidKCP/kmm_plugin_native/src/main/kotlin/com/azharkova/kmm/plugin/domain/AndroidTransformExtension.kt
anioutkazharkova
638,593,180
false
null
package com.azharkova.kcp.plugin.domain import com.azharkova.kcp.plugin.util.createIrBuilder import com.azharkova.kcp.plugin.util.fqName import com.azharkova.kcp.plugin.util.irSafeLet import org.jetbrains.kotlin.backend.common.BackendContext import org.jetbrains.kotlin.backend.common.DeclarationTransformer import org.jetbrains.kotlin.backend.common.IrElementTransformerVoidWithContext import org.jetbrains.kotlin.backend.common.extensions.FirIncompatiblePluginAPI import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext import org.jetbrains.kotlin.backend.common.ir.addDispatchReceiver import org.jetbrains.kotlin.backend.common.lower.DeclarationIrBuilder import org.jetbrains.kotlin.backend.common.lower.callsSuper import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.ir.IrStatement import org.jetbrains.kotlin.ir.ObsoleteDescriptorBasedAPI import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET import org.jetbrains.kotlin.ir.builders.* import org.jetbrains.kotlin.ir.builders.declarations.* import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.declarations.impl.IrExternalPackageFragmentImpl import org.jetbrains.kotlin.ir.declarations.impl.IrFactoryImpl import org.jetbrains.kotlin.ir.expressions.* import org.jetbrains.kotlin.ir.expressions.impl.IrBlockImpl import org.jetbrains.kotlin.ir.expressions.impl.IrCallImpl import org.jetbrains.kotlin.ir.expressions.impl.IrGetFieldImpl import org.jetbrains.kotlin.ir.expressions.impl.IrTypeOperatorCallImpl import org.jetbrains.kotlin.ir.symbols.IrClassifierSymbol import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol import org.jetbrains.kotlin.ir.symbols.IrSymbol import org.jetbrains.kotlin.ir.symbols.impl.IrTypeParameterSymbolImpl import org.jetbrains.kotlin.ir.symbols.impl.IrValueParameterSymbolImpl import org.jetbrains.kotlin.ir.types.* import org.jetbrains.kotlin.ir.util.* import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.FqNameUnsafe import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.descriptorUtil.propertyIfAccessor val bindViewAnnotation = FqName("com.azharkova.annotations.BindView") /** * @BindView(R.id.some) * var someView: View? = getView().findViewById(R.id.some) * */ class AndroidTransformExtension (val pluginContext: IrPluginContext, private val messageCollector: MessageCollector) : IrElementTransformerVoidWithContext() { private val irFactory: IrFactory = IrFactoryImpl private fun irBuilder(scope: IrSymbol, replacing: IrStatement): IrBuilderWithScope = DeclarationIrBuilder(IrGeneratorContextBase(pluginContext.irBuiltIns), scope, replacing.startOffset, replacing.endOffset) override fun visitFunctionNew(declaration: IrFunction): IrStatement { return super.visitFunctionNew(declaration) } override fun visitClassNew(declaration: IrClass): IrStatement { if (declaration.functions.any { it.annotations.hasAnnotation(bindViewAnnotation) }) { messageCollector.report(CompilerMessageSeverity.WARNING, declaration.dump()) } return super.visitClassNew(declaration) } override fun visitPropertyNew(declaration: IrProperty): IrStatement { if (declaration.annotations.hasAnnotation(bindViewAnnotation)) { // declaration.backingField = add declaration.getter?.let { getter -> getter.body = pluginContext.irFactory.createBlockBody(UNDEFINED_OFFSET, UNDEFINED_OFFSET) { val irBuilder = pluginContext.irBuiltIns.createIrBuilder( getter.symbol, startOffset, endOffset ) irBuilder.run { val resultVar = scope.createTmpVariable( irGetField( getter.dispatchReceiverParameter?.let { irGet(it) }, declaration.backingField!! ) ) resultVar.parent = getter statements.add(resultVar) } } } } return super.visitPropertyNew(declaration) } /* class Transformer(val backendContext: BackendContext):DeclarationTransformer { override fun transformFlat(declaration: IrDeclaration): List<IrDeclaration>? { (declaration as? IrProperty)?.let { declaration.backingField = backendContext.buildOrGetNullableField(declaration.backingField!!) } (declaration as? IrSimpleFunction)?.correspondingPropertySymbol?.owner?.let { property -> if (declaration == property.getter) { // f = buildOrGetNullableField is idempotent, i.e. f(f(x)) == f(x) transformGetter(backendContext.buildOrGetNullableField(property.backingField!!), declaration) } } return null } private fun transformGetter(backingField: IrField, getter: IrFunction) { val type = backingField.type // assert(!type.isPrimitiveType()) { "'lateinit' modifier is not allowed on primitive types" } val startOffset = getter.startOffset val endOffset = getter.endOffset getter.body = backendContext.irFactory.createBlockBody(startOffset, endOffset) { val irBuilder = backendContext.irBuiltIns.createIrBuilder(getter.symbol, startOffset, endOffset) irBuilder.run { val resultVar = scope.createTmpVariable( irGetField(getter.dispatchReceiverParameter?.let { irGet(it) }, backingField) ) resultVar.parent = getter statements.add(resultVar) } } } }*/ private fun IrBuilderWithScope.irFindViewById( receiver: IrExpression, id: IrExpression, container: AndroidContainerType ): IrExpression { // this[.getView()?|.getContainerView()?].findViewById(R$id.<name>) val getView = createMethod(container.fqName.child(Name.identifier("getView")), nullableViewType) val findViewByIdParent = if (getView == null) container.fqName else FqName(AndroidConst.VIEW_FQNAME) val findViewById = createMethod(findViewByIdParent.child(Name.identifier("findViewById")), nullableViewType) { addValueParameter("id", pluginContext.irBuiltIns.intType) } val findViewCall = irCall(findViewById).apply { putValueArgument(0, id) } return if (getView == null) { findViewCall.apply { dispatchReceiver = receiver } } else { irSafeLet(findViewCall.type, irCall(getView).apply { dispatchReceiver = receiver }) { parent -> findViewCall.apply { dispatchReceiver = irGet(parent) } } } } private fun createPackage(fqName: FqName) = IrExternalPackageFragmentImpl.createEmptyExternalPackageFragment(pluginContext.moduleDescriptor, fqName) private fun getClass(fqName: FqName, isInterface: Boolean = false) = irFactory.buildClass { name = fqName.shortName() kind = if (isInterface) ClassKind.INTERFACE else ClassKind.CLASS origin = IrDeclarationOrigin.IR_EXTERNAL_JAVA_DECLARATION_STUB }.apply { parent = createPackage(fqName.parent()) createImplicitParameterDeclarationWithWrappedDescriptor() } private fun createMethod(fqName: FqName, type: IrType, inInterface: Boolean = false, f: IrFunction.() -> Unit = {}): IrSimpleFunction { val parent = getClass(fqName = fqName.parent(), isInterface = inInterface) return parent.addFunction { name = fqName.shortName() origin = IrDeclarationOrigin.IR_EXTERNAL_JAVA_DECLARATION_STUB modality = if (inInterface) Modality.ABSTRACT else Modality.FINAL returnType = type }.apply { addDispatchReceiver { this.type = parent.defaultType } f() } } private val nullableViewType = getClass(FqName(AndroidConst.VIEW_FQNAME)).defaultType.makeNullable() }
0
Kotlin
0
0
352b2f9f8ff24ac0698f99731040704bb245edfe
8,547
android-kcp
Apache License 2.0
kotlin-mui/src/main/generated/mui/lab/TreeItem.classes.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! package mui.lab external interface TreeItemClasses { /** Styles applied to the root element. */ var root: String /** Styles applied to the transition component. */ var group: String /** Styles applied to the content element. */ var content: String /** State class applied to the content element when expanded. */ var expanded: String /** State class applied to the content element when selected. */ var selected: String /** State class applied to the content element when focused. */ var focused: String /** State class applied to the element when disabled. */ var disabled: String /** Styles applied to the tree node icon. */ var iconContainer: String /** Styles applied to the label element. */ var label: String }
12
Kotlin
145
983
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
843
kotlin-wrappers
Apache License 2.0
app/src/main/kotlin/io/github/importre/eddystone/Utils.kt
hojinchu99
46,778,834
false
{"Kotlin": 79978, "Java": 674}
// Copyright 2015 Google 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 // // 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.github.importre.eddystone internal object Utils { private val HEX = "0123456789ABCDEF".toCharArray() fun toHexString(bytes: ByteArray): String { if (bytes.size == 0) { return "" } val chars = CharArray(bytes.size * 2) for (i in bytes.indices) { val c = bytes[i].toInt() and 255 chars[i * 2] = HEX[c.ushr(4)] chars[i * 2 + 1] = HEX[c and 15] } return String(chars).toLowerCase() } fun isZeroed(bytes: ByteArray): Boolean { for (b in bytes) { if (!b.equals(0)) { return false } } return true } }
0
Kotlin
0
0
50ff11b443d953f4212268326095c65fd4be5be8
1,298
yeobara-android
MIT License
statcraft-api/src/main/kotlin/com/demonwav/statcraft/api/exceptions/StatCraftNamespaceNotDefinedException.kt
DenWav
67,326,995
false
{"Kotlin": 96559, "Java": 46949}
/* * StatCraft Plugin * * Copyright (c) 2016 <NAME> (DemonWav) * https://www.demonwav.com * * MIT License */ package com.demonwav.statcraft.api.exceptions import com.demonwav.statcraft.StatCraft import com.demonwav.statcraft.api.StatCraftNamespace /** * Thrown when [StatCraft.getApi] is called with an object that isn't annotated with [StatCraftNamespace]. */ class StatCraftNamespaceNotDefinedException : RuntimeException()
0
Kotlin
0
1
1ed39babc661a948b17b2b8ad6f9fad5d5fd5c64
438
StatCraftGradle
MIT License
app/src/main/java/com/ankitdubey021/cowintracker/networking/CovidReportApiClient.kt
ankitdubey021
370,326,516
false
null
package com.ankitdubey021.cowintracker.networking import com.ankitdubey021.cowintracker.data.CovidReportDao import retrofit2.http.GET interface CovidReportApiClient { @GET("data.json") suspend fun getCovidReport() : CovidReportDao }
0
Kotlin
1
5
5aedbe42b485e42593361e7ab45982c57ddb77a0
244
CowinTracker
The Unlicense
QRStoringHelper/app/src/main/java/studios/devs/mobi/qrstoringhelper/repositories/ILaunchRepository.kt
ValeriJordanov
321,771,563
false
null
package studios.devs.mobi.qrstoringhelper.repositories interface ILaunchRepository { }
0
Kotlin
0
0
71d8ecd7c3429157b72de94d096d36208b13b491
87
QR-Storing-Helper
Apache License 2.0
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Systems/intake/Intake.kt
tfgabriel
828,336,489
false
{"Kotlin": 105507, "Java": 41887}
package org.firstinspires.ftc.teamcode.Systems.intake import org.firstinspires.ftc.teamcode.Algorithms.quality_of_life_funcs import org.firstinspires.ftc.teamcode.Algorithms.quality_of_life_funcs.autoupdate_tp import org.firstinspires.ftc.teamcode.Algorithms.quality_of_life_funcs.posdiff import org.firstinspires.ftc.teamcode.Systems.intake.intake_vars.intakeMotorPower import org.firstinspires.ftc.teamcode.Systems.intake.intake_vars.intakePosFour import org.firstinspires.ftc.teamcode.Systems.intake.intake_vars.intakePosThree import org.firstinspires.ftc.teamcode.Systems.intake.intake_vars.intakePosTop import org.firstinspires.ftc.teamcode.Systems.intake.intake_vars.intakePosTwo import org.firstinspires.ftc.teamcode.Systems.intake.intake_vars.lidClosePos import org.firstinspires.ftc.teamcode.Systems.intake.intake_vars.lidOpenPos import org.firstinspires.ftc.teamcode.Variables.system_funcs import org.firstinspires.ftc.teamcode.Variables.system_funcs.hardwareMap import org.firstinspires.ftc.teamcode.Variables.system_funcs.lom import org.firstinspires.ftc.teamcode.Variables.system_funcs.tp import org.firstinspires.ftc.teamcode.Variables.system_vars import org.firstinspires.ftc.teamcode.Variables.system_vars.intakeInit class Intake { val intakeMotor = hardwareMap.dcMotor.get("INTAKE") val intakeServo = hardwareMap.servo.get("INTAKEPOS") val lidServo = hardwareMap.servo.get("LID") fun init(){ intakeServo.position = intakePosTop lidServo.position = lidClosePos autoupdate_tp(tp, "INTAKE", "INITIALIZED") } fun take(){ // intakeServo.position = intakeInit intakeMotor.power = intakeMotorPower } fun spit(){ // intakeServo.position = intakeInit intakeMotor.power = -intakeMotorPower } fun run(){ intakeMotor.power = lom.gamepad2.left_stick_y.toDouble() if(intakeMotor.power != 0.0){ autoupdate_tp(tp, "INTAKE", "RUNNING") } } fun stop(){ intakeMotor.power = 0.0 } var position: Int = 5 fun changepos(){ intakeServo.position = when (position) { 5 -> intakePosTop 4 -> intakePosFour 3 -> intakePosThree 2 -> intakePosTwo else -> intakeInit } --position if (position == 0) { position = 5 } } fun changelidpos(){ if(posdiff(lidServo.position, lidClosePos)) lidServo.position = lidOpenPos else{ lidServo.position = lidClosePos } } }
0
Kotlin
0
0
d5793f78f332e4583e4882b739344bc5a01f5104
2,584
FIREFLY
BSD 3-Clause Clear License
src/me/anno/remsstudio/gpu/DrawSVGv2.kt
AntonioNoack
266,471,164
false
{"Kotlin": 996755, "GLSL": 6755, "Java": 1308}
package me.anno.remsstudio.gpu import me.anno.gpu.buffer.StaticBuffer import me.anno.gpu.drawing.SVGxGFX import me.anno.gpu.texture.Clamping import me.anno.gpu.texture.Texture2D import me.anno.remsstudio.gpu.GFXx3Dv2.defineAdvancedGraphicalFeatures import me.anno.remsstudio.gpu.GFXx3Dv2.shader3DUniforms import me.anno.remsstudio.objects.GFXTransform import org.joml.Matrix4fArrayList import org.joml.Vector4f object GFXxSVGv2 { fun draw3DSVG( video: GFXTransform, time: Double, stack: Matrix4fArrayList, buffer: StaticBuffer, texture: Texture2D, color: Vector4f, filtering: TexFiltering, clamping: Clamping, tiling: Vector4f? ) { val shader = ShaderLibV2.shader3DSVG.value shader.use() shader3DUniforms(shader, stack, texture.width, texture.height, color, filtering, null) texture.bind(0, filtering.convert(), clamping) defineAdvancedGraphicalFeatures(shader, video, time, false) SVGxGFX.draw(stack, buffer, clamping, tiling, shader) } }
2
Kotlin
3
19
c9c0d366d1f2d08a57da72f7315bb161579852f2
1,025
RemsStudio
Apache License 2.0
app/src/main/java/com/rifqimfahmi/alldogbreeds/ui/breeds/adapter/AdapterDogBreeds.kt
rifqimfahmi
125,337,589
false
null
package com.rifqimfahmi.alldogbreeds.ui.breeds.adapter import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.rifqimfahmi.alldogbreeds.R import com.rifqimfahmi.alldogbreeds.ui.base.helper.RecyclerViewActionListener import com.rifqimfahmi.alldogbreeds.util.CommonUtils import kotlinx.android.synthetic.main.item_dog_breed.view.* /* * Created by <NAME> on 19/02/18. */ class AdapterDogBreeds(context: Context) : RecyclerView.Adapter<AdapterDogBreeds.ItemDogBreed>() { val mDogBreed: ArrayList<String> = ArrayList() val mActionItemListener: RecyclerViewActionListener<String> = context as RecyclerViewActionListener<String> override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemDogBreed { val view: View = LayoutInflater.from(parent.context).inflate(R.layout.item_dog_breed, parent, false) return ItemDogBreed(view) } override fun getItemCount(): Int { return mDogBreed.size } override fun onBindViewHolder(holder: ItemDogBreed, position: Int) { holder.bind(mDogBreed[position], mActionItemListener) } fun addData(data: List<String>) { mDogBreed.addAll(data) notifyDataSetChanged() } fun removeAllData() { mDogBreed.clear() } class ItemDogBreed(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(breed: String, mActionItemListener: RecyclerViewActionListener<String>) { itemView.textview_breed.text = CommonUtils.uppercaseTheFirstLetter(breed) itemView.setOnClickListener { mActionItemListener.onItemClick(breed) } } } }
0
Kotlin
1
4
b29dfdd8c690780f649825ef471ab8c590bebd0c
1,762
all-dog-breeds
Apache License 2.0
feature_home/src/main/java/id/co/moviebox/home/vm/HomeVM.kt
zacky-dzacky
659,563,008
false
null
package id.co.moviebox.home.vm import androidx.lifecycle.ViewModel import id.co.moviebox.base_component.extention.StatefulLiveData import id.co.moviebox.service_genre.domain.entity.GetUserReq import id.co.moviebox.service_genre.domain.usecase.GetUsersUseCase import javax.inject.Inject import androidx.lifecycle.viewModelScope class HomeVM @Inject constructor( private val getUsersUseCase: GetUsersUseCase ): ViewModel(), HomeContract.Presenter { override val user = StatefulLiveData(getUsersUseCase, viewModelScope) override fun getUser() { user.get(GetUserReq.DEFAULT) } }
0
Kotlin
0
0
4ad101b9c1c0396bd6f7d371afe91ab59cf037cd
606
MovieBox
Apache License 2.0
koin-projects/koin-androidx-viewmodel/src/main/java/org/koin/androidx/viewmodel/koin/KoinExt.kt
scottyab
224,416,331
true
{"Kotlin": 448333, "HTML": 8581, "Java": 7816, "JavaScript": 4873, "CSS": 827, "Shell": 378}
package org.koin.androidx.viewmodel.koin import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.ViewModel import androidx.savedstate.SavedStateRegistryOwner import org.koin.androidx.viewmodel.ViewModelParameter import org.koin.androidx.viewmodel.scope.getViewModel import org.koin.core.Koin import org.koin.core.parameter.ParametersDefinition import org.koin.core.qualifier.Qualifier import kotlin.reflect.KClass inline fun <reified T : ViewModel> Koin.viewModel( owner: LifecycleOwner, qualifier: Qualifier? = null, noinline parameters: ParametersDefinition? = null ): Lazy<T> { return lazy { rootScope.getViewModel<T>(owner, qualifier, parameters) } } inline fun <reified T : ViewModel> Koin.viewModel( owner: SavedStateRegistryOwner, qualifier: Qualifier? = null, noinline parameters: ParametersDefinition? = null ): Lazy<T> { return lazy { rootScope.getViewModel<T>(owner, qualifier, parameters) } } inline fun <reified T : ViewModel> Koin.getViewModel( owner: LifecycleOwner, qualifier: Qualifier? = null, noinline parameters: ParametersDefinition? = null ): T { return rootScope.getViewModel(owner, qualifier, parameters) } inline fun <reified T : ViewModel> Koin.getViewModel( owner: SavedStateRegistryOwner, qualifier: Qualifier? = null, noinline parameters: ParametersDefinition? = null ): T { return rootScope.getViewModel(owner, qualifier, parameters) } fun <T : ViewModel> Koin.getViewModel( owner: LifecycleOwner, clazz: KClass<T>, qualifier: Qualifier? = null, parameters: ParametersDefinition? = null ): T { return rootScope.getViewModel(owner, clazz, qualifier, parameters) } fun <T : ViewModel> Koin.getViewModel( owner: SavedStateRegistryOwner, clazz: KClass<T>, qualifier: Qualifier? = null, parameters: ParametersDefinition? = null ): T { return rootScope.getViewModel(owner, clazz, qualifier, parameters) } fun <T : ViewModel> Koin.getViewModel(viewModelParameters: ViewModelParameter<T>): T { return rootScope.getViewModel(viewModelParameters) }
0
null
0
0
ddc680884bd66a8a3dd3719f0ad9def791b32929
2,095
koin
Apache License 2.0
src/main/kotlin/me/jinuo/imf/websocket/client/WebSocketClientHandler.kt
17844560
244,380,015
false
null
package me.jinuo.imf.websocket.client import me.jinuo.imf.websocket.codec.message.MessageState import me.jinuo.imf.websocket.handler.DefaultDispatcher import me.jinuo.imf.websocket.session.DefaultSessionManager import me.jinuo.imf.websocket.session.Session import org.springframework.web.socket.BinaryMessage import org.springframework.web.socket.CloseStatus import org.springframework.web.socket.WebSocketSession import org.springframework.web.socket.handler.BinaryWebSocketHandler import javax.annotation.Resource /** * @author frank * @date 2019-11-14 17:24 * @desc **/ class WebSocketClientHandler : BinaryWebSocketHandler() { companion object { val CLIENT_KEY = "WEBSOCKET_CLIENT_KEY" } @Resource private lateinit var sessionManager: DefaultSessionManager @Resource private lateinit var dispatcher: DefaultDispatcher @Resource private lateinit var clientFactory: ClientFactory override fun handleBinaryMessage(webSession: WebSocketSession, binaryMessage: BinaryMessage) { val session = webSession.attributes[Session.SESSION_KEY] as Session val message = dispatcher.decode(binaryMessage) message ?: return if (message.header.hasState(MessageState.RESPONSE.state)) { val client = session.getAttr<Client>(CLIENT_KEY) client ?: return return client.receiver(message) } dispatcher.receiver(session, binaryMessage) } override fun afterConnectionClosed(webSession: WebSocketSession, status: CloseStatus) { val session = webSession.attributes[Session.SESSION_KEY] as Session sessionManager.destroySession(session) } }
0
Kotlin
0
1
3f0ea7867f76912421123e1bc7c1b74eaf7836e3
1,683
hulk-spring-boot-starter
Apache License 2.0
ggdsl-dataframe-lets-plot/src/main/kotlin/org/jetbrains/kotlinx/ggdsl/dataframe/letsplot/layers/qq2Line.kt
Kotlin
502,039,936
false
null
/* * Copyright 2020-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package org.jetbrains.kotlinx.ggdsl.dataframe.letsplot.layers /* import org.jetbrains.kotlinx.dataframe.columns.ColumnReference import org.jetbrains.kotlinx.ggdsl.dataframe.toColRef import org.jetbrains.kotlinx.ggdsl.dsl.contexts.PlotContext import org.jetbrains.kotlinx.ggdsl.letsplot.layers.QQ2LineContext import org.jetbrains.kotlinx.ggdsl.letsplot.layers.qq2Line public inline fun <reified T, reified R> PlotContext.qq2Line( sourceX: ColumnReference<T>, sourceY: org.jetbrains.kotlinx.ggdsl.ir.data.ColumnPointer<R>, quantiles: Pair<Double, Double>? = null, block: QQ2LineContext.() -> Unit <<<<<<< HEAD ) = qq2Line(sourceX.toColRef(), sourceY, quantiles, block) inline fun <reified T, reified R: Any> PlotContext.qq2Line( sourceX: org.jetbrains.kotlinx.ggdsl.ir.data.ColumnPointer<T>, sourceY: ColumnReference<R>, quantiles: Pair<Double, Double>? = null, block: QQ2LineContext.() -> Unit ) = qq2Line(sourceX, sourceY.toColRef(), quantiles, block) ======= ): Unit = qq2Line(sourceX.toDataSource(), sourceY, quantiles, block) public inline fun <reified T, reified R> PlotContext.qq2Line( sourceX: DataSource<T>, sourceY: ColumnReference<R>, quantiles: Pair<Double, Double>? = null, block: QQ2LineContext.() -> Unit ): Unit = qq2Line(sourceX, sourceY.toDataSource(), quantiles, block) >>>>>>> main public inline fun <reified T, reified R> PlotContext.qq2Line( sourceX: ColumnReference<T>, sourceY: ColumnReference<R>, quantiles: Pair<Double, Double>? = null, block: QQ2LineContext.() -> Unit <<<<<<< HEAD ) = qq2Line(sourceX.toColRef(), sourceY.toColRef(), quantiles, block) ======= ): Unit = qq2Line(sourceX.toDataSource(), sourceY.toDataSource(), quantiles, block) >>>>>>> main */
55
Kotlin
2
29
647ebddd2e09173facf6be67cd4ba5a7c81f6d2a
1,863
ggdsl
Apache License 2.0
src/main/kotlin/com/liquidforte/roguelike/builders/Path.kt
cwzero
315,412,403
false
null
package com.liquidforte.roguelike.builders import com.liquidforte.roguelike.blocks.GameBlocks import com.liquidforte.roguelike.extensions.neighbors import com.liquidforte.roguelike.extensions.orthogonalNeighbors import org.hexworks.zircon.api.data.Position import java.lang.Math.sqrt import java.util.* class Path(origin: Position, private val destination: Position) : Stack<Position>() { init { push(origin) } var valid = true fun validate(level: Level) : Boolean { return valid } fun place(level: Level) : Boolean { forEach { level[it] = GameBlocks.roughFloor() } println("connected $destination in $size moves") return true } val current: Position get() = peek() val isComplete: Boolean get() = current.distanceTo(destination) <= 1 fun Position.distanceTo(pos: Position): Double { val deltaX = x - pos.x val deltaY = y - pos.y val d2 = (deltaX * deltaX) + (deltaY * deltaY) return sqrt(d2.toDouble()) } }
0
Kotlin
0
0
ed94313fc89f659d3d1721bfb82be8c09484fc5b
1,067
Roguelike
MIT License
komga/src/main/kotlin/org/gotson/komga/infrastructure/sidecar/SidecarSeriesConsumer.kt
gotson
201,228,816
false
{"Kotlin": 1891230, "Vue": 780324, "TypeScript": 187341, "HTML": 3499, "Smarty": 3190, "JavaScript": 2121, "CSS": 415, "Sass": 309}
package org.gotson.komga.infrastructure.sidecar import org.gotson.komga.domain.model.Sidecar interface SidecarSeriesConsumer { fun getSidecarSeriesType(): Sidecar.Type fun getSidecarSeriesFilenames(): List<String> }
86
Kotlin
240
4,029
6cc14e30beac7598284b9ceb2cdaf18da5aed76c
223
komga
MIT License
httpserver/src/test/kotlin/tbdex/sdk/httpserver/handlers/CreateExchangeTest.kt
TBD54566975
696,627,382
false
{"Kotlin": 190328, "Shell": 2116}
package tbdex.sdk.httpserver.handlers import ServerTest import TestData.aliceDid import TestData.createRfq import io.ktor.client.request.post import io.ktor.client.request.setBody import io.ktor.client.statement.bodyAsText import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode import io.ktor.http.contentType import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.Test import tbdex.sdk.httpclient.models.CreateExchangeRequest import tbdex.sdk.httpclient.models.ErrorResponse import tbdex.sdk.protocol.serialization.Json import kotlin.test.assertContains import kotlin.test.assertEquals class CreateExchangeTest : ServerTest() { @Test fun `returns BadRequest if no request body is provided`() = runBlocking { val response = client.post("/exchanges") { contentType(ContentType.Application.Json) } val errorResponse = Json.jsonMapper.readValue(response.bodyAsText(), ErrorResponse::class.java) assertEquals(HttpStatusCode.BadRequest, response.status) assertContains(errorResponse.errors.first().detail, "Parsing of TBDex createExchange request failed") } @Test fun `returns Conflict if rfq already exists for a given exchangeId`() = runBlocking { val rfq = createRfq() rfq.sign(aliceDid) exchangesApi.addMessage(rfq) val response = client.post("/exchanges") { contentType(ContentType.Application.Json) setBody(CreateExchangeRequest(rfq)) } val errorResponse = Json.jsonMapper.readValue(response.bodyAsText(), ErrorResponse::class.java) assertEquals(HttpStatusCode.Conflict, response.status) assertContains(errorResponse.errors.first().detail, "RFQ already exists.") } @Test fun `returns BadRequest if rfq does not fit offering requirements`() = runBlocking { val rfq = createRfq(null, listOf("foo")) rfq.sign(aliceDid) val response = client.post("/exchanges") { contentType(ContentType.Application.Json) setBody(CreateExchangeRequest(rfq)) } val errorResponse = Json.jsonMapper.readValue(response.bodyAsText(), ErrorResponse::class.java) assertEquals(HttpStatusCode.BadRequest, response.status) assertContains(errorResponse.errors.first().detail, "Failed to verify offering requirements") } @Test fun `returns BadRequest if replyTo is an invalid URL`() = runBlocking { val rfq = createRfq() rfq.sign(aliceDid) val response = client.post("/exchanges") { contentType(ContentType.Application.Json) setBody(CreateExchangeRequest(rfq, "foo")) } val errorResponse = Json.jsonMapper.readValue(response.bodyAsText(), ErrorResponse::class.java) assertEquals(HttpStatusCode.BadRequest, response.status) assertContains(errorResponse.errors.first().detail, "replyTo must be a valid URL") } @Test fun `returns Accepted if rfq is accepted`() = runBlocking { val rfq = createRfq(offeringsApi.getOffering("123")) rfq.sign(aliceDid) val response = client.post("/exchanges") { contentType(ContentType.Application.Json) setBody(CreateExchangeRequest(rfq, "http://localhost:9000/callback")) } assertEquals(HttpStatusCode.Accepted, response.status) } }
34
Kotlin
3
3
51369565314a68078b3192ddc0a613908f072d5b
3,184
tbdex-kt
Apache License 2.0
src/main/kotlin/nl/bjornvanderlaan/livedemospringwebflux/service/PersonService.kt
BjornvdLaan
507,929,903
false
{"Kotlin": 25185}
package nl.bjornvanderlaan.livedemospringwebflux.service import nl.bjornvanderlaan.livedemospringwebflux.model.Person import nl.bjornvanderlaan.livedemospringwebflux.repository.PersonRepository import org.springframework.stereotype.Service import reactor.core.publisher.Mono @Service class PersonService(private val personRepository: PersonRepository) { fun getPersonById(id: Long): Mono<Person> = personRepository.findById(id) }
0
Kotlin
1
0
78872771f5d93f108b1875ed746b890af2c4a573
443
live-demo-spring-webflux-kotlin
MIT License
lib/src/main/java/com/github/provider/PreferencesCursor.kt
pnemonic78
149,122,819
false
{"Kotlin": 217053}
/* * Copyright 2016, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.provider import android.database.MatrixCursor /** * Cursor wrapper for a single preference value. * * @author <NAME> */ class PreferencesCursor : MatrixCursor { constructor() : super( arrayOf<String>( Preferences.Columns.KEY, Preferences.Columns.VALUE, Preferences.Columns.TYPE ), 0 ) constructor( type: String, key: String, value: Any? ) : super( arrayOf<String>( Preferences.Columns.KEY, Preferences.Columns.VALUE, Preferences.Columns.TYPE ), 1 ) { addRow(arrayOf(key, value, type)) } constructor(types: List<String?>, keys: List<String?>, values: List<Any?>) : super( arrayOf<String>( Preferences.Columns.KEY, Preferences.Columns.VALUE, Preferences.Columns.TYPE ), values.size ) { val count = values.size val row = arrayOfNulls<Any>(3) for (i in 0 until count) { row[INDEX_TYPE] = types[i] row[INDEX_KEY] = keys[i] row[INDEX_VALUE] = values[i] addRow(row) } } override fun getColumnIndex(columnName: String): Int { return when (columnName) { Preferences.Columns.KEY -> INDEX_KEY Preferences.Columns.VALUE -> INDEX_VALUE Preferences.Columns.TYPE -> INDEX_TYPE else -> -1 } } companion object { private const val INDEX_KEY = 0 private const val INDEX_VALUE = 1 private const val INDEX_TYPE = 2 } }
0
Kotlin
0
1
7464e3e3c9aff0de8a868619fcfb347995534be9
2,250
android-lib
Apache License 2.0
lib/src/main/java/com/github/provider/PreferencesCursor.kt
pnemonic78
149,122,819
false
{"Kotlin": 217053}
/* * Copyright 2016, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.provider import android.database.MatrixCursor /** * Cursor wrapper for a single preference value. * * @author <NAME> */ class PreferencesCursor : MatrixCursor { constructor() : super( arrayOf<String>( Preferences.Columns.KEY, Preferences.Columns.VALUE, Preferences.Columns.TYPE ), 0 ) constructor( type: String, key: String, value: Any? ) : super( arrayOf<String>( Preferences.Columns.KEY, Preferences.Columns.VALUE, Preferences.Columns.TYPE ), 1 ) { addRow(arrayOf(key, value, type)) } constructor(types: List<String?>, keys: List<String?>, values: List<Any?>) : super( arrayOf<String>( Preferences.Columns.KEY, Preferences.Columns.VALUE, Preferences.Columns.TYPE ), values.size ) { val count = values.size val row = arrayOfNulls<Any>(3) for (i in 0 until count) { row[INDEX_TYPE] = types[i] row[INDEX_KEY] = keys[i] row[INDEX_VALUE] = values[i] addRow(row) } } override fun getColumnIndex(columnName: String): Int { return when (columnName) { Preferences.Columns.KEY -> INDEX_KEY Preferences.Columns.VALUE -> INDEX_VALUE Preferences.Columns.TYPE -> INDEX_TYPE else -> -1 } } companion object { private const val INDEX_KEY = 0 private const val INDEX_VALUE = 1 private const val INDEX_TYPE = 2 } }
0
Kotlin
0
1
7464e3e3c9aff0de8a868619fcfb347995534be9
2,250
android-lib
Apache License 2.0
src/main/java/com/metriql/dbt/DbtModelService.kt
metriql
370,169,788
false
null
package com.metriql.dbt import com.hubspot.jinjava.Jinjava import com.hubspot.jinjava.interpret.JinjavaInterpreter import com.hubspot.jinjava.lib.filter.Filter import com.metriql.db.FieldType import com.metriql.report.ReportType import com.metriql.report.data.recipe.Recipe import com.metriql.report.data.recipe.Recipe.Dependencies.DbtDependency import com.metriql.report.segmentation.SegmentationService import com.metriql.service.auth.ProjectAuth import com.metriql.service.jinja.JinjaRendererService import com.metriql.service.model.IDatasetService import com.metriql.service.model.Model.MappingDimensions.CommonMappings.EVENT_TIMESTAMP import com.metriql.service.model.UpdatableDatasetService import com.metriql.util.JsonHelper import com.metriql.util.MetriqlException import com.metriql.util.YamlHelper import com.metriql.warehouse.spi.DataSource import com.metriql.warehouse.spi.bridge.WarehouseMetriqlBridge import com.metriql.warehouse.spi.querycontext.DependencyFetcher import com.metriql.warehouse.spi.querycontext.QueryGeneratorContext import com.metriql.warehouse.spi.services.MaterializeQuery.Companion.defaultModelName import org.rakam.server.http.HttpServer import javax.inject.Inject class DbtModelService @Inject constructor( private val renderer: JinjaRendererService, private val modelService: IDatasetService?, private val dependencyFetcher: DependencyFetcher ) { private val jinja = Jinjava() init { jinja.globalContext.registerFilter(object : Filter { override fun getName() = "toJson" override fun filter(param: Any?, p1: JinjavaInterpreter?, vararg p2: String?) = JsonHelper.encode(param) }) } fun addDbtFiles( auth: ProjectAuth, committer: FileHandler, recipe: Recipe, dataSource: DataSource, recipeId: Int, ): List<HttpServer.JsonAPIError> { val directory = recipe.getDependenciesWithFallback().dbtDependency().aggregatesDirectory() committer.deletePath(directory) val (_, _, modelConfigMapper) = dataSource.dbtSettings() val models = recipe.models?.map { it.toModel(recipe.packageName ?: "", dataSource.warehouse.bridge, recipeId) } ?: listOf() val modelService = UpdatableDatasetService(modelService) { models } val context = QueryGeneratorContext( auth, dataSource, modelService, renderer, reportExecutor = null, userAttributeFetcher = null, dependencyFetcher = dependencyFetcher ) val segmentationService = SegmentationService() val errors = mutableListOf<HttpServer.JsonAPIError>() recipe.models?.forEach { model -> model.getMaterializes().forEach { materialize -> val modelName = model.name!! val (target, rawRenderedSql) = try { segmentationService.generateMaterializeQuery(auth.projectId, context, modelName, materialize.name, materialize.value) } catch (e: MetriqlException) { errors.add(HttpServer.JsonAPIError.title("Unable to create materialize ${model.name}.${materialize.name}: $e")) return@forEach } val renderedQuery = context.datasource.warehouse.bridge.generateQuery(context.viewModels, rawRenderedSql) val eventTimestamp = model.mappings?.get(EVENT_TIMESTAMP) val (materialized, renderedSql) = if (eventTimestamp != null) { val eventTimestampDim = materialize.value.dimensions?.find { d -> d.name == eventTimestamp && d.relation == null } ?.toDimension(modelName, FieldType.TIMESTAMP)!! val eventDimensionAlias = context.getDimensionAlias( eventTimestamp, null, eventTimestampDim.postOperation ) val renderedEventTimestampDimension = dataSource.warehouse.bridge.renderDimension( context, modelName, eventTimestamp, null, null, WarehouseMetriqlBridge.MetricPositionType.FILTER ) val query = """SELECT * FROM ($renderedQuery) AS $modelName {% if is_incremental() %} WHERE ${renderedEventTimestampDimension.value} > (select max($eventDimensionAlias) from {{ this }}) {% endif %} """.trimIndent() "incremental" to query } else { "table" to renderedQuery } val materializedModelName = materialize.value.getModelName() ?: defaultModelName(modelName, materialize.reportType, materialize.name) val schema = recipe.getDependenciesWithFallback().dbtDependency().aggregateSchema() val config = modelConfigMapper.invoke(Triple(materializedModelName, target.copy(schema = schema), mapOf("materialized" to materialized))) val configs = jinja.render(CONFIG_TEMPLATE, mapOf("configs" to config, "tagName" to tagName)) committer.addFile("$directory/$materializedModelName.sql", configs + "\n" + renderedSql) } } return errors } fun createProfiles(dataSource: DataSource, dependency: DbtDependency): String { val (dbType, credentials, _) = dataSource.dbtSettings() return YamlHelper.mapper.writeValueAsString( mapOf( dependency.profiles() to mapOf( "target" to "prod", "outputs" to mapOf("prod" to mapOf("type" to dbType) + credentials) ) ) ) } companion object { val CONFIG_TEMPLATE = this::class.java.getResource("/dbt/model.sql.jinja2").readText() const val tagName = "metriql_materialize" } }
30
Kotlin
19
253
10fa42434c19d1dbfb9a3d04becea679bb82d0f1
5,950
metriql
Apache License 2.0
Tools/src/main/java/com/eliza/android/tools/logger/TextTools.kt
Elizabevil
490,163,884
false
{"Kotlin": 790257, "Java": 223641}
package com.eliza.android.tools.logger import android.text.TextUtils /*-*- coding:utf-8 -*- * @Author : debi * @Time : 5/2/22 * @Software: Android Studio */ object TextTools { fun StringToInt(info: String?, defaultValue: Int = 0): Int { var value = defaultValue value = if (info.isNullOrEmpty() && info.isNullOrBlank()) { defaultValue } else if (TextUtils.isDigitsOnly(info)) { info.toInt() } else { defaultValue } return value } fun StringNullToBlank(info: String?, defaultValue: String = ""): String { var value = if (info.isNullOrEmpty()) { info.toString() } else { defaultValue } return value } }
0
Kotlin
0
0
877ce3cebe428a72f01327303ec3e44c1a4925de
834
Asip
Apache License 2.0
domain/src/main/kotlin/com/xinh/domain/param/LoginParam.kt
alvinmarshall
230,596,209
true
{"Kotlin": 182918, "Java": 67}
package com.xinh.domain.param data class LoginParam( var email: String? = null, var password: String? = null, var token: String? = null, var loginTypeParam: LoginTypeParam = LoginTypeParam.EMAIL ) enum class LoginTypeParam { EMAIL, TOKEN, FACEBOOK, GOOGLE }
0
null
0
0
06d68aac75481a1dcdab74bb5e09794bfa7352c0
279
mvvm-clean-architecture
MIT License
app-inspection/inspectors/backgroundtask/ide/src/com/android/tools/idea/appinspection/inspectors/backgroundtask/ide/IdeBackgroundTaskInspectorTracker.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.appinspection.inspectors.backgroundtask.ide import com.android.tools.analytics.UsageTracker import com.android.tools.idea.appinspection.inspectors.backgroundtask.model.BackgroundTaskInspectorTracker import com.android.tools.idea.stats.AnonymizerUtil import com.google.wireless.android.sdk.stats.AndroidStudioEvent import com.google.wireless.android.sdk.stats.AppInspectionEvent import com.google.wireless.android.sdk.stats.AppInspectionEvent.BackgroundTaskInspectorEvent import com.intellij.openapi.project.Project class IdeBackgroundTaskInspectorTracker(private val project: Project) : BackgroundTaskInspectorTracker { private var activeMode = BackgroundTaskInspectorEvent.Mode.TABLE_MODE override fun trackTableModeSelected() { track( BackgroundTaskInspectorEvent.Context.TOOL_BUTTON_CONTEXT, BackgroundTaskInspectorEvent.Type.TABLE_MODE_SELECTED.toEvent(), ) activeMode = BackgroundTaskInspectorEvent.Mode.TABLE_MODE } override fun trackGraphModeSelected( context: BackgroundTaskInspectorEvent.Context, chainInfo: BackgroundTaskInspectorEvent.ChainInfo, ) { val event = BackgroundTaskInspectorEvent.Type.GRAPH_MODE_SELECTED.toEvent().setChainInfo(chainInfo) track(context, event) activeMode = BackgroundTaskInspectorEvent.Mode.GRAPH_MODE } override fun trackJumpedToSource() { track( BackgroundTaskInspectorEvent.Context.DETAILS_CONTEXT, BackgroundTaskInspectorEvent.Type.JUMPED_TO_SOURCE.toEvent(), ) } override fun trackWorkCancelled() { track( BackgroundTaskInspectorEvent.Context.TOOL_BUTTON_CONTEXT, BackgroundTaskInspectorEvent.Type.WORK_CANCELED.toEvent(), ) } private fun BackgroundTaskInspectorEvent.Type.toEvent(): BackgroundTaskInspectorEvent.Builder { return BackgroundTaskInspectorEvent.newBuilder().setType(this) } override fun trackWorkSelected(context: BackgroundTaskInspectorEvent.Context) { track(context, BackgroundTaskInspectorEvent.Type.WORK_SELECTED.toEvent()) } override fun trackJobSelected() { track( BackgroundTaskInspectorEvent.Context.TABLE_CONTEXT, BackgroundTaskInspectorEvent.Type.JOB_SELECTED.toEvent(), ) } override fun trackJobUnderWorkSelected() { track( BackgroundTaskInspectorEvent.Context.TABLE_CONTEXT, BackgroundTaskInspectorEvent.Type.JOB_UNDER_WORK_SELECTED.toEvent(), ) } override fun trackAlarmSelected() { track( BackgroundTaskInspectorEvent.Context.TABLE_CONTEXT, BackgroundTaskInspectorEvent.Type.ALARM_SELECTED.toEvent(), ) } override fun trackWakeLockSelected() { track( BackgroundTaskInspectorEvent.Context.TABLE_CONTEXT, BackgroundTaskInspectorEvent.Type.WAKE_LOCK_SELECTED.toEvent(), ) } override fun trackWakeLockUnderJobSelected() { track( BackgroundTaskInspectorEvent.Context.TABLE_CONTEXT, BackgroundTaskInspectorEvent.Type.WAKE_LOCK_UNDER_JOB_SELECTED.toEvent(), ) } // Note: We could have just set |context| directly before calling track, but making it a // parameter ensures we never forget to do so. private fun track( context: BackgroundTaskInspectorEvent.Context, inspectorEvent: BackgroundTaskInspectorEvent.Builder, ) { inspectorEvent.context = context inspectorEvent.mode = activeMode val inspectionEvent = AppInspectionEvent.newBuilder() .setType(AppInspectionEvent.Type.INSPECTOR_EVENT) .setBackgroundTaskInspectorEvent(inspectorEvent) val studioEvent: AndroidStudioEvent.Builder = AndroidStudioEvent.newBuilder() .setKind(AndroidStudioEvent.EventKind.APP_INSPECTION) .setAppInspectionEvent(inspectionEvent) // TODO(b/153270761): Use studioEvent.withProjectId instead, after code is moved out of // monolithic core module studioEvent.projectId = AnonymizerUtil.anonymizeUtf8(project.basePath!!) UsageTracker.log(studioEvent) } }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
4,610
android
Apache License 2.0
src/main/kotlin/tech/challenge/orderservice/domain/ports/out/PedidoGatewayPort.kt
posgraduacao342
749,071,824
false
{"Kotlin": 137033, "Dockerfile": 559, "Gherkin": 180}
package tech.challenge.orderservice.domain.ports.out import tech.challenge.orderservice.domain.enums.PedidoSortingOptions import org.springframework.data.domain.Sort import tech.challenge.orderservice.domain.entities.Pedido import tech.challenge.orderservice.domain.enums.StatusPedido import java.util.* interface PedidoGatewayPort { fun buscarPedidos(sortingProperty: Optional<PedidoSortingOptions>, direction: Optional<Sort.Direction>): List<Pedido> fun buscarPedidosPorStatusPedido(statusPedidoList: List<StatusPedido>, sort: Sort): List<Pedido> fun buscarPedidoPorId(id: UUID): Pedido? fun salvarPedido(pedido: Pedido): Pedido fun deletarPedido(id: UUID) }
0
Kotlin
0
0
1efe7caf4b17e90669493d4e9dfd77a5091cb03f
687
tech-challenge-orders-service
Apache License 2.0
domain/src/main/kotlin/io/github/beomjo/search/usecase/GetSearchPagingData.kt
beomjo
388,829,504
false
null
/* * Designed and developed by 2021 beomjo * * 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.github.beomjo.search.usecase import androidx.paging.PagingData import io.github.beomjo.search.entity.* import io.github.beomjo.search.repository.SearchRepository import io.github.beomjo.search.usecase.base.PagingUseCase import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.onStart import java.util.Date import javax.inject.Inject data class SearchPagingParam( val documentType: DocumentType, val sortType: SortType, val query: String, val sort: Sort = Sort.ACCURACY, val date: Date = Date() ) class GetSearchPagingData @Inject constructor( private val searchRepository: SearchRepository ) : PagingUseCase<SearchPagingParam, SearchDocument>() { override fun execute(param: SearchPagingParam): Flow<PagingData<SearchDocument>> { return searchRepository.getDocumentPagingData(param) .onStart { searchRepository.insertSearchHistory( History( query = param.query, date = param.date ) ) } } }
2
Kotlin
1
2
8f4ad1d4b769fee069d5d4ed7f8bf3d00ee032f9
1,702
kakao-search
Apache License 2.0
dbinspector/src/test/kotlin/com/infinum/dbinspector/domain/pragma/interactors/GetUserVersionInteractorTest.kt
infinum
17,116,181
false
null
package com.infinum.dbinspector.domain.pragma.interactors import com.infinum.dbinspector.data.Sources import com.infinum.dbinspector.domain.Interactors import com.infinum.dbinspector.shared.BaseTest import io.mockk.coEvery import io.mockk.coVerify import io.mockk.mockk import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.koin.core.module.Module import org.koin.dsl.module import org.koin.test.get import org.mockito.kotlin.any @DisplayName("GetUserVersionInteractor tests") internal class GetUserVersionInteractorTest : BaseTest() { override fun modules(): List<Module> = listOf( module { single { mockk<Sources.Local.Pragma>() } factory<Interactors.GetUserVersion> { GetUserVersionInteractor(get()) } } ) @Test fun `Invoking interactor invokes source getUserVersion`() { val interactor: Interactors.GetUserVersion = get() val source: Sources.Local.Pragma = get() coEvery { source.getUserVersion(any()) } returns mockk() launch { interactor.invoke(any()) } coVerify(exactly = 1) { source.getUserVersion(any()) } } }
0
Kotlin
88
902
8d2d695ba35e7b0682e2dc235f5a852bf0fa4db3
1,178
android_dbinspector
Apache License 2.0
features/taxi/src/main/kotlin/by/anegin/vkcup21/features/taxi/data/OrderManager.kt
eugene-kirzhanov
385,482,551
false
null
package by.anegin.vkcup21.features.taxi.data import by.anegin.vkcup21.features.taxi.data.models.Route import by.anegin.vkcup21.features.taxi.data.models.RouteDetails internal interface OrderManager { suspend fun calculateRouteDetails(route: Route): RouteDetails }
0
Kotlin
0
0
00afa06d424810fe80675e333facfd42d6b2b75d
271
vkcup21
MIT License
app/src/main/java/com/abdoul/myweather/model/forecast/Coord.kt
Abdoul02
333,489,372
false
{"Kotlin": 44669}
package com.abdoul.myweather.model.forecast data class Coord( val lat: Double, val lon: Double )
0
Kotlin
0
0
3966d2717ba3dc21d3b1b6f083e2ca6ebcc5208c
105
My-Weather
Apache License 2.0
test/com/nbottarini/asimov/flagz/manager/metadata/FeatureMetadataTest.kt
nbottarini
445,562,246
false
{"Kotlin": 59043}
package com.nbottarini.asimov.flagz.manager.metadata import com.nbottarini.asimov.flagz.Feature import com.nbottarini.asimov.flagz.conditionalStrategies.UsersStrategy import com.nbottarini.asimov.flagz.conditionalStrategies.UsersStrategy.Companion.PARAM_USERS import com.nbottarini.asimov.flagz.conditionalStrategies.annotations.Conditional import com.nbottarini.asimov.flagz.conditionalStrategies.annotations.Param import com.nbottarini.asimov.flagz.EnabledByDefault import com.nbottarini.asimov.flagz.manager.metadata.FeatureMetadataTest.Features.* import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class FeatureMetadataTest { @Test fun `feature is enabled by default if has the EnabledByDefault annotation`() { assertThat(ENABLED_BY_DEFAULT_FEATURE.metadata().isEnabledByDefault).isTrue } @Test fun `feature is not enabled by default if has the EnabledByDefault annotation`() { assertThat(SIMPLE_FEATURE.metadata().isEnabledByDefault).isFalse } @Test fun `feature metadata has conditional strategy id if has an Conditional annotation`() { assertThat(CONDITIONAL_FEATURE.metadata().strategyId).isEqualTo(UsersStrategy.ID) } @Test fun `feature metadata has conditional strategy parameters if has an Conditional annotation`() { assertThat(CONDITIONAL_FEATURE.metadata().strategyParams).isEqualTo(mapOf(PARAM_USERS to "alice, bob")) } @Test fun `defaultState is based on metadata info`() { val metadata = FeatureMetadata(SIMPLE_FEATURE, isEnabledByDefault = true, "some-id", mapOf("param" to "value")) val state = metadata.defaultState() assertThat(state.feature).isEqualTo(metadata.feature) assertThat(state.isEnabled).isEqualTo(metadata.isEnabledByDefault) assertThat(state.strategyId).isEqualTo(metadata.strategyId) assertThat(state.strategyParams).isEqualTo(metadata.strategyParams) } enum class Features: Feature { SIMPLE_FEATURE, @EnabledByDefault ENABLED_BY_DEFAULT_FEATURE, @Conditional(UsersStrategy.ID, [Param(PARAM_USERS, "alice, bob")]) CONDITIONAL_FEATURE, } }
0
Kotlin
0
1
82863cbadf7787ec9b7429bc96ceb81f172d139f
2,205
asimov-flagz-kt
MIT License
module/parser/src/iosTest/kotlin/org/cru/godtools/shared/tool/parser/internal/UsesResources.ios.kt
CruGlobal
310,338,913
false
{"Kotlin": 463697, "ANTLR": 1243, "Ruby": 58}
package org.cru.godtools.shared.tool.parser.internal import org.cru.godtools.shared.tool.parser.xml.IosXmlPullParserFactory import org.cru.godtools.shared.tool.parser.xml.XmlPullParserFactory import platform.Foundation.NSBundle import platform.Foundation.NSData import platform.Foundation.dataWithContentsOfFile internal actual val UsesResources.TEST_XML_PULL_PARSER_FACTORY: XmlPullParserFactory get() = object : IosXmlPullParserFactory() { override fun openFile(fileName: String) = this@TEST_XML_PULL_PARSER_FACTORY::class.qualifiedName ?.replace('.', '/')?.substringBeforeLast('/') ?.let { NSBundle.mainBundle.pathForResource(fileName, null, it) } ?.let { NSData.dataWithContentsOfFile(it) } }
4
Kotlin
1
0
34599be766fd22c1bec10a34604ea38018ce37c8
751
kotlin-mpp-godtools-tool-parser
MIT License
app/src/main/kotlin/de/ljz/questify/ui/features/settings/settingshelp/SettingsHelpUiState.kt
LJZApps
806,522,161
false
{"Kotlin": 229922}
package de.ljz.questify.ui.features.settings.settingshelp data class SettingsHelpUiState( val messageTitle: String = "", val messageDescription: String = "" )
0
Kotlin
0
0
dc04f195c507b4385b8df3cb034a410c253d6603
168
Questify-Android
MIT License
app/src/main/java/com/pilot51/voicenotify/db/AppDatabase.kt
pilot51
6,212,669
false
{"Kotlin": 151162}
/* * Copyright 2011-2024 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pilot51.voicenotify.db import androidx.room.* import androidx.room.migration.AutoMigrationSpec import com.pilot51.voicenotify.VNApplication.Companion.appContext import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.* @Database( version = 2, entities = [ App::class, Settings::class ], autoMigrations = [ AutoMigration (from = 1, to = 2, spec = AppDatabase.Migration1To2::class) ] ) @RewriteQueriesToDropUnusedColumns abstract class AppDatabase : RoomDatabase() { abstract val appDao: AppDao abstract val settingsDao: SettingsDao interface BaseDao<T> { @Insert suspend fun insert(entity: T) @Upsert suspend fun upsert(entity: T) @Delete suspend fun delete(entity: T) } @Dao interface AppDao : BaseDao<App> { @Query("SELECT * FROM apps WHERE package = :pkg") suspend fun get(pkg: String): App @Query("SELECT * FROM apps") suspend fun getAll(): List<App> @Query("SELECT EXISTS (SELECT * FROM apps WHERE package = :pkg)") suspend fun existsByPackage(pkg: String): Boolean @Query("UPDATE apps SET name = :name, is_enabled = :enabled WHERE package = :pkg") suspend fun updateByPackage(pkg: String, name: String, enabled: Boolean) /** * Updates app in database matching package name or adds if no match found. * @param app The app to add or update in the database. */ @Transaction suspend fun addOrUpdateApp(app: App) { if (existsByPackage(app.packageName)) { updateByPackage( pkg = app.packageName, name = app.label, enabled = app.enabled ) } else { insert(app) } } @Transaction suspend fun upsert(apps: List<App>) { apps.forEach { addOrUpdateApp(it) } } /** * Updates enabled value of app in database matching package name. * @param app The app to update in the database. */ @Transaction suspend fun updateAppEnable(app: App) { updateAppEnable(app.packageName, app.enabled) } @Query("UPDATE apps SET is_enabled = :enabled WHERE package = :pkg") suspend fun updateAppEnable(pkg: String, enabled: Boolean?) /** * Removes app from database matching package name. * @param app The app to remove from the database. */ @Transaction suspend fun removeApp(app: App) { removeApp(app.packageName) } @Query("DELETE FROM apps WHERE package = :pkg") suspend fun removeApp(pkg: String) } @Dao interface SettingsDao : BaseDao<Settings> { @Query("SELECT * FROM settings WHERE app_package IS NULL") fun getGlobalSettings(): Flow<Settings?> @Query("SELECT * FROM settings WHERE app_package = :pkg") fun getAppSettings(pkg: String): Flow<Settings?> @Query("SELECT EXISTS (SELECT * FROM settings WHERE app_package IS NULL)") suspend fun hasGlobalSettings(): Boolean @Query("SELECT app_package FROM settings WHERE app_package IS NOT NULL") fun packagesWithOverride(): Flow<List<String>> @Query("DELETE FROM settings WHERE app_package = :pkg") suspend fun deleteByPackage(pkg: String) } @DeleteColumn(tableName = "apps", columnName = "_id") class Migration1To2 : AutoMigrationSpec companion object { const val DB_NAME = "apps.db" private val _db = MutableStateFlow(buildDB()) val db: AppDatabase get() = _db.value @OptIn(ExperimentalCoroutinesApi::class) val globalSettingsFlow = _db.flatMapMerge { it.settingsDao.getGlobalSettings().filterNotNull() } private fun buildDB() = Room.databaseBuilder(appContext, AppDatabase::class.java, DB_NAME).build() fun resetInstance() { _db.value = buildDB() } @OptIn(ExperimentalCoroutinesApi::class) fun getAppSettingsFlow(app: App) = _db.flatMapMerge { db -> db.settingsDao.getAppSettings(app.packageName).map { it ?: Settings(appPackage = app.packageName) } } } }
45
Kotlin
56
158
af7d553c22dcfed12b05521265fd7df4383b27d5
4,358
voicenotify
Apache License 2.0
app/src/main/java/ru/n08i40k/polytechnic/next/network/data/auth/ChangePasswordRequestData.kt
N08I40K
857,687,777
false
{"Kotlin": 136530}
package ru.n08i40k.polytechnic.next.network.data.auth import kotlinx.serialization.Serializable @Serializable data class ChangePasswordRequestData(val oldPassword: String, val newPassword: String)
0
Kotlin
0
1
c98d34bd981e7405d703270fafb19fae4d6af96e
198
polytecnic-android
MIT License
shared/src/iosMain/kotlin/pe/richard/library/core/Log.kt
flight95
364,171,858
false
null
package pe.richard.library.core actual object Log { actual fun e(tag: String, msg: String, throwable: Throwable?) { println("E/$tag: $msg") throwable?.printStackTrace() } }
0
Kotlin
0
0
730dc57cb1a9723fa961f9467f6c39956838c95b
198
kmm
MIT License
android/app/src/main/java/com/example/clockwork/model/Break.kt
jonMueller-clockwork
867,044,088
false
{"Kotlin": 39711, "TypeScript": 8267, "Java": 7518, "CSS": 1745, "JavaScript": 436, "HTML": 366}
package com.example.clockwork.model import java.util.Date class Break( val scheduledStartTime: Date? = null, val scheduledEndTime: Date? = null, var startTime: Date? = null, var endTime: Date? = null ) { constructor() : this(startTime = Date()) fun isActive(currentTime: Date = Date()): Boolean { return startTime != null && endTime == null } fun breakStart() { startTime = Date() } fun backToWork() { endTime = Date() } fun displayStartTime(): Date { startTime?.let { return it } scheduledStartTime?.let { return it } return Date() } fun displayEndTime(): Date { endTime?.let { return it } if (startTime == null) { scheduledEndTime?.let { return it } } return Date() } }
0
Kotlin
0
0
4252333a9617acbe6002d4c347fdf10278a804c1
833
clockwork1
MIT No Attribution
src/main/kotlin/com/iman/bnpl/domain/branch/data/repository/BusinessBranchRepository.kt
imancn
849,339,456
false
{"Kotlin": 68054}
package com.iman.bnpl.domain.branch.data.repository import com.iman.bnpl.domain.branch.data.model.BusinessBranchEntity import org.springframework.data.mongodb.repository.MongoRepository import org.springframework.stereotype.Repository @Repository interface BusinessBranchRepository : MongoRepository<BusinessBranchEntity, String>, CustomBusinessBranchRepository
0
Kotlin
0
0
76e43685753bc904a532a5cb26834929e34f9a3f
363
bnpl
Apache License 2.0
phoenix-android/src/main/kotlin/fr/acinq/phoenix/android/components/Inputs.kt
ACINQ
192,964,514
false
null
/* * Copyright 2021 ACINQ SAS * * 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 fr.acinq.phoenix.android.components import android.view.ViewGroup import android.widget.ImageView import androidx.compose.foundation.layout.* import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.layout.layoutId import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.viewinterop.AndroidView import androidx.constraintlayout.compose.ChainStyle import androidx.constraintlayout.compose.ConstraintLayout import androidx.constraintlayout.compose.ConstraintSet import androidx.constraintlayout.compose.Dimension import fr.acinq.lightning.MilliSatoshi import fr.acinq.lightning.utils.msat import fr.acinq.phoenix.android.LocalBitcoinUnit import fr.acinq.phoenix.android.LocalFiatCurrency import fr.acinq.phoenix.android.R import fr.acinq.phoenix.android.fiatRate import fr.acinq.phoenix.android.utils.Converter.toFiat import fr.acinq.phoenix.android.utils.Converter.toPlainString import fr.acinq.phoenix.android.utils.Converter.toPrettyString import fr.acinq.phoenix.android.utils.PhoenixAndroidTheme import fr.acinq.phoenix.android.utils.logger import fr.acinq.phoenix.android.utils.textFieldColors import fr.acinq.phoenix.data.* @Composable fun TextInput( modifier: Modifier = Modifier, text: String, maxLines: Int = 1, label: @Composable (() -> Unit)? = null, enabled: Boolean = true, onTextChange: (String) -> Unit, ) { val focusManager = LocalFocusManager.current TextField( value = text, onValueChange = onTextChange, maxLines = maxLines, keyboardOptions = KeyboardOptions.Default.copy( imeAction = ImeAction.Done, keyboardType = KeyboardType.Text ), label = label, enabled = enabled, keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() }), colors = textFieldColors(), shape = RectangleShape, modifier = modifier ) } @Preview @Composable fun ComposablePreview() { PhoenixAndroidTheme() { Column { AmountInput(initialAmount = 123456.msat, onAmountChange = { _, _, _ -> Unit }) Spacer(modifier = Modifier.height(24.dp)) AmountInput(initialAmount = -123456.msat, onAmountChange = { _, _, _ -> Unit }, useBasicInput = true) } } } @Composable fun AmountInput( initialAmount: MilliSatoshi?, onAmountChange: (MilliSatoshi?, Double?, FiatCurrency) -> Unit, modifier: Modifier = Modifier, inputModifier: Modifier = Modifier, dropdownModifier: Modifier = Modifier, useBasicInput: Boolean = false, inputTextSize: TextUnit = 16.sp, unitTextSize: TextUnit = 16.sp, ) { val log = logger("AmountInput") // get unit ambients val context = LocalContext.current val prefBitcoinUnit = LocalBitcoinUnit.current val prefFiat = LocalFiatCurrency.current val rate = fiatRate val units = listOf<CurrencyUnit>(BitcoinUnit.Sat, BitcoinUnit.Bit, BitcoinUnit.MBtc, BitcoinUnit.Btc, prefFiat) val focusManager = LocalFocusManager.current // unit selected in the dropdown menu var unit: CurrencyUnit by remember { mutableStateOf(prefBitcoinUnit) } // stores the raw String input entered by the user. var rawAmount: String by remember { mutableStateOf(initialAmount?.toUnit(prefBitcoinUnit).toPlainString()) } var convertedAmount: String by remember { mutableStateOf(initialAmount?.toFiat(rate?.price ?: -1.0).toPlainString()) } // stores the numeric value of rawAmount as a Double. Null if rawAmount is invalid or empty. var amount: Double? by remember { mutableStateOf(initialAmount?.toUnit(prefBitcoinUnit)) } log.debug { "amount input initial [ amount=${amount.toPlainString()} unit=$unit with rate=$rate ]" } /** Convert the input [Double] to a (msat -> fiat) pair, if possible. */ fun convertInputToAmount(): Pair<MilliSatoshi?, Double?> { log.debug { "amount input update [ amount=$amount unit=$unit with rate=$rate ]" } return amount?.let { d -> when (val u = unit) { is FiatCurrency -> { if (rate == null) { log.warning { "cannot convert fiat amount to bitcoin with a null rate" } convertedAmount = context.getString(R.string.utils_no_conversion) null to null } else { val msat = d.toMilliSatoshi(rate.price) if (msat.toUnit(BitcoinUnit.Btc) > 21e6) { convertedAmount = context.getString(R.string.send_amount_error_too_large) null to null } else if (msat < 0.msat) { convertedAmount = context.getString(R.string.send_amount_error_negative) null to null } else { convertedAmount = msat.toPrettyString(prefBitcoinUnit, withUnit = true) msat to amount } } } is BitcoinUnit -> d.toMilliSatoshi(u).run { if (this.toUnit(BitcoinUnit.Btc) > 21e6) { convertedAmount = context.getString(R.string.send_amount_error_too_large) null to null } else if (this < 0.msat) { convertedAmount = context.getString(R.string.send_amount_error_negative) null to null } else if (rate == null) { convertedAmount = context.getString(R.string.utils_no_conversion) this to null // conversion is not possible but that does not stop the payment } else { val fiat = toFiat(rate.price) convertedAmount = fiat.toPrettyString(prefFiat, withUnit = true) this to fiat } } else -> { convertedAmount = "" Pair(null, null) } } } ?: run { convertedAmount = "" Pair(null, null) } } /** * When input changes, refresh the mutable amount field and convert it to a actionable (msat -> fiat) pair. */ val onValueChange: (String) -> Unit = { val d = it.toDoubleOrNull() if (d == null) { rawAmount = "" amount = null } else { rawAmount = it amount = d } convertInputToAmount().let { (msat, fiat) -> onAmountChange(msat, fiat, prefFiat) } } // references for constraint layout val amountRef = "amount_input" val unitRef = "unit_dropdown" val altAmountRef = "alt_amount" val amountLineRef = "amount_line" Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { ConstraintLayout( constraintSet = ConstraintSet { val amountInput = createRefFor(amountRef) val unitDropdown = createRefFor(unitRef) val altAmount = createRefFor(altAmountRef) createHorizontalChain(amountInput, unitDropdown, chainStyle = ChainStyle.Packed) constrain(amountInput) { width = Dimension.preferredValue(150.dp) top.linkTo(parent.top) start.linkTo(parent.start) end.linkTo(unitDropdown.start) } constrain(unitDropdown) { baseline.linkTo(amountInput.baseline) start.linkTo(amountInput.end, margin = 2.dp) end.linkTo(parent.end) } if (useBasicInput) { val amountLine = createRefFor(amountLineRef) constrain(amountLine) { width = Dimension.fillToConstraints top.linkTo(amountInput.bottom, margin = 2.dp) start.linkTo(amountInput.start) end.linkTo(unitDropdown.end) } } constrain(altAmount) { if (useBasicInput) { top.linkTo(amountInput.bottom, margin = 8.dp) } else { top.linkTo(amountInput.bottom, margin = 2.dp) } start.linkTo(parent.start) end.linkTo(parent.end) } }, modifier = modifier .width(IntrinsicSize.Min) .then(if (!useBasicInput) Modifier.fillMaxWidth() else Modifier) ) { if (useBasicInput) { BasicTextField( value = rawAmount, onValueChange = onValueChange, modifier = inputModifier .layoutId(amountRef) .defaultMinSize(minWidth = 32.dp) .sizeIn(maxWidth = 180.dp), textStyle = MaterialTheme.typography.body1.copy( fontSize = 32.sp, color = MaterialTheme.colors.primary ), keyboardOptions = KeyboardOptions( capitalization = KeyboardCapitalization.None, autoCorrect = false, keyboardType = KeyboardType.Number, imeAction = ImeAction.Done ), keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() }), singleLine = true, ) } else { TextField( value = rawAmount, onValueChange = onValueChange, modifier = inputModifier .layoutId(amountRef) .fillMaxWidth(), keyboardOptions = KeyboardOptions( capitalization = KeyboardCapitalization.None, autoCorrect = false, keyboardType = KeyboardType.Number, imeAction = ImeAction.Done ), keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() }), colors = textFieldColors(), singleLine = true, maxLines = 1, shape = RectangleShape, ) } UnitDropdown( selectedUnit = unit, units = units, onUnitChange = { unit = it convertInputToAmount().let { (msat, fiat) -> onAmountChange(msat, fiat, prefFiat) } }, onDismiss = { }, modifier = dropdownModifier.layoutId(unitRef) ) // -- dashed line if (useBasicInput) { AndroidView(modifier = Modifier .layoutId(amountLineRef), factory = { ImageView(it).apply { layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) setBackgroundResource(R.drawable.line_dots) } }) } } Text( text = convertedAmount.takeIf { it.isNotBlank() }?.let { stringResource(id = R.string.utils_converted_amount, it) } ?: "", style = if (useBasicInput) MaterialTheme.typography.caption.copy(textAlign = TextAlign.Center) else MaterialTheme.typography.caption, modifier = Modifier .layoutId(altAmountRef) .fillMaxWidth() ) } } @Composable private fun UnitDropdown( selectedUnit: CurrencyUnit, units: List<CurrencyUnit>, onUnitChange: (CurrencyUnit) -> Unit, onDismiss: () -> Unit, modifier: Modifier = Modifier, ) { var expanded by remember { mutableStateOf(false) } var selectedIndex by remember { mutableStateOf(maxOf(units.lastIndexOf(selectedUnit), 0)) } Box(modifier = modifier.wrapContentSize(Alignment.TopStart)) { Button( text = units[selectedIndex].toString(), icon = R.drawable.ic_chevron_down, onClick = { expanded = true }, padding = PaddingValues(8.dp), space = 8.dp, ) DropdownMenu( expanded = expanded, onDismissRequest = { expanded = false onDismiss() }, modifier = Modifier.fillMaxWidth() ) { units.forEachIndexed { index, s -> DropdownMenuItem(onClick = { selectedIndex = index expanded = false onDismiss() onUnitChange(units[index]) }) { Text(text = s.toString()) } } } } }
61
C
46
219
9112948d9a2af09add9b1b3b2b9fdb7607bd03ec
14,758
phoenix
Apache License 2.0
Kotiln/bacic_concept/core/src/main/kotlin/com/example/core/h_generics/TypeParameterConstraint.kt
bekurin
558,176,225
false
{"Git Config": 1, "Text": 12, "Ignore List": 96, "Markdown": 58, "YAML": 55, "JSON with Comments": 2, "JSON": 46, "HTML": 104, "robots.txt": 6, "SVG": 10, "TSX": 15, "CSS": 64, "Gradle Kotlin DSL": 107, "Shell": 72, "Batchfile": 71, "HTTP": 15, "INI": 112, "Kotlin": 682, "EditorConfig": 1, "Gradle": 40, "Java": 620, "JavaScript": 53, "Go": 8, "XML": 38, "Go Module": 1, "SQL": 7, "Dockerfile": 1, "Gherkin": 1, "Python": 153, "SCSS": 113, "Java Properties": 3, "AsciiDoc": 5, "Java Server Pages": 6, "Unity3D Asset": 451, "C#": 48, "Objective-C": 51, "C": 8, "Objective-C++": 1, "Smalltalk": 1, "OpenStep Property List": 12, "Dart": 17, "Swift": 8, "Ruby": 1}
package com.example.core.h_generics import com.example.core.a_kotlinBasic.iterator.printLine fun <T: Number> oneHalf(value: T): Double { return value.toDouble() / 2.0 } fun <T: Comparable<T>> max(first: T, second: T): T { return if (first > second) first else second } fun <T> ensureTrailingPeriod(seq: T) where T: CharSequence, T: Appendable { if (!seq.endsWith(".")) { seq.append(".") } } /** * 타입 파라미터 제약: 클래스나 함수에 사용할 수 있는 타입 인자를 제한하는 기능이다. * oneHalf 의 경우 Number 하위 타입만 입력으로 넣을 수 있다. * 형식: <T: 상한 타입> ex) <T: Number> * 타입 파라미터에 여러 제약을 가할 수 있다. */ fun main() { println("oneHalf(30) = ${oneHalf(30)}") printLine() println("max(\"kotlin\", \"java\") = ${max("kotlin", "java")}") printLine() val helloWorld = StringBuilder("Hello World") ensureTrailingPeriod(helloWorld) // ensureTrailingPeriod(10) println("helloWorld = $helloWorld") }
0
Java
0
2
ede7cdb0e164ed1d3d2ee91c7770327b2ee71e4d
923
blog_and_study
MIT License
app/src/main/java/com/otonishi/example/mvvmviewpagerdi/ui/viewpager/page/PageOneFragment.kt
yotonishi
362,799,143
false
null
package com.otonishi.example.mvvmviewpagerdi.ui.viewpager.page import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.fragment.app.viewModels import com.otonishi.example.mvvmviewpagerdi.R import com.otonishi.example.mvvmviewpagerdi.databinding.FragmentViewPager1Binding import com.otonishi.example.mvvmviewpagerdi.ui.viewpager.ViewPagerModel import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class PageOneFragment : Fragment() { private var binding: FragmentViewPager1Binding? = null // You can use activityViewModels to share a ViewModel with the parent Activity. private val viewPagerModel: ViewPagerModel by activityViewModels() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { val root = inflater.inflate(R.layout.fragment_view_pager_1, container, false) if (binding == null) { binding = FragmentViewPager1Binding.bind(root) } return binding!!.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding?.apply { viewmodel = [email protected] } } companion object { fun newInstance() = PageOneFragment() } }
0
Kotlin
0
0
11d7c288921baf5b6333939033efa60163fb2cbf
1,472
mvvm-viewpager-di-sample
Apache License 2.0
src/main/kotlin/com/api/test_localiza/TestLocalizaApplication.kt
victorkoji
594,235,361
false
null
package com.api.test_localiza import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class TestLocalizaApplication fun main(args: Array<String>) { runApplication<TestLocalizaApplication>(*args) }
0
Kotlin
0
0
984f8318967503931967765fb131fc182e152099
283
test_localiza
Creative Commons Zero v1.0 Universal
app/src/main/java/com/rmoralf/marveltest/presentation/menu/MenuScreen.kt
rmoralf
515,890,655
false
{"Kotlin": 81685}
package com.rmoralf.marveltest.presentation.menu import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.Button import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment.Companion.CenterHorizontally import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.rmoralf.marveltest.R import com.rmoralf.marveltest.presentation.navigation.Screen @Composable fun MenuScreen( navController: NavController ) { Scaffold { Column( modifier = Modifier .fillMaxSize() .padding(16.dp) ) { Image( painterResource(R.drawable.marvel_logo), stringResource(id = R.string.marvel_logo), modifier = Modifier.padding(32.dp) ) Button(modifier = Modifier .align(CenterHorizontally) .padding(bottom = 32.dp), onClick = { navController.navigate( Screen.SEARCH.route ) }) { Text(text = stringResource(id = R.string.screen_search)) } Button(modifier = Modifier .align(CenterHorizontally), onClick = { navController.navigate( Screen.FAVORITES.route ) }) { Text(text = stringResource(id = R.string.screen_favorites)) } } } }
0
Kotlin
0
0
f0872db0656d302af8bbc011e654309e1b252bca
1,898
marvel-test
Apache License 2.0
app/src/main/java/com/android/code/util/ViewDetectable.kt
JungJongSeok
447,956,335
false
null
package com.android.code.util import androidx.recyclerview.widget.RecyclerView interface ViewDetectable { fun onViewAttachedToWindow(holder: RecyclerView.ViewHolder) fun onViewDetachedFromWindow(holder: RecyclerView.ViewHolder) }
4
Kotlin
0
0
e958e18d2cb1cd5c37965434506b0c88d089915b
240
Android-Playground-2022
Apache License 2.0
android/http-coroutine/bin/main/com/caldremch/http/execute/BaseExecute.kt
android-module
522,390,095
false
{"Kotlin": 149203, "Java": 23434, "Shell": 433}
package com.caldremch.http.execute import com.caldremch.http.Api import com.caldremch.http.CoroutineHandler import com.caldremch.http.RequestHelper import com.caldremch.http.core.abs.* import com.caldremch.http.core.framework.handle.IDialogHandle import com.caldremch.http.core.framework.handle.IRequestHandle import com.caldremch.http.exception.HostConfigErrorException import okhttp3.ResponseBody import org.koin.java.KoinJavaComponent /** * Created by Leon on 2022/7/8 */ internal abstract class BaseExecute { private val serverUrlConfig: IServerUrlConfig by KoinJavaComponent.inject(IServerUrlConfig::class.java) protected val convert: IConvert<ResponseBody> by KoinJavaComponent.inject(IConvert::class.java) private val obsHandler: ICommonRequestEventCallback by KoinJavaComponent.inject(ICommonRequestEventCallback::class.java) private val helpersMap = hashMapOf<Any, RequestHelper>() private fun getUrlByChannel(channels: MutableMap<Any?, IHostConfig>, channel: Any?): String { if (channel == null) { //默认 val hostConfig: IHostConfig = channels[null] ?: (channels.iterator().next() as IHostConfig) return if (hostConfig.enableConfig()) hostConfig.currentUrl() else hostConfig.defaultUrl() } val hostConfig = channels[channel] ?: throw HostConfigErrorException("channel $channel is not config") return if (hostConfig.enableConfig()) hostConfig.currentUrl() else hostConfig.defaultUrl() } protected fun getApi(noCustomerHeader: Boolean, channel: Any?): Api { val channels = serverUrlConfig.channels() if (channels.isEmpty()) throw HostConfigErrorException() if (noCustomerHeader) { val baseUrl = getUrlByChannel(channels, channel) val requestHelper = RequestHelper(false, baseUrl) return requestHelper.getApi() } if (channel == null) { //默认 val hostConfig: IHostConfig = channels[null] ?: (channels.iterator().next() as IHostConfig) return if (hostConfig.enableConfig()) RequestHelper().getApi() else RequestHelper.INSTANCE.getApi() } val hostConfig = channels[channel] ?: throw HostConfigErrorException("channel $channel is not config") val baseUrl = if (hostConfig.enableConfig()) hostConfig.currentUrl() else hostConfig.defaultUrl() return if (hostConfig.enableConfig()) RequestHelper(true, baseUrl).getApi() else { var cacheHelper = helpersMap[channel] if (cacheHelper == null) { val newHelper = RequestHelper(true, baseUrl) helpersMap[channel] = newHelper cacheHelper = newHelper } cacheHelper.getApi() } } fun <T> go( callback: AbsCallback<T>, clazz: Class<T>, dialogEvent: IDialogHandle?, showDialog: Boolean, dialogTips: String, requestHandleEvent: IRequestHandle?, showToast: Boolean ): CoroutineHandler<T> { return CoroutineHandler( callback, obsHandler, dialogEvent, showDialog, dialogTips, requestHandleEvent, showToast ) } }
0
Kotlin
0
1
52b640f9e1e65b15417a4cc61b64845aca837d74
3,280
android-http
Apache License 2.0
schema-dsl/src/commonMain/kotlin/com.chrynan.graphkl/dsl/schema/GraphQLArgumentListBuilder.kt
chRyNaN
230,310,677
false
null
package com.chrynan.graphkl.dsl.schema import com.chrynan.graphkl.language.type.GraphQLArgument import com.chrynan.graphkl.language.type.GraphQLInputType /** * A DSL builder class for creating a list of [GraphQLArgument]s in a Kotlin DSL manner. */ class GraphQLArgumentListBuilder internal constructor() { private val arguments = mutableListOf<GraphQLArgument>() fun argument(name: String? = null, type: GraphQLInputType? = null) { val argumentBuilder = GraphQLArgumentBuilder(initialName = name, initialType = type) arguments.add(argumentBuilder.build()) } fun argument(name: String? = null, type: GraphQLInputType? = null, builder: GraphQLArgumentBuilder.() -> Unit) { val argumentBuilder = GraphQLArgumentBuilder(initialName = name, initialType = type) builder.invoke(argumentBuilder) arguments.add(argumentBuilder.build()) } internal fun build(): List<GraphQLArgument> = arguments }
0
Kotlin
0
2
2526cedddc0a5b5777dea0ec7fc67bc2cd16fe05
959
graphkl
Apache License 2.0
fontawesome/src/de/msrd0/fontawesome/icons/FA_ARROW_UP_LONG.kt
msrd0
363,665,023
false
null
/* @generated * * This file is part of the FontAwesome Kotlin library. * https://github.com/msrd0/fontawesome-kt * * This library is not affiliated with FontAwesome. * * 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 de.msrd0.fontawesome.icons import de.msrd0.fontawesome.Icon import de.msrd0.fontawesome.Style import de.msrd0.fontawesome.Style.SOLID /** Arrow up long */ object FA_ARROW_UP_LONG: Icon { override val name get() = "Arrow up long" override val unicode get() = "f176" override val styles get() = setOf(SOLID) override fun svg(style: Style) = when(style) { SOLID -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><path d="M310.6 182.6c-12.51 12.51-32.76 12.49-45.25 0L192 109.3V480c0 17.69-14.31 32-32 32s-32-14.31-32-32V109.3L54.63 182.6c-12.5 12.5-32.75 12.5-45.25 0s-12.5-32.75 0-45.25l128-128c12.5-12.5 32.75-12.5 45.25 0l128 128C323.1 149.9 323.1 170.1 310.6 182.6z"/></svg>""" else -> null } } /** Alias for [FA_ARROW_UP_LONG]. */ val FA_LONG_ARROW_UP = FA_ARROW_UP_LONG
1
Kotlin
0
0
a49fdedb55f0a931db5121fe187ef199bc72203c
1,556
fontawesome-kt
Apache License 2.0
kotlin/src/main/kotlin/net/timafe/angkor/service/EventConsumer.kt
tillkuhn
219,713,329
false
{"Kotlin": 363265, "TypeScript": 332971, "Go": 139518, "HCL": 95505, "HTML": 82105, "Makefile": 54646, "Shell": 36233, "SCSS": 31379, "Dockerfile": 4705, "JavaScript": 2537, "PLpgSQL": 2280, "CSS": 1037}
package net.timafe.angkor.service import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.ObjectMapper import jakarta.annotation.PostConstruct import net.timafe.angkor.config.AppProperties import net.timafe.angkor.domain.Event import net.timafe.angkor.security.SecurityUtils import org.apache.kafka.clients.consumer.KafkaConsumer import org.apache.kafka.common.header.Headers import org.apache.kafka.common.serialization.StringDeserializer import org.slf4j.LoggerFactory import org.springframework.boot.autoconfigure.kafka.KafkaProperties import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Service import java.time.Duration import java.util.* import java.util.concurrent.TimeUnit /** * Service Implementation for consuming [Event] */ @Service class EventConsumer( // private val repo: EventRepository, private val objectMapper: ObjectMapper, private val appProps: AppProperties, private val kafkaProperties: KafkaProperties, private val eventService: EventService, ) { // Populated by init lateinit var consumerProps: Properties private val log = LoggerFactory.getLogger(javaClass) val logPrefix = "[KafkaConsumer]" @PostConstruct fun init() { log.info("[Kafka] Event Consumer initialized with kafkaSupport=${eventService.kafkaEnabled()} producerBootstrapServers=${kafkaProperties.bootstrapServers}") // https://kafka.apache.org/documentation.html#consumerconfigs this.consumerProps = Properties() this.consumerProps.putAll(eventService.kafkaBaseProperties()) // Consumer props which will raise a warning if used for producer this.consumerProps["group.id"] = "${appProps.kafka.topicPrefix}hase" this.consumerProps["enable.auto.commit"] = "true" this.consumerProps["auto.commit.interval.ms"] = "1000" this.consumerProps["auto.offset.reset"] = "earliest" this.consumerProps["session.timeout.ms"] = "30000" this.consumerProps["key.deserializer"] = StringDeserializer::class.java.name this.consumerProps["value.deserializer"] = StringDeserializer::class.java.name } // CAUTION: each call of consumeMessages requires an active DB Connection from the Pool // Value increased to 300000 (5min) to increase the time that hikari cp can be scaled to 0 // durations are in milliseconds. also supports ${my.delay.property} (escape with \ or kotlin compiler complains) // 600000 = 10 Minutes make sure @EnableScheduling is active in AsyncConfig 600000 = 10 min, 3600000 = 1h // #{__listener.publicTopic} Starting with version 2.1.2, the SpEL expressions support a special token: __listener. It is a pseudo bean name // that represents the current bean instance within which this annotation exists. // https://docs.spring.io/spring-kafka/reference/kafka/receiving-messages/listener-annotation.html#annotation-properties // https://stackoverflow.com/a/27817678/4292075 @Scheduled( fixedRateString = "\${app.kafka.fixed-rate-seconds}", initialDelay = 20, timeUnit = TimeUnit.SECONDS, ) // @Scheduled(fixedRateString = "300000", initialDelay = 20000) fun consumeMessages() { // https://www.tutorialspoint.com/apache_kafka/apache_kafka_consumer_group_example.htm // https://www.oreilly.com/library/view/kafka-the-definitive/9781491936153/ch04.html val consumer: KafkaConsumer<String, String> = KafkaConsumer<String, String>(this.consumerProps) val topics = listOf("imagine", "audit", "system", "app").map { "${appProps.kafka.topicPrefix}$it" } log.debug(" {} Consuming fresh messages from kafka topics {}", logPrefix, topics) consumer.subscribe(topics) var (received, persisted) = listOf(0, 0) val records = consumer.poll(Duration.ofMillis(10L * 1000)) if (! records.isEmpty) { // Lazy invoke authenticate which is marked @Transactional // Advantage: We don't need a transaction if there are no events to persist, // so we can keep the active connection pool count at zero (nice for neon db) eventService.authenticate() } for (record in records) { val eventVal = record.value() log.info("$logPrefix Polled record #$received topic=${record.topic()}, partition/offset=${record.partition()}/${record.offset()}, key=${record.key()}, value=$eventVal") try { val parsedEvent: Event = objectMapper .reader() .withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .readValue(eventVal, Event::class.java) parsedEvent.topic = record.topic().removePrefix(appProps.kafka.topicPrefix) parsedEvent.partition = record.partition() parsedEvent.offset = record.offset() parsedEvent.id = computeMessageId(record.headers()) eventService.save(parsedEvent) persisted++ } catch (e: Exception) { log.warn("$logPrefix Cannot parse $eventVal to Event: ${e.message}") } received++ } if (received > 0) { log.info("$logPrefix Polled $received records ($persisted persisted), see you again at a fixed rate") } else { log.trace("$logPrefix No records to poll in this run") } consumer.close() } fun computeMessageId(headers: Headers): UUID { for (header in headers) { if (header.key().toString() == "messageId") { val mid = String(header.value()) val midUUID = SecurityUtils.safeConvertToUUID(mid) return if (midUUID == null) { log.warn("$logPrefix Could not convert messageId $mid to UUID, generating new one") UUID.randomUUID() } else { log.debug("{} using messageId from header {}", logPrefix, midUUID) midUUID } } } val newId = UUID.randomUUID() log.warn("$logPrefix Could not find messageId in any header, generated $newId") return newId } }
18
Kotlin
4
17
45cb63ba0fbed123b2e095f0d4eaf07a4950c22c
6,327
angkor
Apache License 2.0
dsl/jpql/src/test/kotlin/com/linecorp/kotlinjdsl/dsl/jpql/predicate/CustomPredicateDslTest.kt
line
442,633,985
false
{"Kotlin": 1959613, "JavaScript": 5144, "Shell": 1023}
package com.linecorp.kotlinjdsl.dsl.jpql.predicate import com.linecorp.kotlinjdsl.dsl.jpql.queryPart import com.linecorp.kotlinjdsl.querymodel.jpql.expression.Expressions import com.linecorp.kotlinjdsl.querymodel.jpql.predicate.Predicate import com.linecorp.kotlinjdsl.querymodel.jpql.predicate.Predicates import org.assertj.core.api.WithAssertions import org.junit.jupiter.api.Test class CustomPredicateDslTest : WithAssertions { private val template1: String = "template1" private val stringExpression1 = Expressions.value("string1") private val stringExpression2 = Expressions.value("string2") private val string1 = "string1" private val string2 = "string2" @Test fun `customPredicate() with strings`() { // when val predicate = queryPart { customPredicate(template1, string1, string2) } val actual: Predicate = predicate // for type check // then val expected = Predicates.customPredicate( template1, listOf( Expressions.value(string1), Expressions.value(string2), ), ) assertThat(actual).isEqualTo(expected) } @Test fun `customPredicate() with string expressions`() { // when val predicate = queryPart { customPredicate(template1, stringExpression1, stringExpression2) } val actual: Predicate = predicate // for type check // then val expected = Predicates.customPredicate( template1, listOf( stringExpression1, stringExpression2, ), ) assertThat(actual).isEqualTo(expected) } }
4
Kotlin
86
705
3a58ff84b1c91bbefd428634f74a94a18c9b76fd
1,728
kotlin-jdsl
Apache License 2.0
android/app/src/main/java/bg/crc/roamingapp/activity/LoginTypeActivity.kt
governmentbg
404,617,376
false
{"Kotlin": 308009, "Java": 259847, "TypeScript": 200185, "HTML": 95111, "JavaScript": 74716, "CSS": 4924, "PLpgSQL": 4314}
package bg.crc.roamingapp.activity import android.content.Intent import android.os.Bundle import android.text.Html import android.text.Spannable import android.text.TextPaint import android.text.method.LinkMovementMethod import android.text.style.URLSpan import android.text.style.UnderlineSpan import android.view.View import bg.crc.roamingapp.R import bg.crc.roamingapp.app.ApplicationSession import bg.crc.roamingapp.app.ApplicationSession.LOGIN_TYPE_FACEBOOK import bg.crc.roamingapp.app.ApplicationSession.LOGIN_TYPE_GOOGLE import bg.crc.roamingapp.constant.AppUtils import bg.crc.roamingapp.constant.AppUtils.isLoginWithFacebook import bg.crc.roamingapp.constant.Constants import bg.crc.roamingapp.constant.Constants.EMAIL import bg.crc.roamingapp.constant.Constants.PUBLIC_PROFILE import bg.crc.roamingapp.constant.ErrorHandler import bg.crc.roamingapp.debug.MyDebug import bg.crc.roamingapp.dialog.CustomDialog import bg.crc.roamingapp.helper.TelecomsHelper import bg.crc.roamingapp.server.ApiClient import bg.crc.roamingapp.server.ConnectionDetector import bg.crc.roamingapp.server.RequestInterface import bg.crc.roamingapp.server.RequestParameters import com.facebook.* import com.facebook.login.LoginManager import com.facebook.login.LoginResult import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInClient import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.android.gms.common.api.ApiException import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.GoogleAuthProvider import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_login_type.* import kotlinx.android.synthetic.main.dialogue_permission_usage.* import kotlinx.android.synthetic.main.internet_connectivity_view.* import java.util.* /** * This screen display Login Type UI. * User can login into application using this screen by facebook, google and email. */ class LoginTypeActivity : BaseActivity() { private var compositeDisposable = CompositeDisposable() // Api Calling common private val RC_SIGN_IN = 234 // companion object { // private const val RC_SIGN_IN = 234 // } private var callbackManager: CallbackManager = CallbackManager.Factory.create() private lateinit var googleSignInClient: GoogleSignInClient private lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login_type) val language = if(Locale.getDefault().language == "bg") "bg" else "en" val content = getString(R.string.privacy_policy_link) val s = Html.fromHtml("<a href=\"https://roaming.crc.bg/privacy-policy?lang=$language\">$content</a>", Html.FROM_HTML_MODE_COMPACT) as Spannable for (u in s.getSpans(0, s.length, URLSpan::class.java)) { s.setSpan(object : UnderlineSpan() { override fun updateDrawState(tp: TextPaint) { tp.isUnderlineText = false tp.color = resources.getColor(R.color.white, theme) } }, s.getSpanStart(u), s.getSpanEnd(u), 0) } tv_privacy_policy_login.text = s tv_privacy_policy_login.movementMethod = LinkMovementMethod.getInstance() init() setListeners() } private fun init() { initFacebookManager() initGoogle() displayPermissionUsage() } /** *display permission usage dialogue if first run **/ private fun displayPermissionUsage() { val prefs = super.getSharedPreferences("bg.crc.roamingapp", MODE_PRIVATE) if(!prefs.getBoolean("hasRun", false)) { // DISPLAY PERMISSION USAGE permissionDialogueInclude.visibility = View.VISIBLE prefs.edit().putBoolean("hasRun", true).apply() } } /** *set listeners **/ private fun setListeners() { btnEmailLogin.setOnClickListener { startActivity(Intent(this, LoginActivity::class.java)) finish() } btnOk.setOnClickListener { permissionDialogueInclude.visibility = View.GONE } btnRegister.setOnClickListener { startActivity(Intent(this, RegistrationTypeActivity::class.java)) finish() } btnGoogleLogin.setOnClickListener { if (ConnectionDetector.isConnectedToInternet(this)) { signInWithGoogle() } else { AppUtils.showInternetDialog(this) } } btnFacebookLogin.setOnClickListener { if (ConnectionDetector.isConnectedToInternet(this)) { LoginManager.getInstance().logInWithReadPermissions( this, listOf(PUBLIC_PROFILE, EMAIL) ) } else { AppUtils.showInternetDialog(this) } } } /** * This function for facebook login. * Get email, token, userid after successfully login with facebook * After success redirect to [apiCallForFacebookLogin] for request to server. * */ private fun initFacebookManager() { if (isLoginWithFacebook()) { AppUtils.logoutFacebook() } LoginManager.getInstance().registerCallback(callbackManager, object : FacebookCallback<LoginResult> { override fun onSuccess(loginResult: LoginResult) { val accessToken = AccessToken.getCurrentAccessToken() val request: GraphRequest = GraphRequest.newMeRequest(accessToken) { objectResponse, response -> if (response.error == null) { val email = objectResponse.optString("email") val fbUserId = accessToken.userId val fbToken = AccessToken.getCurrentAccessToken().token apiCallForFacebookLogin(email, fbUserId, fbToken) } } val parameters = Bundle() parameters.putString("fields", "id,name,email") request.parameters = parameters request.executeAsync() } override fun onCancel() { if (MyDebug.IS_DEBUG) MyDebug.showLog("Facebook login", "canceled") } override fun onError(exception: FacebookException) { AppUtils.showToast(this@LoginTypeActivity, getString(R.string.failed_facebook_login)) if (MyDebug.IS_DEBUG) MyDebug.showLog("Facebook login", exception.toString()) } }) } /** *This function for Configure Google Sign In. * */ private fun initGoogle() { val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestId() .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build() googleSignInClient = GoogleSignIn.getClient(this, gso) //Initialize firebase auth auth = Firebase.auth //sign out if user already sign in googleSignOut() } private fun signInWithGoogle() { val signInIntent = googleSignInClient.signInIntent startActivityForResult(signInIntent, RC_SIGN_IN) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { callbackManager.onActivityResult(requestCode, resultCode, data) super.onActivityResult(requestCode, resultCode, data) // Result returned from launching Intent if (requestCode == RC_SIGN_IN) { val task = GoogleSignIn.getSignedInAccountFromIntent(data) try { // Google Sign In was successful val account = task.getResult(ApiException::class.java) if (MyDebug.IS_DEBUG) MyDebug.showLog("Token", account.idToken) pbLoginType.visibility = View.VISIBLE firebaseAuthWithGoogle(account.id!!, account.idToken!!) } catch (e: ApiException) { // Google Sign In failed if (MyDebug.IS_DEBUG) MyDebug.showLog("catch", e.message) } } } /** * This function authenticate credential with Firebase * After success redirect to [apiCallForGoogleLogin] for request to server. **/ private fun firebaseAuthWithGoogle(gglUserId: String, idToken: String) { val credential = GoogleAuthProvider.getCredential(idToken, null) auth.signInWithCredential(credential) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { //sign in successfully apiCallForGoogleLogin(gglUserId, idToken) } else { // If sign in fails pbLoginType.visibility = View.GONE AppUtils.showToast(this, getString(R.string.failed_google_login)) if (MyDebug.IS_DEBUG) MyDebug.showLog("catch", task.exception.toString()) } } } /** *This override function notify to user about internet connectivity. * */ override fun onInternetConnectivityChange() { tvInternetConnection?.visibility = if (isInternetAvailable) { View.GONE } else { View.VISIBLE } } /** * This function request to server for login via facebook. * This function also store [Constants.PREF_USERID],[Constants.PREF_SECRET_KEY] and [Constants.PREF_SIGN_IN_WITH_SOCIAL_LOG_IN] in session after success. * After successfully response getting from server, check that any update in telecoms list version or not. * After success redirect to [HomeActivity]. **/ private fun apiCallForFacebookLogin(email: String, fbUserId: String, fbToken: String) { if (ConnectionDetector.isConnectedToInternet(this)) { try { pbLoginType.visibility = View.VISIBLE ApplicationSession.clearLoginData() val parameter = RequestParameters.getLoginViaFacebookParameter( email, fbUserId, fbToken ) val apiClient = ApiClient.getClient(this).create(RequestInterface::class.java) compositeDisposable.add( apiClient.loginViaFacebook(parameter) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe({ pbLoginType.visibility = View.GONE when (it.ec) { ErrorHandler.OK -> { ApplicationSession.putLoginData(LOGIN_TYPE_FACEBOOK, fbUserId, it.id, it.key) ApplicationSession.setUserTelecomsUpdate(it.telcos_vn) TelecomsHelper.initUserTelecomSelection(false); HomeActivity.start(this@LoginTypeActivity) finish() } else -> { ErrorHandler.serverHandleError(this, it.ec, null, true) } } }, { error -> pbLoginType.visibility = View.GONE if (MyDebug.IS_DEBUG) MyDebug.showLog("error", error.message) }) ) } catch (e: Exception) { pbLoginType.visibility = View.GONE if (MyDebug.IS_DEBUG) MyDebug.showLog("catch", e.message) } } else { AppUtils.showInternetDialog(this) } } /** * This function request to server for login via google. * This function also store [Constants.PREF_USERID],[Constants.PREF_SECRET_KEY] and [Constants.PREF_SIGN_IN_WITH_SOCIAL_LOG_IN] after success. * After successfully response getting from server, check that any update in telecoms list version or not. * After success redirect to [HomeActivity]. * */ private fun apiCallForGoogleLogin(gglUserId: String, token: String) { if (ConnectionDetector.isConnectedToInternet(this)) { try { pbLoginType.visibility = View.VISIBLE ApplicationSession.clearLoginData() val parameter = RequestParameters.getLoginViaGoogleParameter(token) val apiClient = ApiClient.getClient(this).create(RequestInterface::class.java) compositeDisposable.add( apiClient.loginViaGoogle(parameter) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe({ pbLoginType.visibility = View.GONE when (it.ec) { ErrorHandler.OK -> { ApplicationSession.putLoginData(LOGIN_TYPE_GOOGLE, gglUserId, it.id, it.key) ApplicationSession.setUserTelecomsUpdate(it.telcos_vn) TelecomsHelper.initUserTelecomSelection(false) HomeActivity.start(this@LoginTypeActivity) finish() } else -> { ErrorHandler.serverHandleError(this, it.ec, null, true) } } }, { error -> pbLoginType.visibility = View.GONE if (MyDebug.IS_DEBUG) MyDebug.showLog("error", error.message) }) ) } catch (e: Exception) { pbLoginType.visibility = View.GONE if (MyDebug.IS_DEBUG) MyDebug.showLog("catch", e.message) } } else { AppUtils.showInternetDialog(this) } } /** * In this function sign out from Firebase and Google **/ private fun googleSignOut() { // Firebase sign out auth.signOut() // Google sign out googleSignInClient.signOut().addOnCompleteListener(this) { } } }
0
Kotlin
1
0
afba722d8d25d2cd6bd1806378bc06a19b2c4c73
14,942
crc-roaming
Apache License 2.0
app/src/main/java/com/nguyen/pagingexample/utils/NetworkState.kt
nguyenkhiem7789
269,125,967
false
null
package com.nguyen.pagingexample.utils class NetworkState( val status: Status, val msg: String ) { enum class Status { RUNNING, SUCCESS, FAILED } companion object { var LOADED: NetworkState? = null var LOADING: NetworkState? = null init { LOADED = NetworkState( Status.SUCCESS, "Success" ) LOADING = NetworkState( Status.RUNNING, "Running" ) } } }
0
Kotlin
0
0
814b847f14e9db33525a725da5b0b2b72b72f5c6
543
PagingExample
MIT License
plugin/src/main/kotlin/org/jetbrains/research/pynose/plugin/quickfixes/common/RedundantAssertionTestSmellQuickFix.kt
JetBrains-Research
299,979,830
false
{"Kotlin": 207840, "Python": 50580, "HTML": 6359}
package org.jetbrains.research.pynose.plugin.quickfixes.common import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.project.Project import com.jetbrains.python.psi.PyAssertStatement import com.jetbrains.python.psi.PyCallExpression import org.jetbrains.research.pynose.plugin.util.TestSmellBundle class DuplicateAssertionTestSmellQuickFix : LocalQuickFix { override fun getFamilyName(): String { return TestSmellBundle.message("quickfixes.duplicate.message") } override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val assertion = descriptor.psiElement if (assertion is PyCallExpression) { assertion.parent.delete() } else if (assertion is PyAssertStatement) { assertion.delete() } } }
6
Kotlin
9
47
081e5f9dcc416da4a290bcc5102ce46f104afefa
863
PyNose
Apache License 2.0
app/src/main/java/me/bytebeats/compose/bitcoin/feature/SplashScreen.kt
bytebeats
431,009,469
false
null
package me.bytebeats.compose.bitcoin.feature import android.content.res.Configuration import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.navigation.NavController import me.bytebeats.compose.bitcoin.R import me.bytebeats.compose.bitcoin.navigation.BitcoinRoute import me.bytebeats.compose.bitcoin.ui.theme.ComposeBitcoinTheme /** * Created by bytebeats on 2021/11/23 : 19:31 * E-mail: <EMAIL> * Quote: Peasant. Educated. Worker */ @Composable fun SplashScreen( navController: NavController? = null, alphaAnimationTargetValue: Float = 0F, alphaAnimationDurationMillis: Int = 1000 ) { Surface { Box( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colors.background), contentAlignment = Alignment.Center, ) { var targetValue by remember { mutableStateOf(alphaAnimationTargetValue) } val alpha by animateFloatAsState( targetValue = targetValue, animationSpec = tween(alphaAnimationDurationMillis), finishedListener = { navController?.popBackStack() navController?.navigate(BitcoinRoute.Quote.value) }, ) Image( painter = painterResource(id = R.drawable.ic_splash), contentDescription = null, modifier = Modifier.alpha(alpha) ) LaunchedEffect(key1 = Unit, block = { targetValue = 1F }) } } } @Preview(showBackground = true, showSystemUi = true) @Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES, showSystemUi = true) @Composable fun SplashScreenPreview() { ComposeBitcoinTheme { SplashScreen(alphaAnimationTargetValue = 1F) } }
0
Kotlin
2
3
9f10a8c79b4b67785b76a43f9fd54a41773bee73
2,422
compose-bitcoin
MIT License
aceleracao-trybe/sd-001-exercise-kotlin-playground-1/src/main/kotlin/Req12.kt
carolbezerra-dev
841,641,357
false
{"Kotlin": 55169}
fun multiplyLists(list1: List<Int>, list2: List<Int>, result: MutableList<Int>) { for (i in list1.indices) { result.add(list1[i] * list2[i]) } } fun main() {}
0
Kotlin
0
0
a1f3409e1003e069eda55f2ec4273d5b4080c6b8
176
personal-kotlin
MIT License
buildSrc/src/main/kotlin/karakum/mui/TypeParameter.kt
karakum-team
387,062,541
false
{"Kotlin": 1399430, "TypeScript": 2249, "JavaScript": 1167, "HTML": 724, "CSS": 86}
package karakum.mui internal fun String.toTypeParameter(): String = removeSurrounding("Partial<", ">") .replace("React.HTMLAttributes<", "react.dom.html.HTMLAttributes<") .replace("React.LabelHTMLAttributes<", "react.dom.html.LabelHTMLAttributes<") .replace("React.TextareaHTMLAttributes<", "react.dom.html.TextareaHTMLAttributes<") .replace("<HTMLElement>", "<web.html.HTMLElement>") .replace("<HTMLDivElement>", "<web.html.HTMLDivElement>") .replace("<HTMLTextAreaElement>", "<web.html.HTMLTextAreaElement>") .replace("<HTMLSpanElement>", "<web.html.HTMLSpanElement>") .replace("<HTMLUListElement>", "<web.html.HTMLUListElement>") .replace("<HTMLLIElement>", "<web.html.HTMLLIElement>") .replace("<HTMLHeadingElement>", "<web.html.HTMLHeadingElement>") .replace("<HTMLLabelElement>", "<web.html.HTMLLabelElement>") .replace("<HTMLInputElement | HTMLTextAreaElement>", "<web.html.HTMLElement>") .replace("TypographyProps", "mui.material.TypographyProps") .replace("TransitionProps", "mui.material.transitions.TransitionProps")
0
Kotlin
5
36
8465a0cb0cc3635d7b7c88637e850cca689029fb
1,145
mui-kotlin
Apache License 2.0
kactoos-common/src/main/kotlin/nnl/rocks/kactoos/collection/Solid.kt
neonailol
117,650,092
false
null
package nnl.rocks.kactoos.collection import nnl.rocks.kactoos.iterable.IterableOf import nnl.rocks.kactoos.scalar.SolidScalar /** * A [Collection] that is both synchronized and sticky. * * Objects of this class are thread-safe. * * @param T List type * @see Sticky * @since 0.4 */ class Solid<out T : Any> : CollectionEnvelope<T> { constructor(source: Collection<T>) : super(SolidScalar<Collection<T>> { Synced(Sticky(source)) }) constructor(vararg args: T) : this(IterableOf(args.asIterable())) constructor(iterable: Iterable<T>) : this(CollectionOf(iterable)) }
0
Kotlin
1
19
ce10c0bc7e6e65076b8ace90770b9f7648facf4a
589
kactoos
MIT License
protocol/osrs-221-desktop/src/main/kotlin/net/rsprot/protocol/game/incoming/codec/misc/user/UpdatePlayerModelDecoder.kt
blurite
771,753,685
false
{"Kotlin": 1458066}
package net.rsprot.protocol.game.incoming.codec.misc.user import net.rsprot.buffer.JagByteBuf import net.rsprot.protocol.ClientProt import net.rsprot.protocol.game.incoming.misc.user.UpdatePlayerModel import net.rsprot.protocol.game.incoming.prot.GameClientProt import net.rsprot.protocol.message.codec.MessageDecoder import net.rsprot.protocol.metadata.Consistent import net.rsprot.protocol.tools.MessageDecodingTools @Consistent public class UpdatePlayerModelDecoder : MessageDecoder<UpdatePlayerModel> { override val prot: ClientProt = GameClientProt.UPDATE_PLAYER_MODEL override fun decode( buffer: JagByteBuf, tools: MessageDecodingTools, ): UpdatePlayerModel { val bodyType = buffer.g1() val identKit = ByteArray(7) for (i in identKit.indices) { identKit[i] = buffer.g1().toByte() } val colours = ByteArray(5) for (i in colours.indices) { colours[i] = buffer.g1().toByte() } return UpdatePlayerModel( bodyType, identKit, colours, ) } }
4
Kotlin
0
7
b72a9ddbbf607e357b783c4c8a1f5dc91b5de4f0
1,109
rsprot
MIT License
app/src/main/java/com/example/kiyotaka/githubusers/presentation/detail/UserDetailActivity.kt
soranakk
125,732,340
false
null
package com.example.kiyotaka.githubusers.presentation.detail import android.graphics.drawable.Drawable import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.util.Log import android.view.View import android.widget.Toast import com.bumptech.glide.Glide import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.target.Target import com.example.kiyotaka.githubusers.R import com.example.kiyotaka.githubusers.domain.model.User import com.example.kiyotaka.githubusers.presentation.detail.UserDetailConstraint.UserDetailView import com.github.florent37.viewanimator.ViewAnimator import kotlinx.android.synthetic.main.activity_user_detail.* /** * ユーザーの詳細画面のActivity * Created by kiyotaka on 2018/03/18. */ class UserDetailActivity : AppCompatActivity(), UserDetailView { companion object { private const val TAG = "UserDetailActivity" private const val DATA_STORE_TAG = "data_store_tag" const val USER_LOGIN_ID_KEY = "user_login_id_key" const val USER_AVATAR_URL_KEY = "user_avatar_url_key" } private lateinit var presenter: UserDetailPresenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.i(TAG, "onCreate") setContentView(R.layout.activity_user_detail) val fm = supportFragmentManager val dataStore = fm.findFragmentByTag(DATA_STORE_TAG) as? UserDetailDataStoreFragment ?: UserDetailDataStoreFragment().also { fm.beginTransaction().add(it, DATA_STORE_TAG).commit() } presenter = UserDetailPresenter(this, dataStore) val loginId = intent?.getStringExtra(USER_LOGIN_ID_KEY) val avatarUrl = intent?.getStringExtra(USER_AVATAR_URL_KEY) // アバター画像を読み込んだ後にSharedElementでアニメーションさせるために一旦止める supportPostponeEnterTransition() avatar.transitionName = loginId // Glideに読み込み済みのURLを渡すことでキャッシュを利用させる(消えてなければ利用できる) Glide.with(this) .load(avatarUrl) .listener(object : RequestListener<Drawable> { override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean { return false } override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean { supportStartPostponedEnterTransition() return false } }) .into(avatar) presenter.onCreate(loginId!!) } override fun onDestroy() { presenter.onDestroy() super.onDestroy() } override fun initView() { } override fun showUser(user: User) { login_id.text = user.loginId location.text = user.location email.text = user.email public_repos.text = user.publicRepos.toString() followers.text = user.followers.toString() // フェードインさせる ViewAnimator.animate(login_id_title, login_id, location_title, location, email_title, email_title, email, public_repos_title, public_repos, followers_title, followers) .onStart { login_id_title.visibility = View.VISIBLE login_id.visibility = View.VISIBLE location_title.visibility = View.VISIBLE location.visibility = View.VISIBLE email_title.visibility = View.VISIBLE email.visibility = View.VISIBLE public_repos_title.visibility = View.VISIBLE public_repos.visibility = View.VISIBLE followers_title.visibility = View.VISIBLE followers.visibility = View.VISIBLE } .fadeIn() .duration(200) .start() } override fun showErrorMessage(messageResId: Int) { Toast.makeText(this, getString(messageResId), Toast.LENGTH_LONG).show() } }
0
Kotlin
0
0
b4ab78f8eeb147e0e5a2b645d580bd89777455d0
4,275
GitHubUsers
Apache License 2.0