path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/example/taskorganizaer/ui/presentation/updateTaskScreen/UpdateTaskTopBar.kt
MadhavJai007
668,012,882
false
null
package com.example.taskorganizaer.ui.presentation.updateTaskScreen import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Check import androidx.compose.material.icons.filled.Close import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import com.example.taskorganizaer.data.models.TaskModel @OptIn(ExperimentalMaterial3Api::class) @Composable fun UpdateTaskTopBar( viewModel: UpdateTaskViewModel, taskId: Int, navigateBack: () -> Unit, title: String, note: String, ) { CenterAlignedTopAppBar( title = { Text( text = title, // fontFamily = FontFamily(Font(R.font.playfair_display_regular)), ) }, navigationIcon = { IconButton(onClick = { navigateBack() }) { Icon( Icons.Default.Close, contentDescription = "back") } }, actions = { IconButton(onClick = { val updatedTask = TaskModel(taskId, title, note) viewModel.updateTasks(updatedTask) navigateBack() }) { Icon( Icons.Default.Check, contentDescription = "save") } } ) }
0
Kotlin
0
0
4a3482f847cfc490f31ab600b11d5a8bc0324827
1,513
the-task-organizer
MIT License
backend/src/main/kotlin/de/thkoeln/web2024/longexposure/application/LongExposureController.kt
mi-classroom
790,855,752
false
{"Kotlin": 8073, "Svelte": 5820, "JavaScript": 2892, "Dockerfile": 500, "TypeScript": 449, "HTML": 346, "CSS": 58}
package de.thkoeln.web2024.longexposure.application import jakarta.servlet.http.HttpServletResponse import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.async import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.http.ResponseEntity.ok import org.springframework.web.bind.annotation.* import org.springframework.web.multipart.MultipartFile import org.springframework.web.servlet.mvc.method.annotation.SseEmitter import java.util.UUID import java.util.logging.Logger @RestController class LongExposureController( private val applicationService: LongExposureApplicationService ) { companion object { val LOGGER: Logger = Logger.getLogger(LongExposureController::class.java.name) } private val emitters = mutableMapOf<UUID, SseEmitter>() @PostMapping("/split-video/events", produces = [MediaType.TEXT_EVENT_STREAM_VALUE]) fun registerSplitVideoEventEmitter( @RequestParam(required = false) id: UUID?, response: HttpServletResponse ): SseEmitter { response.setHeader("X-Accel-Buffering", "no") return SseEmitter(-1L).apply { val emitterId = UUID.randomUUID() LOGGER.info("Registered SSE Emitter with id: $emitterId") emitters[emitterId] = this this.send( SseEmitter.event() .name("registered") .id("registered") .data(emitterId.toString()) .build() ) } } @OptIn(DelicateCoroutinesApi::class) @PostMapping("/split-video") fun splitVideo(@RequestParam("file") file: MultipartFile, @RequestParam emitterId: UUID): ResponseEntity<UUID> { val projectId = UUID.randomUUID() GlobalScope.async { applicationService.splitVideo( file, projectId, emitters[emitterId] ?: throw RuntimeException("Emitter not found") ) } return ok(projectId) } @PostMapping("/blend-images") fun blendImages(@RequestBody images: BlendImageDTO): String { return applicationService.blendImages(images.project, images.images) } @GetMapping("/images/{project}/{img}", produces = ["image/png"]) fun getImage(@PathVariable project: String, @PathVariable img: String): ResponseEntity<ByteArray> { return ok(applicationService.getImage(project, img)) } }
9
Kotlin
0
0
5bd45aeedf11d1a4f07421ee0afe872cd04f80b8
2,536
mi-web-technologien-beiboot-ss2024-denwae
MIT License
aws-lambda-kotlin-events/src/main/kotlin/dev/jtkt/services/lambda/runtime/events/kafka/KafkaEvent.kt
jtaub
735,085,227
false
{"Kotlin": 37607}
package dev.jtkt.services.lambda.runtime.events.kafka import kotlinx.serialization.Serializable @Serializable data class KafkaEvent( val bootstrapServers: String = "", val eventSource: String = "", val eventSourceArn: String = "", val records: Map<String, List<KafkaEventRecord>> = emptyMap(), ) @Serializable data class KafkaEventRecord( val headers: List<Map<String, ByteArray>> = emptyList(), val key: String = "", val offset: Long = 0L, val partition: Int = 0, val timestamp: Long = 0L, val timestampType: String = "", val topic: String = "", val value: String = "", ) @Serializable data class TopicPartition( val partition: Int = 0, val topic: String = "", ) { override fun toString(): String = "$topic-$partition" }
0
Kotlin
0
0
0975c2dae77126133841a743639a439f08cf0539
786
aws-lambda-kotlin-libs
Apache License 2.0
idea/testData/quickfix/removeUnused/unusedConstructor.kt
JakeWharton
99,388,807
false
null
// "Safe delete constructor" "true" class Owner(val x: Int) { <caret>constructor(): this(42) } // FUS_QUICKFIX_NAME: org.jetbrains.kotlin.idea.inspections.SafeDeleteFix
1
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
172
kotlin
Apache License 2.0
fontawesome/src/de/msrd0/fontawesome/icons/FA_BED.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 object FA_BED: Icon { override val name get() = "Bed" override val unicode get() = "f236" 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 640 512"><path d="M176 256c44.11 0 80-35.89 80-80s-35.89-80-80-80-80 35.89-80 80 35.89 80 80 80zm352-128H304c-8.84 0-16 7.16-16 16v144H64V80c0-8.84-7.16-16-16-16H16C7.16 64 0 71.16 0 80v352c0 8.84 7.16 16 16 16h32c8.84 0 16-7.16 16-16v-48h512v48c0 8.84 7.16 16 16 16h32c8.84 0 16-7.16 16-16V240c0-61.86-50.14-112-112-112z"/></svg>""" else -> null } }
0
Kotlin
0
0
2fc4755051325e730e9d012c9dfe94f5ea800fdd
1,492
fontawesome-kt
Apache License 2.0
dynabuffers-java/src/main/kotlin/dynabuffers/header/DynabuffersVersion.kt
leftshiftone
211,060,714
false
{"Python": 167058, "Kotlin": 122239, "JavaScript": 58785, "ANTLR": 1629, "TypeScript": 1099}
package dynabuffers.header import dynabuffers.exception.DynabuffersException // This file is autogenerated from DynabuffersVersion.vm class DynabuffersVersion(private val version: String) { companion object { val current = DynabuffersVersion("2.5.0") } fun getMajor(): Byte { try { val major = version.split('.')[0] return major.toByte() } catch (ex: Exception) { throw DynabuffersException("Dynabuffers major version cannot be extracted from: $version.\nReason: $ex") } } }
9
Python
1
4
d7e26ebf07ca1d13fbb527027350fe65b071dd11
563
dynabuffers
Apache License 2.0
app/src/main/java/com/cobeisfresh/azil/ui/adopt_pet/AdoptPetInterface.kt
vejathegreat
162,910,055
false
null
package com.cobeisfresh.azil.ui.adopt_pet import com.cobeisfresh.azil.data.response.DogDetailsResponse import com.cobeisfresh.azil.presentation.base.BasePresenter /** * Created by <NAME> on 04/08/2017. */ interface AdoptPetInterface { interface View { fun showImage(image: String) fun showPlaceholder() fun showName(name: String) fun showEmailInvalidError() fun showNoInternetError() fun showServerError() fun showSuccessAdoptionLayout() fun showProgressBar() fun hideProgressBar() fun showUserEmail(emailText: String) fun showUserName(name: String) fun goBack() fun setEmailBlueLine() fun setNameBlueLine() fun setEmailGreenLine() fun setNameGreenLine() fun setEmailRedLine() fun setNameRedLine() fun removeEmailError() fun removeNameError() fun enableAdopt() fun disableAdopt() fun setNameError() fun setEmailError() fun sendAdoptionFeatureSelectedEvent() fun clearFocusFromInputFields() fun hideKeyboard() fun hideErrorLayout() } interface Presenter : BasePresenter<View> { fun setDogData(dogDetailsResponse: DogDetailsResponse) fun getMe(hasInternet: Boolean) fun iconBackClicked() fun adoptPetClicked(hasInternet: Boolean) fun setIsAcceptBrochure(isChecked: Boolean) fun fullNameChanged(fullName: String) fun emailChanged(email: String) fun messageChanged(message: String) fun onNameChangeFocus(hasFocus: Boolean) fun onEmailChangeFocus(hasFocus: Boolean) fun successAdoptionLayoutClicked() fun touchRootLayout() fun unSubscribe() } }
0
Kotlin
0
0
174c15f617b5766bd2f093a7780c7d090b632d40
1,831
Azil-Osijek-Android
The Unlicense
Corona-Warn-App/src/test/java/de/rki/coronawarnapp/worker/BackgroundWorkHelperTest.kt
covid-be-app
281,650,940
false
null
package de.rki.coronawarnapp.worker import androidx.work.NetworkType import org.junit.Assert import org.junit.Test class BackgroundWorkHelperTest { @Test fun getDiagnosisKeyRetrievalPeriodicWorkTimeInterval() { Assert.assertEquals( BackgroundWorkHelper.getDiagnosisKeyRetrievalPeriodicWorkTimeInterval(), 120 ) } @Test fun getDiagnosisTestResultRetrievalPeriodicWorkTimeInterval() { Assert.assertEquals( BackgroundWorkHelper.getDiagnosisTestResultRetrievalPeriodicWorkTimeInterval(), 120 ) } @Test fun getDiagnosisKeyRetrievalMaximumCalls() { Assert.assertEquals(BackgroundWorkHelper.getDiagnosisKeyRetrievalMaximumCalls(), 12) } @Test fun getConstraintsForDiagnosisKeyOneTimeBackgroundWork() { val constraints = BackgroundWorkHelper.getConstraintsForDiagnosisKeyOneTimeBackgroundWork() Assert.assertEquals(constraints.requiredNetworkType, NetworkType.CONNECTED) } }
6
null
8
55
d556b0b9f29e76295b59be2a1ba89bc4cf6ec33b
1,024
cwa-app-android
Apache License 2.0
app-tracking-protection/vpn-impl/src/main/java/com/duckduckgo/mobile/android/vpn/ui/onboarding/DeviceShieldOnboardingAdapter.kt
hojat72elect
822,396,044
false
{"Kotlin": 11627106, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784}
package com.duckduckgo.mobile.android.vpn.ui.onboarding import android.view.LayoutInflater import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.airbnb.lottie.LottieAnimationView import com.airbnb.lottie.LottieCompositionFactory import com.duckduckgo.common.ui.view.addClickableLink import com.duckduckgo.common.ui.view.gone import com.duckduckgo.common.ui.view.show import com.duckduckgo.mobile.android.vpn.R class DeviceShieldOnboardingAdapter( private val pages: List<VpnOnboardingViewModel.OnboardingPage>, private val clickListener: () -> Unit, ) : RecyclerView.Adapter<PageViewHolder>() { override fun onCreateViewHolder( parent: ViewGroup, viewType: Int, ) = PageViewHolder(parent) override fun getItemCount() = pages.size override fun onBindViewHolder( holder: PageViewHolder, position: Int, ) { holder.bind(pages[position], position, clickListener) } } class PageViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder( LayoutInflater.from(parent.context).inflate(R.layout.activity_vpn_onboarding_page, parent, false), ) { private val pageTitle: TextView = itemView.findViewById(R.id.onboarding_page_title) private val pageText: TextView = itemView.findViewById(R.id.onboarding_page_text) private val onboardingHeader: ImageView = itemView.findViewById(R.id.onboarding_page_image) private val onboardingAnimation: LottieAnimationView = itemView.findViewById(R.id.onboarding_page_animation) fun bind( page: VpnOnboardingViewModel.OnboardingPage, position: Int, clickListener: () -> Unit, ) { pageTitle.setText(page.title) pageText.setText(page.text) when (position) { 0 -> { showAnimationView(page.imageHeader) } 1 -> { showAnimationView(page.imageHeader) } 2 -> { showHeaderView(page.imageHeader) pageText.addClickableLink("learn_more_link", pageText.context.getText(page.text)) { clickListener() } } 3 -> { showAnimationView(page.imageHeader) } } } private fun showAnimationView(animation: Int) { onboardingAnimation.show() onboardingHeader.gone() LottieCompositionFactory.fromRawRes(itemView.context, animation) onboardingAnimation.setAnimation(animation) onboardingAnimation.playAnimation() } private fun showHeaderView(image: Int) { onboardingAnimation.gone() onboardingHeader.show() onboardingHeader.setImageResource(image) } }
0
Kotlin
0
0
54351d039b85138a85cbfc7fc3bd5bc53637559f
2,819
DuckDuckGo
Apache License 2.0
composeApp/src/androidMain/kotlin/com/jetbrains/spacetutorial/AppModule.kt
GustavoZaffani
799,703,010
false
{"Kotlin": 33841, "Swift": 4007}
package com.jetbrains.spacetutorial import com.jetbrains.spacetutorial.network.ServerApi import com.jetbrains.spacetutorial.presentaction.MedicoViewModel import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val appModule = module { single<ServerApi> { ServerApi() } single<ServerSDK> { ServerSDK( api = get() ) } viewModel { MedicoViewModel(sdk = get()) } }
0
Kotlin
0
0
81c1d12005f62094e28edaa1577e06ec84624cd8
426
kmmprojetofinal
Apache License 2.0
core/src/main/java/knaufdan/android/core/calendar/Weekday.kt
DanielKnauf
219,150,024
false
null
package knaufdan.android.core.calendar import androidx.annotation.StringRes import knaufdan.android.core.R sealed class Weekday( val name: String, @StringRes val displayName: Int, @StringRes val shortDisplayName: Int ) { object Monday : Weekday( name = NAME_MONDAY, displayName = R.string.core_calendar_monday, shortDisplayName = R.string.core_calendar_monday_short ) object Tuesday : Weekday( name = NAME_TUESDAY, displayName = R.string.core_calendar_tuesday, shortDisplayName = R.string.core_calendar_tuesday_short ) object Wednesday : Weekday( name = NAME_WEDNESDAY, displayName = R.string.core_calendar_wednesday, shortDisplayName = R.string.core_calendar_wednesday_short ) object Thursday : Weekday( name = NAME_THURSDAY, displayName = R.string.core_calendar_thursday, shortDisplayName = R.string.core_calendar_thursday_short ) object Friday : Weekday( name = NAME_FRIDAY, displayName = R.string.core_calendar_friday, shortDisplayName = R.string.core_calendar_friday_short ) object Saturday : Weekday( name = NAME_SATURDAY, displayName = R.string.core_calendar_saturday, shortDisplayName = R.string.core_calendar_saturday_short ) object Sunday : Weekday( name = NAME_SUNDAY, displayName = R.string.core_calendar_sunday, shortDisplayName = R.string.core_calendar_sunday_short ) companion object { const val NAME_MONDAY = "Monday" const val NAME_TUESDAY = "Tuesday" const val NAME_WEDNESDAY = "Wednesday" const val NAME_THURSDAY = "Thursday" const val NAME_FRIDAY = "Friday" const val NAME_SATURDAY = "Saturday" const val NAME_SUNDAY = "Sunday" val week: List<Weekday> by lazy { listOf(Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday) } fun String.toDay(): Weekday = when (this) { NAME_MONDAY -> Monday NAME_TUESDAY -> Tuesday NAME_WEDNESDAY -> Wednesday NAME_THURSDAY -> Thursday NAME_FRIDAY -> Friday NAME_SATURDAY -> Saturday NAME_SUNDAY -> Sunday else -> Sunday } } }
0
Kotlin
0
2
62ede8066096bb0e3c8a5eada577ccdae2df0d0f
2,389
ArchServices
Apache License 2.0
lib/src/main/kotlin/com/swmansion/starknet/data/serializers/JsonRpcErrorPolymorphicSerializer.kt
software-mansion
503,730,882
false
{"Kotlin": 543318, "Cairo": 13181, "Java": 10748, "C++": 4788, "CMake": 3882, "Shell": 2550, "C": 1775}
package com.swmansion.starknet.data.serializers import com.swmansion.starknet.provider.rpc.JsonRpcContractError import com.swmansion.starknet.provider.rpc.JsonRpcError import com.swmansion.starknet.provider.rpc.JsonRpcStandardError import kotlinx.serialization.DeserializationStrategy import kotlinx.serialization.KSerializer import kotlinx.serialization.SerializationException import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import kotlinx.serialization.json.* internal object JsonRpcErrorPolymorphicSerializer : JsonContentPolymorphicSerializer<JsonRpcError>(JsonRpcError::class) { override fun selectDeserializer(element: JsonElement): DeserializationStrategy<JsonRpcError> { val jsonElement = element.jsonObject val isContractError = "data" in jsonElement && jsonElement["data"]!! is JsonObject && "revert_error" in jsonElement["data"]!!.jsonObject && jsonElement["data"]!!.jsonObject.size == 1 return when { isContractError -> JsonRpcContractError.serializer() else -> JsonRpcStandardError.serializer() } } } internal object JsonRpcStandardErrorSerializer : KSerializer<JsonRpcStandardError> { override fun deserialize(decoder: Decoder): JsonRpcStandardError { val input = decoder as? JsonDecoder ?: throw SerializationException("Expected JsonInput for ${decoder::class}") val jsonObject = input.decodeJsonElement().jsonObject val code = jsonObject.getValue("code").jsonPrimitive.content.toInt() val message = jsonObject.getValue("message").jsonPrimitive.content val data = jsonObject["data"]?.let { when (it) { is JsonPrimitive -> it.jsonPrimitive.content is JsonArray -> it.jsonArray.toString() is JsonObject -> it.jsonObject.toString() } } return JsonRpcStandardError( code = code, message = message, data = data, ) } override val descriptor: SerialDescriptor get() = PrimitiveSerialDescriptor("JsonRpcStandardError", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, value: JsonRpcStandardError) { throw SerializationException("Class used for deserialization only.") } }
18
Kotlin
11
52
db947fb92e5a7d61487eae28296c95a850ffa4b2
2,534
starknet-jvm
MIT License
app/src/main/java/ca/sxxxi/titter/data/utils/contracts/UserMapper.kt
sxxxi
675,507,006
false
null
package ca.sxxxi.titter.data.utils.contracts import ca.sxxxi.titter.data.local.entities.UserEntity import ca.sxxxi.titter.data.models.User import ca.sxxxi.titter.data.network.models.UserNM interface UserMapper : Mapper<UserNM, UserEntity, User>, NDMapper<UserNM, User>
0
Kotlin
0
1
ff71eed870630a31747a6814fff7fac324ad84f2
270
TwitterCloneApp
MIT License
app/src/main/java/org/wikipedia/suggestededits/SuggestionsActivity.kt
greatfire
460,298,221
false
null
package org.wikipedia.suggestededits import android.content.Context import android.content.Intent import android.os.Bundle import org.wikipedia.Constants import org.wikipedia.Constants.INTENT_EXTRA_ACTION import org.wikipedia.Constants.INTENT_EXTRA_INVOKE_SOURCE import org.wikipedia.R import org.wikipedia.activity.SingleFragmentActivity import org.wikipedia.descriptions.DescriptionEditActivity.Action import org.wikipedia.descriptions.DescriptionEditActivity.Action.* import org.wikipedia.suggestededits.SuggestedEditsCardsFragment.Companion.newInstance class SuggestionsActivity : SingleFragmentActivity<SuggestedEditsCardsFragment>() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) supportActionBar!!.setDisplayHomeAsUpEnabled(true) supportActionBar!!.title = getActionBarTitle(intent.getSerializableExtra(INTENT_EXTRA_ACTION) as Action) setImageZoomHelper() } override fun createFragment(): SuggestedEditsCardsFragment { return newInstance(intent.getSerializableExtra(INTENT_EXTRA_ACTION) as Action, intent.getSerializableExtra(INTENT_EXTRA_INVOKE_SOURCE) as Constants.InvokeSource) } private fun getActionBarTitle(action: Action): String { return if (action == ADD_IMAGE_TAGS) { getString(R.string.suggested_edits_tag_images) } else if (action == ADD_CAPTION || action == TRANSLATE_CAPTION) { getString(R.string.suggested_edits_caption_images) } else { getString(R.string.suggested_edits_describe_articles) } } companion object { const val EXTRA_SOURCE_ADDED_CONTRIBUTION = "addedContribution" fun newIntent(context: Context, action: Action, source: Constants.InvokeSource): Intent { return Intent(context, SuggestionsActivity::class.java) .putExtra(INTENT_EXTRA_ACTION, action) .putExtra(INTENT_EXTRA_INVOKE_SOURCE, source) } } }
2
null
480
38
8c8de602274b0132fc5d22b394a2c47fcd0bf2eb
2,019
apps-android-wikipedia-envoy
Apache License 2.0
app/src/main/java/ru/nbsp/pushka/presentation/subscription/params/control/dropdown/DropdownControl.kt
dimorinny
51,604,851
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "JSON": 1, "Proguard": 11, "Java": 14, "XML": 102, "Kotlin": 258}
package ru.nbsp.pushka.presentation.subscription.params.control.dropdown import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.AdapterView import android.widget.LinearLayout import android.widget.Spinner import android.widget.TextView import ru.nbsp.pushka.R import ru.nbsp.pushka.presentation.core.model.subscription.control.Option import ru.nbsp.pushka.presentation.subscription.params.control.Control import ru.nbsp.pushka.presentation.subscription.params.control.dropdown.adapter.DropdownAdapter import ru.nbsp.pushka.util.bindView class DropdownControl(context: Context, values: List<Option>, attrs: AttributeSet? = null) : LinearLayout(context, attrs), Control { val adapter: DropdownAdapter = DropdownAdapter( getContext(), android.R.layout.simple_spinner_dropdown_item, values, context.getString(R.string.subscribe_dropdown_placeholder)) val title: TextView by bindView(R.id.dropdown_title) val errorIndicator: TextView by bindView(R.id.dropdown_error) val spinner: Spinner by bindView(R.id.dropdown_spinner) init { val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater inflater.inflate(R.layout.control_dropdown, this, true) spinner.adapter = adapter } override fun setNoError() { errorIndicator.visibility = GONE } override fun setError() { errorIndicator.visibility = VISIBLE errorIndicator.text = context.getString(R.string.subscribe_control_error) } override fun getValue(): String? = adapter.options[spinner.selectedItemPosition].value override fun setValue(value: String?) { if (value != null) { val index = adapter.getIndexByValue(value) if (index != null) { spinner.setSelection(index) } } } override fun setOnChangeListener(onChangeListener: Control.OnChangeListener) { spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) {} override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { onChangeListener.onChange(adapter.options[position].value) } } } fun setTitle(value: String) { title.text = value } }
0
Kotlin
0
0
71ac416b33f628bbcec12fad4776f7abc242c882
2,498
pushka-android
MIT License
depstoml/src/test/resources/NoVersionFoundFile.kt
overpas
649,800,541
false
{"Kotlin": 30813}
object Dependencies2 { const val version = "1.1.1" const val artifact = "my:artifact:${Versions.Kotlin.version}" }
7
Kotlin
0
1
69b88b54ff483dea67fc9f207c956a9b9631eba6
124
depstoml
MIT License
src/main/kotlin/lv/gdg/kotlin/kata/Task8.kt
siga111
76,856,221
false
null
package lv.gdg.kotlin.kata /** * Description: * * Adding values of arrays in a shifted way * * You have to write a method, that gets two parameter: * * 1. An array of arrays with int-numbers * 2. The shifting value * * The method should add the values of the arrays to one new array. * * The arrays in the array will all have the same size and this size will always be greater than 0. * The shifting value is always a value from 0 up to the size of the arrays. * There are always arrays in the array, so you do not need to check for null or empty. * * 1. Example: * * [[1,2,3,4,5,6], [7,7,7,7,7,-7]], 0 * * 1,2,3,4,5,6 * 7,7,7,7,7,-7 * * --> [8,9,10,11,12,-1] * * 2. Example * * [[1,2,3,4,5,6], [7,7,7,7,7,7]], 3 * * 1,2,3,4,5,6 * 7,7,7,7,7,7 * * --> [1,2,3,11,12,13,7,7,7] * * 3. Example * * [[1,2,3,4,5,6], [7,7,7,-7,7,7], [1,1,1,1,1,1]], 3 * * 1,2,3,4,5,6 * 7,7,7,-7,7,7 * 1,1,1,1,1,1 * * --> [1,2,3,11,12,13,-6,8,8,1,1,1] * * Have fun coding it and please don't forget to vote and rank this kata! :-) * I have created other katas. Have a look if you like coding and challenges. */
0
Kotlin
0
0
3a853aab5f7b9e4d2f823737632adf93c93a00aa
1,157
gdg-riga-kotlin
Apache License 2.0
app/src/main/java/com/paypay/currencyconverter/ui/currencyconverter/CurrencyConverterViewModel.kt
mnhmasum
523,544,422
false
null
package com.paypay.currencyconverter.ui.currencyconverter import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.paypay.currencyconverter.database.models.CurrencyResponse import com.paypay.currencyconverter.database.models.ExchangeRate import com.paypay.currencyconverter.repository.CurrencyConverterRepositoryInterface import com.paypay.currencyconverter.utils.ConverterIntent import com.paypay.currencyconverter.utils.ConverterIntent.* import com.paypay.currencyconverter.utils.ConverterUtil import com.paypay.currencyconverter.utils.DataState import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.consumeAsFlow import kotlinx.coroutines.launch class CurrencyConverterViewModel internal constructor(private val currencyRepoInterface: CurrencyConverterRepositoryInterface) : ViewModel() { val intentAction = Channel<ConverterIntent>() val currencyLiveData = MutableLiveData<CurrencyResponse>() private var selectedRate = MutableLiveData(0.0) private val _dataState = MutableStateFlow<DataState>(DataState.Idle) val dataState: StateFlow<DataState> get() = _dataState init { handleIntentAction() } private fun handleIntentAction() { viewModelScope.launch { intentAction.consumeAsFlow().collect { when (it) { is Fetch -> fetchCurrencyExchangeData() is UpdateSpinner -> updateSpinner(it.currencyResponse) is Convert -> startConversion(it) } } } } private fun fetchCurrencyExchangeData() { viewModelScope.launch(Dispatchers.IO) { _dataState.value = DataState.Loading _dataState.value = DataState.Success(fetchDataFromRepository()) } } private suspend fun fetchDataFromRepository(): CurrencyResponse? { return currencyRepoInterface.getCurrencyData() } private fun updateSpinner(currencyResponse: CurrencyResponse?) { currencyResponse?.let { currencyLiveData.postValue(it) } } private fun startConversion(it: Convert) { viewModelScope.launch(Dispatchers.IO) { _dataState.value = DataState.Loading _dataState.value = DataState.ConversionSuccess(getConvertedCurrencyList(it)) } } private fun getConvertedCurrencyList(it: Convert): List<ExchangeRate> { it.baseRate?.let { selectedRate.postValue(it) } val convertedRateList = ConverterUtil.convertValueAndGet(it.baseRate, it.amount, currencyLiveData.value) if (it.amount == 0.0) (convertedRateList as ArrayList<ExchangeRate>).clear() return convertedRateList } fun onTextChangeComplete(text: CharSequence?) { val input = if (text.toString().isNotEmpty()) text.toString().toDouble() else 0.0 viewModelScope.launch(Dispatchers.IO) { intentAction.send(Convert(input, selectedRate.value)) } } }
0
Kotlin
0
2
d1e1a4288748388ef4ef5a7a19937e37d285329e
3,200
Currency-Converter-MVVM
Apache License 2.0
src/main/kotlin/io/emeraldpay/dshackle/archive/runner/RunCopy.kt
emeraldpay
461,364,978
false
null
package io.emeraldpay.dshackle.archive.runner import io.emeraldpay.dshackle.archive.BlocksRange import io.emeraldpay.dshackle.archive.config.RunConfig import io.emeraldpay.dshackle.archive.storage.BlocksReader import io.emeraldpay.dshackle.archive.storage.CompleteWriter import io.emeraldpay.dshackle.archive.storage.SourceStorage import io.emeraldpay.dshackle.archive.storage.TransactionsReader import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Profile import org.springframework.stereotype.Service import reactor.core.publisher.Flux import reactor.core.publisher.Mono import reactor.core.scheduler.Schedulers import java.nio.file.Path @Service @Profile("run-copy") class RunCopy( @Autowired private val completeWriter: CompleteWriter, @Autowired private val runConfig: RunConfig, @Autowired private val blocksRange: BlocksRange, @Autowired private val sourceStorage: SourceStorage, @Autowired private val transactionsReader: TransactionsReader, @Autowired private val blocksReader: BlocksReader, ) : RunCommand { companion object { private val log = LoggerFactory.getLogger(RunCopy::class.java) } override fun run(): Mono<Void> { log.info("Recover files") if (runConfig.inputFiles == null) { log.warn("List of input files is not set") return Mono.empty() } val sources = sourceStorage.getInputFiles() return Mono.zip( processBlocks(sources.blocks) .thenReturn(true) .subscribeOn(Schedulers.boundedElastic()), processTransactions(sources.transactions) .thenReturn(true) .subscribeOn(Schedulers.boundedElastic()), ).then(completeWriter.closeOpenFiles()).then() } fun processBlocks(files: Flux<Path>): Mono<Void> { // not it's overriden for compactions val source = files .doOnSubscribe { log.info("Process blocks") } .flatMap(blocksReader::open) .filter { blocksRange.includes(it.height) } return completeWriter.consumeBlocks(source).then() } fun processTransactions(files: Flux<Path>): Mono<Void> { // not it's overriden for compactions val source = files .doOnSubscribe { log.info("Process transactions") } .flatMap(transactionsReader::open) .filter { blocksRange.includes(it.height) } return completeWriter.consumeTransactions(source).then() } }
1
Kotlin
0
5
40a52ff813f0abb1f651e8c95205726eb7b6caa9
2,647
dshackle-archive
Apache License 2.0
githubusers/src/main/java/com/bblackbelt/githubusers/GitHubApp.kt
droidizer
134,574,322
true
{"Kotlin": 71388, "Java": 3014}
package com.bblackbelt.githubusers import android.app.Activity import android.app.Application import android.content.Context import com.bblackbelt.githubusers.di.DaggerGitHubComponent import dagger.android.AndroidInjector import dagger.android.DispatchingAndroidInjector import dagger.android.HasActivityInjector import javax.inject.Inject import android.support.multidex.MultiDex open class GitHubApp : Application(), HasActivityInjector { @Inject lateinit var mAndroidDispatchingInjector: DispatchingAndroidInjector<Activity> override fun onCreate() { super.onCreate() DaggerGitHubComponent .builder() .application(this) .build() .inject(this) } override fun attachBaseContext(base: Context) { super.attachBaseContext(base) MultiDex.install(this) } override fun activityInjector(): AndroidInjector<Activity> = mAndroidDispatchingInjector }
0
Kotlin
1
0
a60f0d61ddb0b3d09087b02cc1fd673ca3f2f94c
973
BindingsCollections
Apache License 2.0
buildSrc/src/main/kotlin/DependencyGradle.kt
amirisback
229,149,549
false
{"Kotlin": 189516, "Java": 35619}
/* * Created by faisalamir on 19/09/21 * FrogoRecyclerView * ----------------------------------------- * Name : <NAME> * E-mail : <EMAIL> * Github : github.com/amirisback * ----------------------------------------- * Copyright (C) 2021 FrogoBox Inc. * All rights reserved * */ object DependencyGradle { // dependencies version const val KOTLIN_VERSION = Version.JetBrains.kotlin const val FROGO_PATH_RECYCLER_VIEW = ":frogorecyclerview" const val FROGO_UI_VERSION = "1.1.5" const val FROGO_CONSUME_API_VERSION = "2.4.5" const val FROGO_UI = "com.github.frogobox:frogo-ui:$FROGO_UI_VERSION" const val FROGO_CONSUME_API = "com.github.frogobox:frogo-consume-api:$FROGO_CONSUME_API_VERSION" }
1
Kotlin
16
161
d7946c2b4706abb8742c7d73aafd3e44b988af0a
742
frogo-recycler-view
Apache License 2.0
src/test/kotlin/net/pwall/json/schema/codegen/CodeGeneratorBaseDerivedRequiredTest.kt
pwall567
287,935,667
false
{"Kotlin": 721424, "Mustache": 64184, "Java": 12785}
/* * @(#) CodeGeneratorBaseDerivedRequiredTest.kt * * json-kotlin-schema-codegen JSON Schema Code Generation * Copyright (c) 2022 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.pwall.json.schema.codegen import kotlin.test.Test import kotlin.test.expect import java.io.File import io.kjson.JSON import io.kjson.pointer.JSONPointer import net.pwall.json.schema.codegen.CodeGeneratorTestUtil.OutputDetails import net.pwall.json.schema.codegen.CodeGeneratorTestUtil.createHeader import net.pwall.json.schema.codegen.CodeGeneratorTestUtil.dirs import net.pwall.json.schema.codegen.CodeGeneratorTestUtil.outputCapture class CodeGeneratorBaseDerivedRequiredTest { @Test fun `should generate base and derived classes where derived adds required`() { val input = File("src/test/resources/test-base-derived-required.schema.json") val codeGenerator = CodeGenerator() val outputDetailsBase = OutputDetails(TargetFileName("Base", "kt", dirs)) val outputDetailsDerived = OutputDetails(TargetFileName("Derived", "kt", dirs)) codeGenerator.basePackageName = "com.example" codeGenerator.outputResolver = outputCapture(outputDetailsBase, outputDetailsDerived) codeGenerator.generateAll(JSON.parseNonNull(input.readText()), JSONPointer("/\$defs")) expect(createHeader("Base.kt") + expectedBase) { outputDetailsBase.output() } expect(createHeader("Derived.kt") + expectedDerived) { outputDetailsDerived.output() } } @Test fun `should generate base and derived classes where derived adds required in Java`() { val input = File("src/test/resources/test-base-derived-required.schema.json") val codeGenerator = CodeGenerator(TargetLanguage.JAVA) val outputDetailsBase = OutputDetails(TargetFileName("Base", "java", dirs)) val outputDetailsDerived = OutputDetails(TargetFileName("Derived", "java", dirs)) codeGenerator.basePackageName = "com.example" codeGenerator.outputResolver = outputCapture(outputDetailsBase, outputDetailsDerived) codeGenerator.generateAll(JSON.parseNonNull(input.readText()), JSONPointer("/\$defs")) expect(createHeader("Base.java") + expectedBaseJava) { outputDetailsBase.output() } expect(createHeader("Derived.java") + expectedDerivedJava) { outputDetailsDerived.output() } } companion object { const val expectedBase = """package com.example open class Base( aaa: String? = null, val bbb: Int ) { init { require(bbb in 0..99) { "bbb not in range 0..99 - ${'$'}bbb" } } open val aaa: String? = aaa override fun equals(other: Any?): Boolean = this === other || other is Base && aaa == other.aaa && bbb == other.bbb override fun hashCode(): Int = aaa.hashCode() xor bbb.hashCode() override fun toString() = "Base(aaa=${'$'}aaa, bbb=${'$'}bbb)" open fun copy( aaa: String? = this.aaa, bbb: Int = this.bbb ) = Base(aaa, bbb) operator fun component1() = aaa operator fun component2() = bbb } """ const val expectedDerived = """package com.example class Derived( override val aaa: String, bbb: Int, val ccc: String ) : Base(aaa, bbb) { init { require(aaa.length <= 30) { "aaa length > maximum 30 - ${'$'}{aaa.length}" } } override fun equals(other: Any?): Boolean = this === other || other is Derived && super.equals(other) && ccc == other.ccc override fun hashCode(): Int = super.hashCode() xor ccc.hashCode() override fun toString() = "Derived(aaa=${'$'}aaa, bbb=${'$'}bbb, ccc=${'$'}ccc)" fun copy( aaa: String = this.aaa, bbb: Int = this.bbb, ccc: String = this.ccc ) = Derived(aaa, bbb, ccc) operator fun component3() = ccc } """ const val expectedBaseJava = """package com.example; public class Base { private final String aaa; private final int bbb; public Base( String aaa, int bbb ) { this.aaa = aaa; if (bbb < 0 || bbb > 99) throw new IllegalArgumentException("bbb not in range 0..99 - " + bbb); this.bbb = bbb; } public String getAaa() { return aaa; } public int getBbb() { return bbb; } @Override public boolean equals(Object cg_other) { if (this == cg_other) return true; if (!(cg_other instanceof Base)) return false; Base cg_typedOther = (Base)cg_other; if (aaa == null ? cg_typedOther.aaa != null : !aaa.equals(cg_typedOther.aaa)) return false; return bbb == cg_typedOther.bbb; } @Override public int hashCode() { int hash = (aaa != null ? aaa.hashCode() : 0); return hash ^ bbb; } public static class Builder { private String aaa; private int bbb; public Builder withAaa(String aaa) { this.aaa = aaa; return this; } public Builder withBbb(int bbb) { this.bbb = bbb; return this; } public Base build() { return new Base( aaa, bbb ); } } } """ const val expectedDerivedJava = """package com.example; public class Derived extends Base { private final String ccc; public Derived( String aaa, int bbb, String ccc ) { super(cg_valid_aaa(aaa), bbb); if (ccc == null) throw new IllegalArgumentException("Must not be null - ccc"); this.ccc = ccc; } private static String cg_valid_aaa(String aaa) { if (aaa == null) throw new IllegalArgumentException("Must not be null - aaa"); if (aaa.length() > 30) throw new IllegalArgumentException("aaa length > maximum 30 - " + aaa.length()); return aaa; } public String getCcc() { return ccc; } @Override public boolean equals(Object cg_other) { if (this == cg_other) return true; if (!(cg_other instanceof Derived)) return false; if (!super.equals(cg_other)) return false; Derived cg_typedOther = (Derived)cg_other; return ccc.equals(cg_typedOther.ccc); } @Override public int hashCode() { int hash = super.hashCode(); return hash ^ ccc.hashCode(); } public static class Builder { private String aaa; private int bbb; private String ccc; public Builder withAaa(String aaa) { this.aaa = aaa; return this; } public Builder withBbb(int bbb) { this.bbb = bbb; return this; } public Builder withCcc(String ccc) { this.ccc = ccc; return this; } public Derived build() { return new Derived( aaa, bbb, ccc ); } } } """ } }
31
Kotlin
14
77
96ed248ace4be8d2f90baa72535163cb31f188d5
8,249
json-kotlin-schema-codegen
MIT License
src/test/kotlin/eZmaxApi/apis/ObjectPermissionApiTest.kt
eZmaxinc
271,950,932
false
{"Kotlin": 6909939}
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package eZmaxApi.apis import io.kotlintest.shouldBe import io.kotlintest.specs.ShouldSpec import eZmaxApi.apis.ObjectPermissionApi import eZmaxApi.models.CommonResponseError import eZmaxApi.models.PermissionCreateObjectV1Request import eZmaxApi.models.PermissionCreateObjectV1Response import eZmaxApi.models.PermissionDeleteObjectV1Response import eZmaxApi.models.PermissionEditObjectV1Request import eZmaxApi.models.PermissionEditObjectV1Response import eZmaxApi.models.PermissionGetObjectV2Response class ObjectPermissionApiTest : ShouldSpec() { init { // uncomment below to create an instance of ObjectPermissionApi //val apiInstance = ObjectPermissionApi() // to test permissionCreateObjectV1 should("test permissionCreateObjectV1") { // uncomment below to test permissionCreateObjectV1 //val permissionCreateObjectV1Request : PermissionCreateObjectV1Request = // PermissionCreateObjectV1Request | //val result : PermissionCreateObjectV1Response = apiInstance.permissionCreateObjectV1(permissionCreateObjectV1Request) //result shouldBe ("TODO") } // to test permissionDeleteObjectV1 should("test permissionDeleteObjectV1") { // uncomment below to test permissionDeleteObjectV1 //val pkiPermissionID : kotlin.Int = 56 // kotlin.Int | The unique ID of the Permission //val result : PermissionDeleteObjectV1Response = apiInstance.permissionDeleteObjectV1(pkiPermissionID) //result shouldBe ("TODO") } // to test permissionEditObjectV1 should("test permissionEditObjectV1") { // uncomment below to test permissionEditObjectV1 //val pkiPermissionID : kotlin.Int = 56 // kotlin.Int | The unique ID of the Permission //val permissionEditObjectV1Request : PermissionEditObjectV1Request = // PermissionEditObjectV1Request | //val result : PermissionEditObjectV1Response = apiInstance.permissionEditObjectV1(pkiPermissionID, permissionEditObjectV1Request) //result shouldBe ("TODO") } // to test permissionGetObjectV2 should("test permissionGetObjectV2") { // uncomment below to test permissionGetObjectV2 //val pkiPermissionID : kotlin.Int = 56 // kotlin.Int | The unique ID of the Permission //val result : PermissionGetObjectV2Response = apiInstance.permissionGetObjectV2(pkiPermissionID) //result shouldBe ("TODO") } } }
0
Kotlin
0
0
961c97a9f13f3df7986ea7ba55052874183047ab
2,827
eZmax-SDK-kotlin
MIT License
misc/src/main/java/good/damn/sav/misc/extensions/Canvas.kt
GoodDamn
850,249,504
false
{"Kotlin": 87179, "Java": 1420}
package good.damn.sav.misc.extensions import android.graphics.Canvas import android.graphics.Paint import android.graphics.PointF inline fun Canvas.drawLine( point1: PointF, point2: PointF, paint: Paint ) { drawLine( point1.x, point1.y, point2.x, point2.y, paint ) } inline fun Canvas.drawCircle( point: PointF, radius: Float, paint: Paint ) { drawCircle( point.x, point.y, radius, paint ) }
0
Kotlin
0
1
c6fb9b2eb99b1d87efeda949ff9e8cd4ccc4442b
506
VectorEditorAndroid
MIT License
layouts-ktx/tests/src/javafxx/layouts/scene/layout/AnchorPaneTest.kt
gitter-badger
143,415,479
true
{"Kotlin": 475058, "HTML": 1425, "Java": 731}
package javafxx.layouts.scene.layout import javafx.scene.layout.Region import javafxx.layouts.anchorPane import javafxx.layouts.pane import javafxx.layouts.region import javafxx.test.PlatformLayoutTest import kotlin.test.assertEquals class AnchorPaneTest : PlatformLayoutTest() { override fun newInstance() { assertEquals(anchorPane(Region()).children.size, 1) } override fun newInstanceInitialized() { anchorPane { val region1 = region() anchorAll 10.0 assertEquals(region1.anchorTop, 10.0) assertEquals(region1.anchorLeft, 10.0) assertEquals(region1.anchorBottom, 10.0) assertEquals(region1.anchorRight, 10.0) val region2 = region() anchorTop 10.0 assertEquals(region2.anchorTop, 10.0) val region3 = region() anchorLeft 10.0 assertEquals(region3.anchorLeft, 10.0) val region4 = region() anchorBottom 10.0 assertEquals(region4.anchorBottom, 10.0) val region5 = region() anchorRight 10.0 assertEquals(region5.anchorRight, 10.0) region1.reset() assertEquals(region1.anchorTop, null) assertEquals(region1.anchorLeft, null) assertEquals(region1.anchorBottom, null) assertEquals(region1.anchorRight, null) region2.reset() assertEquals(region2.anchorTop, null) region3.reset() assertEquals(region3.anchorLeft, null) region4.reset() assertEquals(region4.anchorBottom, null) region5.reset() assertEquals(region5.anchorRight, null) assertEquals(children.size, 5) } } override fun withManager() { assertEquals(pane { anchorPane() }.children.size, 1) } override fun withManagerInitialized() { assertEquals(pane { anchorPane { } }.children.size, 1) } }
0
Kotlin
0
0
fe550237f725e398e3f78ed2e73a779a133088c2
1,985
javafxx
Apache License 2.0
app/src/main/java/uk/ac/cam/smw98/bletracker/ui/screens/BLETrackerApp.kt
sowalks
749,925,143
false
{"Kotlin": 107473}
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. * * Modified from MarsPhotos Code Lab from MarsPhtosApplication.kt. */ package com.example.bletracker.ui import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.lifecycle.viewmodel.compose.viewModel import com.example.bletracker.data.utils.PermissionManager import com.example.bletracker.ui.screens.PermissionScreen import com.example.bletracker.ui.screens.ScreenTabLayout import com.example.bletracker.ui.viewmodel.PermissionViewModel import org.altbeacon.beacon.RegionViewModel @Composable fun BLETrackerApp(regionViewModel: RegionViewModel,permissionManager: PermissionManager) { val snackBarHostState = remember { SnackbarHostState() } Scaffold( snackbarHost = { SnackbarHost(snackBarHostState) }, modifier = Modifier ) { Surface( modifier = Modifier .fillMaxSize() .padding(it) ) { val permissionsViewModel: PermissionViewModel = viewModel(factory = PermissionViewModel.Factory(permissions = permissionManager).factory) val permissionsGranted = permissionsViewModel.uiState.collectAsState().value.hasAllAccess if (!permissionsGranted) { PermissionScreen(viewModel = permissionsViewModel, onConfirm = {}) } else { ScreenTabLayout( regionViewModel = regionViewModel, snackBarHostState = snackBarHostState, modifier = Modifier.fillMaxSize() ) } } } }
0
Kotlin
0
0
d739e864f5940855186b5883005fbf38fb3da9d6
2,599
android-ble-tracker
Apache License 2.0
manager-test/src/main/kotlin/com/github/lee/managertest/ManagerTestApplication.kt
291700351
142,010,755
false
{"Java": 55328, "Kotlin": 19403, "Dockerfile": 1295, "Shell": 154, "Batchfile": 140}
package com.github.lee.managertest import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.cloud.netflix.eureka.EnableEurekaClient import org.springframework.cloud.openfeign.EnableFeignClients @EnableEurekaClient @EnableFeignClients @SpringBootApplication class ManagerTestApplication fun main(args: Array<String>) { runApplication<ManagerTestApplication>(*args) }
1
null
1
1
d7f65afb5ef880b22249ddd2df002e9268582c2b
458
CloudManager
MIT License
plugins/github/src/org/jetbrains/plugins/github/api/data/GHCommitStatusContextStatus.kt
hieuprogrammer
284,920,751
true
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.api.data class GHCommitStatusContextStatus(val context: String, val state: GHCommitStatusContextState)
1
null
1
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
282
intellij-community
Apache License 2.0
ejson/src/test/kotlin/com/eygraber/ejson/test_utils.kt
eygraber
374,549,580
false
null
package com.eygraber.ejson import assertk.assertThat import assertk.assertions.isEqualTo import assertk.assertions.isInstanceOf import assertk.assertions.isNotNull import com.google.common.jimfs.Configuration import com.google.common.jimfs.Jimfs import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.jsonObject import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.assertThrows import java.nio.file.FileSystem import kotlin.io.path.createDirectories import kotlin.io.path.createFile import kotlin.io.path.writeText internal inline fun <reified T : Throwable> assertThrowsWithMessage( message: String, noinline action: () -> Unit ) { assertThat(assertThrows<T>(action).message).isEqualTo(message) } internal inline fun usingFileSystem( fsConfig: Configuration = Configuration.forCurrentPlatform(), block: (FileSystem) -> Unit ) { Jimfs.newFileSystem(fsConfig).use(block) } internal inline fun FileSystem.withDefaultKeyDir( block: (EjsonKeyPair, Ejson) -> Unit ) { val kp = EjsonKeyPair.generate() val keyDir = rootDirectories.first().resolve(getPath("opt", "ejson", "keys")).createDirectories() keyDir.resolve(getPath(kp.publicKey.toHexString())).createFile().writeText( kp.secretKey.toHexString() ) val ejson = Ejson(filesystem = this) block(kp, ejson) } internal inline fun FileSystem.withEnvVarKeyDir( block: (EjsonKeyPair, Ejson) -> Unit ) { val kp = EjsonKeyPair.generate() val envvar = System.getenv("EJSON_KEYDIR") assertThat(envvar).isNotNull() val keyDir = getPath(envvar).createDirectories() keyDir.resolve(getPath(kp.publicKey.toHexString())).createFile().writeText( kp.secretKey.toHexString() ) val ejson = Ejson(filesystem = this) block(kp, ejson) } internal inline fun FileSystem.withOverrideKeyDir( path: String, block: (EjsonKeyPair, Ejson) -> Unit ) { val kp = EjsonKeyPair.generate() val keyDir = rootDirectories.first().resolve(getPath(path)).createDirectories() keyDir.resolve(getPath(kp.publicKey.toHexString())).createFile().writeText( kp.secretKey.toHexString() ) val ejson = Ejson(overrideKeyDir = keyDir, filesystem = this) block(kp, ejson) } internal fun Ejson.assertEncryptSucceeded(input: String): Ejson.Result.Success = Assertions.assertDoesNotThrow<Ejson.Result.Success> { encrypt(input).assertSucceeded() } internal fun Ejson.assertDecryptSucceeded(input: String, userSuppliedPrivateKey: String? = null): Ejson.Result.Success = Assertions.assertDoesNotThrow<Ejson.Result.Success> { decrypt(input, userSuppliedPrivateKey).assertSucceeded() } internal fun Ejson.assertEncryptSucceededJson(input: String): JsonObject = assertEncryptSucceeded(input).toJson() internal fun Ejson.assertDecryptSucceededJson(input: String, userSuppliedPrivateKey: String? = null): JsonObject = Assertions.assertDoesNotThrow<JsonObject> { assertDecryptSucceeded(input, userSuppliedPrivateKey).toJson() } internal fun Ejson.Result.assertSucceeded(): Ejson.Result.Success { assertThat(this).isInstanceOf(Ejson.Result.Success::class) return this as Ejson.Result.Success } internal fun Ejson.Result.Success.toJson() = Json.Default.parseToJsonElement(json).jsonObject internal fun Ejson.assertDecryptFailed(input: String): Ejson.Result.Error = Assertions.assertDoesNotThrow<Ejson.Result.Error> { decrypt(input).assertFailed() } internal fun Ejson.Result.assertFailed(): Ejson.Result.Error { assertThat(this).isInstanceOf(Ejson.Result.Error::class) return this as Ejson.Result.Error } internal fun EjsonKeyPair.createValidSecretsJson( keyValue: Pair<String, String>, vararg keyValues: Pair<String, String> ) = """ |{ |"_public_key": "${publicKey.toHexString()}", |"${keyValue.first}": "${keyValue.second}" |${if(keyValues.isEmpty()) "" else keyValues.joinToString(prefix = ",") { """"${it.first}": "${it.second}"""" }} |} """.trimMargin()
3
null
0
1
1d0483375c9edf314728d8ee48213ab11610ec50
3,975
ejson-kotlin
MIT License
app/src/main/kotlin/io/github/yeobara/android/meetup/User.kt
hojinchu99
46,778,834
false
{"Kotlin": 79978, "Java": 674}
package io.github.yeobara.android.meetup import com.fasterxml.jackson.annotation.JsonIgnoreProperties @JsonIgnoreProperties(ignoreUnknown = true) public class User(val id: String, val nickname: String, val email: String, var status: String = "", val profileImageURL: String? = null, val gcmToken: String? = null) { constructor() : this("", "", "") { } }
0
Kotlin
0
0
50ff11b443d953f4212268326095c65fd4be5be8
455
yeobara-android
MIT License
notes-biz/src/commonMain/kotlin/org/avr/notes/biz/workers/note/StubNoteValidationBadTitle.kt
alex-avr
589,281,806
false
null
package org.avr.notes.biz.workers.note import org.avr.notes.common.NoteContext import org.avr.notes.common.models.NotesError import org.avr.notes.common.models.NotesState import org.avr.notes.common.stubs.NotesStubs import org.avr.notes.cor.ICorChainDsl import org.avr.notes.cor.worker fun ICorChainDsl<NoteContext>.stubNoteValidationBadTitle(title: String) = worker { this.title = title on { stubCase == NotesStubs.BAD_FOLDER_NAME && state == NotesState.RUNNING } handle { state = NotesState.FAILING this.errors.add( NotesError( group = "validation", code = "validation-note-title", field = "title", message = "Wrong title field" ) ) } }
0
Kotlin
0
0
03aaa0789fd602dcacd4f4ef2747f80cb80f331a
768
notes
Apache License 2.0
test-suite-kotlin-kapt-server-generator/src/main/kotlin/io/micronaut/openapi/test/filter/MyFilter.kt
micronaut-projects
178,205,672
false
null
package io.micronaut.openapi.test.filter import io.micronaut.core.annotation.Nullable import java.util.regex.Pattern /** * A type for specifying result filtering. * * This is used to demonstrate custom parameter mapping, as it is mapped from the * Filter header and bound with a custom binder. * * @param conditions The filtering conditions */ data class MyFilter( val conditions: List<Condition> ) { override fun toString() = conditions.joinToString(",", transform = { it.toString() }) /** * A filtering condition. * * @param propertyName the parameter to use for filtering * @param comparator the filtering comparator * @param value the value to compare with */ data class Condition( val propertyName: String, val comparator: ConditionComparator, val value: Any, ) { override fun toString() = propertyName + comparator + value companion object { /** * Parse the condition from a string representation. * * @param string the string * @return the parsed condition */ @JvmStatic fun parse(string: String): Condition { val matcher = CONDITION_PATTERN.matcher(string) if (!matcher.find()) { throw ParseException("The filter condition must match '$CONDITION_REGEX' but is '$string'") } return Condition( matcher.group(1), ConditionComparator.parse(matcher.group(2)), matcher.group(3) ) } } } /** * An enum value for specifying how to compare in the condition. */ enum class ConditionComparator( private val representation: String ) { EQUALS("="), GREATER_THAN(">"), LESS_THAN("<"); override fun toString(): String { return representation } companion object { private val VALUE_MAPPING = entries.associateBy { it.representation } /** * Parse the condition comparator from string representation. * * @param representation the string * @return the comparator */ @JvmStatic fun parse(representation: String): ConditionComparator { require(VALUE_MAPPING.containsKey(representation)) { ParseException("Condition comparator not supported: '$representation'") } return VALUE_MAPPING[representation]!! } } } /** * A custom exception for failed parsing */ class ParseException( message: String ) : RuntimeException(message) companion object { private const val CONDITION_REGEX = "^(.+)([<>=])(.+)$" /** * An implementation with no filtering. */ private val EMPTY = MyFilter(listOf()) private val CONDITION_PATTERN = Pattern.compile(CONDITION_REGEX) /** * Parse the filter from a query parameter. * * @param value the string representation of filter. * @return the filter. */ @JvmStatic fun parse(value: @Nullable String?): MyFilter { if (value == null) { return EMPTY } val conditions = value.split(",") .map { Condition.parse(it) } return MyFilter(conditions) } } }
9
null
93
79
6d5c15f603831ba8b8c0134c7cd4be169e6b478a
3,555
micronaut-openapi
Apache License 2.0
app/src/main/java/com/zaneschepke/wireguardautotunnel/service/foreground/ServiceManager.kt
zaneschepke
644,710,160
false
{"Kotlin": 334681, "Ruby": 860}
package com.zaneschepke.wireguardautotunnel.service.foreground import android.app.Service import android.content.Context import android.content.Intent import android.net.VpnService import timber.log.Timber object ServiceManager { private fun <T : Service> actionOnService(action: Action, context: Context, cls: Class<T>, extras: Map<String, Int>? = null) { if (VpnService.prepare(context) != null) return val intent = Intent(context, cls).also { it.action = action.name extras?.forEach { (k, v) -> it.putExtra(k, v) } } intent.component?.javaClass try { when (action) { Action.START_FOREGROUND, Action.STOP_FOREGROUND -> context.startForegroundService( intent, ) Action.START, Action.STOP -> context.startService(intent) } } catch (e: Exception) { Timber.e(e.message) } } fun startWatcherServiceForeground(context: Context) { actionOnService( Action.START_FOREGROUND, context, AutoTunnelService::class.java, ) } fun startWatcherService(context: Context) { actionOnService( Action.START, context, AutoTunnelService::class.java, ) } fun stopWatcherService(context: Context) { actionOnService( Action.STOP, context, AutoTunnelService::class.java, ) } fun startTunnelBackgroundService(context: Context) { actionOnService( Action.START_FOREGROUND, context, TunnelBackgroundService::class.java, ) } fun stopTunnelBackgroundService(context: Context) { actionOnService( Action.STOP, context, TunnelBackgroundService::class.java, ) } }
69
Kotlin
47
860
560d46ad87e5b7b365214a601831b0b32928db48
1,571
wgtunnel
MIT License
app/src/main/java/com/zaneschepke/wireguardautotunnel/service/foreground/ServiceManager.kt
zaneschepke
644,710,160
false
{"Kotlin": 334681, "Ruby": 860}
package com.zaneschepke.wireguardautotunnel.service.foreground import android.app.Service import android.content.Context import android.content.Intent import android.net.VpnService import timber.log.Timber object ServiceManager { private fun <T : Service> actionOnService(action: Action, context: Context, cls: Class<T>, extras: Map<String, Int>? = null) { if (VpnService.prepare(context) != null) return val intent = Intent(context, cls).also { it.action = action.name extras?.forEach { (k, v) -> it.putExtra(k, v) } } intent.component?.javaClass try { when (action) { Action.START_FOREGROUND, Action.STOP_FOREGROUND -> context.startForegroundService( intent, ) Action.START, Action.STOP -> context.startService(intent) } } catch (e: Exception) { Timber.e(e.message) } } fun startWatcherServiceForeground(context: Context) { actionOnService( Action.START_FOREGROUND, context, AutoTunnelService::class.java, ) } fun startWatcherService(context: Context) { actionOnService( Action.START, context, AutoTunnelService::class.java, ) } fun stopWatcherService(context: Context) { actionOnService( Action.STOP, context, AutoTunnelService::class.java, ) } fun startTunnelBackgroundService(context: Context) { actionOnService( Action.START_FOREGROUND, context, TunnelBackgroundService::class.java, ) } fun stopTunnelBackgroundService(context: Context) { actionOnService( Action.STOP, context, TunnelBackgroundService::class.java, ) } }
69
Kotlin
47
860
560d46ad87e5b7b365214a601831b0b32928db48
1,571
wgtunnel
MIT License
platform/platform-impl/src/com/intellij/openapi/application/coroutines.kt
siosio
31,403,159
false
null
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:ApiStatus.Experimental package com.intellij.openapi.application import com.intellij.openapi.application.constraints.ConstrainedExecution.ContextConstraint import com.intellij.openapi.application.rw.ReadAction import com.intellij.openapi.progress.Progress import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import kotlinx.coroutines.CancellableContinuation import kotlinx.coroutines.Runnable import kotlinx.coroutines.suspendCancellableCoroutine import org.jetbrains.annotations.ApiStatus import kotlin.coroutines.CoroutineContext /** * Suspends until it's possible to obtain the read lock and then * runs the [action] holding the lock **without** preventing write actions. * See [constrainedReadAction] for semantic details. */ suspend fun <T> readAction(action: (progress: Progress) -> T): T { return constrainedReadAction(ReadConstraints.unconstrained(), action) } /** * Suspends until it's possible to obtain the read lock in smart mode and then * runs the [action] holding the lock **without** preventing write actions. * See [constrainedReadAction] for semantic details. */ suspend fun <T> smartReadAction(project: Project, action: (progress: Progress) -> T): T { return constrainedReadAction(ReadConstraints.inSmartMode(project), action) } /** * Runs given [action] under [read lock][com.intellij.openapi.application.Application.runReadAction] * **without** preventing write actions. * * The function suspends if at the moment of calling it's not possible to acquire the read lock, * or if [constraints] are not [satisfied][ContextConstraint.isCorrectContext]. * If the write action happens while the [action] is running, then the [action] is canceled, * and the function suspends until its possible to acquire the read lock, and then the [action] is tried again. * * Since the [action] might me executed several times, it must be idempotent. * The function returns when given [action] was completed fully. * [Progress] passed to the action must be used to check for cancellation inside the [action]. */ suspend fun <T> constrainedReadAction(constraints: ReadConstraints, action: (progress: Progress) -> T): T { return ReadAction(constraints, action).runReadAction() } /** * Suspends until dumb mode is over and runs [action] in Smart Mode on EDT */ suspend fun <T> smartAction(project: Project, action: (ctx: CoroutineContext) -> T): T { return suspendCancellableCoroutine { continuation -> DumbService.getInstance(project).runWhenSmart(SmartRunnable(action, continuation)) } } private class SmartRunnable<T>(action: (ctx: CoroutineContext) -> T, continuation: CancellableContinuation<T>) : Runnable { @Volatile private var myAction: ((ctx: CoroutineContext) -> T)? = action @Volatile private var myContinuation: CancellableContinuation<T>? = continuation init { continuation.invokeOnCancellation { myAction = null myContinuation = null // it's not possible to unschedule the runnable, so we make it do nothing instead } } override fun run() { val continuation = myContinuation ?: return val action = myAction ?: return continuation.resumeWith(kotlin.runCatching { action.invoke(continuation.context) }) } }
1
null
1
1
117af19733434a3d47889dc9f624094c0650fdde
3,416
intellij-community
Apache License 2.0
server-base/src/main/kotlin/ai/dstack/server/jersey/resources/payload/CreateJobPayload.kt
riwajsapkota
276,221,429
false
{"JavaScript": 278424, "Kotlin": 272573, "CSS": 103546, "HTML": 2402}
package ai.dstack.server.jersey.resources.payload import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonInclude @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) data class CreateJobPayload( val user: String?, val title: String?, val runtime: String?, val code: String?, val schedule: String? )
0
null
10
0
ecda9f4d85e9c65a6221ae4c878d048d3a5453e5
404
dstack-server
Apache License 2.0
android/src/main/java/com/reactnativepedometerdetails/step/background/Restarter.kt
zaixiaoqu
437,058,689
false
{"Kotlin": 90481, "JavaScript": 2795}
package com.reactnativepedometerdetails.step.background import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.Build class Restarter : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent?) { // restart the step counting service (different code to achieve this depending on Android version) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(Intent(context, StepCounterService::class.java)) } else { context.startService(Intent(context, StepCounterService::class.java)) } } }
6
Kotlin
9
7
77eba39e286c7799920c87a9b676e367b0810a3b
667
react-native-pedometer-details
MIT License
SingleModuleApp/app/src/main/java/com/github/yamamotoj/singlemoduleapp/package35/Foo03570.kt
yamamotoj
163,851,411
false
null
package com.github.yamamotoj.singlemoduleapp.package35 class Foo03570 { fun method0() { Foo03569().method5() } fun method1() { method0() } fun method2() { method1() } fun method3() { method2() } fun method4() { method3() } fun method5() { method4() } }
0
Kotlin
0
9
2a771697dfebca9201f6df5ef8441578b5102641
355
android_multi_module_experiment
Apache License 2.0
utbot-instrumentation/src/main/kotlin/org/utbot/instrumentation/instrumentation/execution/UtExecutionInstrumentation.kt
UnitTestBot
480,810,501
false
null
package org.utbot.instrumentation.instrumentation.execution import org.utbot.framework.UtSettings import org.utbot.framework.plugin.api.* import org.utbot.framework.plugin.api.util.singleExecutableId import org.utbot.instrumentation.instrumentation.ArgumentList import org.utbot.instrumentation.instrumentation.Instrumentation import org.utbot.instrumentation.instrumentation.InvokeInstrumentation import org.utbot.instrumentation.instrumentation.et.TraceHandler import org.utbot.instrumentation.instrumentation.execution.constructors.ConstructOnlyUserClassesOrCachedObjectsStrategy import org.utbot.instrumentation.instrumentation.execution.constructors.UtModelConstructor import org.utbot.instrumentation.instrumentation.execution.context.InstrumentationContext import org.utbot.instrumentation.instrumentation.execution.context.SimpleInstrumentationContext import org.utbot.instrumentation.instrumentation.execution.ndd.NonDeterministicClassVisitor import org.utbot.instrumentation.instrumentation.execution.ndd.NonDeterministicDetector import org.utbot.instrumentation.instrumentation.execution.phases.PhasesController import org.utbot.instrumentation.instrumentation.instrumenter.Instrumenter import org.utbot.instrumentation.instrumentation.mock.MockClassVisitor import java.security.ProtectionDomain import kotlin.reflect.jvm.javaMethod /** * Consists of the data needed to execute the method concretely. Also includes method arguments stored in models. * * @property [stateBefore] is necessary for construction of parameters of a concrete call. * @property [instrumentation] is necessary for mocking static methods and new instances. * @property [timeout] is timeout for specific concrete execution (in milliseconds). * By default is initialized from [UtSettings.concreteExecutionDefaultTimeoutInInstrumentedProcessMillis] */ data class UtConcreteExecutionData( val stateBefore: EnvironmentModels, val instrumentation: List<UtInstrumentation>, val timeout: Long ) data class UtConcreteExecutionResult( val stateAfter: EnvironmentModels, val result: UtExecutionResult, val coverage: Coverage, val newInstrumentation: List<UtInstrumentation>? = null, ) { override fun toString(): String = buildString { appendLine("UtConcreteExecutionResult(") appendLine("stateAfter=$stateAfter") appendLine("result=$result") appendLine("coverage=$coverage)") } } // TODO if possible make it non singleton object UtExecutionInstrumentation : Instrumentation<UtConcreteExecutionResult> { private val delegateInstrumentation = InvokeInstrumentation() var instrumentationContext: InstrumentationContext = SimpleInstrumentationContext() private val traceHandler = TraceHandler() private val ndDetector = NonDeterministicDetector() private val pathsToUserClasses = mutableSetOf<String>() override fun init(pathsToUserClasses: Set<String>) { UtExecutionInstrumentation.pathsToUserClasses.clear() UtExecutionInstrumentation.pathsToUserClasses += pathsToUserClasses } /** * Ignores [arguments], because concrete arguments will be constructed * from models passed via [parameters]. * * Argument [parameters] must be of type [UtConcreteExecutionData]. */ override fun invoke( clazz: Class<*>, methodSignature: String, arguments: ArgumentList, parameters: Any? ): UtConcreteExecutionResult = invoke(clazz, methodSignature, arguments, parameters, phasesWrapper = { it() }) fun invoke( clazz: Class<*>, methodSignature: String, arguments: ArgumentList, parameters: Any?, phasesWrapper: PhasesController.(invokeBasePhases: () -> UtConcreteExecutionResult) -> UtConcreteExecutionResult ): UtConcreteExecutionResult { if (parameters !is UtConcreteExecutionData) { throw IllegalArgumentException("Argument parameters must be of type UtConcreteExecutionData, but was: ${parameters?.javaClass}") } val (stateBefore, instrumentations, timeout) = parameters // smart cast to UtConcreteExecutionData return PhasesController( instrumentationContext, traceHandler, delegateInstrumentation, timeout ).computeConcreteExecutionResult { phasesWrapper { try { // some preparation actions for concrete execution val constructedData = applyPreprocessing(parameters) val (params, statics, cache) = constructedData // invocation val concreteResult = executePhaseInTimeout(invocationPhase) { invoke(clazz, methodSignature, params.map { it.value }) } // statistics collection val (coverage, ndResults) = executePhaseInTimeout(statisticsCollectionPhase) { getCoverage(clazz) to getNonDeterministicResults() } // model construction val (executionResult, stateAfter, newInstrumentation) = executePhaseInTimeout(modelConstructionPhase) { configureConstructor { this.cache = cache strategy = ConstructOnlyUserClassesOrCachedObjectsStrategy( pathsToUserClasses, cache ) } val ndStatics = constructStaticInstrumentation(ndResults.statics) val ndNews = constructNewInstrumentation(ndResults.news, ndResults.calls) val newInstrumentation = mergeInstrumentations(instrumentations, ndStatics, ndNews) val returnType = clazz.singleExecutableId(methodSignature).returnType val executionResult = convertToExecutionResult(concreteResult, returnType) val stateAfterParametersWithThis = constructParameters(params) val stateAfterStatics = constructStatics(stateBefore, statics) val (stateAfterThis, stateAfterParameters) = if (stateBefore.thisInstance == null) { null to stateAfterParametersWithThis } else { stateAfterParametersWithThis.first() to stateAfterParametersWithThis.drop(1) } val stateAfter = EnvironmentModels(stateAfterThis, stateAfterParameters, stateAfterStatics) Triple(executionResult, stateAfter, newInstrumentation) } UtConcreteExecutionResult( stateAfter, executionResult, coverage, newInstrumentation ) } finally { // restoring data after concrete execution applyPostprocessing() } } } } override fun getStaticField(fieldId: FieldId): Result<UtModel> = delegateInstrumentation.getStaticField(fieldId).map { value -> UtModelConstructor.createOnlyUserClassesConstructor(pathsToUserClasses) .construct(value, fieldId.type) } override fun transform( loader: ClassLoader?, className: String, classBeingRedefined: Class<*>?, protectionDomain: ProtectionDomain, classfileBuffer: ByteArray ): ByteArray { val instrumenter = Instrumenter(classfileBuffer, loader) traceHandler.registerClass(className) instrumenter.visitInstructions(traceHandler.computeInstructionVisitor(className)) instrumenter.visitClass { writer -> NonDeterministicClassVisitor(writer, ndDetector) } val mockClassVisitor = instrumenter.visitClass { writer -> MockClassVisitor( writer, InstrumentationContext.MockGetter::getMock.javaMethod!!, InstrumentationContext.MockGetter::checkCallSite.javaMethod!!, InstrumentationContext.MockGetter::hasMock.javaMethod!! ) } mockClassVisitor.signatureToId.forEach { (method, id) -> instrumentationContext.methodSignatureToId += method to id } return instrumenter.classByteCode } }
367
null
27
86
b05163453557356b677d1b8ce06e2f1109be9b0f
8,592
UTBotJava
Apache License 2.0
tiltak/src/test/kotlin/no/nav/amt/tiltak/tiltak/repositories/HentKoordinatorerForGjennomforingQueryTest.kt
navikt
393,356,849
false
null
package no.nav.amt.tiltak.tiltak.repositories import ch.qos.logback.classic.Level import ch.qos.logback.classic.Logger import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.collections.shouldContainAll import io.kotest.matchers.shouldBe import no.nav.amt.tiltak.test.database.DbTestDataUtils import no.nav.amt.tiltak.test.database.SingletonPostgresContainer import no.nav.amt.tiltak.test.database.data.TestData.ARRANGOR_1 import no.nav.amt.tiltak.test.database.data.TestData.ARRANGOR_ANSATT_1 import no.nav.amt.tiltak.test.database.data.TestData.ARRANGOR_ANSATT_2 import no.nav.amt.tiltak.test.database.data.TestData.GJENNOMFORING_1 import no.nav.amt.tiltak.test.database.data.TestData.GJENNOMFORING_2 import no.nav.amt.tiltak.test.database.data.TestData.GJENNOMFORING_TILGANG_1 import no.nav.amt.tiltak.test.database.data.TestData.NAV_ENHET_1 import no.nav.amt.tiltak.test.database.data.TestData.TILTAK_1 import no.nav.amt.tiltak.test.database.data.TestDataRepository import no.nav.amt.tiltak.test.database.data.inputs.ArrangorAnsattInput import no.nav.amt.tiltak.test.database.data.inputs.ArrangorAnsattRolleInput import org.slf4j.LoggerFactory import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate import java.util.* class HentKoordinatorerForGjennomforingQueryTest : FunSpec({ val dataSource = SingletonPostgresContainer.getDataSource() val testDataRepository = TestDataRepository(NamedParameterJdbcTemplate(dataSource)) lateinit var query: HentKoordinatorerForGjennomforingQuery beforeEach { val rootLogger: Logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME) as Logger rootLogger.level = Level.WARN query = HentKoordinatorerForGjennomforingQuery(NamedParameterJdbcTemplate(dataSource)) DbTestDataUtils.cleanDatabase(dataSource) testDataRepository.insertTiltak(TILTAK_1) testDataRepository.insertArrangor(ARRANGOR_1) testDataRepository.insertNavEnhet(NAV_ENHET_1) testDataRepository.insertGjennomforing(GJENNOMFORING_1) } fun createAnsatt( baseInput: ArrangorAnsattInput = ARRANGOR_ANSATT_1, fornavn: String = "Steve", mellomnavn: String? = null, etternavn: String = "<NAME>" ) { testDataRepository.insertArrangorAnsatt( baseInput.copy( fornavn = fornavn, mellomnavn = mellomnavn, etternavn = etternavn ) ) } fun createRolleForAnsatt( rolleName: String, ansattId: UUID = ARRANGOR_ANSATT_1.id ) { testDataRepository.insertArrangorAnsattRolle( ArrangorAnsattRolleInput( id = UUID.randomUUID(), arrangorId = ARRANGOR_1.id, ansattId = ansattId, rolle = rolleName ) ) } fun createGjennomforingTilgang(ansattId: UUID = ARRANGOR_ANSATT_1.id) { testDataRepository.insertArrangorAnsattGjennomforingTilgang( GJENNOMFORING_TILGANG_1.copy( id = UUID.randomUUID(), ansattId = ansattId, gjennomforingId = GJENNOMFORING_1.id ) ) } test("Returnerer tomt array om gjennomføring ikke eksisterer") { val koordinatorer = query.query(UUID.randomUUID()) koordinatorer shouldBe emptyList() } test("Returnerer tomt array om gjennomføring ikke har koordinator") { val koordinatorer = query.query(GJENNOMFORING_2.id) koordinatorer shouldBe emptyList() } test("Returnerer ikke personer som ikke er koordinatorer") { createAnsatt() createRolleForAnsatt("VEILEDER") createGjennomforingTilgang() val koordinatorer = query.query(GJENNOMFORING_1.id) koordinatorer shouldBe emptyList() } test("Returnerer koordinator om gjennomføringen har en koordinator") { createAnsatt() createRolleForAnsatt("KOORDINATOR") createGjennomforingTilgang() val koordinatorer = query.query(GJENNOMFORING_1.id) koordinatorer.size shouldBe 1 koordinatorer[0] shouldBe "<NAME>" } test("Returnerer koordinator med mellomnavn om gjennomføringen har en koordinator") { createAnsatt(mellomnavn = "mellomnavn") createRolleForAnsatt("KOORDINATOR") createGjennomforingTilgang() val koordinatorer = query.query(GJENNOMFORING_1.id) koordinatorer.size shouldBe 1 koordinatorer[0] shouldBe "Steve mellomnavn <NAME>" } test("Returnerer alle koordinatoerer for en gjennomføring") { createAnsatt() createRolleForAnsatt("KOORDINATOR") createGjennomforingTilgang() createAnsatt( baseInput = ARRANGOR_ANSATT_2, fornavn = "Jane", etternavn = "Doe" ) createRolleForAnsatt("KOORDINATOR", ARRANGOR_ANSATT_2.id) createGjennomforingTilgang(ARRANGOR_ANSATT_2.id) val koordinatorer = query.query(GJENNOMFORING_1.id) koordinatorer.size shouldBe 2 koordinatorer shouldContainAll listOf( "<NAME>", "<NAME>" ) } })
4
Kotlin
2
3
fd7fda363d9aeb793b269a5fdd6072a93e904c96
4,607
amt-tiltak
MIT License
1.12.2/src/main/kotlin/matterlink/command/MatterLinkCommandSender.kt
Abchrisabc
134,620,702
true
{"Kotlin": 78218}
package matterlink.command import matterlink.bridge.command.IMinecraftCommandSender import net.minecraft.command.ICommandSender import net.minecraft.server.MinecraftServer import net.minecraft.util.text.ITextComponent import net.minecraft.util.text.TextComponentString import net.minecraft.world.World import net.minecraftforge.fml.common.FMLCommonHandler import javax.annotation.Nonnull class MatterLinkCommandSender(user: String, userId: String, server: String, op: Boolean) : IMinecraftCommandSender(user, userId, server, op), ICommandSender { override fun execute(cmdString: String): Boolean { return 0 < FMLCommonHandler.instance().minecraftServerInstance.commandManager.executeCommand( this, cmdString ) } override fun getDisplayName(): ITextComponent { return TextComponentString(user) } override fun getName() = accountName override fun getEntityWorld(): World { return FMLCommonHandler.instance().minecraftServerInstance.getWorld(0) } override fun canUseCommand(permLevel: Int, commandName: String): Boolean { //permissions are checked on our end return canExecute(commandName) } override fun getServer(): MinecraftServer? { return FMLCommonHandler.instance().minecraftServerInstance } override fun sendMessage(@Nonnull component: ITextComponent?) { sendReply(component!!.unformattedComponentText) } override fun sendCommandFeedback(): Boolean { return true } }
0
Kotlin
0
0
07bc1736e64f0145a437450264c387bf2b1a3f38
1,543
MatterLink
MIT License
kotlin-node/src/jsMain/generated/node/inspector/debugger/SearchInContentParameterType.kt
JetBrains
93,250,841
false
null
// Generated by Karakum - do not modify it manually! package node.inspector.debugger sealed external interface SearchInContentParameterType { /** * Id of the script to search in. */ var scriptId: node.inspector.runtime.ScriptId /** * String to search for. */ var query: String /** * If true, search is case sensitive. */ var caseSensitive: Boolean? /** * If true, treats string parameter as regex. */ var isRegex: Boolean? }
40
null
165
1,347
997ed3902482883db4a9657585426f6ca167d556
502
kotlin-wrappers
Apache License 2.0
app/src/main/java/com/mofuapps/selectablenotificationsound/ui/timer/TimerViewModel.kt
mofutaro
677,690,424
false
null
package com.mofuapps.selectablenotificationsound.ui.timer import android.net.Uri import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.mofuapps.selectablenotificationsound.domain.alarm.NotifyZeroAlarmManager import com.mofuapps.selectablenotificationsound.domain.notification.AlarmNotificationManager import com.mofuapps.selectablenotificationsound.domain.session.CancelSessionUseCase import com.mofuapps.selectablenotificationsound.domain.session.FinishSessionUseCase import com.mofuapps.selectablenotificationsound.domain.session.PauseSessionUseCase import com.mofuapps.selectablenotificationsound.domain.session.ResumeSessionUseCase import com.mofuapps.selectablenotificationsound.domain.session.Session import com.mofuapps.selectablenotificationsound.domain.session.SessionRepository import com.mofuapps.selectablenotificationsound.domain.session.SessionState import com.mofuapps.selectablenotificationsound.domain.session.StartSessionUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.mapLatest import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.transformLatest import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import java.util.Date import javax.inject.Inject @OptIn(ExperimentalCoroutinesApi::class) @HiltViewModel class TimerViewModel @Inject constructor( sessionRepository: SessionRepository, private val startSession: StartSessionUseCase, private val pauseSession: PauseSessionUseCase, private val resumeSession: ResumeSessionUseCase, private val cancelSession: CancelSessionUseCase, private val finishSession: FinishSessionUseCase, private val alarmManager: NotifyZeroAlarmManager, private val notificationManager: AlarmNotificationManager ): ViewModel() { private val initialDurationSec = 5 private val initialUIState = TimerScreenUIState( stage = TimerScreenStage.STAND_BY, visualIndicator = 1f, numericalIndicator = "00:05", sound = null, soundName = null, repeat = false ) private fun Session.textProgress(): String { val waitingMillis = (durationMillis() - currentProgressMillis()) val waiting = waitingMillis / 1000 + if (waitingMillis%1000>0) 1 else 0 val hours = (waiting / 3600).toInt() val residue = (waiting % 3600).toInt() val minutes = residue / 60 val seconds = residue % 60 val str: String = if (waiting >= 3600) { "%02d:%02d:%02d".format(hours, minutes, seconds) } else { "%02d:%02d".format(minutes, seconds) } return if (str.length <= 8) { str } else { "" } } init { sessionRepository.flow.mapLatest { it }.onEach { session -> if (session == null) { notificationManager.stopNotification() } session?.let { when(it.state) { SessionState.RUNNING -> alarmManager.setAlarm(Date().time + it.remainingMillis(), "HogeHoge", _uiState.value.repeat, _uiState.value.sound) SessionState.PAUSED -> alarmManager.cancelAlarm() SessionState.FINISHED -> {} } } }.launchIn(viewModelScope) val tickFlow: Flow<Session?> = sessionRepository.flow.transformLatest { session: Session? -> emit(session) if (session != null && session.state == SessionState.RUNNING) { while(true) { delay(1000L) emit(session) } } } tickFlow.onEach { result: Session? -> var stage = initialUIState.stage var visualIndicator = initialUIState.visualIndicator var numericalIndicator = initialUIState.numericalIndicator result?.let { session: Session -> Log.d("session", session.toString()) stage = when(session.state) { SessionState.RUNNING -> TimerScreenStage.RUNNING SessionState.PAUSED -> TimerScreenStage.PAUSED SessionState.FINISHED -> TimerScreenStage.FINISHED } visualIndicator = 1f - (session.progressPercent() / 100).toFloat() numericalIndicator = session.textProgress() } _uiState.update { it.copy( stage = stage, visualIndicator = visualIndicator, numericalIndicator = numericalIndicator ) } if (result != null && result.state == SessionState.RUNNING && result.remainingMillis() <= 0) { finishSession() } }.launchIn(viewModelScope) } private val _uiState = MutableStateFlow ( initialUIState ) internal val uiState = _uiState.asStateFlow() internal fun setSound(sound: Uri?, soundName: String?) { _uiState.update { it.copy(sound = sound, soundName = soundName) } } internal fun updateRepeat(repeat: Boolean) { _uiState.update { it.copy(repeat = repeat) } } internal fun startTimer() { alarmManager.setAlarm(Date().time + initialDurationSec * 1000L, "A", _uiState.value.repeat, _uiState.value.sound) viewModelScope.launch { startSession(initialDurationSec) } } internal fun pauseTimer() { alarmManager.cancelAlarm() viewModelScope.launch { pauseSession() } } internal fun resumeTimer() { viewModelScope.launch { resumeSession() } } internal fun cancelTimer() { viewModelScope.launch { cancelSession() } } }
0
Kotlin
0
0
870eccad20db2ec990bf54c3975cfaad7b8b8bfd
6,172
android-selectable-notification-sound-sample
Apache License 2.0
sql/src/main/kotlin/net/aquadc/persistence/sql/templates.kt
Miha-x64
102,399,925
false
null
@file:[JvmName("SqlTemplate") Suppress("NOTHING_TO_INLINE")] package net.aquadc.persistence.sql.template import net.aquadc.persistence.FuncXImpl import net.aquadc.persistence.sql.Exec import net.aquadc.persistence.sql.Fetch import net.aquadc.persistence.sql.FuncN import net.aquadc.persistence.sql.Session import net.aquadc.persistence.sql.Transaction import net.aquadc.persistence.type.DataType import net.aquadc.persistence.type.Ilk import org.intellij.lang.annotations.Language inline fun <SRC, R> Query( @Language("SQL") query: String, fetch: Fetch<SRC, R> ): Session<SRC>.() -> R = Template(query, emptyArray(), fetch) inline fun <SRC, T : Any, R> Query( @Language("SQL") query: String, type: Ilk<T, DataType.NotNull<T>>, fetch: Fetch<SRC, R> ): Session<SRC>.(T) -> R = Template(query, arrayOf(type), fetch) inline fun <SRC, T1 : Any, T2 : Any, R> Query( @Language("SQL") query: String, type1: Ilk<T1, DataType.NotNull<T1>>, type2: Ilk<T2, DataType.NotNull<T2>>, fetch: Fetch<SRC, R> ): Session<SRC>.(T1, T2) -> R = Template(query, arrayOf<Ilk<*, DataType.NotNull<*>>>(type1, type2), fetch) inline fun <SRC, T1 : Any, T2 : Any, T3 : Any, R> Query( @Language("SQL") query: String, type1: Ilk<T1, DataType.NotNull<T1>>, type2: Ilk<T2, DataType.NotNull<T2>>, type3: Ilk<T3, DataType.NotNull<T3>>, fetch: Fetch<SRC, R> ): Session<SRC>.(T1, T2, T3) -> R = Template(query, arrayOf<Ilk<*, DataType.NotNull<*>>>(type1, type2, type3), fetch) inline fun <SRC, T1 : Any, T2 : Any, T3 : Any, T4 : Any, R> Query( @Language("SQL") query: String, type1: Ilk<T1, DataType.NotNull<T1>>, type2: Ilk<T2, DataType.NotNull<T2>>, type3: Ilk<T3, DataType.NotNull<T3>>, type4: Ilk<T4, DataType.NotNull<T4>>, fetch: Fetch<SRC, R> ): Session<SRC>.(T1, T2, T3, T4) -> R = Template(query, arrayOf<Ilk<*, DataType.NotNull<*>>>(type1, type2, type3, type4), fetch) inline fun <SRC, T1 : Any, T2 : Any, T3 : Any, T4 : Any, T5 : Any, R> Query( @Language("SQL") query: String, type1: Ilk<T1, DataType.NotNull<T1>>, type2: Ilk<T2, DataType.NotNull<T2>>, type3: Ilk<T3, DataType.NotNull<T3>>, type4: Ilk<T4, DataType.NotNull<T4>>, type5: Ilk<T5, DataType.NotNull<T5>>, fetch: Fetch<SRC, R> ): Session<SRC>.(T1, T2, T3, T4, T5) -> R = Template(query, arrayOf<Ilk<*, DataType.NotNull<*>>>(type1, type2, type3, type4, type5), fetch) inline fun <SRC, T1 : Any, T2 : Any, T3 : Any, T4 : Any, T5 : Any, T6 : Any, R> Query( @Language("SQL") query: String, type1: Ilk<T1, DataType.NotNull<T1>>, type2: Ilk<T2, DataType.NotNull<T2>>, type3: Ilk<T3, DataType.NotNull<T3>>, type4: Ilk<T4, DataType.NotNull<T4>>, type5: Ilk<T5, DataType.NotNull<T5>>, type6: Ilk<T6, DataType.NotNull<T6>>, fetch: Fetch<SRC, R> ): Session<SRC>.(T1, T2, T3, T4, T5, T6) -> R = Template(query, arrayOf<Ilk<*, DataType.NotNull<*>>>(type1, type2, type3, type4, type5, type6), fetch) inline fun <SRC, T1 : Any, T2 : Any, T3 : Any, T4 : Any, T5 : Any, T6 : Any, T7 : Any, R> Query( @Language("SQL") query: String, type1: Ilk<T1, DataType.NotNull<T1>>, type2: Ilk<T2, DataType.NotNull<T2>>, type3: Ilk<T3, DataType.NotNull<T3>>, type4: Ilk<T4, DataType.NotNull<T4>>, type5: Ilk<T5, DataType.NotNull<T5>>, type6: Ilk<T6, DataType.NotNull<T6>>, type7: Ilk<T7, DataType.NotNull<T7>>, fetch: Fetch<SRC, R> ): Session<SRC>.(T1, T2, T3, T4, T5, T6, T7) -> R = Template(query, arrayOf<Ilk<*, DataType.NotNull<*>>>(type1, type2, type3, type4, type5, type6, type7), fetch) inline fun <SRC, T1 : Any, T2 : Any, T3 : Any, T4 : Any, T5 : Any, T6 : Any, T7 : Any, T8 : Any, R> Query( @Language("SQL") query: String, type1: Ilk<T1, DataType.NotNull<T1>>, type2: Ilk<T2, DataType.NotNull<T2>>, type3: Ilk<T3, DataType.NotNull<T3>>, type4: Ilk<T4, DataType.NotNull<T4>>, type5: Ilk<T5, DataType.NotNull<T5>>, type6: Ilk<T6, DataType.NotNull<T6>>, type7: Ilk<T7, DataType.NotNull<T7>>, type8: Ilk<T8, DataType.NotNull<T8>>, fetch: Fetch<SRC, R> ): Session<SRC>.(T1, T2, T3, T4, T5, T6, T7, T8) -> R = Template(query, arrayOf<Ilk<*, DataType.NotNull<*>>>(type1, type2, type3, type4, type5, type6, type7, type8), fetch) inline fun <SRC, R> Mutation( @Language("SQL") query: String, exec: Exec<SRC, R> ): Transaction<SRC>.() -> R = Template(query, emptyArray(), exec) inline fun <SRC, T : Any, R> Mutation( @Language("SQL") query: String, type: Ilk<T, DataType.NotNull<T>>, exec: Exec<SRC, R> ): Transaction<SRC>.(T) -> R = Template(query, arrayOf(type), exec) inline fun <SRC, T1 : Any, T2 : Any, R> Mutation( @Language("SQL") query: String, type1: Ilk<T1, DataType.NotNull<T1>>, type2: Ilk<T2, DataType.NotNull<T2>>, exec: Exec<SRC, R> ): Transaction<SRC>.(T1, T2) -> R = Template(query, arrayOf<Ilk<*, DataType.NotNull<*>>>(type1, type2), exec) inline fun <SRC, T1 : Any, T2 : Any, T3 : Any, R> Mutation( @Language("SQL") query: String, type1: Ilk<T1, DataType.NotNull<T1>>, type2: Ilk<T2, DataType.NotNull<T2>>, type3: Ilk<T3, DataType.NotNull<T3>>, exec: Exec<SRC, R> ): Transaction<SRC>.(T1, T2, T3) -> R = Template(query, arrayOf<Ilk<*, DataType.NotNull<*>>>(type1, type2, type3), exec) inline fun <SRC, T1 : Any, T2 : Any, T3 : Any, T4 : Any, R> Mutation( @Language("SQL") query: String, type1: Ilk<T1, DataType.NotNull<T1>>, type2: Ilk<T2, DataType.NotNull<T2>>, type3: Ilk<T3, DataType.NotNull<T3>>, type4: Ilk<T4, DataType.NotNull<T4>>, exec: Exec<SRC, R> ): Transaction<SRC>.(T1, T2, T3, T4) -> R = Template(query, arrayOf<Ilk<*, DataType.NotNull<*>>>(type1, type2, type3, type4), exec) inline fun <SRC, T1 : Any, T2 : Any, T3 : Any, T4 : Any, T5 : Any, R> Mutation( @Language("SQL") query: String, type1: Ilk<T1, DataType.NotNull<T1>>, type2: Ilk<T2, DataType.NotNull<T2>>, type3: Ilk<T3, DataType.NotNull<T3>>, type4: Ilk<T4, DataType.NotNull<T4>>, type5: Ilk<T5, DataType.NotNull<T5>>, exec: Exec<SRC, R> ): Transaction<SRC>.(T1, T2, T3, T4, T5) -> R = Template(query, arrayOf<Ilk<*, DataType.NotNull<*>>>(type1, type2, type3, type4, type5), exec) inline fun <SRC, T1 : Any, T2 : Any, T3 : Any, T4 : Any, T5 : Any, T6 : Any, R> Mutation( @Language("SQL") query: String, type1: Ilk<T1, DataType.NotNull<T1>>, type2: Ilk<T2, DataType.NotNull<T2>>, type3: Ilk<T3, DataType.NotNull<T3>>, type4: Ilk<T4, DataType.NotNull<T4>>, type5: Ilk<T5, DataType.NotNull<T5>>, type6: Ilk<T6, DataType.NotNull<T6>>, exec: Exec<SRC, R> ): Transaction<SRC>.(T1, T2, T3, T4, T5, T6) -> R = Template(query, arrayOf<Ilk<*, DataType.NotNull<*>>>(type1, type2, type3, type4, type5, type6), exec) inline fun <SRC, T1 : Any, T2 : Any, T3 : Any, T4 : Any, T5 : Any, T6 : Any, T7 : Any, R> Mutation( @Language("SQL") query: String, type1: Ilk<T1, DataType.NotNull<T1>>, type2: Ilk<T2, DataType.NotNull<T2>>, type3: Ilk<T3, DataType.NotNull<T3>>, type4: Ilk<T4, DataType.NotNull<T4>>, type5: Ilk<T5, DataType.NotNull<T5>>, type6: Ilk<T6, DataType.NotNull<T6>>, type7: Ilk<T7, DataType.NotNull<T7>>, exec: Exec<SRC, R> ): Transaction<SRC>.(T1, T2, T3, T4, T5, T6, T7) -> R = Template(query, arrayOf<Ilk<*, DataType.NotNull<*>>>(type1, type2, type3, type4, type5, type7), exec) inline fun <SRC, T1 : Any, T2 : Any, T3 : Any, T4 : Any, T5 : Any, T6 : Any, T7 : Any, T8 : Any, R> Mutation( @Language("SQL") query: String, type1: Ilk<T1, DataType.NotNull<T1>>, type2: Ilk<T2, DataType.NotNull<T2>>, type3: Ilk<T3, DataType.NotNull<T3>>, type4: Ilk<T4, DataType.NotNull<T4>>, type5: Ilk<T5, DataType.NotNull<T5>>, type6: Ilk<T6, DataType.NotNull<T6>>, type7: Ilk<T7, DataType.NotNull<T7>>, type8: Ilk<T8, DataType.NotNull<T8>>, exec: Exec<SRC, R> ): Transaction<SRC>.(T1, T2, T3, T4, T5, T6, T7, T8) -> R = Template(query, arrayOf<Ilk<*, DataType.NotNull<*>>>(type1, type2, type3, type4, type5, type6, type7, type8), exec) @PublishedApi internal class Template<SRC, R>( private val query: String, private val argumentTypes: Array<out Ilk<*, DataType.NotNull<*>>>, private val fetch: Fetch<SRC, R> ) : FuncXImpl<Any, R>(), FuncN<Any, R> { override fun invokeUnchecked(vararg args: Any): R = (args[0] as? Session<SRC> ?: (args[0] as Transaction<SRC>).mySession).rawQuery(query, argumentTypes, args, fetch) // for debugging override fun toString(): String = fetch.javaClass.simpleName + '(' + query + ')' } // TODO named placeholders
11
Kotlin
10
118
d0a804271d0aaaa6368a2addce3ef7f081f5f560
8,697
Lychee
Apache License 2.0
src/test/kotlin/org/ujorm/kotlin/ormBreaf/entity/Database.kt
pponec
382,561,643
false
null
package org.ujorm.kotlin.ormBreaf.entity import org.ujorm.kotlin.orm.AbstractDatabase /** Database tables provider */ object Database : AbstractDatabase() { }
0
Kotlin
0
3
c5c915f311f47c18b88eab6fb6655c49475cf8d4
163
ujormKt
Apache License 2.0
domain/src/main/java/com/gameshow/button/domain/entities/Profile.kt
forceindia712
642,417,682
false
null
package com.gameshow.button.domain.entities data class Profile( var nickname: String = "", var avatarID: String = "" )
0
Kotlin
0
0
92fd09b0c56414e612e998a74fc5a9841dfa9ae7
128
ButtonGameShowAndroidApp
Apache License 2.0
utbot-junit-contest/src/main/kotlin/org/utbot/contest/Contest.kt
UnitTestBot
480,810,501
false
null
package org.utbot.contest import mu.KotlinLogging import org.objectweb.asm.Type import org.utbot.common.FileUtil import org.utbot.common.measureTime import org.utbot.common.filterWhen import org.utbot.common.info import org.utbot.common.isAbstract import org.utbot.engine.EngineController import org.utbot.framework.TestSelectionStrategyType import org.utbot.framework.UtSettings import org.utbot.framework.codegen.domain.ForceStaticMocking import org.utbot.framework.codegen.domain.StaticsMocking import org.utbot.framework.codegen.domain.junitByVersion import org.utbot.framework.codegen.CodeGenerator import org.utbot.framework.plugin.api.util.UtContext import org.utbot.framework.plugin.api.util.executableId import org.utbot.framework.plugin.api.util.id import org.utbot.framework.plugin.api.util.jClass import org.utbot.framework.plugin.api.util.utContext import org.utbot.framework.plugin.api.util.withUtContext import org.utbot.framework.plugin.services.JdkInfoService import org.utbot.framework.util.isKnownImplicitlyDeclaredMethod import org.utbot.fuzzer.UtFuzzedExecution import org.utbot.instrumentation.ConcreteExecutor import org.utbot.instrumentation.ConcreteExecutorPool import org.utbot.instrumentation.Settings import org.utbot.instrumentation.warmup.Warmup import java.io.File import java.lang.reflect.Method import java.lang.reflect.Modifier import java.net.URL import java.net.URLClassLoader import java.nio.file.Paths import kotlin.concurrent.thread import kotlin.math.max import kotlin.math.min import kotlin.reflect.KCallable import kotlin.reflect.jvm.isAccessible import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.ObsoleteCoroutinesApi import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.job import kotlinx.coroutines.launch import kotlinx.coroutines.newSingleThreadContext import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeoutOrNull import org.utbot.framework.SummariesGenerationType import org.utbot.framework.codegen.domain.ProjectType import org.utbot.framework.codegen.services.language.CgLanguageAssistant import org.utbot.framework.minimization.minimizeExecutions import org.utbot.framework.plugin.api.* import org.utbot.framework.plugin.api.util.isSynthetic import org.utbot.framework.util.jimpleBody import org.utbot.summary.summarizeAll internal const val junitVersion = 4 private val logger = KotlinLogging.logger {} @Suppress("unused") object Contest enum class ContestMessage { INIT, READY, RUN; override fun toString(): String { return "[${super.toString()}]" } } val charset = Charsets.UTF_8 val generatedLanguage: CodegenLanguage = CodegenLanguage.JAVA val mockStrategyApi: MockStrategyApi = mockStrategyApiFromString(System.getProperty("utBotMockStrategyApi")) ?: MockStrategyApi.NO_MOCKS val staticsMocking = StaticsMocking.defaultItem val forceStaticMocking: ForceStaticMocking = ForceStaticMocking.FORCE val dependencyPath = System.getProperty("java.class.path") fun mockStrategyApiFromString(value:String?):MockStrategyApi? = when(value) { "NO_MOCKS" -> MockStrategyApi.NO_MOCKS "OTHER_PACKAGES" -> MockStrategyApi.OTHER_PACKAGES "OTHER_CLASSES" -> MockStrategyApi.OTHER_CLASSES else -> null } @ObsoleteCoroutinesApi fun main(args: Array<String>) { require(args.size == 3) { """Wrong arguments. Expected arguments: <classfileDir> <classpathString> <output directory for generated tests> |Actual arguments: ${args.joinToString()} """.trimMargin() } setOptions() val classfileDir = Paths.get(args[0]) val classpathString = args[1] val outputDir = File(args[2]) println("Started UtBot Contest, classfileDir = $classfileDir, classpathString=$classpathString, outputDir=$outputDir, mocks=$mockStrategyApi") val cpEntries = classpathString.split(File.pathSeparator).map { File(it) } val classLoader = URLClassLoader(cpEntries.map { it.toUrl() }.toTypedArray()) val context = UtContext(classLoader) withUtContext(context) { // Initialize the soot before a contest is started. // This saves the time budget for real work instead of soot initialization. TestCaseGenerator(listOf(classfileDir), classpathString, dependencyPath, JdkInfoService.provide()) logger.info().measureTime({ "warmup: kotlin reflection :: init" }) { prepareClass(ConcreteExecutorPool::class.java, "") prepareClass(Warmup::class.java, "") } println("${ContestMessage.INIT}") while (true) { val line = readLine() println(">> $line") if (line == null) { return } val cmd = line.split(" ") if (cmd.isEmpty() || cmd[0] != "${ContestMessage.RUN}") continue val classUnderTestName = cmd[1] val timeBudgetSec = cmd[2].toLong() val cut = ClassUnderTest(classLoader.loadClass(classUnderTestName).id, outputDir, classfileDir.toFile()) runGeneration( project = "Contest", cut, timeBudgetSec, fuzzingRatio = 0.1, classpathString, runFromEstimator = false, expectedExceptions = ExpectedExceptionsForClass(), methodNameFilter = null ) println("${ContestMessage.READY}") } } ConcreteExecutor.defaultPool.close() } fun setOptions() { Settings.defaultConcreteExecutorPoolSize = 1 UtSettings.useFuzzing = true UtSettings.classfilesCanChange = false // We need to use assemble model generator to increase readability UtSettings.useAssembleModelGenerator = true UtSettings.summaryGenerationType = SummariesGenerationType.LIGHT UtSettings.preferredCexOption = false UtSettings.warmupConcreteExecution = true UtSettings.testMinimizationStrategyType = TestSelectionStrategyType.COVERAGE_STRATEGY UtSettings.ignoreStringLiterals = true UtSettings.maximizeCoverageUsingReflection = true UtSettings.useSandbox = false } @ObsoleteCoroutinesApi @SuppressWarnings fun runGeneration( project: String, cut: ClassUnderTest, timeLimitSec: Long, fuzzingRatio: Double, classpathString: String, runFromEstimator: Boolean, expectedExceptions: ExpectedExceptionsForClass, methodNameFilter: String? = null // For debug purposes you can specify method name ): StatsForClass = runBlocking { val testsByMethod: MutableMap<ExecutableId, MutableList<UtExecution>> = mutableMapOf() val currentContext = utContext val timeBudgetMs = timeLimitSec * 1000 val generationTimeout: Long = timeBudgetMs - timeBudgetMs * 15 / 100 // 4000 ms for terminate all activities and finalize code in file logger.debug { "-----------------------------------------------------------------------------" } logger.info( "Contest.runGeneration: Time budget: $timeBudgetMs ms, Generation timeout=$generationTimeout ms, " + "classpath=$classpathString, methodNameFilter=$methodNameFilter" ) if (runFromEstimator) { setOptions() //will not be executed in real contest logger.info().measureTime({ "warmup: 1st optional soot initialization and executor warmup (not to be counted in time budget)" }) { TestCaseGenerator(listOf(cut.classfileDir.toPath()), classpathString, dependencyPath, JdkInfoService.provide(), forceSootReload = false) } logger.info().measureTime({ "warmup (first): kotlin reflection :: init" }) { prepareClass(ConcreteExecutorPool::class.java, "") prepareClass(Warmup::class.java, "") } } //remaining budget val startTime = System.currentTimeMillis() fun remainingBudget() = max(0, generationTimeout - (System.currentTimeMillis() - startTime)) logger.info("$cut") if (cut.classLoader.javaClass != URLClassLoader::class.java) { logger.error("Seems like classloader for cut not valid (maybe it was backported to system): ${cut.classLoader}") } val statsForClass = StatsForClass(project, cut.fqn) val codeGenerator = CodeGenerator( cut.classId, projectType = ProjectType.PureJvm, testFramework = junitByVersion(junitVersion), staticsMocking = staticsMocking, forceStaticMocking = forceStaticMocking, generateWarningsForStaticMocking = false, cgLanguageAssistant = CgLanguageAssistant.getByCodegenLanguage(CodegenLanguage.defaultItem), ) logger.info().measureTime({ "class ${cut.fqn}" }, { statsForClass }) { val filteredMethods = logger.info().measureTime({ "preparation class ${cut.clazz}: kotlin reflection :: run" }) { prepareClass(cut.clazz, methodNameFilter) } statsForClass.methodsCount = filteredMethods.size // nothing to process further if (filteredMethods.isEmpty()) return@runBlocking statsForClass val testCaseGenerator = logger.info().measureTime({ "2nd optional soot initialization" }) { TestCaseGenerator(listOf(cut.classfileDir.toPath()), classpathString, dependencyPath, JdkInfoService.provide(), forceSootReload = false) } val engineJob = CoroutineScope(SupervisorJob() + newSingleThreadContext("SymbolicExecution") + currentContext ).launch { if (remainingBudget() == 0L) { logger.warn {"No time left for processing class"} return@launch } var remainingMethodsCount = filteredMethods.size val method2controller = filteredMethods.associateWith { EngineController() } for ((method, controller) in method2controller) { val job = launch(currentContext) { val methodJob = currentCoroutineContext().job logger.debug { " ... " } val statsForMethod = StatsForMethod( "${method.classId.simpleName}#${method.name}", expectedExceptions.getForMethod(method.name).exceptionNames ) statsForClass.statsForMethods.add(statsForMethod) if (!isActive) { logger.warn { "Stop processing methods of [${cut.fqn}] because job has been canceled" } return@launch } val minSolverTimeout = 10L val remainingBudget = remainingBudget() if (remainingBudget < minSolverTimeout*2 ) { logger.warn { "No time left for [${cut.fqn}]" } return@launch } val budgetForMethod = remainingBudget / remainingMethodsCount val solverTimeout = min(1000L, max(minSolverTimeout /* 0 means solver have no timeout*/, budgetForMethod / 2)).toInt() // @todo change to the constructor parameter UtSettings.checkSolverTimeoutMillis = solverTimeout val budgetForLastSolverRequestAndConcreteExecutionRemainingStates = min(solverTimeout + 200L, budgetForMethod / 2) val budgetForSymbolicExecution = max(0, budgetForMethod - budgetForLastSolverRequestAndConcreteExecutionRemainingStates) UtSettings.utBotGenerationTimeoutInMillis = budgetForMethod UtSettings.fuzzingTimeoutInMillis = (budgetForMethod * fuzzingRatio).toLong() //start controller that will activate symbolic execution GlobalScope.launch(currentContext) { delay(budgetForSymbolicExecution) if (methodJob.isActive) { logger.info { "|> Starting concrete execution for remaining state: $method" } controller.executeConcretely = true } delay(budgetForLastSolverRequestAndConcreteExecutionRemainingStates) if (methodJob.isActive) { logger.info { "(X) Cancelling concrete execution: $method" } methodJob.cancel() } } var testsCounter = 0 logger.info().measureTime({ "method $method" }, { statsForMethod }) { logger.info { " -- Remaining time budget: $remainingBudget ms, " + "#remaining_methods: $remainingMethodsCount, " + "budget for method: $budgetForMethod ms, " + "solver timeout: $solverTimeout ms, " + "budget for symbolic execution: $budgetForSymbolicExecution ms, " + "budget for concrete execution: $budgetForLastSolverRequestAndConcreteExecutionRemainingStates ms, " + " -- " } testCaseGenerator.generateAsync(controller, method, mockStrategyApi) .collect { result -> when (result) { is UtExecution -> { try { val testMethodName = testMethodName(method.toString(), ++testsCounter) val className = Type.getInternalName(method.classId.jClass) logger.debug { "--new testCase collected, to generate: $testMethodName" } statsForMethod.testsGeneratedCount++ result.result.exceptionOrNull()?.let { exception -> statsForMethod.detectedExceptionFqns += exception::class.java.name } result.coverage?.let { statsForClass.updateCoverage( newCoverage = it, isNewClass = !statsForClass.testedClassNames.contains(className), fromFuzzing = result is UtFuzzedExecution ) } statsForClass.testedClassNames.add(className) testsByMethod.getOrPut(method) { mutableListOf() } += result } catch (e: Throwable) { //Here we need isolation logger.error(e) { "Code generation failed" } } } is UtError -> { if (statsForMethod.failReasons.add(FailReason(result))) logger.error(result.error) { "Symbolic execution FAILED" } else logger.error { "Symbolic execution FAILED ... <<stack trace duplicated>>" } } } } //hack if (statsForMethod.isSuspicious && (ConcreteExecutor.lastSendTimeMs - ConcreteExecutor.lastReceiveTimeMs) > 5000) { logger.error { "HEURISTICS: close instrumented process, because it haven't responded for long time: ${ConcreteExecutor.lastSendTimeMs - ConcreteExecutor.lastReceiveTimeMs}" } ConcreteExecutor.defaultPool.close() } } } controller.job = job //don't start other methods while last method still in progress try { job.join() } catch (t: Throwable) { logger.error(t) { "Internal job error" } } remainingMethodsCount-- } } val cancellator = GlobalScope.launch(currentContext) { delay(remainingBudget()) if (engineJob.isActive) { logger.warn { "Cancelling job because timeout $generationTimeout ms elapsed (real cancellation can take time)" } statsForClass.canceledByTimeout = true engineJob.cancel() } } withTimeoutOrNull(remainingBudget() + 200 /* Give job some time to finish gracefully */) { try { engineJob.join() } catch (_: CancellationException) { } catch (e: Exception) { // need isolation because we want to write tests for class in any case logger.error(e) { "Error in engine invocation on class [${cut.fqn}]" } } } cancellator.cancel() val testSets = testsByMethod.map { (method, executions) -> UtMethodTestSet(method, minimizeExecutions(executions), jimpleBody(method)) }.summarizeAll(cut.classfileDir.toPath(), sourceFile = null) logger.info().measureTime({ "Flushing tests for [${cut.simpleName}] on disk" }) { writeTestClass(cut, codeGenerator.generateAsString(testSets)) } //write classes } statsForClass } private fun prepareClass(javaClazz: Class<*>, methodNameFilter: String?): List<ExecutableId> { //1. all methods from cut val methods = javaClazz.declaredMethods .filterNot { it.isAbstract } .filterNotNull() //2. all constructors from cut val constructors = if (javaClazz.isAbstract || javaClazz.isEnum) emptyList() else javaClazz.declaredConstructors.filterNotNull() //3. Now join methods and constructors together val methodsToGenerate = methods.filter { it.isVisibleFromGeneratedTest } + constructors val classFilteredMethods = methodsToGenerate .map { it.executableId } .filter { methodNameFilter?.equals(it.name) ?: true } .filterWhen(UtSettings.skipTestGenerationForSyntheticAndImplicitlyDeclaredMethods) { !it.isSynthetic && !it.isKnownImplicitlyDeclaredMethod } .toList() return if (javaClazz.declaredClasses.isEmpty()) { classFilteredMethods } else { val nestedFilteredMethods = javaClazz.declaredClasses.flatMap { prepareClass(it, methodNameFilter) } classFilteredMethods + nestedFilteredMethods } } fun writeTestClass(cut: ClassUnderTest, testSetsAsString: String) { logger.info { "File size for ${cut.testClassSimpleName}: ${FileUtil.byteCountToDisplaySize(testSetsAsString.length.toLong())}" } cut.generatedTestFile.parentFile.mkdirs() cut.generatedTestFile.writeText(testSetsAsString, charset) } private inline fun <R> KCallable<*>.withAccessibility(block: () -> R): R { val prevAccessibility = isAccessible try { isAccessible = true return block() } finally { isAccessible = prevAccessibility } } @Suppress("DEPRECATION", "SameParameterValue") private inline fun <T> runWithTimeout(timeout: Long, crossinline block: () -> T): T? { var value: T? = null val thread = thread { value = block() //highly depends that block doesn't throw exceptions } try { thread.join(timeout) if (thread.isAlive) { thread.interrupt() thread.join(50) } if (thread.isAlive) thread.stop() } catch (e: Exception) { logger.error(e) { "Can't run with timeout" } } return value } //val start = System.currentTimeMillis() //internal fun currentTime(start: Long) = (System.currentTimeMillis() - start) internal fun File.toUrl(): URL = toURI().toURL() internal fun testMethodName(name: String, num: Int): String = "test${name.capitalize()}$num" internal val Method.isVisibleFromGeneratedTest: Boolean get() = (this.modifiers and Modifier.ABSTRACT) == 0 && (this.modifiers and Modifier.NATIVE) == 0 private fun StatsForClass.updateCoverage(newCoverage: Coverage, isNewClass: Boolean, fromFuzzing: Boolean) { coverage.update(newCoverage, isNewClass) // other coverage type updates by empty coverage to respect new class val emptyCoverage = newCoverage.copy( coveredInstructions = emptyList() ) if (fromFuzzing) { fuzzedCoverage to concolicCoverage } else { concolicCoverage to fuzzedCoverage }.let { (targetSource, otherSource) -> targetSource.update(newCoverage, isNewClass) otherSource.update(emptyCoverage, isNewClass) } } private fun CoverageInstructionsSet.update(newCoverage: Coverage, isNewClass: Boolean) { if (isNewClass) { newCoverage.instructionsCount?.let { totalInstructions += it } } coveredInstructions.addAll(newCoverage.coveredInstructions) }
415
null
38
91
abb62682c70d7d2ecc4ad610851d304f7ad716e4
21,678
UTBotJava
Apache License 2.0
code/core/src/test/java/com/adobe/marketing/mobile/services/ui/alert/AlertPresentableTest.kt
adobe
458,293,389
false
null
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.services.ui.alert import com.adobe.marketing.mobile.services.ui.Alert import com.adobe.marketing.mobile.services.ui.FloatingButton import com.adobe.marketing.mobile.services.ui.InAppMessage import com.adobe.marketing.mobile.services.ui.PresentationDelegate import com.adobe.marketing.mobile.services.ui.PresentationUtilityProvider import com.adobe.marketing.mobile.services.ui.common.AppLifecycleProvider import kotlinx.coroutines.CoroutineScope import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.Mockito.mock import org.mockito.MockitoAnnotations import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue class AlertPresentableTest { @Mock private lateinit var mockAlert: Alert @Mock private lateinit var mockPresentationDelegate: PresentationDelegate @Mock private lateinit var mockPresentationUtilityProvider: PresentationUtilityProvider @Mock private lateinit var mockAppLifecycleProvider: AppLifecycleProvider @Mock private lateinit var mockScope: CoroutineScope private lateinit var alertPresentable: AlertPresentable @Before fun setUp() { MockitoAnnotations.openMocks(this) alertPresentable = AlertPresentable(mockAlert, mockPresentationDelegate, mockPresentationUtilityProvider, mockAppLifecycleProvider, mockScope) } @Test fun `Test #gateDisplay`() { assertFalse(alertPresentable.gateDisplay()) } @Test fun `Test #getPresentation`() { assertEquals(mockAlert, alertPresentable.getPresentation()) } @Test fun `Test #hasConflicts`() { assertTrue( alertPresentable.hasConflicts( listOf( mock(Alert::class.java), mock(InAppMessage::class.java), mock(FloatingButton::class.java) ) ) ) assertFalse( alertPresentable.hasConflicts( listOf( mock(FloatingButton::class.java) ) ) ) assertTrue( alertPresentable.hasConflicts( listOf( mock(InAppMessage::class.java) ) ) ) assertTrue( alertPresentable.hasConflicts( listOf( mock(Alert::class.java) ) ) ) } }
15
null
24
9
d3e61e63f80799942171e04e7d1b79a3a1a7c717
3,116
aepsdk-core-android
Apache License 2.0
src/main/kotlin/org/piecesapp/client/models/PersonType.kt
pieces-app
726,212,140
false
{"Kotlin": 1349331}
/** * Pieces Isomorphic OpenAPI * Endpoints for Assets, Formats, Users, Asset, Format, User. * * The version of the OpenAPI document: 1.0 * Contact: <EMAIL> * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.client.models import org.openapitools.client.models.EmbeddedModelSchema import org.openapitools.client.models.PersonBasicType import org.openapitools.client.models.UserProfile import com.squareup.moshi.Json /** * basic or platform is absolutely required here. basic: if provided is just information that has been either extracted from the piece or other wise added here. platform: is a real Pieces User.(this user will also exist within the user's users collection. && if not then we will just use the data we have.) * @param schema * @param basic * @param platform */ data class PersonType ( @Json(name = "schema") val schema: EmbeddedModelSchema? = null, @Json(name = "basic") val basic: PersonBasicType? = null, @Json(name = "platform") val platform: UserProfile? = null )
4
Kotlin
0
1
2f1e1749ed018f93a333c52400fdbf0bd08503e1
1,159
pieces-os-client-sdk-for-kotlin
MIT License
db/src/main/kotlin/com/dzirbel/kotify/db/SpotifyEntity.kt
dzirbel
211,595,180
false
null
package com.dzirbel.kotify.db import org.jetbrains.exposed.dao.Entity import org.jetbrains.exposed.dao.EntityClass import org.jetbrains.exposed.dao.id.EntityID import org.jetbrains.exposed.sql.Column import org.jetbrains.exposed.sql.javatime.timestamp import java.time.Instant /** * Base class for tables which contain a [SpotifyEntity], and provides common columns like [name]. */ abstract class SpotifyEntityTable(name: String = "") : StringIdTable(name = name) { val name: Column<String> = text("name") val uri: Column<String?> = text("uri").nullable() val createdTime: Column<Instant> = timestamp("created_time").clientDefault { Instant.now() } val updatedTime: Column<Instant> = timestamp("updated_time").clientDefault { Instant.now() } val fullUpdatedTime: Column<Instant?> = timestamp("full_updated_time").nullable() } /** * Base class for entity objects in a [SpotifyEntityTable]. * * TODO refactor UI to avoid direct use of (unstable) database entities */ abstract class SpotifyEntity(id: EntityID<String>, table: SpotifyEntityTable) : Entity<String>(id) { var name: String by table.name var uri: String? by table.uri var createdTime: Instant by table.createdTime var updatedTime: Instant by table.updatedTime var fullUpdatedTime: Instant? by table.fullUpdatedTime // TODO practically unused } /** * Base [EntityClass] which serves as the companion object for a [SpotifyEntityTable]. */ abstract class SpotifyEntityClass<EntityType : SpotifyEntity>(table: SpotifyEntityTable) : EntityClass<String, EntityType>(table)
2
Kotlin
2
34
a151c4c4aba2500e014d18f6409b43d9319c846e
1,584
kotify
MIT License
analysis/analysis-api-impl-base/src/org/jetbrains/kotlin/analysis/api/impl/base/references/KaBaseSimpleNameReference.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.analysis.api.impl.base.references import com.intellij.openapi.project.Project import org.jetbrains.kotlin.analysis.api.KaImplementationDetail import org.jetbrains.kotlin.analysis.api.platform.projectStructure.KotlinCompilerPluginsProvider import org.jetbrains.kotlin.analysis.api.platform.projectStructure.KotlinCompilerPluginsProvider.CompilerPluginType import org.jetbrains.kotlin.analysis.api.projectStructure.KaSourceModule import org.jetbrains.kotlin.analysis.api.platform.projectStructure.KotlinProjectStructureProvider import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtBinaryExpression import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtOperationReferenceExpression import org.jetbrains.kotlin.psi.KtSimpleNameExpression import org.jetbrains.kotlin.psi.KtUnaryExpression import org.jetbrains.kotlin.types.expressions.OperatorConventions import org.jetbrains.kotlin.types.expressions.OperatorConventions.ASSIGN_METHOD import org.jetbrains.kotlin.utils.addToStdlib.runIf @KaImplementationDetail abstract class KaBaseSimpleNameReference(expression: KtSimpleNameExpression) : KtSimpleNameReference(expression) { override val resolvesByNames: Collection<Name> get() { val element = element if (element is KtOperationReferenceExpression) { val tokenType = element.operationSignTokenType if (tokenType != null) { val name = OperatorConventions.getNameForOperationSymbol( tokenType, element.parent is KtUnaryExpression, element.parent is KtBinaryExpression ) ?: (expression.parent as? KtBinaryExpression)?.let { runIf(it.operationToken == KtTokens.EQ && isAssignmentResolved(element.project, it)) { ASSIGN_METHOD } } ?: return emptyList() val counterpart = OperatorConventions.ASSIGNMENT_OPERATION_COUNTERPARTS[tokenType] return if (counterpart != null) { val counterpartName = OperatorConventions.getNameForOperationSymbol(counterpart, false, true)!! listOf(name, counterpartName) } else { listOf(name) } } } return listOf(element.getReferencedNameAsName()) } private fun isAssignmentResolved(project: Project, binaryExpression: KtBinaryExpression): Boolean { val sourceModule = KotlinProjectStructureProvider.getModule(project, binaryExpression, useSiteModule = null) if (sourceModule !is KaSourceModule) { return false } val reference = binaryExpression.operationReference.reference ?: return false val compilerPluginsProvider = KotlinCompilerPluginsProvider.getInstance(project) ?: return false return compilerPluginsProvider.isPluginOfTypeRegistered(sourceModule, CompilerPluginType.ASSIGNMENT) && (reference.resolve() as? KtNamedFunction)?.nameAsName == ASSIGN_METHOD } }
182
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
3,501
kotlin
Apache License 2.0
coordinator/persistence/db/src/testFixtures/kotlin/net/consensys/zkevm/persistence/test/CleanDbTestSuiteParallel.kt
Consensys
681,656,806
false
{"Go": 3732756, "Kotlin": 2036043, "TypeScript": 1677629, "Solidity": 1011831, "Java": 190613, "Shell": 25336, "Python": 25050, "Jupyter Notebook": 14509, "Makefile": 13574, "Dockerfile": 8023, "JavaScript": 7341, "C": 5181, "Groovy": 2557, "CSS": 787, "Nix": 315, "Batchfile": 117}
package net.consensys.zkevm.persistence.test import io.vertx.core.Vertx import io.vertx.sqlclient.Pool import io.vertx.sqlclient.SqlClient import net.consensys.zkevm.persistence.db.Db import net.consensys.zkevm.persistence.db.Db.vertxConnectionPool import net.consensys.zkevm.persistence.db.Db.vertxSqlClient import net.consensys.zkevm.persistence.db.DbHelper import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.postgresql.ds.PGSimpleDataSource import javax.sql.DataSource abstract class CleanDbTestSuiteParallel { private val host = "localhost" private val port = 5432 abstract val databaseName: String private val username = "postgres" private val password = "<PASSWORD>" private lateinit var dataSource: DataSource lateinit var pool: Pool lateinit var sqlClient: SqlClient val target: String = "4" private fun createDataSource(databaseName: String): DataSource { return PGSimpleDataSource().also { it.serverNames = arrayOf(host) it.portNumbers = intArrayOf(port) it.databaseName = databaseName it.user = username it.password = <PASSWORD> } } @BeforeEach open fun setUp(vertx: Vertx) { val dbCreationDataSource = createDataSource("postgres") DbHelper.createDataBase(dbCreationDataSource, databaseName) dataSource = createDataSource(databaseName) pool = vertxConnectionPool(vertx, host, port, databaseName, username, password) sqlClient = vertxSqlClient(vertx, host, port, databaseName, username, password) // drop flyway db metadata table as well // to recreate new db tables; Db.applyDbMigrations(dataSource, target) } @AfterEach open fun tearDown() { pool.close { ar: io.vertx.core.AsyncResult<Void?> -> if (ar.failed()) { System.err.println("Error closing connection pool: " + ar.cause().message) } } sqlClient.close { ar: io.vertx.core.AsyncResult<Void?> -> if (ar.failed()) { System.err.println("Error closing sqlclient " + ar.cause().message) } } DbHelper.resetAllConnections(dataSource, databaseName) } }
27
Go
2
26
48547c9f3fb21e9003d990c9f62930f4facee0dd
2,122
linea-monorepo
Apache License 2.0
domain/src/commonMain/kotlin/domain/AllNowPlayingMovieUseCaseImpl.kt
ibenabdallah
748,016,150
false
{"Kotlin": 80015, "Swift": 589}
package domain import data.model.NetworkMovieItem import domain.paging.PaginatedContent import domain.paging.PaginatedContentImpl import data.repository.MovieRepository class AllNowPlayingMovieUseCaseImpl(private val repository: MovieRepository) : AllNowPlayingMovieUseCase { override operator fun invoke(): PaginatedContent<NetworkMovieItem> { return PaginatedContentImpl { repository.nowPlayingMovie() } } }
0
Kotlin
1
65
0345f3547f8bfab98c0f10a80fc00c29cd8c96ca
433
the-movie-db
Apache License 2.0
extension-compose/src/main/java/com/mapbox/maps/extension/compose/style/layers/generated/FillExtrusionLayer.kt
mapbox
330,365,289
false
null
// This file is generated. package com.mapbox.maps.extension.compose.style.layers.generated import androidx.compose.runtime.Composable import androidx.compose.runtime.ComposeNode import androidx.compose.runtime.currentComposer import androidx.compose.runtime.key import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import com.mapbox.maps.extension.compose.MapboxMapComposable import com.mapbox.maps.extension.compose.internal.MapApplier import com.mapbox.maps.extension.compose.style.IdGenerator.generateRandomLayerId import com.mapbox.maps.extension.compose.style.layers.internal.LayerNode import com.mapbox.maps.extension.compose.style.sources.SourceState /** * An extruded (3D) polygon. * * This composable function inserts a [FillExtrusionLayer] to the map. For convenience, if there's * no need to hoist the [fillExtrusionLayerState], use `FillExtrusionLayer(sourceState, layerId, init)` with trailing lambda instead. * * @see [The online documentation](https://docs.mapbox.com/style-spec/reference/layers#fill-extrusion) * * @param sourceState the source that drives this layer. * @param layerId the ID of the layer, by default, a random id will be generated with UUID. * @param fillExtrusionLayerState the state holder for [FillExtrusionLayer]'s properties. */ @Composable @MapboxMapComposable public fun FillExtrusionLayer( sourceState: SourceState, layerId: String = remember { generateRandomLayerId("fill-extrusion") }, fillExtrusionLayerState: FillExtrusionLayerState = remember { FillExtrusionLayerState() } ) { val mapApplier = currentComposer.applier as? MapApplier ?: throw IllegalStateException("Illegal use of FillExtrusionLayer inside unsupported composable function") val coroutineScope = rememberCoroutineScope() val layerNode = remember { LayerNode( map = mapApplier.mapView.mapboxMap, layerType = "fill-extrusion", sourceState = sourceState, layerId = layerId, coroutineScope = coroutineScope ) } ComposeNode<LayerNode, MapApplier>( factory = { layerNode }, update = { update(sourceState) { updateSource(sourceState) } update(layerId) { updateLayerId(layerId) } } ) { key(fillExtrusionLayerState) { fillExtrusionLayerState.UpdateProperties(layerNode) } } sourceState.UpdateProperties() } /** * An extruded (3D) polygon. * * This composable function inserts a [FillExtrusionLayer] to the map. * * @see [The online documentation](https://docs.mapbox.com/style-spec/reference/layers#fill-extrusion) * * @param sourceState the source that drives this layer. * @param layerId the ID of the layer, by default, a random id will be generated with UUID. * @param init the lambda that will be applied to the remembered [FillExtrusionLayerState]. */ @Composable @MapboxMapComposable public inline fun FillExtrusionLayer( sourceState: SourceState, layerId: String = remember { generateRandomLayerId("fill-extrusion") }, crossinline init: FillExtrusionLayerState.() -> Unit ) { FillExtrusionLayer(sourceState = sourceState, layerId = layerId, fillExtrusionLayerState = remember { FillExtrusionLayerState() }.apply(init)) } // End of generated file.
225
null
131
472
2700dcaf18e70d23a19fc35b479bff6a2d490475
3,280
mapbox-maps-android
Apache License 2.0
src/main/kotlin/com/examples/abbasdgr8/view/ViewCommons.kt
abbasdgr8
293,219,115
false
null
package com.examples.abbasdgr8.view import java.io.File import kotlin.text.StringBuilder class ViewCommons { companion object { fun getScreen(fileName: String): String { return File("$SCREENS_DIR_PATH/$fileName.txt").readText() } fun getFieldsWithBanner(fields: List<String>, banner: String): String { val sb = StringBuilder() fields.forEach {field -> lineBreak(sb) sb.append(field) } lineBreak(sb) lineBreak(sb) return banner + sb.toString() } fun <T> getSearchResults(records: List<T>, recordType: String, associationSearch: Boolean = false): String { val sb = StringBuilder() sb.append(getSearchedRecords(records)) sb.append(getSearchResultSummary(records.size, recordType, associationSearch)) return sb.toString() } fun getFieldNameErrorMsg(): String { return fieldNameErrorMsg } fun getFieldValueErrorMsg(): String { return fieldValueErrorMsg } fun getAssocationsErrorMsg(): String { return assocationsErrorMsg } fun lineBreak(sb: StringBuilder) { sb.append(System.lineSeparator()) } fun horizontalRule(sb: StringBuilder) { sb.append(horizontalRule) } private fun <T> getSearchedRecords(records: List<T>): String { val sb = StringBuilder() records.forEach { record -> lineBreak(sb) sb.append(record.toString()) lineBreak(sb) } return sb.toString() } private fun getSearchResultSummary(count: Int, recordType: String, isAssociationSearch: Boolean = false): String { val sb = StringBuilder() val searchType: String = if (isAssociationSearch) "associated" else "matching" lineBreak(sb) horizontalRule(sb) lineBreak(sb) sb.append("Found $count $searchType $recordType(s)") lineBreak(sb) horizontalRule(sb) lineBreak(sb) return sb.toString() } private const val SCREENS_DIR_PATH = "src/main/resources/screens" private val fieldNameErrorMsg = getScreen("field-name-error") private val fieldValueErrorMsg = getScreen("field-value-error") private val assocationsErrorMsg = getScreen("assocations-error") private val horizontalRule = getScreen("horizontal-rule") } }
0
Kotlin
0
0
a979c79ee61fe014458085396cf624df7022577a
2,625
ticketing-search-app
Apache License 2.0
adventure-serialization/src/main/kotlin/net/bladehunt/kotstom/serialization/adventure/AdventureNbt.kt
bladehuntmc
822,386,546
false
{"Kotlin": 117270}
package net.bladehunt.kotstom.serialization.adventure import kotlin.reflect.KClass import kotlinx.serialization.InternalSerializationApi import kotlinx.serialization.SerialFormat import kotlinx.serialization.modules.EmptySerializersModule import kotlinx.serialization.modules.SerializersModule import kotlinx.serialization.serializer import net.kyori.adventure.nbt.CompoundBinaryTag open class AdventureNbt( val discriminator: String = "type", val shouldEncodeDefaults: Boolean = false, override val serializersModule: SerializersModule = EmptySerializersModule() ) : SerialFormat { data class Builder( var discriminator: String = "type", var shouldEncodeDefaults: Boolean = false, var serializersModule: SerializersModule? = null ) { fun build(): AdventureNbt = AdventureNbt( discriminator, shouldEncodeDefaults, serializersModule ?: EmptySerializersModule()) } @OptIn(InternalSerializationApi::class) fun <T : Any> encodeToCompound(clazz: KClass<T>, value: T): CompoundBinaryTag { val encoder = AdventureCompoundEncoder(this) encoder.encodeSerializableValue(clazz.serializer(), value) return encoder.toBinaryTag() } inline fun <reified T : Any> encodeToCompound(value: T): CompoundBinaryTag = encodeToCompound(T::class, value) @OptIn(InternalSerializationApi::class) fun <T : Any> decodeFromCompound(clazz: KClass<T>, compoundBinaryTag: CompoundBinaryTag): T = AdventureCompoundDecoder(this, compoundBinaryTag) .decodeSerializableValue(clazz.serializer()) inline fun <reified T : Any> decodeFromCompound(compoundBinaryTag: CompoundBinaryTag): T = decodeFromCompound(T::class, compoundBinaryTag) companion object Default : AdventureNbt() } inline fun AdventureNbt(block: AdventureNbt.Builder.() -> Unit): AdventureNbt = AdventureNbt.Builder().apply(block).build()
0
Kotlin
0
9
f0bd4675be3ecd858b057d2d936aa93e5ed20cc2
1,953
KotStom
MIT License
WeatherApp/app/src/main/java/com/arcapp/weatherapp/api/AuthInterceptor.kt
mrnirva
552,269,945
false
{"Kotlin": 44256}
package com.arcapp.weatherapp.api import com.arcapp.weatherapp.constant.Constants import okhttp3.Interceptor import okhttp3.Request import okhttp3.Response class AuthInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { // create chain and add api key val request: Request = chain.request().newBuilder() .url(chain.request().url.newBuilder().addQueryParameter(Constants.API_KEY_NAME, Constants.API_KEY).build()) .build() return chain.proceed(request) } }
0
Kotlin
0
1
10da4a7931a02fec72558ed01476feeccd317a43
551
Patika-Pazarama-Bootcamp-Week-4-Task
MIT License
core/data/src/main/kotlin/com/kevlina/budgetplus/core/data/JoinInfoProcessor.kt
kevinguitar
517,537,183
false
{"Kotlin": 690086}
package com.kevlina.budgetplus.core.data import com.google.firebase.firestore.CollectionReference import com.kevlina.budgetplus.core.data.remote.JoinInfo import com.kevlina.budgetplus.core.data.remote.JoinInfoDb import java.util.UUID import javax.inject.Inject class JoinInfoProcessor @Inject constructor( @JoinInfoDb private val joinInfoDb: dagger.Lazy<CollectionReference>, ) { fun generateJoinId(bookId: String): String { val joinId = UUID.randomUUID().toString() joinInfoDb.get().document(joinId).set( JoinInfo( bookId = bookId, generatedOn = System.currentTimeMillis() ) ) return joinId } suspend fun resolveJoinId(joinId: String): JoinInfo? { // joinId could be the random referral from GP, ignore these cases. if (joinId.startsWith("utm_source") || joinId.startsWith("gclid")) { return null } return try { joinInfoDb.get().document(joinId).get().requireValue() } catch (e: Exception) { e.toString() throw JoinBookException.JoinInfoNotFound("Couldn't resolve the join id. $joinId") } } }
0
Kotlin
0
9
ab973c1d8b29e41c0ed33ad3568a6e0aef1c6e47
1,202
budgetplus-android
MIT License
src/main/java/com/keithmackay/api/tasks/TestTask.kt
kamackay
204,213,721
false
null
package com.keithmackay.api.tasks import com.google.gson.GsonBuilder import com.google.inject.Inject import com.google.inject.Singleton import com.keithmackay.api.email.EmailSender import com.keithmackay.api.model.CryptoLookupBean import com.keithmackay.api.services.CryptoService import com.keithmackay.api.services.NewsService import com.keithmackay.api.services.WeatherService import com.keithmackay.api.utils.SecretsGrabber import com.keithmackay.api.utils.getLogger import org.quartz.JobExecutionContext @Singleton class TestTask @Inject internal constructor( private val emailSender: EmailSender, private val secrets: SecretsGrabber, private val weatherService: WeatherService, private val cryptoService: CryptoService, private val newsService: NewsService ) : CronTask() { private val log = getLogger(this::class) override fun name() = "TestTask" override fun cron() = CronTimes.minutes(2) override fun execute(ctx: JobExecutionContext?) { // No-op } private fun testNewsService() = log.info(GsonBuilder() .setPrettyPrinting() .create() .toJson(newsService.getDaysTopNews())) private fun testWeather() = log.info(GsonBuilder() .setPrettyPrinting() .create() .toJson(weatherService.getWeatherForLocation(WeatherService.Location( name = "Durm", latitude = 36.06, longitude = -78.87 )))) }
0
Kotlin
0
0
31e091fc6a3cdf4c3acb49e25ad02dd1aff1db37
1,409
api
MIT License
plugins/kotlin/idea/tests/testData/intentions/joinDeclarationAndAssignment/comment4.kt
JetBrains
2,489,216
false
null
// AFTER-WARNING: Variable 'foo' is never used fun test() { // comment 1 <caret>val foo: String // comment 2 // comment 3 bar() foo = "" } fun bar() {}
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
173
intellij-community
Apache License 2.0
sample/counter/shared/src/androidMain/kotlin/com/arkivanov/sample/counter/shared/ui/android/CounterRootContainerView.kt
badoo
287,788,515
false
null
package com.arkivanov.sample.counter.shared.ui.android import android.view.View import com.arkivanov.decompose.ExperimentalDecomposeApi import com.arkivanov.decompose.extensions.android.RouterView import com.arkivanov.decompose.extensions.android.ViewContext import com.arkivanov.decompose.extensions.android.child import com.arkivanov.decompose.extensions.android.layoutInflater import com.arkivanov.sample.counter.shared.R import com.arkivanov.sample.counter.shared.root.CounterRoot @ExperimentalDecomposeApi @Suppress("FunctionName") // Factory function fun ViewContext.CounterRootView(counterRoot: CounterRoot): View { val layout = layoutInflater.inflate(R.layout.counter_root, parent, false) val nextButton: View = layout.findViewById(R.id.button_next) val router: RouterView = layout.findViewById(R.id.router) nextButton.setOnClickListener { counterRoot.onNextChild() } child(layout.findViewById(R.id.container_counter)) { CounterView(counterRoot.counter) } router.children(counterRoot.routerState, lifecycle) { parent, child, _ -> parent.removeAllViews() parent.addView(CounterInnerView(child.inner)) } return layout }
7
Kotlin
44
806
acc4374212839bfaaffeab89bbcceebdb63cbe13
1,192
Decompose
Apache License 2.0
sample/counter/shared/src/androidMain/kotlin/com/arkivanov/sample/counter/shared/ui/android/CounterRootContainerView.kt
badoo
287,788,515
false
null
package com.arkivanov.sample.counter.shared.ui.android import android.view.View import com.arkivanov.decompose.ExperimentalDecomposeApi import com.arkivanov.decompose.extensions.android.RouterView import com.arkivanov.decompose.extensions.android.ViewContext import com.arkivanov.decompose.extensions.android.child import com.arkivanov.decompose.extensions.android.layoutInflater import com.arkivanov.sample.counter.shared.R import com.arkivanov.sample.counter.shared.root.CounterRoot @ExperimentalDecomposeApi @Suppress("FunctionName") // Factory function fun ViewContext.CounterRootView(counterRoot: CounterRoot): View { val layout = layoutInflater.inflate(R.layout.counter_root, parent, false) val nextButton: View = layout.findViewById(R.id.button_next) val router: RouterView = layout.findViewById(R.id.router) nextButton.setOnClickListener { counterRoot.onNextChild() } child(layout.findViewById(R.id.container_counter)) { CounterView(counterRoot.counter) } router.children(counterRoot.routerState, lifecycle) { parent, child, _ -> parent.removeAllViews() parent.addView(CounterInnerView(child.inner)) } return layout }
7
Kotlin
44
806
acc4374212839bfaaffeab89bbcceebdb63cbe13
1,192
Decompose
Apache License 2.0
src/main/kotlin/com/casper/sdk/getdeploy/ExecutableDeployItem/ExecutableDeployItem.kt
tqhuy2018
468,191,022
false
{"Kotlin": 453890}
package com.casper.sdk.getdeploy.ExecutableDeployItem import net.jemzart.jsonkraken.get import net.jemzart.jsonkraken.toJsonString import net.jemzart.jsonkraken.values.JsonArray import net.jemzart.jsonkraken.values.JsonObject /** Class built for storing ExecutableDeployItem enum in general * This class has 2 attributes: * 1) itsType is for the type of the ExecutableDeployItem enum, which can be a string among these values: * ModuleBytes, StoredContractByHash, StoredContractByName, StoredVersionedContractByHash, StoredVersionedContractByName, Transfer * 2) itsValue: To hold the real ExecutableDeployItem enum value, which can be 1 among the following class * ExecutableDeployItem_ModuleBytes * ExecutableDeployItem_StoredContractByHash * ExecutableDeployItem_StoredContractByName * ExecutableDeployItem_StoredVersionedContractByHash * ExecutableDeployItem_StoredVersionedContractByName * ExecutableDeployItem_Transfer */ class ExecutableDeployItem { var itsType: String= "" var itsValue: MutableList<Any> = mutableListOf() companion object{ // Constant values for the type of the ExecutableDeployItem enum const val MODULE_BYTES = "ModuleBytes" const val STORED_CONTRACT_BY_HASH = "StoredContractByHash" const val STORED_CONTRACT_BY_NAME = "StoredContractByName" const val STORED_VERSIONED_CONTRACT_BY_HASH = "StoredVersionedContractByHash" const val STORED_VERSIONED_CONTRACT_BY_NAME = "StoredVersionedContractByName" const val TRANSFER = "Transfer" /** This function parse the JsonArray (taken from server RPC method call) to get the ExecutableDeployItem object */ fun fromJsonToExecutableDeployItem(from: JsonObject): ExecutableDeployItem { val ret = ExecutableDeployItem() val ediModuleBytes: String = from.get("ModuleBytes").toJsonString() if(ediModuleBytes != "null" ) { ret.itsType = MODULE_BYTES val eMB = ExecutableDeployItem_ModuleBytes() eMB.module_bytes = from.get("ModuleBytes").get("module_bytes").toString() eMB.args = RuntimeArgs.fromJsonArrayToObj(from.get("ModuleBytes").get("args") as JsonArray) ret.itsValue.add(eMB) return ret } val ediStoredContractByHash = from.get("StoredContractByHash").toJsonString() if(ediStoredContractByHash != "null") { ret.itsType = STORED_CONTRACT_BY_HASH val eSCBH = ExecutableDeployItem_StoredContractByHash() eSCBH.itsHash = from.get("StoredContractByHash").get("hash").toString() eSCBH.entryPoint = from.get("StoredContractByHash").get("entry_point").toString() eSCBH.args = RuntimeArgs.fromJsonArrayToObj(from.get("StoredContractByHash").get("args") as JsonArray) ret.itsValue.add(eSCBH) return ret } val ediStoredContractByName = from.get("StoredContractByName").toJsonString() if(ediStoredContractByName != "null") { ret.itsType = STORED_CONTRACT_BY_NAME val eSCBN = ExecutableDeployItem_StoredContractByName() eSCBN.itsName = from.get("StoredContractByName").get("name").toString() eSCBN.entryPoint = from.get("StoredContractByName").get("entry_point").toString() eSCBN.args = RuntimeArgs.fromJsonArrayToObj(from.get("StoredContractByName").get("args") as JsonArray) ret.itsValue.add(eSCBN) return ret } val ediStoredVersionedContractByHash = from.get("StoredVersionedContractByHash").toJsonString() if(ediStoredVersionedContractByHash != "null") { ret.itsType = STORED_VERSIONED_CONTRACT_BY_HASH val eSCBH = ExecutableDeployItem_StoredVersionedContractByHash() eSCBH.itsHash = from.get("StoredVersionedContractByHash").get("hash").toString() eSCBH.entryPoint = from.get("StoredVersionedContractByHash").get("entry_point").toString() eSCBH.args = RuntimeArgs.fromJsonArrayToObj(from.get("StoredVersionedContractByHash").get("args") as JsonArray) val version = from.get("StoredVersionedContractByHash").get("version").toJsonString() if(version == "null") { eSCBH.isVersionExisted = false } else { // val contractVersion: ContractVersion = ContractVersion.fromJsonToContractVersion(from.get("StoredVersionedContractByHash").get("version") as JsonObject) eSCBH.version = from.get("StoredVersionedContractByHash").get("version") as UInt } ret.itsValue.add(eSCBH) return ret } val ediStoredVersionedContractByName = from.get("StoredVersionedContractByName").toJsonString() if(ediStoredVersionedContractByName != "null") { ret.itsType = STORED_VERSIONED_CONTRACT_BY_NAME val eSCBH = ExecutableDeployItem_StoredVersionedContractByName() eSCBH.itsName = from.get("StoredVersionedContractByName").get("name").toString() eSCBH.entryPoint = from.get("StoredVersionedContractByName").get("entry_point").toString() eSCBH.args = RuntimeArgs.fromJsonArrayToObj(from.get("StoredVersionedContractByName").get("args") as JsonArray) val version = from.get("StoredVersionedContractByName").get("version").toJsonString() if(version == "null") { eSCBH.isVersionExisted = false } else { //val contractVersion: ContractVersion = ContractVersion.fromJsonToContractVersion(from.get("StoredVersionedContractByHash").get("version") as JsonObject) eSCBH.version = from.get("StoredVersionedContractByName").get("version") as UInt } ret.itsValue.add(eSCBH) return ret } val ediTransfer = from.get("Transfer").toJsonString() if (ediTransfer != "null") { ret.itsType = TRANSFER val transfer = ExecutableDeployItem_Transfer() transfer.args = RuntimeArgs.fromJsonArrayToObj(from.get("Transfer").get("args") as JsonArray) ret.itsValue.add(transfer) return ret } return ret } } }
0
Kotlin
2
7
6ee0ac2490b249d482096bff6b6316aed7b133ee
7,872
Casper-Kotlin-sdk
MIT License
domain/learningandworkprogress/src/testFixtures/kotlin/uk/gov/justice/digital/hmpps/domain/learningandworkprogress/PagedResultBuilder.kt
ministryofjustice
653,598,082
false
{"Kotlin": 1539869, "Mustache": 2705, "Dockerfile": 1375}
package uk.gov.justice.digital.hmpps.domain.learningandworkprogress fun <T> aValidPagedResult( content: List<T> = emptyList(), page: Int = 0, pageSize: Int = 20, ): PagedResult<T> = PagedResult( totalElements = content.size, totalPages = (content.size / pageSize) + 1, pageNumber = page, pageSize = pageSize, content = content.chunked(pageSize).getOrNull(page) ?: emptyList(), )
4
Kotlin
0
2
47e8a533f050ef307a775f4774dd2d74bd1be0fe
410
hmpps-education-and-work-plan-api
MIT License
spring-data-graphql-r2dbc/src/main/kotlin/io/github/wickedev/graphql/spring/data/r2dbc/strategy/GraphQLAdditionalIsNewStrategy.kt
wickedev
439,584,762
false
{"Kotlin": 269467, "JavaScript": 6748, "Java": 2439, "CSS": 1699}
package io.github.wickedev.graphql.spring.data.r2dbc.strategy import io.github.wickedev.graphql.types.ID class GraphQLAdditionalIsNewStrategy : AdditionalIsNewStrategy { override fun isNew(type: Class<*>?, value: Any?): Boolean { return if (type == ID::class.java) (value as ID).value.isEmpty() else false } }
0
Kotlin
0
19
d6913beaecf9e7ef065acdb1805794a10b07d55e
349
graphql-jetpack
The Unlicense
theta-iscp-plugin/app/src/main/java/com/aptpod/theta/plugin/iscpstreaming/helpers/ApplicationSettings.kt
aptpod
697,116,031
false
{"OASv3-yaml": 2, "JSON": 1, "Text": 1, "Markdown": 215, "Gradle": 5, "Scala": 1, "Shell": 3, "Maven POM": 1, "INI": 2, "Java Properties": 3, "Ignore List": 4, "Batchfile": 2, "YAML": 2, "Java": 460, "XML": 24, "Proguard": 1, "Kotlin": 12, "HTML": 1}
package com.aptpod.theta.plugin.iscpstreaming.helpers import android.util.Log import android.util.Size import org.json.JSONObject import java.io.BufferedReader import java.io.FileInputStream import java.io.InputStreamReader class ApplicationSettings { companion object { const val TAG = "ApplicationSettings" const val FILE_PATH = "/storage/self/primary/iscp_plugin_settings.json" const val KEY_INTDASH = "intdash" const val KEY_VIDEO = "video" const val KEY_AUDIO = "audio" fun load() : ApplicationSettings { var settings = ApplicationSettings() var reader: BufferedReader? = null try { reader = BufferedReader(InputStreamReader(FileInputStream(FILE_PATH))) var jsonStr = reader.readText() //Log.d(TAG, "load settings json: $jsonStr") var jsonObj = JSONObject(jsonStr) if(jsonObj.has(KEY_INTDASH)) settings.intdash = Intdash.parse(jsonObj.getJSONObject(KEY_INTDASH)) if(jsonObj.has(KEY_VIDEO)) settings.video = Video.parse(jsonObj.getJSONObject(KEY_VIDEO)) if(jsonObj.has(KEY_AUDIO)) settings.audio = Audio.parse(jsonObj.getJSONObject(KEY_AUDIO)) return settings } catch (e: Exception) { Log.e(TAG, "load application settings error. $e") } finally { try { reader?.close() } catch (e: Exception) { e.printStackTrace() } } return settings } } private constructor() //region intdash class Intdash { companion object { const val KEY_INTDASH_SERVER_URL = "server_url" const val KEY_INTDASH_SERVER_PATH = "/api" const val KEY_INTDASH_NODE_CLIENT_ID = "node_client_id" const val KEY_INTDASH_NODE_CLIENT_SECRET = "node_client_secret" const val KEY_INTDASH_SAVE_TO_SERVER = "save_to_server" fun parse(json: JSONObject) : Intdash { var model = Intdash() model.serverUrl = json.getString(KEY_INTDASH_SERVER_URL) if (json.has(KEY_INTDASH_SERVER_PATH)) model.serverPath = json.getString( KEY_INTDASH_SERVER_PATH) model.nodeClientId = json.getString(KEY_INTDASH_NODE_CLIENT_ID) model.nodeClientSecretId = json.getString(KEY_INTDASH_NODE_CLIENT_SECRET) if (json.has(KEY_INTDASH_SAVE_TO_SERVER)) model.saveToServer = json.getBoolean( KEY_INTDASH_SAVE_TO_SERVER) return model } } var serverUrl = "" var serverPath = "/api" var nodeClientId = "" var nodeClientSecretId = "" var saveToServer: Boolean = false } var intdash: Intdash? = null //endregion //region Video class Video { companion object { const val KEY_ENABLED = "enabled" const val KEY_RESOLUTION = "resolution" const val KEY_RESOLUTION_WIDTH = "width" const val KEY_RESOLUTION_HEIGHT = "height" const val KEY_SAMPLE_RATE = "sample_rate" const val KEY_ENCODE_RATE = "encode_rate" const val KEY_BIT_RATE = "bit_rate" const val KEY_I_FRAME_INTERVAL = "i_frame_interval" fun parse(json: JSONObject) : Video { var model = Video() model.enabled = json.getBoolean(KEY_ENABLED) var resolution = json.getJSONObject(KEY_RESOLUTION) model.resolution = Size(resolution.getInt(KEY_RESOLUTION_WIDTH), resolution.getInt( KEY_RESOLUTION_HEIGHT)) if (json.has(KEY_SAMPLE_RATE)) model.sampleRate = json.getDouble(KEY_SAMPLE_RATE).toFloat() if (json.has(KEY_SAMPLE_RATE)) model.encodeRate = json.getDouble(KEY_ENCODE_RATE).toFloat() if (json.has(KEY_BIT_RATE)) model.bitRate = json.getInt(KEY_BIT_RATE) if (json.has(KEY_I_FRAME_INTERVAL)) model.iFrameInterval = json.getInt( KEY_I_FRAME_INTERVAL) return model } } var enabled: Boolean = false var resolution: Size = Size(1920, 960) var sampleRate: Float = 29.97f var encodeRate: Float = 29.97f var bitRate: Int = 2000000 var iFrameInterval: Int = 2 } var video: Video? = null //endregion //region Audio class Audio { companion object { const val KEY_ENABLED = "enabled" const val KEY_SAMPLE_RATE = "sample_rate" const val KEY_FRAME_SIZE = "frame_size" fun parse(json: JSONObject) : Audio { var model = Audio() model.enabled = json.getBoolean(KEY_ENABLED) if (json.has(KEY_SAMPLE_RATE)) model.sampleRate = json.getInt(KEY_SAMPLE_RATE) if (json.has(KEY_FRAME_SIZE)) model.frameSize = json.getInt(KEY_FRAME_SIZE) return model } } var enabled: Boolean = false var sampleRate: Int = 48000 var frameSize: Int = 1024 } var audio: Audio? = null //endregion }
0
Java
0
0
b9300ec4ff5dd127a67671d6f028f62d40f48867
5,269
theta-iscp-plugin
Apache License 2.0
shared/src/main/java/com/benkkstudios/ads/shared/consent/ConsentManager.kt
benkkstudios
834,326,902
false
{"Kotlin": 174900, "Java": 41761}
package com.benkkstudios.ads.shared.consent import android.app.Activity import com.benkkstudios.ads.shared.AdsConstant import com.google.android.ump.ConsentDebugSettings import com.google.android.ump.ConsentDebugSettings.DebugGeography import com.google.android.ump.ConsentForm import com.google.android.ump.ConsentInformation import com.google.android.ump.ConsentRequestParameters import com.google.android.ump.FormError import com.google.android.ump.UserMessagingPlatform class ConsentManager { fun interface OnConsentGatheringCompleteListener { fun consentGatheringComplete(error: FormError?) } fun request(activity: Activity, onSuccess: () -> Unit) { UserMessagingPlatform.getConsentInformation(activity).let { consentInformation -> gatherConsent(activity, consentInformation) { canRequestAds = consentInformation.canRequestAds() onSuccess.invoke() } } } private fun createDebugSetting(activity: Activity): ConsentDebugSettings { return ConsentDebugSettings.Builder(activity) .setDebugGeography(DebugGeography.DEBUG_GEOGRAPHY_EEA) .setForceTesting(true) .build() } private fun createRequestParameter(activity: Activity): ConsentRequestParameters { return if (AdsConstant.DEBUG_MODE) { ConsentRequestParameters.Builder() .setConsentDebugSettings(createDebugSetting(activity)) .build() } else { ConsentRequestParameters.Builder().build() } } private fun gatherConsent( activity: Activity, consentInformation: ConsentInformation, onConsentGatheringCompleteListener: OnConsentGatheringCompleteListener, ) { consentInformation.requestConsentInfoUpdate( activity, createRequestParameter(activity), { UserMessagingPlatform.loadAndShowConsentFormIfRequired(activity) { formError -> onConsentGatheringCompleteListener.consentGatheringComplete(formError) } }, { requestConsentError -> onConsentGatheringCompleteListener.consentGatheringComplete(requestConsentError) }, ) } fun showPrivacyOptionsForm( activity: Activity, onConsentFormDismissedListener: ConsentForm.OnConsentFormDismissedListener, ) { UserMessagingPlatform.showPrivacyOptionsForm(activity, onConsentFormDismissedListener) } companion object { var canRequestAds = true @Volatile private var instance: ConsentManager? = null fun getInstance() = instance ?: synchronized(this) { instance ?: ConsentManager().also { instance = it } } } }
0
Kotlin
0
0
f1bbdb1eb5e9b42f63cf0c89f711b918f5b9fd2d
2,874
BeeAds
Apache License 2.0
src/Day11.kt
wujingwe
574,096,169
false
null
object Day11 { class Monkey( val id: Int, val levels: MutableList<Long>, val op: Int, val operand: Int, val divider: Int, val pos: Int, val neg: Int, var count: Int = 0 ) private const val OP_ADD = 0 private const val OP_MUL = 1 private const val OP_SQUARE = 2 private fun parse(inputs: String): List<Monkey> { return inputs.split("\n\n").map { s -> val tokens = s.split("\n") val id = tokens[0].split(" ")[1].trimEnd(':').toInt() // Monkey 0 val levels = tokens[1] .trim() .split(" ") .drop(2) .map { it.trimEnd(',').toLong() } .toMutableList() val (_op, _operand) = tokens[2].trim().split(" ").drop(4) val (op, operand) = if (_op == "+") { OP_ADD to _operand.toInt() } else if (_op == "*" && _operand == "old") { OP_SQUARE to 0 } else { OP_MUL to _operand.toInt() } val divider = tokens[3].trim().split(" ")[3].toInt() val pos = tokens[4].trim().split(" ")[5].toInt() val neg = tokens[5].trim().split(" ")[5].toInt() Monkey(id, levels, op, operand, divider, pos, neg) } } private fun iteration(monkeys: List<Monkey>, count: Int, mitigateFunc: (Long) -> Long) { repeat(count) { monkeys.forEach { monkey -> val levels = monkey.levels.toList() monkey.levels.clear() levels.forEach { level -> val newLevel = when (monkey.op) { OP_ADD -> (level + monkey.operand) OP_SQUARE -> (level * level) else -> (level * monkey.operand) } val worry = mitigateFunc(newLevel) if (worry % monkey.divider == 0L) { monkeys[monkey.pos].levels.add(worry) } else { monkeys[monkey.neg].levels.add(worry) } monkey.count++ } } } } fun part1(inputs: String): Long { val monkeys = parse(inputs) iteration(monkeys, 20) { it / 3 } val (a, b) = monkeys.sortedByDescending { it.count } return a.count.toLong() * b.count } fun part2(inputs: String): Long { val monkeys = parse(inputs) val divider = monkeys.map(Monkey::divider).reduce(Int::times).toLong() iteration(monkeys, 10_000) { it % divider } val (a, b) = monkeys.sortedByDescending { it.count } return a.count.toLong() * b.count } } fun main() { fun part1(inputs: String): Long { return Day11.part1(inputs) } fun part2(inputs: String): Long { return Day11.part2(inputs) } val testInput = readText("../data/Day11_test") check(part1(testInput) == 10605L) check(part2(testInput) == 2713310158L) val input = readText("../data/Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a5777a67d234e33dde43589602dc248bc6411aee
3,211
advent-of-code-kotlin-2022
Apache License 2.0
library/src/main/java/com/silverpine/uu/ux/UUFragmentActivity.kt
SilverPineSoftware
594,244,482
false
{"Kotlin": 153852, "Shell": 10612}
package com.silverpine.uu.ux import android.os.Bundle import androidx.annotation.LayoutRes import androidx.fragment.app.FragmentActivity open class UUFragmentActivity(@LayoutRes val layoutResourceId: Int = R.layout.uu_fragment_activity): FragmentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (layoutResourceId != -1) { setContentView(layoutResourceId) } } }
0
Kotlin
0
0
0992a8f26c6478b2e2868db92393e4690ca8fc98
475
UUKotlinUX
MIT License
app/src/main/java/ton/coin/wallet/common/ui/formatter/TonCoinsFormatter.kt
protoshadowmaker
643,940,461
false
null
package ton.coin.wallet.common.ui.formatter import ton.coin.wallet.data.TonCoins import java.math.BigDecimal import java.math.RoundingMode object TonCoinsFormatter { fun format(coins: TonCoins, scale: Int = -1): String { val result = coins.value.toBigDecimal().divide(BigDecimal.valueOf(1_000_000_000)) return if (scale == -1) { result.stripTrailingZeros().toPlainString() } else { result.setScale(scale, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString() } } }
0
Kotlin
0
0
adf8eb798a8e044427b7295136913869bf264e7e
535
tonwallet
MIT License
app/src/main/kotlin/com/g00fy2/developerwidget/activities/widgetconfig/DeviceDataAdapter.kt
G00fY2
96,943,329
false
null
package com.g00fy2.developerwidget.activities.widgetconfig import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.g00fy2.developerwidget.base.BaseAdapter import com.g00fy2.developerwidget.base.BaseViewHolder import com.g00fy2.developerwidget.data.DeviceDataItem import com.g00fy2.developerwidget.databinding.DeviceDataHeaderItemBinding import com.g00fy2.developerwidget.databinding.DeviceDataValueItemBinding class DeviceDataAdapter : BaseAdapter<Pair<String, DeviceDataItem>, BaseViewHolder<Pair<String, DeviceDataItem>>>(DeviceDataDiffUtilsCallback()) { class DeviceDataHeaderViewHolder(val binding: DeviceDataHeaderItemBinding) : BaseViewHolder<Pair<String, DeviceDataItem>>(binding) { override fun onBind(item: Pair<String, DeviceDataItem>) { item.run { binding.headerDividerView.visibility = if (bindingAdapterPosition == 0) View.INVISIBLE else View.VISIBLE binding.headerTitleTextview.text = itemView.context.getString(second.title) } } } class DeviceDataValueViewHolder(val binding: DeviceDataValueItemBinding) : BaseViewHolder<Pair<String, DeviceDataItem>>(binding) { override fun onBind(item: Pair<String, DeviceDataItem>) { item.run { binding.deviceDataTitle.text = itemView.context.getString(second.title) binding.deviceData.text = second.value } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<Pair<String, DeviceDataItem>> { return when (viewType) { HEADER_TYPE -> DeviceDataHeaderViewHolder( DeviceDataHeaderItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) ) VALUE_TYPE -> DeviceDataValueViewHolder( DeviceDataValueItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) ) else -> { throw IllegalStateException("Unknown ViewType") } } } override fun getItemViewType(position: Int) = if (getItem(position).second.isHeader) HEADER_TYPE else VALUE_TYPE companion object { const val HEADER_TYPE = 0 const val VALUE_TYPE = 1 } }
0
null
10
38
d1d3fc69c89a7b3cfeec0062b69d149e8bb568b4
2,149
DeveloperWidget
MIT License
app/src/main/java/org/stepik/android/view/course_list/ui/delegate/CoursePropertiesDelegate.kt
StepicOrg
42,045,161
false
null
package org.stepik.android.view.course_list.ui.delegate import android.view.View import android.view.ViewGroup import androidx.core.view.children import androidx.core.view.isVisible import kotlinx.android.synthetic.main.item_course.view.* import kotlinx.android.synthetic.main.layout_course_properties.view.* import org.stepic.droid.R import org.stepic.droid.util.TextUtil import org.stepic.droid.util.safeDiv import org.stepic.droid.util.toFixed import org.stepik.android.domain.course.model.CourseStats import org.stepik.android.domain.course.model.EnrollmentState import org.stepik.android.domain.course_list.model.CourseListItem import org.stepik.android.domain.user_courses.model.UserCourse import org.stepik.android.model.Course import ru.nobird.android.core.model.safeCast import java.util.Locale class CoursePropertiesDelegate( root: View, private val view: ViewGroup ) { private val learnersCountImage = view.learnersCountImage private val learnersCountText = view.learnersCountText private val courseItemProgress = view.courseItemProgressView private val courseItemProgressTitle = view.courseItemProgressTitle private val courseRatingImage = view.courseRatingImage private val courseRatingText = view.courseRatingText private val courseCertificateImage = view.courseCertificateImage private val courseCertificateText = view.courseCertificateText private val courseArchiveImage = view.courseArchiveImage private val courseArchiveText = view.courseArchiveText private val courseFavoriteImage = root.courseListFavorite fun setStats(courseListItem: CourseListItem.Data) { setLearnersCount(courseListItem.course.learnersCount, courseListItem.course.enrollment > 0L) setProgress(courseListItem.courseStats) setRating(courseListItem.courseStats) setCertificate(courseListItem.course) setUserCourse(courseListItem.courseStats.enrollmentState.safeCast<EnrollmentState.Enrolled>()?.userCourse) view.isVisible = view.children.any(View::isVisible) } private fun setLearnersCount(learnersCount: Long, isEnrolled: Boolean) { val needShowLearners = learnersCount > 0 && !isEnrolled if (needShowLearners) { learnersCountText.text = TextUtil.formatNumbers(learnersCount) } learnersCountImage.isVisible = needShowLearners learnersCountText.isVisible = needShowLearners } private fun setProgress(courseStats: CourseStats) { val progress = courseStats.progress val needShow = if ( progress != null && progress.cost > 0 && courseStats.enrollmentState.safeCast<EnrollmentState.Enrolled>()?.userCourse?.isArchived != true ) { val score = progress .score ?.toFloatOrNull() ?: 0f prepareViewForProgress(score, progress.cost) true } else { false } courseItemProgress.isVisible = needShow courseItemProgressTitle.isVisible = needShow } private fun prepareViewForProgress(score: Float, cost: Long) { courseItemProgress.progress = (score * 100 safeDiv cost) / 100f courseItemProgressTitle.text = view .resources .getString(R.string.course_content_text_progress, score.toFixed(view.resources.getInteger(R.integer.score_decimal_count)), cost) } private fun setRating(courseStats: CourseStats) { val needShow = courseStats.review > 0 if (needShow) { courseRatingText.text = String.format(Locale.ROOT, view.resources.getString(R.string.course_rating_value), courseStats.review) } courseRatingImage.isVisible = needShow courseRatingText.isVisible = needShow } private fun setCertificate(course: Course) { val isEnrolled = course.enrollment > 0L val needShow = course.hasCertificate && !isEnrolled courseCertificateImage.isVisible = needShow courseCertificateText.isVisible = needShow } private fun setUserCourse(userCourse: UserCourse?) { courseFavoriteImage.isVisible = userCourse?.isFavorite == true val isArchived = userCourse?.isArchived == true courseArchiveImage.isVisible = isArchived courseArchiveText.isVisible = isArchived } }
12
null
57
176
d1c1c96a25240d4057b5363a1a44715c10e181d2
4,381
stepik-android
Apache License 2.0
sample/src/main/java/com/murphy/status/sample/ErrorFragment.kt
WxSmile
287,671,181
false
null
package com.murphy.status.sample import com.murphy.status.placeholder.PlaceholderFragment import javax.inject.Inject class ErrorFragment @Inject constructor(): PlaceholderFragment() { override fun getPlaceholderLayout(): Int { return R.layout.common_fragment_error_placeholder } }
0
Kotlin
0
1
8086c7a5dae15934558bbe5f0542982263de144d
299
ViewStatus-Placeholder
Apache License 2.0
src/main/kotlin/autocomplete/MhwItem.kt
ricochhet
211,928,761
false
{"Kotlin": 83077, "JavaScript": 2914, "Dockerfile": 203}
package autocomplete import ApiClient import com.kotlindiscord.kord.extensions.utils.FilterStrategy import com.kotlindiscord.kord.extensions.utils.suggestStringMap import dev.kord.core.entity.interaction.AutoCompleteInteraction import dev.kord.core.event.interaction.AutoCompleteInteractionCreateEvent val MhwItemAutoComplete: suspend AutoCompleteInteraction.(AutoCompleteInteractionCreateEvent) -> Unit = { val search = data.data.options.value?.get(0)?.values?.value?.get(0)?.value as String if (search.isNotEmpty()) { val results = findSimilarElements( ApiClient.MHW.items.entries, JaroOptions( input = search, matchEntryKey = { it.key }, ) ) suggestStringMap( results.associate { item -> Pair(item.value.name, item.value.name) }, FilterStrategy { _, _ -> true } ) } else { val results = ApiClient.MHW.items.entries.take(25) suggestStringMap( results.associate { item -> Pair(item.value.name, item.value.name) }, FilterStrategy { _, _ -> true } ) } }
0
Kotlin
1
3
19b4dfc0433df0367dd502c4b560ef55f1169c4a
1,144
CatBot
MIT License
app/src/main/java/com/sahu/dinningroom/ui/AppViewModel.kt
sahruday
384,670,370
false
null
package com.sahu.dinningroom.ui import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.sahu.dinningroom.data.Repository import com.sahu.dinningroom.dataHolders.MenuItem import com.sahu.dinningroom.dataHolders.Order import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class AppViewModel @Inject constructor( private val repository: Repository ) : ViewModel() { val availableItems: Flow<List<MenuItem>> = getMenuItems() var selectedCategory: MutableLiveData<Int> = MutableLiveData(0) var searchString: MutableLiveData<String> = MutableLiveData("") fun getMenuItems(): Flow<List<MenuItem>> = repository.getMenuData() fun getOrders(): Flow<List<Order>> = repository.getData() fun placeAnOrder() = viewModelScope.launch { repository.postMockOrder() } fun updateOrderState(orderId: Int, updateStatus: Int) = viewModelScope.launch { repository.updateOrderState(orderId, updateStatus) } fun searchInIngredients(searchText: String) = viewModelScope.launch { repository.searchForIngredients(searchText) } fun clearOrders() = viewModelScope.launch { repository.clearOrders() } }
0
Kotlin
0
0
125df8cf94654e69b2f01822d7e3d40fd8314f96
1,318
DinningRoom
Apache License 2.0
src/main/kotlin/org/move/cli/runConfigurations/aptos/FunctionCallConfigurationEditor.kt
pontem-network
279,299,159
false
{"Kotlin": 2175494, "Move": 38620, "Lex": 5509, "HTML": 2114, "Java": 1275}
package org.move.cli.runConfigurations.aptos import com.intellij.icons.AllIcons import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.options.SettingsEditor import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.ui.* import com.intellij.openapi.util.Disposer import com.intellij.ui.JBColor import com.intellij.ui.dsl.builder.* import com.intellij.xdebugger.impl.ui.TextViewer import org.move.cli.MoveProject import org.move.cli.moveProjectsService import org.move.stdext.RsResult import org.move.utils.ui.CompletionTextField import java.util.function.Supplier import javax.swing.JButton import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JTextField data class MoveProjectItem(val moveProject: MoveProject) { override fun toString(): String { return "${moveProject.currentPackage.packageName} [${moveProject.contentRootPath}]" } } class FunctionCallConfigurationEditor<T: FunctionCallConfigurationBase>( private val project: Project, private val commandHandler: CommandConfigurationHandler, ): SettingsEditor<T>() { private var moveProject: MoveProject? = null // null to clear selection private val projectComboBox: ComboBox<MoveProjectItem> = ComboBox() private val accountTextField = JTextField() private val functionItemField = CompletionTextField(project, "", emptyList()) private val functionApplyButton = JButton("Select and refresh UI") private val functionParametersPanel = FunctionParametersPanel(project, commandHandler) private val functionValidator: ComponentValidator private val rawCommandField = TextViewer("", project, true) private val errorLabel = JLabel("") private lateinit var editorPanel: DialogPanel init { errorLabel.foreground = JBColor.RED project.moveProjectsService.allProjects .forEach { projectComboBox.addItem(MoveProjectItem(it)) } projectComboBox.isEnabled = projectComboBox.model.size > 1 // validates this.functionValidator = ComponentValidator(this) .withValidator(Supplier<ValidationInfo?> { val text = functionItemField.text if (text.isBlank()) return@Supplier ValidationInfo("Required", functionItemField) val moveProject = moveProject ?: return@Supplier null val functionItem = commandHandler.getFunctionItem(moveProject, text) if (functionItem == null) { return@Supplier ValidationInfo("Invalid entry function", functionItemField) } null }) .andRegisterOnDocumentListener(functionItemField) .installOn(functionItemField) val editor = this functionParametersPanel.addFunctionCallListener(object: FunctionParameterPanelListener { override fun functionParametersChanged(functionCall: FunctionCall) { // if current project is null, this shouldn't really be doing anything, just quit val mp = editor.moveProject ?: return // editor.functionCall = functionCall editor.rawCommandField.text = commandHandler.generateCommand(mp, functionCall, accountTextField.text).unwrapOrNull() ?: "" } }) // enables Apply button if function name is changed and valid functionItemField.addDocumentListener(object: DocumentListener { override fun documentChanged(event: DocumentEvent) { // do nothing if project is null val mp = moveProject ?: return val oldFunctionName = functionParametersPanel.functionItem?.element?.qualName?.editorText() val newFunctionName = event.document.text functionApplyButton.isEnabled = newFunctionName != oldFunctionName && commandHandler.getFunctionItem(mp, newFunctionName) != null } }) // update type parameters form and value parameters form on "Apply" button click functionApplyButton.addActionListener { // do nothing if project is null val mp = moveProject ?: return@addActionListener val functionItemName = functionItemField.text val functionItem = commandHandler.getFunctionItem(mp, functionItemName) ?: error("Button should be disabled if function name is invalid") val functionCall = FunctionCall.template(functionItem) functionParametersPanel.updateFromFunctionCall(functionCall) functionValidator.revalidate() functionParametersPanel.fireChangeEvent() functionApplyButton.isEnabled = false } } // called in every producer run override fun resetEditorFrom(commandSettings: T) { val workingDirectory = commandSettings.workingDirectory if (workingDirectory == null) { // if set to null, then no project was present at the time of creation, this is invalid command replacePanelWithErrorText("Deserialization error: no workingDirectory is present") return } val moveProject = project.moveProjectsService.findMoveProjectForPath(workingDirectory) if (moveProject == null) { replacePanelWithErrorText("Deserialization error: no Aptos project at the $workingDirectory") return } projectComboBox.selectedItem = MoveProjectItem(moveProject) setMoveProject(moveProject) val (profile, functionCall) = when (commandSettings.command) { "" -> Pair("", FunctionCall.empty()) else -> { val res = commandHandler.parseTransactionCommand(moveProject, commandSettings.command) when (res) { is RsResult.Ok -> res.ok is RsResult.Err -> { replacePanelWithErrorText("Deserialization error: ${res.err}") return } } } } // this.signerAccount = profile this.accountTextField.text = profile this.functionItemField.text = functionCall.itemName() ?: "" functionApplyButton.isEnabled = false functionParametersPanel.updateFromFunctionCall(functionCall) functionValidator.revalidate() } override fun applyEditorTo(s: T) { functionParametersPanel.fireChangeEvent() s.command = rawCommandField.text s.workingDirectory = moveProject?.contentRootPath } override fun createEditor(): JComponent { editorPanel = createEditorPanel() val outerPanel = panel { row { cell(errorLabel) } row { cell(editorPanel) .align(AlignX.FILL + AlignY.FILL) } } return DumbService.getInstance(project).wrapGently(outerPanel, this) } override fun disposeEditor() { super.disposeEditor() Disposer.dispose(functionParametersPanel) } fun setMoveProject(moveProject: MoveProject) { this.moveProject = moveProject functionItemField.text = "" accountTextField.text = "" functionApplyButton.isEnabled = false functionParametersPanel.updateFromFunctionCall(FunctionCall.empty()) // refill completion variants val completionVariants = commandHandler.getFunctionCompletionVariants(moveProject) this.functionItemField.setVariants(completionVariants) } private fun createEditorPanel(): DialogPanel { val editorPanel = panel { row { cell(errorLabel) } row("Project") { @Suppress("UnstableApiUsage") cell(projectComboBox) .align(AlignX.FILL) .columns(COLUMNS_LARGE) .whenItemSelectedFromUi { setMoveProject(it.moveProject) } } row("Account") { cell(accountTextField) .align(AlignX.FILL) } row("Entry function") { cell(functionItemField) .align(AlignX.FILL) .resizableColumn() cell(functionApplyButton) } separator() row { cell(functionParametersPanel) .align(AlignX.FILL + AlignY.FILL) } separator() row("Raw") { cell(rawCommandField) .align(AlignX.FILL) } } editorPanel.registerValidators(this) return editorPanel } private fun replacePanelWithErrorText(text: String) { errorLabel.text = text errorLabel.foreground = MessageType.ERROR.titleForeground errorLabel.icon = if (text.isBlank()) null else AllIcons.Actions.Lightning editorPanel.isVisible = false } // private fun validateEditor() { // val functionCall = this.functionCall // if (functionCall == null) { // setErrorText("FunctionId is required") // return // } // val functionItemName = functionCall.itemName() // if (functionItemName == null) { // setErrorText("FunctionId is required") // return // } // val function = handler.getFunction(moveProject, functionItemName) // if (function == null) { // setErrorText("Cannot resolve function from functionId") // return // } // val typeParams = functionCall.typeParams.filterValues { it == null } // if (typeParams.isNotEmpty()) { // setErrorText("Missing required type parameters: ${typeParams.keys.joinToString()}") // return // } // val valueParams = functionCall.valueParams.filterValues { it == null } // if (valueParams.isNotEmpty()) { // setErrorText("Missing required value parameters: ${valueParams.keys.joinToString()}") // return // } // setErrorText("") // } }
3
Kotlin
29
69
51a5703d064a4b016ff2a19c2f00fe8f8407d473
10,450
intellij-move
MIT License
app/src/main/java/com/stone/weather/model/ResponseStatus.kt
thantsinhtun-dev
452,777,744
false
null
package com.stone.weather.model enum class ResponseStatus { SUCCESS, ERROR, NETWORK_ERROR }
1
Kotlin
0
0
747cb8e7ba8b56a5149db6d13ed026123de4019e
104
WeatherApp
Apache License 2.0
components/widget/impl/src/main/java/com/flipperdevices/widget/impl/tasks/invalidate/renderer/error/OutOfRangeWidgetStateRenderer.kt
flipperdevices
288,258,832
false
{"Kotlin": 2760721, "FreeMarker": 10084, "CMake": 1780, "C++": 1152, "Fluent": 21}
package com.flipperdevices.widget.impl.tasks.invalidate.renderer.error import android.content.Context import com.flipperdevices.core.di.AppGraph import com.flipperdevices.keyscreen.api.DeepLinkOpenKey import com.flipperdevices.widget.impl.R import com.flipperdevices.widget.impl.model.WidgetRendererOf import com.flipperdevices.widget.impl.model.WidgetState import com.flipperdevices.widget.impl.tasks.invalidate.renderer.WidgetStateRenderer import com.squareup.anvil.annotations.ContributesMultibinding import javax.inject.Inject @WidgetRendererOf(WidgetState.ERROR_OUT_OF_RANGE) @ContributesMultibinding(AppGraph::class, WidgetStateRenderer::class) class OutOfRangeWidgetStateRenderer @Inject constructor( context: Context, deepLinkOpenKey: DeepLinkOpenKey ) : RetryErrorWidgetStateRenderer(context, deepLinkOpenKey, R.string.widget_err_cant_connect) { override val TAG = "OutOfRangeWidgetStateRenderer" }
13
Kotlin
131
999
ef27b6b6a78a59b603ac858de2c88f75b743f432
922
Flipper-Android-App
MIT License
app/src/main/java/com/greedygame/musicwiki/util_mw/Constants.kt
himanshuyadv
628,220,734
false
null
package com.greedygame.musicwiki.util_mw import com.greedygame.musicwiki.BuildConfig val tabTitles = arrayOf("Albums", "Artists", "Tracks") const val TAG = "global tag" const val apiKeyLastFm = BuildConfig.lastFmApiKey const val GET_TAG_INFO = "?api_key=$apiKeyLastFm&format=json&method=tag.getinfo" const val GET_TAG_TOP_ALBUMS = "?api_key=$apiKeyLastFm&format=json&method=tag.gettopalbums" const val GET_TAG_TOP_ARTISTS = "?api_key=$apiKeyLastFm&format=json&method=tag.gettopartists" const val GET_TAG_TOP_TRACKS = "?api_key=$apiKeyLastFm&format=json&method=tag.gettoptracks" const val GET_ALBUM_INFO = "?api_key=$apiKeyLastFm&format=json&method=album.getinfo" const val GET_ALBUM_TOP_TAGS = "?api_key=$apiKeyLastFm&format=json&method=album.gettoptags" // image sizes const val SMALL_SIZE_IMG = 0 const val MEDIUM_SIZE_IMG = 1 const val LARGE_SIZE_IMG = 2 const val X_LARGE_SIZE_IMG = 3
0
Kotlin
0
0
7d3f179715ff2f64581fc487058e25cf7f6adec0
900
music_wiki
MIT License
core/src/main/kotlin/info/laht/threekt/cameras/Camera.kt
markaren
196,544,572
false
null
package info.laht.threekt.cameras import info.laht.threekt.core.Object3D import info.laht.threekt.core.Object3DImpl import info.laht.threekt.math.Matrix4 import info.laht.threekt.math.Vector3 interface Camera : Object3D { val matrixWorldInverse: Matrix4 val projectionMatrix: Matrix4 val projectionMatrixInverse: Matrix4 override fun getWorldDirection(target: Vector3): Vector3 { this.updateMatrixWorld(true) val e = this.matrixWorld.elements return target.set(-e[8], -e[9], -e[10]).normalize() } override fun updateMatrixWorld(force: Boolean) { super.updateMatrixWorld(force) this.matrixWorldInverse.getInverse(this.matrixWorld) } fun copy(source: Camera, recursive: Boolean): Camera { super.copy(source, recursive) this.matrixWorldInverse.copy(source.matrixWorldInverse) this.projectionMatrix.copy(source.projectionMatrix) this.projectionMatrixInverse.copy(source.projectionMatrixInverse) return this } override fun clone(): Camera } open class AbstractCamera : Camera, Object3DImpl() { override val matrixWorldInverse = Matrix4() override val projectionMatrix = Matrix4() override val projectionMatrixInverse = Matrix4() override fun clone(): AbstractCamera { return AbstractCamera().apply { copy(this, true) } } } interface CameraWithZoom : Camera { var zoom: Float } interface CameraWithNearAndFar : Camera { var near: Float var far: Float } interface CameraCanUpdateProjectionMatrix : Camera { fun updateProjectionMatrix() }
7
null
14
187
8dc6186d777182da6831cf1c79f39ee2d5960cd7
1,651
three.kt
MIT License
data/src/main/java/com/bikcodeh/notes_compose/data/local/database/ImagesDatabase.kt
Bikcodeh
613,661,627
false
null
package com.bikcodeh.notes_compose.data.local.database import androidx.room.Database import androidx.room.RoomDatabase import com.bikcodeh.notes_compose.data.local.database.dao.ImageToDeleteDao import com.bikcodeh.notes_compose.data.local.database.dao.ImagesToUploadDao import com.bikcodeh.notes_compose.data.local.database.entity.ImageToDelete import com.bikcodeh.notes_compose.data.local.database.entity.ImageToUpload @Database( entities = [ImageToUpload::class, ImageToDelete::class], version = 1, exportSchema = false ) abstract class ImagesDatabase: RoomDatabase() { abstract fun imageToUploadDao(): ImagesToUploadDao abstract fun imageToDeleteDao(): ImageToDeleteDao companion object { const val DB_NAME = "images_db" } }
0
Kotlin
0
1
b9fc53bb7531f957fc801a19770f6d1b48a38705
765
notes_compose
MIT License
app/src/main/java/com/example/newz/presentation/common/ArticleCard.kt
Razorquake
747,503,854
false
{"Kotlin": 101030}
package com.example.newz.presentation.common import android.content.res.Configuration.UI_MODE_NIGHT_YES import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width 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.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import coil.request.ImageRequest import com.example.newz.R import com.example.newz.domain.model.Article import com.example.newz.ui.theme.NewzTheme @Composable fun ArticleCard( modifier: Modifier = Modifier, article: Article, onClick: () -> Unit ) { val context = LocalContext.current Row (modifier = modifier.clickable { onClick() }){ AsyncImage( modifier = Modifier .size(96.dp) .clip(shape = MaterialTheme.shapes.medium), contentScale = ContentScale.Crop, model = ImageRequest.Builder(context).data(article.urlToImage).build(), contentDescription = null) Column( verticalArrangement = Arrangement.SpaceAround, modifier = Modifier .padding(horizontal = 4.dp) .height(96.dp) ) { Text( text = article.title, style = MaterialTheme.typography.bodyMedium, color = colorResource(id = R.color.text_title), maxLines = 2, overflow = TextOverflow.Ellipsis ) Row (verticalAlignment = Alignment.CenterVertically){ Text( text = article.source.name, style = MaterialTheme.typography.labelMedium.copy(fontWeight = FontWeight.Bold), color = colorResource(id = R.color.body), ) Spacer(modifier = Modifier.width(4.dp)) Icon( painter = painterResource(id = R.drawable.ic_time), contentDescription = null, modifier = Modifier.size(12.dp), tint = colorResource(id = R.color.body) ) Spacer(modifier = Modifier.width(4.dp)) Text( text = article.getLocalizedDateTime(), style = MaterialTheme.typography.labelMedium.copy(fontWeight = FontWeight.Bold), color = colorResource(id = R.color.body), ) } } } } @Preview(showBackground = true) @Preview(showBackground = false, uiMode = UI_MODE_NIGHT_YES) @Composable fun ArticleCardPreview() { NewzTheme { ArticleCard( article = Article( title = "On the road again with the Google Maps API for Android" + " - Google Developers Blog " + "- Google Developers", description = "description", urlToImage = "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png", url = "https://www.google.com", publishedAt = "2021-09-01T12:00:00Z", content = "content", author = "author", source = com.example.newz.domain.model.Source( id = "id", name = "<NAME>" ) ), onClick = {} ) } }
0
Kotlin
0
0
fb2d7b77ec5a52d6e8f1665ea4e774b170dec994
4,269
Newz
MIT License
app/src/main/java/com/fjjukic/furniture4you/ui/checkout/CheckoutViewModel.kt
franjojosip
678,130,646
false
{"Kotlin": 378486}
package com.fjjukic.furniture4you.ui.checkout import androidx.lifecycle.ViewModel import com.fjjukic.furniture4you.ui.common.mock.MockRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.update import javax.inject.Inject @HiltViewModel class CheckoutViewModel @Inject constructor() : ViewModel() { private val _uiState = MutableStateFlow(MockRepository.getCheckoutViewState()) val uiState: StateFlow<CheckoutViewState> = _uiState fun onDeliveryOptionSelect(optionId: String) { _uiState.update { val selectedDelivery = it.deliveryOptions.first { deliveryOption -> deliveryOption.id == optionId } it.copy( selectedDelivery = selectedDelivery, priceInfo = PriceInfo( it.priceInfo.orderPrice, selectedDelivery.price ) ) } } fun onPaymentInfoChange(paymentInfo: PaymentInfo) { _uiState.update { it.copy( paymentInfo = paymentInfo ) } } fun onShippingInfoChange(shippingInfo: ShippingInfo) { _uiState.update { it.copy( shippingInfo = shippingInfo ) } } }
0
Kotlin
0
0
548708706a707ecebcc77c00439dc4a6ab230c3a
1,383
Furniture4You
MIT License
plugin/src/main/kotlin/si/kamino/gradle/VersionPlugin.kt
kaminomobile
78,854,771
false
null
package si.kamino.gradle import com.android.build.api.artifact.Artifacts import com.android.build.api.artifact.SingleArtifact import com.android.build.api.variant.ApplicationAndroidComponentsExtension import com.android.build.gradle.AppPlugin import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.tasks.TaskProvider import si.kamino.gradle.extensions.VersionExtension import si.kamino.gradle.task.CalculateVariantVersionTask import si.kamino.gradle.task.ManifestVersionTransformationTask import java.io.File class VersionPlugin : Plugin<Project> { override fun apply(project: Project) { var hasAndroidAppPlugin = false project.plugins.all { if (it is AppPlugin) { createExtensions(project) createTasks(project) hasAndroidAppPlugin = true } } project.afterEvaluate { if (!hasAndroidAppPlugin) { project.logger.warn("Android version plugin not applied as android gradle plugin was not applied!") } } } private fun createExtensions(project: Project): VersionExtension { return project.extensions.create("androidVersion", VersionExtension::class.java, project.objects) } private fun createTasks(project: Project) { val components = project.extensions.findByName("androidComponents") as ApplicationAndroidComponentsExtension components.onVariants { variant -> val taskName = "version${variant.name.capitalize()}" val versionTask = project.tasks.register(taskName, CalculateVariantVersionTask::class.java) { it.productFlavors.set(variant.productFlavors) it.buildType.set(variant.buildType!!) it.versionExtension.set(project.extensions.findByType(VersionExtension::class.java)!!) it.versionOutputFile.set(File(project.buildDir, "intermediates/version/${variant.name}")) } val manifestUpdater = project.tasks.register( "${taskName}ManifestUpdater", ManifestVersionTransformationTask::class.java ) { it.versionFile.set(versionTask.flatMap { it.versionOutputFile }) } setupMerger(variant.artifacts, manifestUpdater) } } private fun setupMerger(artifacts: Artifacts, manifestUpdater: TaskProvider<ManifestVersionTransformationTask>) { // and wire things up with the Android Gradle Plugin artifacts.use(manifestUpdater) .wiredWithFiles({ it.mergedManifestFile }, { it.updatedManifestFile }) .toTransform(SingleArtifact.MERGED_MANIFEST) } }
0
Kotlin
2
10
b5b1dbb648a522dc078db79018c11a3bda2b6ceb
2,811
AndroidVersion
MIT License
app/src/main/java/com/example/dimmerlamp/ui/home/HomeScreen.kt
artfath
713,732,950
false
{"Kotlin": 26789}
package com.example.dimmerlamp.ui.home import android.util.Log import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Slider import androidx.compose.material3.SliderDefaults import androidx.compose.material3.Switch import androidx.compose.material3.SwitchDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import com.example.dimmerlamp.ui.AppViewModelProvider import com.example.dimmerlamp.ui.component.CircleGraph import com.example.dimmerlamp.ui.theme.Blue700 import com.example.dimmerlamp.ui.theme.Blue900 import com.example.dimmerlamp.ui.theme.DimmerLampTheme import com.example.dimmerlamp.ui.theme.Neutral300 import com.example.dimmerlamp.ui.theme.Neutral600 @Composable fun HomeScreen( modifier: Modifier = Modifier, viewModel: HomeViewModel = viewModel(factory = AppViewModelProvider.Factory), ) { val dataUiState by viewModel.uiState.collectAsState() HomeBody(modifier = modifier, sliderPosition = dataUiState.brightnessValue, checked = dataUiState.switchValue, onCheckedChange = { viewModel.setSwitch(it.toString()) }, onSliderChange = { viewModel.setBrightness(it.toInt()) }) } @Composable fun HomeBody( modifier: Modifier, sliderPosition: Float, checked: Boolean, onCheckedChange: (Boolean) -> Unit, onSliderChange: (Float) -> Unit ) { BoxWithConstraints { Column( modifier = modifier .fillMaxWidth() .fillMaxHeight() .background(color = Color.White) ) { Row( modifier = modifier .fillMaxWidth() .height(340.dp) .background( brush = Brush.verticalGradient( colors = listOf(Color(0xFF29B1F7), Color(0xFFE0F4FE)), startY = 100f, ) ) ) { Text( modifier = modifier.padding(top = 24.dp, start = 16.dp), text = "Smart Lamp", style = MaterialTheme.typography.headlineLarge, color = Color.White ) // Image(modifier=modifier // .height(260.dp),painter = painterResource(id = R.drawable.lamp), contentDescription = null) } } Box( modifier = modifier .padding(top = 280.dp), contentAlignment = Alignment.Center ) { Column { Box( modifier = modifier .fillMaxWidth() .padding(top = 16.dp, start = 16.dp, end = 16.dp), contentAlignment = Alignment.Center ) { CircleGraph( modifier = modifier, values = sliderPosition ) } Slider( enabled = checked, modifier = modifier .padding(top = 16.dp, start = 16.dp, end = 16.dp), value = sliderPosition, onValueChange = onSliderChange, valueRange = 0f..100f, colors = SliderDefaults.colors( thumbColor = Blue700, activeTrackColor = Blue900 ) ) SwitchCard( modifier = modifier, checked = checked, onCheckedChange = onCheckedChange ) WattMeterCard(modifier = modifier, value = sliderPosition) } } } } @Composable fun SwitchCard( modifier: Modifier, checked: Boolean, onCheckedChange: (Boolean) -> Unit ) { Box( modifier = modifier .fillMaxWidth() .padding(top = 16.dp, start = 16.dp, end = 16.dp) .shadow(elevation = 6.dp, ambientColor = Color.Gray) .clip(RoundedCornerShape(15.dp)) .background(color = Color.White) ) { Row( modifier = modifier .fillMaxWidth() .padding(top = 24.dp, start = 16.dp, end = 16.dp, bottom = 24.dp), verticalAlignment = Alignment.CenterVertically ) { Column( modifier = modifier .weight(1f) .padding(end = 16.dp) ) { Text( modifier = modifier, text = "Light in The Room", style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Medium, color = Color.Black ) Text( modifier = modifier.padding(top = 8.dp), text = if (checked) "Turn On" else "Turn Off", style = MaterialTheme.typography.bodyLarge, color = Color.Black ) } Box( modifier = Modifier.weight(0.4f), contentAlignment = Alignment.Center ) { Switch( checked = checked, onCheckedChange = onCheckedChange, colors = SwitchDefaults.colors( checkedTrackColor = Blue700, uncheckedBorderColor = Neutral300, uncheckedTrackColor = Neutral300, uncheckedThumbColor = Neutral600, disabledUncheckedBorderColor = Neutral600 ) ) } } } } @Composable fun WattMeterCard(modifier: Modifier, value: Float) { val wattage = ((value / 100f) * 3) Box( modifier = modifier .fillMaxWidth() .padding(top = 16.dp, start = 16.dp, end = 16.dp) .shadow(elevation = 6.dp, ambientColor = Color.Gray) .clip(RoundedCornerShape(15.dp)) .background(color = Color.White) ) { Row( modifier = modifier .fillMaxWidth() .padding(top = 24.dp, start = 16.dp, end = 16.dp, bottom = 24.dp), verticalAlignment = Alignment.CenterVertically ) { Text( modifier = modifier .weight(1f), text = "Energy", style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Medium, color = Color.Black ) Row( modifier = modifier .weight(0.9f), verticalAlignment = Alignment.CenterVertically ) { Text( modifier = modifier .weight(1f) .padding(end = 8.dp), text = "%.1f".format(wattage), style = MaterialTheme.typography.headlineMedium, color = Blue900 ) Text( modifier = modifier.weight(1f), text = "Watt", style = MaterialTheme.typography.bodyLarge, color = Color.Black ) } } } } @Preview(showBackground = true) @Composable fun HomeScreenPreview() { DimmerLampTheme(darkTheme = false) { HomeBody(modifier = Modifier, sliderPosition = 80f, checked = true, onCheckedChange = {}, onSliderChange = {} ) } }
0
Kotlin
0
0
72f132ecfd5eb9545562512f4d36196554359b29
8,959
Dimmer-Lamp-MQTT
Apache License 2.0
app/src/main/java/io/github/wulkanowy/ui/modules/login/options/LoginOptionsItem.kt
pavuloff
161,793,734
true
{"Kotlin": 383246, "IDL": 131}
package io.github.wulkanowy.ui.modules.login.options import android.view.View import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.AbstractFlexibleItem import eu.davidea.flexibleadapter.items.IFlexible import eu.davidea.viewholders.FlexibleViewHolder import io.github.wulkanowy.R import io.github.wulkanowy.data.db.entities.Student import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.main.item_login_options.view.* class LoginOptionsItem(val student: Student) : AbstractFlexibleItem<LoginOptionsItem.ItemViewHolder>() { override fun getLayoutRes(): Int = R.layout.item_login_options override fun createViewHolder(view: View?, adapter: FlexibleAdapter<IFlexible<*>>?): ItemViewHolder { return ItemViewHolder(view, adapter) } override fun bindViewHolder(adapter: FlexibleAdapter<IFlexible<*>>?, holder: ItemViewHolder?, position: Int, payloads: MutableList<Any>?) { holder?.bind(student) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as LoginOptionsItem if (student != other.student) return false return true } override fun hashCode(): Int { return student.hashCode() } class ItemViewHolder(view: View?, adapter: FlexibleAdapter<*>?) : FlexibleViewHolder(view, adapter), LayoutContainer { override val containerView: View? get() = itemView fun bind(item: Student) { itemView.run { loginItemName.text = item.studentName loginItemSchool.text = item.schoolName } } } }
0
Kotlin
0
0
5ee979447f891bb715780b0ffd85b267fd521963
1,771
wulkanowy
Apache License 2.0
api-client/src/main/java/com/kshitijpatil/tazabazar/api/CacheInterceptor.kt
Kshitij09
395,308,440
false
null
package com.kshitijpatil.tazabazar.api import okhttp3.CacheControl import okhttp3.Interceptor import okhttp3.Response import java.io.IOException import java.util.concurrent.TimeUnit // credits: https://stackoverflow.com/a/49455438/6738702 class CacheInterceptor(private val cacheDurationInMinutes: Int) : Interceptor { @Throws(IOException::class) override fun intercept(chain: Interceptor.Chain): Response { val response: Response = chain.proceed(chain.request()) val cacheControl: CacheControl = CacheControl.Builder() .maxAge(cacheDurationInMinutes, TimeUnit.MINUTES) .build() return response.newBuilder() .removeHeader("Pragma") .removeHeader("Cache-Control") .header("Cache-Control", cacheControl.toString()) .build() } }
8
Kotlin
2
1
d709b26d69cf46c3d6123a217190f098b79a6562
835
TazaBazar
Apache License 2.0
app/src/main/java/com/head/views/ui/spinner/SpinnerViewModel.kt
headwww
501,487,085
false
{"Kotlin": 177693}
package com.head.views.ui.spinner import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class SpinnerViewModel : ViewModel() { }
0
Kotlin
0
1
856c5aca1eb522255afe0baf3ef47be6cba92b58
190
HeadViews
Apache License 2.0
app/src/main/java/me/lazy_assedninja/demo/data/source/remote/ApiSuccessResponse.kt
henryhuang1219
357,838,778
false
null
package me.lazy_assedninja.demo.data.source.remote data class ApiSuccessResponse<T>(val body: T) : ApiResponse<T>()
0
Kotlin
1
2
2f5a79974f8d6b6af516a8959824558324bab8ce
116
Android-Demo
Apache License 2.0
src/Day04.kt
bromhagen
572,988,081
false
{"Kotlin": 3615}
import kotlin.math.min fun main() { fun splitToIntRanges(pair: String): Pair<IntRange, IntRange> { val ranges = pair.split(",").map { val start = it.split("-")[0] val end = it.split("-")[1] IntRange(start.toInt(), end.toInt()) } val first = ranges[0] val second = ranges[1] return Pair(first, second) } fun part1(input: List<String>): Int { return input.count { pair -> val (first, second) = splitToIntRanges(pair) first.intersect(second).size >= min(first.count(), second.count()) } } fun part2(input: List<String>): Int { return input.count { pair -> val (first, second) = splitToIntRanges(pair) first.intersect(second).isNotEmpty() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0ee6d96e790d9ebfab882351b3949c9ba372cb3e
1,064
advent-of-code
Apache License 2.0
vzd-cli/src/main/kotlin/de/gematik/ti/directory/cli/GlobalConfig.kt
gematik
455,597,084
false
{"Kotlin": 344102, "HTML": 87329, "TypeScript": 41771, "Shell": 6186, "SCSS": 5370, "JavaScript": 1430, "Makefile": 353, "Batchfile": 91}
package de.gematik.ti.directory.cli import de.gematik.ti.directory.cli.util.FileObjectStore import kotlinx.serialization.Serializable import kotlinx.serialization.decodeFromString import java.nio.file.Path @Serializable data class HttpProxyConfig( var proxyURL: String, var enabled: Boolean, ) @Serializable data class UpdatesConfig( var preReleasesEnabled: Boolean, var lastCheck: Long, var latestRelease: String, ) @Serializable data class GlobalConfig( var httpProxy: HttpProxyConfig, var updates: UpdatesConfig, ) internal class GlobalConfigFileStore(customConfigPath: Path? = null) : FileObjectStore<GlobalConfig>( "directory-global.yaml", { GlobalConfig( httpProxy = HttpProxyConfig( proxyURL = "http://192.168.110.10:3128/", enabled = false, ), updates = UpdatesConfig( preReleasesEnabled = false, lastCheck = -1, latestRelease = BuildConfig.APP_VERSION, ), ) }, { yaml, stringValue -> yaml.decodeFromString(stringValue) }, customConfigPath, )
2
Kotlin
1
3
76e943f417d651f7f172696b4b11869f78bf4c1d
1,208
app-vzd-cli
MIT License
app/src/main/java/com/zs/gallery/MainActivity.kt
iZakirSheikh
828,405,870
false
null
/* * Copyright 2024 Zakir Sheikh * * Created by Zakir Sheikh on 20-07-2024. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zs.gallery import android.annotation.SuppressLint import android.content.Intent import android.content.res.Configuration import android.hardware.biometrics.BiometricManager.Authenticators.BIOMETRIC_STRONG import android.hardware.biometrics.BiometricManager.Authenticators.DEVICE_CREDENTIAL import android.hardware.biometrics.BiometricPrompt import android.os.Build import android.os.Bundle import android.os.CancellationSignal import android.util.Log import android.view.WindowManager import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.annotation.RequiresApi import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Downloading import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.NonRestartableComposable import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.graphics.vector.ImageVector import androidx.core.content.res.ResourcesCompat import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat import androidx.lifecycle.lifecycleScope import androidx.navigation.NavController import androidx.navigation.NavDestination import androidx.navigation.NavHostController import androidx.navigation.compose.rememberNavController import com.google.android.play.core.appupdate.AppUpdateManagerFactory import com.google.android.play.core.ktx.AppUpdateResult import com.google.android.play.core.ktx.requestAppUpdateInfo import com.google.android.play.core.ktx.requestReview import com.google.android.play.core.ktx.requestUpdateFlow import com.google.android.play.core.review.ReviewManagerFactory import com.google.firebase.Firebase import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.analytics import com.google.firebase.analytics.logEvent import com.google.firebase.crashlytics.crashlytics import com.primex.core.MetroGreen import com.primex.core.getText2 import com.primex.core.runCatching import com.primex.preferences.Key import com.primex.preferences.Preferences import com.primex.preferences.longPreferenceKey import com.primex.preferences.observeAsState import com.primex.preferences.value import com.zs.foundation.toast.Toast import com.zs.foundation.toast.ToastHostState import com.zs.gallery.common.NightMode import com.zs.gallery.common.SystemFacade import com.zs.gallery.common.domain import com.zs.gallery.common.getPackageInfoCompat import com.zs.gallery.files.RouteTimeline import com.zs.gallery.lockscreen.RouteLockScreen import com.zs.gallery.settings.Settings import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import org.koin.android.ext.android.inject import kotlin.time.Duration.Companion.days import kotlin.time.Duration.Companion.minutes import android.widget.Toast as PlatformToast private const val TAG = "MainActivity" // In-app update and review settings // Maximum staleness days allowed for a flexible update. // If the app is older than this, an immediate update will be enforced. private const val FLEXIBLE_UPDATE_MAX_STALENESS_DAYS = 2 // Minimum number of app launches before prompting for a review. private const val MIN_LAUNCHES_BEFORE_REVIEW = 5 // Number of days to wait before showing the first review prompt. private val INITIAL_REVIEW_DELAY = 3.days // Minimum number of days between subsequent review prompts. // Since we cannot confirm if the user actually left a review, we use this interval // to avoid prompting too frequently. private val STANDARD_REVIEW_DELAY = 5.days private val KEY_LAST_REVIEW_TIME = longPreferenceKey(TAG + "_last_review_time", 0) /** * @property inAppUpdateProgress A simple property that represents the progress of the in-app update. * The progress value is a float between 0.0 and 1.0, indicating the percentage of the * update that has been completed. The Float.NaN represents a default value when no update * is going on. * @property timeAppWentToBackground The time in mills until the app was in background state. default value -1L * @property isAuthenticationRequired A boolean flag indicating whether authentication is required. */ class MainActivity : ComponentActivity(), SystemFacade, NavController.OnDestinationChangedListener { private val toastHostState: ToastHostState by inject() private val preferences: Preferences by inject() private var navController: NavHostController? = null private val inAppUpdateProgress = mutableFloatStateOf(Float.NaN) /** * Timestamp (mills) indicating when the app last went to the background. * * Possible values: * - `-1L`: The app has just started and hasn't been in the background yet. * - `0L`: The app was launched for the first time (initial launch). * - `> 0L`: The time in milliseconds when the app last entered the background. */ private var timeAppWentToBackground = -1L /** * Checks if authentication is required. * * Authentication is not supported on Android versions below P. * * @return `true` if authentication should be shown, `false` otherwise. */ private val isAuthenticationRequired: Boolean get() { // App lock is not supported on Android versions below P. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { return false } // If the timestamp is 0L, the user has recently unlocked the app, // so authentication is not required. if (timeAppWentToBackground == 0L) { return false } // Check the app lock timeout setting. return when (val timeoutValue = preferences.value(Settings.KEY_APP_LOCK_TIME_OUT)) { -1 -> false // App lock is disabled (timeout value of -1) 0 -> true // Immediate authentication required (timeout value of 0) else -> { // Calculate the time elapsed since the app went to background. val currentTime = System.currentTimeMillis() val timeSinceBackground = currentTime - timeAppWentToBackground timeSinceBackground >= timeoutValue.minutes.inWholeMilliseconds } } } override fun onPause() { super.onPause() // The time when app went to background. // irrespective of what value it holds update it. Log.d(TAG, "onPause") timeAppWentToBackground = System.currentTimeMillis() } @SuppressLint("NewApi") override fun onResume() { super.onResume() Log.d(TAG, "onStart") // Only navigate to the lock screen if authentication is required and // this is not a fresh app start. // On a fresh start, timeAppWentToBackground is -1L. // If authentication is required on a fresh start, the app will be // automatically navigated to the lock screen in onCreate(). if (timeAppWentToBackground != -1L && isAuthenticationRequired) { Log.d(TAG, "onResume: navigating -> RouteLockScreen.") navController?.navigate(RouteLockScreen()){ launchSingleTop = true } unlock() } } override fun showPlatformToast(string: Int) = PlatformToast.makeText(this, getString(string), PlatformToast.LENGTH_SHORT).show() override fun showPlatformToast(string: String) = PlatformToast.makeText(this, string, PlatformToast.LENGTH_SHORT).show() @RequiresApi(Build.VERSION_CODES.P) override fun authenticate(desc: String?, onAuthenticated: () -> Unit) { Log.d(TAG, "preparing to show authentication dialog.") // Build the BiometricPrompt val prompt = BiometricPrompt.Builder(this).apply { setTitle(getString(R.string.scr_lock_screen_title)) setSubtitle(getString(R.string.scr_lock_screen_subtitle)) if (desc != null) setDescription(desc) // Set allowed authenticators for Android R and above if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) setAllowedAuthenticators(BIOMETRIC_STRONG or DEVICE_CREDENTIAL) // Allow device credential fallback for Android Q if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) setDeviceCredentialAllowed(true) // On Android P and below, BiometricPrompt crashes if a negative button is not set. // We provide a "Dismiss" button to avoid the crash, but this does not offer alternative // authentication (like PIN). // Future versions might include support for alternative authentication on older Android versions // if a compatibility library or API becomes available. if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) setNegativeButton("Dismiss", mainExecutor, { _, _ -> }) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) setConfirmationRequired(false) /*if (Build.VERSION.SDK_INT >= 35) { setLogoRes(R.drawable.ic_app) }*/ }.build() // Start the authentication process prompt.authenticate( CancellationSignal(), mainExecutor, object : BiometricPrompt.AuthenticationCallback() { // Implement callback methods for authentication events (success, error, etc.) override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult?) { showPlatformToast("Authentication Successful! Welcome back.") onAuthenticated() } override fun onAuthenticationFailed() { super.onAuthenticationFailed() showPlatformToast("Authentication Failed! Please try again or use an alternative method.") } override fun onAuthenticationError(errorCode: Int, errString: CharSequence?) { super.onAuthenticationError(errorCode, errString) showPlatformToast("Authentication Error: $errString") } } ) } override fun <T> getDeviceService(name: String): T = getSystemService(name) as T @SuppressLint("NewApi") override fun unlock() = authenticate(getString(R.string.src_lock_screen_desc)) { val navController = navController ?: return@authenticate // if it is initial app_lock update timeAppWentToBackground to 0 if (timeAppWentToBackground == -1L) timeAppWentToBackground = 0L // Check if the start destination needs to be updated // Update the start destination to RouteTimeline if (navController.graph.startDestinationRoute == RouteLockScreen()) { Log.d(TAG, "unlock: updating start destination") navController.graph.setStartDestination(RouteTimeline()) navController.navigate(RouteTimeline()) { popUpTo(RouteLockScreen()) { inclusive = true } } // return from here; return@authenticate } Log.d(TAG, "unlock: poping lock_screen from graph") // If the start destination is already RouteTimeline, just pop back navController.popBackStack() } override fun enableEdgeToEdge( hide: Boolean?, translucent: Boolean?, dark: Boolean? ) { // Get the WindowInsetsController for managing system bars val controller = WindowCompat.getInsetsController(window, window.decorView) // ensure edge to edge is enabled WindowCompat.setDecorFitsSystemWindows(window, false) // If hide is true, hide the system bars and return if (hide == true) return controller.hide(WindowInsetsCompat.Type.systemBars()) // Otherwise, show the system bars controller.show(WindowInsetsCompat.Type.systemBars()) // Determine translucency based on provided value or preference val translucent = translucent ?: !preferences.value(Settings.KEY_TRANSPARENT_SYSTEM_BARS) // Set the color for status and navigation bars based on translucency val color = when (translucent) { false -> Color.Transparent.toArgb() else -> Color(0x20000000).toArgb() } // Set the status and navigation bar colors window.statusBarColor = color window.navigationBarColor = color // Determine dark mode based on provided value, preference, or system setting val isAppearanceDark = dark ?: preferences.value(Settings.KEY_NIGHT_MODE).let { when (it) { NightMode.YES -> false NightMode.NO -> true NightMode.FOLLOW_SYSTEM -> { val config = resources.configuration val uiMode = config.uiMode Log.d(TAG, "configureSystemBars: $uiMode") (uiMode and Configuration.UI_MODE_NIGHT_MASK) != Configuration.UI_MODE_NIGHT_YES } } } // Set the appearance of system bars based on dark mode controller.isAppearanceLightStatusBars = isAppearanceDark controller.isAppearanceLightNavigationBars = isAppearanceDark } override fun showToast( message: CharSequence, icon: ImageVector?, accent: Color, action: CharSequence?, duration: Int ) { lifecycleScope.launch { toastHostState.showToast(message, action, icon, accent, duration) } } override fun showToast( message: Int, icon: ImageVector?, accent: Color, action: Int, duration: Int ) { lifecycleScope.launch { val action = if (action == ResourcesCompat.ID_NULL) null else resources.getText2(action) toastHostState.showToast( resources.getText2(id = message), action, icon, accent, duration ) } } @Composable @NonRestartableComposable override fun <S, O> observeAsState(key: Key.Key1<S, O>) = preferences.observeAsState(key = key) @Composable @NonRestartableComposable override fun <S, O> observeAsState(key: Key.Key2<S, O>) = preferences.observeAsState(key = key) override fun launch(intent: Intent, options: Bundle?) = startActivity(intent, options) override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) // caused the change in config. means the system bars need to be configured again // but what would happen if the system bars are already configured? enableEdgeToEdge() Log.d(TAG, "onConfigurationChanged: ${navController?.currentDestination?.route}") } private fun initialize() { if (preferences.value(Settings.KEY_SECURE_MODE)) { window.setFlags( WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE ) } val flow1 = preferences[Settings.KEY_NIGHT_MODE] val flow2 = preferences[Settings.KEY_TRANSPARENT_SYSTEM_BARS] flow1.combine(flow2) { _, _ -> enableEdgeToEdge() } .launchIn(scope = lifecycleScope) lifecycleScope.launch { launchUpdateFlow() } } override fun launchUpdateFlow(report: Boolean) { val manager = AppUpdateManagerFactory.create(this@MainActivity) manager.requestUpdateFlow().onEach { result -> when (result) { is AppUpdateResult.NotAvailable -> if (report) showToast(R.string.msg_update_not_available) is AppUpdateResult.InProgress -> { val state = result.installState val total = state.totalBytesToDownload() val downloaded = state.bytesDownloaded() val progress = when { total <= 0 -> -1f total == downloaded -> Float.NaN else -> downloaded / total.toFloat() } inAppUpdateProgress.floatValue = progress } is AppUpdateResult.Downloaded -> { val info = manager.requestAppUpdateInfo() //when update first becomes available //don't force it. // make it required when staleness days overcome allowed limit val isFlexible = (info.clientVersionStalenessDays() ?: -1) <= FLEXIBLE_UPDATE_MAX_STALENESS_DAYS // forcefully update; if it's flexible if (!isFlexible) { manager.completeUpdate() return@onEach } // else show the toast. val res = toastHostState.showToast( message = resources.getText2(R.string.msg_new_update_downloaded), action = resources.getText2(R.string.install), duration = Toast.DURATION_INDEFINITE, accent = Color.MetroGreen, icon = Icons.Outlined.Downloading ) // complete update when ever user clicks on action. if (res == Toast.ACTION_PERFORMED) manager.completeUpdate() } is AppUpdateResult.Available -> { // if user choose to skip the update handle that case also. val isFlexible = (result.updateInfo.clientVersionStalenessDays() ?: -1) <= FLEXIBLE_UPDATE_MAX_STALENESS_DAYS if (isFlexible) result.startFlexibleUpdate( activity = this@MainActivity, 1000 ) else result.startImmediateUpdate( activity = this@MainActivity, 1000 ) // no message needs to be shown } } }.catch { Firebase.crashlytics.recordException(it) if (!report) return@catch showToast(R.string.msg_update_check_error) }.launchIn(lifecycleScope) } override fun launchReviewFlow() { lifecycleScope.launch { // Get the app launch count from preferences. val count = preferences.value(Settings.KEY_LAUNCH_COUNTER) // Check if the minimum launch count has been reached. if (count < MIN_LAUNCHES_BEFORE_REVIEW) return@launch // Get the first install time of the app. // Check if enough time has passed since the first install. val firstInstallTime = packageManager.getPackageInfoCompat(BuildConfig.APPLICATION_ID)?.firstInstallTime ?: 0 val currentTime = System.currentTimeMillis() if (currentTime - firstInstallTime < INITIAL_REVIEW_DELAY.inWholeMilliseconds) return@launch // Get the last time the review prompt was shown. // Check if enough time has passed since the last review prompt. val lastAskedTime = preferences.value(KEY_LAST_REVIEW_TIME) if (currentTime - lastAskedTime <= STANDARD_REVIEW_DELAY.inWholeMilliseconds) return@launch // Request and launch the review flow. runCatching(TAG) { val reviewManager = ReviewManagerFactory.create(this@MainActivity) // Update the last asked time in preferences preferences[KEY_LAST_REVIEW_TIME] = System.currentTimeMillis() val info = reviewManager.requestReview() reviewManager.launchReviewFlow(this@MainActivity, info) // Optionally log an event to Firebase Analytics. // host.fAnalytics.logReviewPromptShown() } } } override fun onDestinationChanged( controller: NavController, destination: NavDestination, arguments: Bundle? ) { // Log the event. Firebase.analytics.logEvent(FirebaseAnalytics.Event.SCREEN_VIEW) { // create params for the event. val domain = destination.domain ?: "unknown" Log.d(TAG, "onNavDestChanged: $domain") param(FirebaseAnalytics.Param.SCREEN_NAME, domain) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d(TAG, "onCreate") // Manage SplashScreen installSplashScreen() // init the heavy duty tasks in initialize() initialize() // Set the content of the activity setContent { val navController = rememberNavController() // if authentication is required move to lock screen Gallery(toastHostState, navController) DisposableEffect(Unit) { Log.d(TAG, "onCreate - DisposableEffect: $timeAppWentToBackground") navController.addOnDestinationChangedListener(this@MainActivity) // since auth is required; we will cover the scrren with lock_screen // only when user authenticate can remove this veil. if (isAuthenticationRequired) { navController.navigate(RouteLockScreen()) unlock() } [email protected] = navController onDispose { navController.removeOnDestinationChangedListener(this@MainActivity) [email protected] = null } } } } }
2
null
0
6
5bc9839431d35ff3a0ebfb3fca7572dced3352a0
23,067
Gallery
Apache License 2.0
src/test/kotlin/dsx/bps/core/InvoiceProcessorUnitTest.kt
dsx-tech
167,199,361
false
null
package dsx.bps.core import com.uchuhimo.konf.Config import com.uchuhimo.konf.source.yaml import dsx.bps.DBservices.Datasource import dsx.bps.DBservices.core.InvoiceService import dsx.bps.DBservices.core.TxService import dsx.bps.TestUtils import dsx.bps.config.DatabaseConfig import dsx.bps.config.InvoiceProcessorConfig import dsx.bps.core.datamodel.* import io.reactivex.disposables.Disposable import org.jetbrains.exposed.sql.transactions.transaction import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.EnumSource import org.mockito.Mockito import java.io.File import java.math.BigDecimal @TestInstance(TestInstance.Lifecycle.PER_CLASS) internal class InvoiceProcessorUnitTest { private val manager: BlockchainPaymentSystemManager = Mockito.mock(BlockchainPaymentSystemManager::class.java) private lateinit var invoiceProcessor: InvoiceProcessor private val datasource = Datasource() private lateinit var invService: InvoiceService private lateinit var txService: TxService private lateinit var testConfig: Config @BeforeAll fun setUp() { val initConfig = Config() val configPath = TestUtils.getResourcePath("TestBpsConfig.yaml") val configFile = File(configPath) testConfig = with(initConfig) { addSpec(InvoiceProcessorConfig) from.yaml.file(configFile) } testConfig.validateRequired() val databaseConfig = with (Config()) { addSpec(DatabaseConfig) from.yaml.file(configFile) } databaseConfig.validateRequired() datasource.initConnection(databaseConfig) txService = TxService() DatabaseCreation().createInvoices() invoiceProcessor = InvoiceProcessor(manager, testConfig, txService) invService = InvoiceService() } @ParameterizedTest @EnumSource(value = Currency::class) @DisplayName("create invoice and get invoice test") fun createInvoiceTest(currency: Currency) { val invoice = invoiceProcessor.createInvoice(currency, BigDecimal.TEN,"testaddress", "1") Assertions.assertNotNull(invService.getBySystemId(invoice.id)) Assertions.assertEquals(invoice, invService.makeInvFromDB(invService.getBySystemId(invoice.id))) Assertions.assertNotNull(invoiceProcessor.getInvoice(invoice.id)) Assertions.assertEquals(invoice, invoiceProcessor.getInvoice(invoice.id)) } @Nested inner class OnNextTest { @Test @DisplayName("onNextTest: right tx") fun onNextTest1() { val tx = Mockito.mock(Tx::class.java) Mockito.`when`(tx.currency()).thenReturn(Currency.BTC) Mockito.`when`(tx.destination()).thenReturn("invtestaddress") Mockito.`when`(tx.paymentReference()).thenReturn("1") Mockito.`when`(tx.amount()).thenReturn(BigDecimal.TEN) Mockito.`when`(tx.status()).thenReturn(TxStatus.CONFIRMED) Mockito.`when`(tx.txid()).thenReturn(TxId("txhash1",1)) val invoice = invoiceProcessor.createInvoice(Currency.BTC, BigDecimal.TEN, "invtestaddress", "1") txService.add( tx.status(), "invtestaddress", "1", BigDecimal.TEN, BigDecimal.ZERO, "txhash1", 1, tx.currency() ) invoiceProcessor.onNext(tx) Assertions.assertEquals(InvoiceStatus.PAID, invService.getBySystemId(invoice.id).status) Assertions.assertEquals(invoice.received, invService.getBySystemId(invoice.id).received.setScale(0)) Assertions.assertEquals(invoice.status, InvoiceStatus.PAID) Assertions.assertEquals(invoice.received, BigDecimal.TEN) Assertions.assertTrue(invoice.txids.contains(TxId("txhash1", 1))) Assertions.assertTrue(transaction { txService.getByTxId("txhash1", 1).cryptoAddress == invService.getBySystemId(invoice.id).cryptoAddress }) } @Test @DisplayName("onNextTest: wrong tx tag") fun onNextTest2() { val tx1 = Mockito.mock(Tx::class.java) Mockito.`when`(tx1.currency()).thenReturn(Currency.BTC) Mockito.`when`(tx1.destination()).thenReturn("testaddress") Mockito.`when`(tx1.paymentReference()).thenReturn(null) Mockito.`when`(tx1.amount()).thenReturn(BigDecimal.TEN) Mockito.`when`(tx1.status()).thenReturn(TxStatus.CONFIRMED) Mockito.`when`(tx1.txid()).thenReturn(TxId("hash2", 2)) val invoice = invoiceProcessor.createInvoice(Currency.BTC, BigDecimal.TEN, "testaddress", "1") invoiceProcessor.onNext(tx1) Assertions.assertEquals(InvoiceStatus.UNPAID, invService.getBySystemId(invoice.id).status) Assertions.assertEquals(invoice.received, invService.getBySystemId(invoice.id).received.setScale(0)) Assertions.assertEquals(invoice.status, InvoiceStatus.UNPAID) Assertions.assertEquals(invoice.received, BigDecimal.ZERO) Assertions.assertFalse(invoice.txids.contains(TxId("hash2", 2))) } @Test @DisplayName("onNextTest: wrong tx address") fun onNextTest3() { val tx1 = Mockito.mock(Tx::class.java) Mockito.`when`(tx1.currency()).thenReturn(Currency.BTC) Mockito.`when`(tx1.destination()).thenReturn("testaddressother") Mockito.`when`(tx1.paymentReference()).thenReturn("1") Mockito.`when`(tx1.amount()).thenReturn(BigDecimal.TEN) Mockito.`when`(tx1.status()).thenReturn(TxStatus.CONFIRMED) Mockito.`when`(tx1.txid()).thenReturn(TxId("hash3", 3)) val invoice = invoiceProcessor.createInvoice(Currency.BTC, BigDecimal.TEN, "testaddress", "1") invoiceProcessor.onNext(tx1) Assertions.assertEquals(InvoiceStatus.UNPAID, invService.getBySystemId(invoice.id).status) Assertions.assertEquals(invoice.received, invService.getBySystemId(invoice.id).received.setScale(0)) Assertions.assertEquals(invoice.status, InvoiceStatus.UNPAID) Assertions.assertEquals(invoice.received, BigDecimal.ZERO) Assertions.assertFalse(invoice.txids.contains(TxId("hash3", 3))) } @ParameterizedTest @DisplayName("onNextTest: wrong tx currency") @EnumSource(value = Currency::class, names = ["TRX", "XRP"]) fun onNextTest4(currency: Currency) { val tx1 = Mockito.mock(Tx::class.java) Mockito.`when`(tx1.currency()).thenReturn(currency) Mockito.`when`(tx1.destination()).thenReturn("testaddress") Mockito.`when`(tx1.paymentReference()).thenReturn("1") Mockito.`when`(tx1.amount()).thenReturn(BigDecimal.TEN) Mockito.`when`(tx1.status()).thenReturn(TxStatus.CONFIRMED) Mockito.`when`(tx1.txid()).thenReturn(TxId("hash4", 4)) val invoice = invoiceProcessor.createInvoice(Currency.BTC, BigDecimal.TEN, "testaddress", "1") invoiceProcessor.onNext(tx1) Assertions.assertEquals(InvoiceStatus.UNPAID, invService.getBySystemId(invoice.id).status) Assertions.assertEquals(invoice.received, invService.getBySystemId(invoice.id).received.setScale(0)) Assertions.assertEquals(invoice.status, InvoiceStatus.UNPAID) Assertions.assertEquals(invoice.received, BigDecimal.ZERO) Assertions.assertFalse(invoice.txids.contains(TxId("hash4", 4))) } @ParameterizedTest @DisplayName("onNextTest: wrong tx status") @EnumSource(value = TxStatus::class, names = ["VALIDATING", "REJECTED"]) fun onNextTest5(txStatus: TxStatus) { val tx1 = Mockito.mock(Tx::class.java) Mockito.`when`(tx1.currency()).thenReturn(Currency.BTC) Mockito.`when`(tx1.destination()).thenReturn("testaddress") Mockito.`when`(tx1.paymentReference()).thenReturn("1") Mockito.`when`(tx1.amount()).thenReturn(BigDecimal.TEN) Mockito.`when`(tx1.status()).thenReturn(txStatus) Mockito.`when`(tx1.txid()).thenReturn(TxId("hash5", 5)) val invoice = invoiceProcessor.createInvoice(Currency.BTC, BigDecimal.TEN, "testaddress", "1") invoiceProcessor.onNext(tx1) Assertions.assertEquals(InvoiceStatus.UNPAID, invService.getBySystemId(invoice.id).status) Assertions.assertEquals(invoice.received, invService.getBySystemId(invoice.id).received.setScale(0)) Assertions.assertEquals(invoice.status, InvoiceStatus.UNPAID) Assertions.assertEquals(invoice.received, BigDecimal.ZERO) Assertions.assertTrue(invoice.txids.contains(TxId("hash5", 5))) } @Test @DisplayName("onNextTest: invoices initialisation from db") fun onNextTest6() { val tx = Mockito.mock(Tx::class.java) Mockito.`when`(tx.currency()).thenReturn(Currency.BTC) Mockito.`when`(tx.destination()).thenReturn("addr1") Mockito.`when`(tx.paymentReference()).thenReturn(null) Mockito.`when`(tx.amount()).thenReturn(BigDecimal.ONE) Mockito.`when`(tx.status()).thenReturn(TxStatus.CONFIRMED) Mockito.`when`(tx.txid()).thenReturn(TxId("txhashdb", 1)) txService.add(tx.status(), tx.destination(), null, BigDecimal.ONE, BigDecimal.ZERO, "txhashdb", 1, Currency.BTC) val invoice = invoiceProcessor.getInvoice("inv1") invoiceProcessor.onNext(tx) Assertions.assertEquals(InvoiceStatus.PAID, invService.getBySystemId(invoice!!.id).status) Assertions.assertEquals(invoice.received, invService.getBySystemId(invoice.id).received.setScale(0)) Assertions.assertTrue(transaction { txService.getByTxId("txhashdb", 1).cryptoAddress == invService.getBySystemId(invoice.id).cryptoAddress }) Assertions.assertEquals(invoice.status, InvoiceStatus.PAID) Assertions.assertEquals(invoice.received, BigDecimal.ONE) Assertions.assertTrue(invoice.txids.contains(TxId("txhashdb", 1))) Assertions.assertNotNull(invoiceProcessor.getInvoice("inv2")) } } @Test fun onErrorTest() { val e = Mockito.mock(Throwable::class.java) invoiceProcessor.onError(e) } @Test fun onCompleteTest() { invoiceProcessor.onComplete() } @Test fun onSubscribeTest() { val d = Mockito.mock(Disposable::class.java) invoiceProcessor.onSubscribe(d) } }
0
Kotlin
7
5
97c22beec449216af3a02e027a0d68c079a44fbf
10,993
Blockchain-Payment-System
Apache License 2.0
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/PoolOff.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.tabler.tabler.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Round import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup public val OutlineGroup.PoolOff: ImageVector get() { if (_poolOff != null) { return _poolOff!! } _poolOff = Builder(name = "PoolOff", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(2.0f, 20.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, false, 2.0f, 1.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, false, 2.0f, -1.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, true, 2.0f, -1.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, true, 2.0f, 1.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, false, 2.0f, 1.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, false, 2.0f, -1.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, true, 2.0f, -1.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, true, 2.0f, 1.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, false, 2.0f, 1.0f) curveToRelative(0.303f, 0.0f, 0.6f, -0.045f, 0.876f, -0.146f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(2.0f, 16.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, false, 2.0f, 1.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, false, 2.0f, -1.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, true, 2.0f, -1.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, true, 2.0f, 1.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, false, 2.0f, 1.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, false, 2.0f, -1.0f) arcToRelative(2.4f, 2.4f, 0.0f, false, true, 1.13f, -0.856f) moveToRelative(5.727f, 1.717f) arcToRelative(2.4f, 2.4f, 0.0f, false, false, 1.143f, -0.861f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(15.0f, 11.0f) verticalLineToRelative(-6.5f) arcToRelative(1.5f, 1.5f, 0.0f, false, true, 3.0f, 0.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(9.0f, 12.0f) verticalLineToRelative(-3.0f) moveToRelative(0.0f, -4.0f) verticalLineToRelative(-0.5f) arcToRelative(1.5f, 1.5f, 0.0f, false, false, -1.936f, -1.436f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(15.0f, 5.0f) horizontalLineToRelative(-6.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(9.0f, 10.0f) horizontalLineToRelative(1.0f) moveToRelative(4.0f, 0.0f) horizontalLineToRelative(1.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(3.0f, 3.0f) lineToRelative(18.0f, 18.0f) } } .build() return _poolOff!! } private var _poolOff: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
5,341
compose-icon-collections
MIT License
app/src/main/java/com/ph03nix_x/capacityinfo/fragments/HistoryFragment.kt
Ph03niX-X
204,125,869
false
null
package com.ph03nix_x.capacityinfo.fragments import android.annotation.SuppressLint import android.content.SharedPreferences import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.RelativeLayout import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.preference.PreferenceManager import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.ph03nix_x.capacityinfo.R import com.ph03nix_x.capacityinfo.adapters.HistoryAdapter import com.ph03nix_x.capacityinfo.databases.HistoryDB import com.ph03nix_x.capacityinfo.helpers.HistoryHelper import kotlinx.android.synthetic.main.history_fragment.* class HistoryFragment : Fragment(R.layout.history_fragment) { private lateinit var pref: SharedPreferences private lateinit var historyAdapter: HistoryAdapter lateinit var recView: RecyclerView lateinit var refreshEmptyHistory: SwipeRefreshLayout lateinit var refreshHistory: SwipeRefreshLayout lateinit var emptyHistoryLayout: RelativeLayout companion object { @SuppressLint("StaticFieldLeak") var instance: HistoryFragment? = null } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { pref = PreferenceManager.getDefaultSharedPreferences(requireContext()) return super.onCreateView(inflater, container, savedInstanceState) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) instance = this recView = view.findViewById(R.id.history_recycler_view) refreshEmptyHistory = view.findViewById(R.id.refresh_empty_history) refreshHistory = view.findViewById(R.id.refresh_history) emptyHistoryLayout = view.findViewById(R.id.empty_history_layout) val historyDB = HistoryDB(requireContext()) if(historyDB.getCount() > 0) { emptyHistoryLayout.visibility = View.GONE refresh_empty_history.visibility = View.GONE recView.visibility = View.VISIBLE historyAdapter = HistoryAdapter(historyDB.readDB()) recView.adapter = historyAdapter } else { recView.visibility = View.GONE refresh_empty_history.visibility = View.VISIBLE emptyHistoryLayout.visibility = View.VISIBLE } refreshEmptyHistory() refreshHistory() } override fun onResume() { super.onResume() if(HistoryHelper.getHistoryCount(requireContext()) > 0) { historyAdapter.update(requireContext()) refresh_empty_history.visibility = View.GONE emptyHistoryLayout.visibility = View.GONE recView.visibility = View.VISIBLE } else { recView.visibility = View.GONE refresh_empty_history.visibility = View.VISIBLE emptyHistoryLayout.visibility = View.VISIBLE } } override fun onDestroy() { instance = null HistoryAdapter.instance = null super.onDestroy() } private fun refreshEmptyHistory() { refreshEmptyHistory.apply { setColorSchemeColors(ContextCompat.getColor(requireContext(), R.color.swipe_refresh_layout_progress)) setProgressBackgroundColorSchemeColor(ContextCompat.getColor(requireContext(), R.color.swipe_refresh_layout_progress_background)) setOnRefreshListener { isRefreshing = true if(HistoryHelper.getHistoryCount(requireContext()) > 0) { historyAdapter.update(requireContext()) visibility = View.GONE refresh_history.visibility = View.VISIBLE emptyHistoryLayout.visibility = View.GONE recView.visibility = View.VISIBLE } else { recView.visibility = View.GONE refresh_history.visibility = View.GONE visibility = View.VISIBLE emptyHistoryLayout.visibility = View.VISIBLE } isRefreshing = false } } } private fun refreshHistory() { refreshHistory.apply { setColorSchemeColors(ContextCompat.getColor(requireContext(), R.color.swipe_refresh_layout_progress)) setProgressBackgroundColorSchemeColor(ContextCompat.getColor(requireContext(), R.color.swipe_refresh_layout_progress_background)) setOnRefreshListener { isRefreshing = true if(HistoryHelper.getHistoryCount(requireContext()) > 0) { historyAdapter.update(requireContext()) refresh_empty_history.visibility = View.GONE visibility = View.VISIBLE emptyHistoryLayout.visibility = View.GONE recView.visibility = View.VISIBLE } else { recView.visibility = View.GONE visibility = View.GONE refresh_empty_history.visibility = View.VISIBLE emptyHistoryLayout.visibility = View.VISIBLE } isRefreshing = false } } } }
0
Kotlin
2
15
2899b280f41c87d5da6a3bd07ec2dc9550a70d75
5,561
CapacityInfo
Apache License 2.0
app/src/main/java/com/vpaliy/mediaplayer/ui/utils/OnReachBottomListener.kt
winterdl
107,023,216
true
{"Kotlin": 152343, "Java": 1707}
package com.vpaliy.mediaplayer.ui.utils import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.StaggeredGridLayoutManager abstract class OnReachBottomListener(private val layoutManager:RecyclerView.LayoutManager, private val dataLoading: SwipeRefreshLayout?=null) : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { // bail out if scrolling upward or already loading data val firstVisibleItem = fetchFirstVisibleItemPosition() if (dy < 0 || dataLoading != null && dataLoading.isRefreshing || firstVisibleItem == -1) return val visibleItemCount = recyclerView!!.childCount val totalItemCount = layoutManager.itemCount if (totalItemCount - visibleItemCount <= firstVisibleItem + VISIBLE_THRESHOLD) { onLoadMore() } } private fun fetchFirstVisibleItemPosition(): Int { if (layoutManager is LinearLayoutManager) { return LinearLayoutManager::class.java.cast(layoutManager).findFirstVisibleItemPosition() } else if (layoutManager is StaggeredGridLayoutManager) { val manager = StaggeredGridLayoutManager::class.java.cast(layoutManager) val result = manager.findFirstVisibleItemPositions(null) if (result != null && result.isNotEmpty()) { return result[0] } } return -1 } abstract fun onLoadMore() companion object { private val VISIBLE_THRESHOLD = 5 } }
0
Kotlin
0
0
62c106e4c0179cd3505ad72e009cd1999bbc417c
1,711
Flash
MIT License
src/commonMain/kotlin/data/general/avatar/TrialAvatarGrantRecord.kt
Hartie95
642,871,918
false
{"Kotlin": 301622}
package data.general.avatar import annotations.AddedIn import data.general.item.Item import messages.VERSION import org.anime_game_servers.annotations.ProtoModel @AddedIn(VERSION.VCB2) @ProtoModel internal interface TrialAvatarGrantRecord { var grantReason: Int var fromParentQuestId: Int }
0
Kotlin
2
5
cb458b49dc9618e3826b890689becc0f12585998
300
anime-game-multi-proto
MIT License
client/app/src/main/java/org/feup/cmov/acmeclient/data/db/details/ItemUpdate.kt
miguelalexbt
305,443,061
false
null
package org.feup.cmov.acmeclient.data.db.details import androidx.room.ColumnInfo import androidx.room.Entity @Entity data class ItemUpdate( @ColumnInfo(name = "id") val id: String, @ColumnInfo(name = "usersFavorite") val usersFavorite: Set<String> )
0
Kotlin
0
0
bbd82c059b35525faf78de35c217b661ee7ad259
268
ACME-Coffee-App
MIT License
shared/src/commonMain/kotlin/co/nimblehq/ic/kmm/suv/data/remote/model/UserApiModel.kt
suho
523,936,897
false
{"Kotlin": 232630, "Swift": 119332, "Ruby": 21329, "Shell": 81}
package co.nimblehq.ic.kmm.suv.data.remote.model import co.nimblehq.ic.kmm.suv.domain.model.User import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class UserApiModel( @SerialName("id") val id: String, @SerialName("type") val type: String, @SerialName("email") val email: String, @SerialName("name") val name: String, @SerialName("avatar_url") val avatarUrl: String ) fun UserApiModel.toUser() = User( email, name, avatarUrl )
0
Kotlin
0
3
d34b39d4755770898c8236db0318535a5aa15dcf
532
kmm-ic
MIT License
imla/src/main/java/dev/serhiiyaremych/imla/uirenderer/RenderableRootLayer.kt
desugar-64
792,899,184
false
{"Kotlin": 220573, "GLSL": 11616}
/* * Copyright 2024, <NAME> * SPDX-License-Identifier: MIT */ package dev.serhiiyaremych.imla.uirenderer import android.graphics.Color import android.graphics.PorterDuff import android.graphics.SurfaceTexture import android.view.Surface import androidx.annotation.MainThread import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Canvas import androidx.compose.ui.graphics.drawscope.CanvasDrawScope import androidx.compose.ui.graphics.layer.GraphicsLayer import androidx.compose.ui.graphics.layer.drawLayer import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.toSize import androidx.tracing.trace import dev.serhiiyaremych.imla.renderer.Bind import dev.serhiiyaremych.imla.renderer.Framebuffer import dev.serhiiyaremych.imla.renderer.FramebufferAttachmentSpecification import dev.serhiiyaremych.imla.renderer.FramebufferSpecification import dev.serhiiyaremych.imla.renderer.FramebufferTextureFormat import dev.serhiiyaremych.imla.renderer.FramebufferTextureSpecification import dev.serhiiyaremych.imla.renderer.RenderCommand import dev.serhiiyaremych.imla.renderer.Renderer2D import dev.serhiiyaremych.imla.renderer.Texture import dev.serhiiyaremych.imla.renderer.Texture2D internal class RenderableRootLayer( private val layerDownsampleFactor: Int, private val density: Density, internal val graphicsLayer: GraphicsLayer, internal val renderer2D: Renderer2D, private val onLayerTextureUpdated: () -> Unit ) { val sizeInt: IntSize get() = graphicsLayer.size val sizeDec: Size get() = sizeInt.toSize() val lowResTexture: Texture2D get() = lowResFBO.colorAttachmentTexture val scale: Float get() = 1.0f / layerDownsampleFactor val isReady: Boolean get() = sizeInt == IntSize.Zero private lateinit var renderableScope: RenderableScope private val drawingScope: CanvasDrawScope = CanvasDrawScope() private lateinit var layerExternalTexture: SurfaceTexture private lateinit var layerSurface: Surface private lateinit var extOesLayerTexture: Texture2D private lateinit var lowResFBO: Framebuffer lateinit var highResFBO: Framebuffer private set private var isInitialized: Boolean = false private var isDestroyed: Boolean = false fun initialize() { require(!isDestroyed) { "Can't re-init destroyed layer" } if (!isReady) { trace("RenderableRootLayer#initialize") { renderableScope = RenderableScope(scale = scale, originalSizeInt = sizeInt, renderer = renderer2D) val specification = FramebufferSpecification( size = sizeInt, attachmentsSpec = FramebufferAttachmentSpecification( listOf(FramebufferTextureSpecification(format = FramebufferTextureFormat.RGBA8)) ), downSampleFactor = layerDownsampleFactor // downsample layer texture later ) lowResFBO = Framebuffer.create(specification) highResFBO = Framebuffer.create(specification.copy(downSampleFactor = 1)) // no downsampling extOesLayerTexture = Texture2D.create( target = Texture.Target.TEXTURE_EXTERNAL_OES, specification = Texture.Specification(size = sizeInt, flipTexture = false) ) extOesLayerTexture.bind() layerExternalTexture = SurfaceTexture(extOesLayerTexture.id) layerExternalTexture.setDefaultBufferSize(sizeInt.width, sizeInt.height) layerSurface = Surface(layerExternalTexture) layerExternalTexture.setOnFrameAvailableListener { trace("surfaceTexture#updateTexImage") { it.updateTexImage() } copyTextureToFrameBuffer() onLayerTextureUpdated() } isInitialized = true } } } fun resize() { TODO("Implement runtime layer resizing") } private fun copyTextureToFrameBuffer() = trace( "copyExtTextureToFrameBuffer" ) { with(renderableScope) { trace("fullSizeBuffer") { highResFBO.bind(Bind.DRAW) drawScene(camera = cameraController.camera) { drawQuad( position = center, size = size, texture = extOesLayerTexture ) } } trace("scaledSizeBuffer") { highResFBO.bind(Bind.READ) lowResFBO.bind(Bind.DRAW) val highResTexSize = highResFBO.specification.size highResFBO.readBuffer(0) RenderCommand.blitFramebuffer( srcX0 = 0, srcY0 = 0, srcX1 = highResTexSize.width, srcY1 = highResTexSize.height, dstX0 = 0, dstY0 = 0, dstX1 = lowResFBO.colorAttachmentTexture.width, dstY1 = lowResFBO.colorAttachmentTexture.height, mask = RenderCommand.colorBufferBit, filter = RenderCommand.linearTextureFilter, ) } } } // context(GLRenderer.RenderCallback) @MainThread fun updateTex() = trace("RenderableRootLayer#updateTex") { require(!isDestroyed) { "Can't update destroyed layer" } require(!graphicsLayer.isReleased) { "GraphicsLayer has been released!" } require(isInitialized) { "RenderableRootLayer not initialized!" } trace("drawLayerToExtTexture[$sizeInt]") { var hwCanvas: android.graphics.Canvas? = null try { hwCanvas = trace("lockHardwareCanvas") { layerSurface.lockHardwareCanvas() } trace("hwCanvasClear") { hwCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR) } drawingScope.draw(density, LayoutDirection.Ltr, Canvas(hwCanvas), sizeDec) { trace("drawGraphicsLayer") { drawLayer(graphicsLayer) } } } finally { trace("unlockCanvasAndPost") { layerSurface.unlockCanvasAndPost(hwCanvas) } } } } fun destroy() { layerExternalTexture.release() layerSurface.release() extOesLayerTexture.destroy() isDestroyed = true } } internal operator fun IntSize.compareTo(other: IntSize): Int { return (width.toLong() * height).compareTo((other.width.toLong() * other.height)) }
1
Kotlin
3
79
d72a90165993d1f9f0187ef9a6ac4aa849e9a563
6,888
imla
MIT License