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/androiddevchallenge/ui/list/CatList.kt
1jGabriel
342,024,616
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.example.androiddevchallenge.ui.list import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.Divider import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.example.androiddevchallenge.ui.Cat @Composable fun CatList( cats: List<Cat>, onSelected: (String) -> Unit ) { LazyColumn { items(cats) { cat -> CatItem(cat = cat, onSelected = onSelected) Divider( modifier = Modifier.padding(horizontal = 16.dp), color = MaterialTheme.colors.onSurface.copy(alpha = 0.08f) ) } } }
0
Kotlin
0
0
ad673319493ebadf417cb1797291ba883d838bd2
1,439
android-dev-challenge-compose
Apache License 2.0
app/src/main/java/com/example/compose/ui/theme/Color.kt
zhqnrf
862,237,493
false
{"Kotlin": 65537}
package com.example.compose.ui.theme import androidx.compose.ui.graphics.Color val TwitterBlue = Color(0xFF1DA1F2) // Biru Twitter val Black = Color(0xFF14171A) // Hitam val DarkGray = Color(0xFF657786) // Abu-abu Gelap val LightGray = Color(0xFFAAB8C2) // Abu-abu Terang val White = Color(0xFFFFFFFF) // Putih
0
Kotlin
0
0
e515b2d74c29a6e9929abb19c2e7fa897c66fec2
313
konosuba-jetpackapp
MIT License
core-kotlin-modules/core-kotlin-io/src/test/kotlin/com/baeldung/renameFile/RenameFileUnitTest.kt
Baeldung
260,481,121
false
{"Kotlin": 1855665, "Java": 48276, "HTML": 4883, "Dockerfile": 292}
package com.baeldung.renameFile import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.fail import org.junit.jupiter.api.Test import java.nio.file.Files import java.nio.file.Paths import java.nio.file.StandardCopyOption class RenameFileUnitTest { @Test fun `when using renameTo, then file is renamed`() { val oldFilePath = Paths.get("src/test/resources/oldFile.txt") val newFilePath = Paths.get("src/test/resources/newFile.txt") val oldFile = oldFilePath.toFile() oldFile.writeText("Hello Kotlin") val newFile = newFilePath.toFile() if (oldFile.renameTo(newFile)) { assertThat(newFile.exists()).isTrue() } else { fail("Failed to rename file.") } //cleanup newFile.delete() } @Test fun `when renaming, checks on files succeed`() { val oldFilePath = Paths.get("src/test/resources/oldFile.txt") val newFilePath = Paths.get("src/test/resources/newFile.txt") val oldFile = oldFilePath.toFile() oldFile.writeText("Hello Kotlin") val newFile = newFilePath.toFile() if (oldFile.exists()) { if (newFile.exists()) { fail("A file with the new name already exists.") } else { if (oldFile.renameTo(newFile)) { assertThat(newFile.exists()).isTrue() } else { fail("Fail rename failed") } } } else { fail("The old file does not exist.") } //cleanup newFile.delete() } @Test fun `when using move, then file is renamed`() { val oldFilePath = Paths.get("src/test/resources/oldFile.txt") val newFilePath = Paths.get("src/test/resources/newFile.txt") val oldFile = oldFilePath.toFile() oldFile.writeText("Hello Kotlin") Files.move(oldFilePath, newFilePath, StandardCopyOption.REPLACE_EXISTING) val newFile = newFilePath.toFile() assertThat(newFile.exists()).isTrue() //cleanup newFile.delete() } }
14
Kotlin
294
465
f1ef5d5ded3f7ddc647f1b6119f211068f704577
2,076
kotlin-tutorials
MIT License
app/src/test/java/com/abidria/presentation/experience/show/MyExperiencesPresenterTest.kt
jordifierro
98,501,336
false
null
package com.abidria.presentation.experience.show import com.abidria.data.auth.AuthRepository import com.abidria.data.common.Result import com.abidria.data.experience.Experience import com.abidria.data.experience.ExperienceRepository import com.abidria.presentation.common.injection.scheduler.SchedulerProvider import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.schedulers.Schedulers import io.reactivex.subjects.PublishSubject import org.junit.Assert.assertFalse import org.junit.Test import org.mockito.BDDMockito import org.mockito.BDDMockito.given import org.mockito.BDDMockito.then import org.mockito.Mock import org.mockito.MockitoAnnotations class MyExperiencesPresenterTest { @Test fun test_if_cannot_create_content_shows_register_dialog() { given { an_auth_repo_that_returns_false_on_can_create_content() } whenn { create_presenter() } then { should_show_view_register_dialog() } } @Test fun test_create_asks_experiences_and_shows_if_can_create_content() { given { an_auth_repo_that_returns_true_on_can_create_content() an_experience() another_experience() an_experience_repo_that_returns_both_on_my_experiences_flowable() } whenn { create_presenter() } then { should_show_view_loader() should_show_received_experiences() should_hide_view_loader() } } @Test fun test_resume_checks_if_can_create_content_has_changed_and_connects_to_experiences() { given { an_auth_repo_that_returns_true_on_can_create_content() an_experience() another_experience() an_experience_repo_that_returns_both_on_my_experiences_flowable() } whenn { resume_presenter() } then { should_show_view_loader() should_show_received_experiences() should_hide_view_loader() } } @Test fun test_resume_does_nothing_if_cannot_create_content() { given { an_auth_repo_that_returns_false_on_can_create_content() } whenn { resume_presenter() } then { should_do_nothing() } } @Test fun test_resume_does_nothing_if_already_connected_to_experiences_flowable() { given { an_auth_repo_that_returns_true_on_can_create_content() an_experience() another_experience() an_experience_repo_that_returns_both_on_my_experiences_flowable() } whenn { create_presenter() } then { should_show_view_loader() should_call_repo_my_experience_flowable() should_show_received_experiences() should_hide_view_loader() } whenn { resume_presenter() } then { should_do_nothing() } } @Test fun test_create_when_response_error_shows_retry() { given { an_auth_repo_that_returns_true_on_can_create_content() an_experience_repo_that_returns_exception() } whenn { create_presenter() } then { should_hide_view_loader() should_show_view_retry() } } @Test fun test_on_retry_click_retrive_experiences_and_shows_them() { given { nothing() } whenn { retry_clicked() } then { should_hide_view_retry() should_show_view_loader() should_call_repo_refresh_experiences() } } @Test fun test_experience_tapped() { given { nothing() } whenn { experience_click("2") } then { should_navigate_to_experience("2") } } @Test fun test_create_new_experience_button_click_when_can_create_content() { given { an_auth_repo_that_returns_true_on_can_create_content() } whenn { on_create_experience_click() } then { should_navigate_to_create_experience() } } @Test fun test_create_new_experience_button_click_if_cannot_create_content_shows_register_dialog() { given { an_auth_repo_that_returns_false_on_can_create_content() } whenn { on_create_experience_click() } then { should_show_view_register_dialog() } } @Test fun test_unsubscribe_on_destroy() { given { a_test_observable() an_experience_repo_that_returns_test_observable() } whenn { create_presenter() destroy_presenter() } then { should_unsubscribe_observable() } } @Test fun test_on_proceed_to_register_navigates_to_register() { given { nothing() } whenn { proceed_to_register() } then { should_navigate_to_register() } } @Test fun test_on_dont_proceed_to_register_must_do_nothing() { given { nothing() } whenn { dont_proceed_to_register() } then { should_do_nothing() } } private fun given(func: ScenarioMaker.() -> Unit) = ScenarioMaker().given(func) class ScenarioMaker { lateinit var presenter: MyExperiencesPresenter @Mock lateinit var mockView: MyExperiencesView @Mock lateinit var mockExperiencesRepository: ExperienceRepository @Mock lateinit var mockAuthRepository: AuthRepository lateinit var experienceA: Experience lateinit var experienceB: Experience lateinit var testObservable: PublishSubject<Result<List<Experience>>> fun buildScenario(): ScenarioMaker { MockitoAnnotations.initMocks(this) val testSchedulerProvider = SchedulerProvider(Schedulers.trampoline(), Schedulers.trampoline()) presenter = MyExperiencesPresenter(mockExperiencesRepository, mockAuthRepository, testSchedulerProvider) presenter.view = mockView return this } fun nothing() {} fun an_experience() { experienceA = Experience(id = "1", title = "A", description = "", picture = null) } fun another_experience() { experienceB = Experience(id = "2", title = "B", description = "", picture = null) } fun an_experience_repo_that_returns_both_on_my_experiences_flowable() { given(mockExperiencesRepository.myExperiencesFlowable()).willReturn(Flowable.just( Result<List<Experience>>(arrayListOf(experienceA, experienceB), null))) } fun an_experience_repo_that_returns_exception() { given(mockExperiencesRepository.myExperiencesFlowable()) .willReturn(Flowable.just(Result<List<Experience>>(null, Exception()))) } fun an_auth_repo_that_returns_true_on_can_create_content() { BDDMockito.given(mockAuthRepository.canPersonCreateContent()).willReturn(true) } fun an_auth_repo_that_returns_false_on_can_create_content() { BDDMockito.given(mockAuthRepository.canPersonCreateContent()).willReturn(false) } fun create_presenter() { presenter.create() } fun resume_presenter() { presenter.resume() } fun proceed_to_register() { presenter.onProceedToRegister() } fun retry_clicked() { presenter.onRetryClick() } fun on_create_experience_click() { presenter.onCreateExperienceClick() } fun experience_click(experienceId: String) { presenter.onExperienceClick(experienceId) } fun dont_proceed_to_register() { presenter.onDontProceedToRegister() } fun should_show_view_loader() { then(mockView).should().showLoader() } fun should_show_received_experiences() { then(mockView).should().showExperienceList(arrayListOf(experienceA, experienceB)) } fun should_hide_view_loader() { then(mockView).should().hideLoader() } fun should_show_view_retry() { then(mockView).should().showRetry() } fun should_hide_view_retry() { then(mockView).should().hideRetry() } fun should_call_repo_refresh_experiences() { then(mockExperiencesRepository).should().refreshMyExperiences() } fun should_navigate_to_experience(experienceId: String) { then(mockView).should().navigateToExperience(experienceId) } fun should_navigate_to_create_experience() { then(mockView).should().navigateToCreateExperience() } fun a_test_observable() { testObservable = PublishSubject.create<Result<List<Experience>>>() assertFalse(testObservable.hasObservers()) } fun an_experience_repo_that_returns_test_observable() { given(mockExperiencesRepository.myExperiencesFlowable()) .willReturn(testObservable.toFlowable(BackpressureStrategy.LATEST)) } fun destroy_presenter() { presenter.destroy() } fun should_unsubscribe_observable() { assertFalse(testObservable.hasObservers()) } fun should_show_view_register_dialog() { BDDMockito.then(mockView).should().showRegisterDialog() } fun should_do_nothing() { BDDMockito.then(mockView).shouldHaveNoMoreInteractions() BDDMockito.then(mockExperiencesRepository).shouldHaveNoMoreInteractions() } fun should_call_repo_my_experience_flowable() { BDDMockito.then(mockExperiencesRepository).should().myExperiencesFlowable() } fun should_navigate_to_register() { BDDMockito.then(mockView).should().navigateToRegister() } infix fun given(func: ScenarioMaker.() -> Unit) = buildScenario().apply(func) infix fun whenn(func: ScenarioMaker.() -> Unit) = apply(func) infix fun then(func: ScenarioMaker.() -> Unit) = apply(func) } }
0
Kotlin
1
2
f6ec0112c4a555232c8544e4f380dd733dddb286
10,459
abidria-android
Apache License 2.0
app/src/main/java/de/lukasneugebauer/nextcloudcookbook/feature_settings/presentation/SettingsViewModel.kt
lneugebauer
397,373,765
false
null
package de.lukasneugebauer.nextcloudcookbook.feature_settings.presentation import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import de.lukasneugebauer.nextcloudcookbook.core.domain.use_case.ClearPreferencesUseCase import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class SettingsViewModel @Inject constructor( private val clearPreferencesUseCase: ClearPreferencesUseCase ) : ViewModel() { fun logout() { viewModelScope.launch { clearPreferencesUseCase() } } }
4
Kotlin
0
0
d4a0d3515484c733cba11dff875c1b52ddd38a39
604
nextcloud-cookbook
MIT License
command/src/main/kotlin/com/amarcolini/joos/hardware/Servo.kt
amarcolini
424,457,806
false
null
package com.amarcolini.joos.hardware import com.amarcolini.joos.command.Command import com.amarcolini.joos.command.Component import com.amarcolini.joos.command.TimeCommand import com.amarcolini.joos.geometry.Angle import com.amarcolini.joos.util.* import com.qualcomm.robotcore.hardware.HardwareMap import com.qualcomm.robotcore.hardware.Servo import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.math.sign /** * A wrapper for the [Servo] object in the FTC SDK. * * @param servo the servo for this wrapper to use * @param range the range of the servo */ class Servo @JvmOverloads constructor( servo: Servo, @JvmField val range: Angle = 300.deg, private val clock: NanoClock = NanoClock.system ) : Component { /** * @param hMap the hardware map from the OpMode * @param id the device id from the RC config * @param range the range of the servo */ @JvmOverloads constructor( hMap: HardwareMap, id: String, range: Angle = 180.deg, clock: NanoClock = NanoClock.system ) : this( hMap.get(Servo::class.java, id), range, clock ) @JvmField val internal = servo /** * Whether this servo is reversed. */ var reversed: Boolean = false @JvmSynthetic set(value) { internal.direction = if (value) Servo.Direction.REVERSE else Servo.Direction.FORWARD field = value } @JvmName("isReversed") get fun setReversed(reversed: Boolean): com.amarcolini.joos.hardware.Servo { this.reversed = reversed return this } /** * Angular representation of the servo's position in the range `[0.0, `[range]`]`. * Setting the angle sets [position] and vice versa. Note that the angle of the servo is independent of * [scaleRange], but the available angle range is not. * * @see position * @see scaleRange */ var angle: Angle = 0.deg get() = range * internal.position set(value) { val actual = value.coerceIn(currentAngleRange.first, currentAngleRange.second) field = actual internal.position = actual / range } /** * The currently available movement range of the servo. Affected by [scaleRange]. * @see scaleRange */ var currentAngleRange: Pair<Angle, Angle> = 0.deg to range private set /** * The currently available movement range of the servo. Affected by [scaleRange]. * @see scaleRange */ var currentRange: Pair<Double, Double> = 0.0 to 1.0 private set /** * Scales the available movement range of the servo to be a subset of its maximum range. Subsequent * positioning calls will operate within that subset range. This is useful if your servo has only a limited * useful range of movement due to the physical hardware that it is manipulating (as is often the case) but * you don't want to have to manually scale and adjust the input to [position] each time. * For example, if `scaleRange(0.2, 0.8)` is set; then servo positions will be scaled to fit in that range: * * `setPosition(0.0)` scales to `0.2` * * `setPosition(1.0)` scales to `0.8` * * `setPosition(0.5)` scales to `0.5` * * `setPosition(0.25)` scales to `0.35` * * `setPosition(0.75)` scales to `0.65` * * Note the parameters passed here are relative to the underlying full range of motion of the servo, * not its currently scaled range, if any. Thus, scaleRange(0.0, 1.0) will reset the servo to * its full range of movement. * @see position */ fun scaleRange(min: Double, max: Double) { val correctedMin = min.coerceIn(0.0, 1.0) val correctedMax = max.coerceIn(0.0, 1.0) val actualMin = min(correctedMin, correctedMax) val actualMax = max(correctedMin, correctedMax) currentRange = actualMin to actualMax currentAngleRange = range * actualMin to range * actualMax } /** * Scales the available movement range of the servo to be a subset of its maximum range. Subsequent * positioning calls will operate within that subset range. This is useful if your servo has only a limited * useful range of movement due to the physical hardware that it is manipulating (as is often the case) but * you don't want to have to manually adjust the input to [position] each time. * For example, if the range of the servo is 180°, and `scaleRange(30°, 90°)` is set; then servo * positions will be clamped to fit in that range: * * `setPosition(10°)` is clamped to `30°` * * `setPosition(135°)` is clamped to `90°` * * `setPosition(60°)` still becomes `60°` * * And scaleRange(0°, 180°) would reset the servo to its full range of movement. * Note that this also scales the position range as well. * @see position */ fun scaleRange(min: Angle, max: Angle) { val correctedMin = min.coerceIn(0.deg, range) val correctedMax = max.coerceIn(0.deg, range) val actualMin = min(correctedMin, correctedMax) val actualMax = max(correctedMin, correctedMax) currentRange = actualMin / range to actualMax / range currentAngleRange = actualMin to actualMax } /** * The position of this servo in the range `[0.0, 1.0]`. * @see angle */ var position: Double = 0.0 set(value) { field = value.coerceIn(0.0, 1.0) internal.position = scalePosition(field) } private fun scalePosition(position: Double) = position * (currentRange.second - currentRange.first) + currentRange.first /** * Returns a command that uses [range] and [speed] (specified in units per second) to go to the specified position * at the desired speed by slowly incrementing the position. Note that since there is no feedback from the servo, it may or may not * actually achieve the desired speed. */ fun goToPosition(position: Double, speed: Angle) = goToPosition(position, speed / range) /** * Returns a command that goes to the specified position at the desired speed. * Note that since there is no feedback from the servo, it may or may not * actually achieve the desired speed. */ fun goToPosition(position: Double, speed: Double): Command = Command.select { val distance = abs(position - this.position) val duration = speed / distance TimeCommand { t, _ -> this.position += t * speed * sign(position - this.position) t >= duration || this.position == position } .onEnd { this.position = position } .requires(this) } /** * Returns a command that uses [range] and [speed] (specified in units per second) to go to the specified angle * at the desired speed. Note that since there is no feedback from the servo, it may or may not * actually achieve the desired speed. */ fun goToAngle(angle: Angle, speed: Angle): Command = goToPosition(angle / range, speed) /** * Returns a command that goes to the specified angle at the desired speed. * Note that since there is no feedback from the servo, it may or may not * actually achieve the desired speed. */ fun goToAngle(angle: Angle, speed: Double): Command = goToPosition(angle / range, speed) /** * Returns a command that uses [range] and [speed] (specified in units per second) to estimate * when the servo will reach the specified position, and waits until that point. */ fun waitForPosition(position: Double, speed: Angle): Command = waitForPosition(position, speed / range) /** * Returns a command that uses [speed] to estimate when the servo will reach * the specified position, and waits until that point. */ fun waitForPosition(position: Double, speed: Double): Command = Command.select { val correctedPos = position.coerceIn(0.0, 1.0) val currentPosition = this.position Command.of { this.position = scalePosition(correctedPos) } .wait(abs(currentPosition - scalePosition(correctedPos)) / speed) .requires(this) } /** * Returns a command that uses [range] and [speed] (specified in units per second) to estimate * when the servo will reach the specified angle, and waits until that point. */ fun waitForAngle(angle: Angle, speed: Angle): Command = waitForPosition(angle / range, speed) /** * Returns a command that uses [speed] to estimate when the servo will reach * the specified angle, and waits until that point. */ fun waitForAngle(angle: Angle, speed: Double): Command = waitForPosition(angle / range, speed) }
1
null
2
9
3ed0c4a444f8934b9bf39a9a95270447696e3a0c
8,932
joos
MIT License
src/main/kotlin/me/melijn/melijnbot/commands/utility/InfoCommand.kt
ToxicMushroom
107,187,088
false
null
package me.melijn.melijnbot.commands.utility import com.sedmelluq.discord.lavaplayer.tools.PlayerLibrary import me.duncte123.weebJava.WeebInfo import me.melijn.melijnbot.internals.command.AbstractCommand import me.melijn.melijnbot.internals.command.CommandCategory import me.melijn.melijnbot.internals.command.ICommandContext import me.melijn.melijnbot.internals.embed.Embedder import me.melijn.melijnbot.internals.utils.awaitOrNull import me.melijn.melijnbot.internals.utils.message.sendEmbedRsp import me.melijn.melijnbot.internals.utils.withVariable import net.dv8tion.jda.api.JDAInfo class InfoCommand : AbstractCommand("command.info") { init { id = 14 name = "info" aliases = arrayOf("bot", "botInfo", "melijn", "version", "versions") commandCategory = CommandCategory.UTILITY } override suspend fun execute(context: ICommandContext) { val title1 = context.getTranslation("$root.field1.title") val value1 = replaceValueOneVars(context.getTranslation("$root.field1.value"), context) val title2 = context.getTranslation("$root.field2.title") val value2 = replaceValueTwoVars(context.getTranslation("$root.field2.value"), context) val title3 = context.getTranslation("$root.field3.title") val value3 = replaceValueThreeVars(context.getTranslation("$root.field3.value"), context) val eb = Embedder(context) .setThumbnail(context.selfUser.effectiveAvatarUrl) .addField(title1, value1, false) .addField(title2, value2, false) .addField(title3, value3, false) sendEmbedRsp(context, eb.build()) } private fun replaceValueThreeVars(string: String, context: ICommandContext): String = string .withVariable("javaVersion", System.getProperty("java.version")) .withVariable( "kotlinVersion", "${KotlinVersion.CURRENT.major}.${KotlinVersion.CURRENT.minor}.${KotlinVersion.CURRENT.patch}" ) .withVariable("jdaVersion", JDAInfo.VERSION) .withVariable("lavaplayerVersion", PlayerLibrary.VERSION) .withVariable("weebVersion", WeebInfo.VERSION) .withVariable("dbVersion", context.daoManager.dbVersion) .withVariable("dbConnectorVersion", context.daoManager.connectorVersion) private fun replaceValueTwoVars(string: String, context: ICommandContext): String = string .withVariable( "os", "${System.getProperty("os.name")} ${System.getProperty("os.arch")} ${System.getProperty("os.version")}" ) .withVariable("commandCount", context.commandList.size.toString()) private suspend fun replaceValueOneVars(string: String, context: ICommandContext): String = string .withVariable( "ownerTag", context.jda.shardManager?.retrieveUserById(231459866630291459L)?.awaitOrNull()?.asTag ?: "ToxicMushroom#2610" ) .withVariable("invite", "https://discord.gg/tfQ9s7u") .withVariable("botInvite", "https://melijn.com/invite") .withVariable("website", "https://melijn.com") .withVariable("contact", "[email protected]") }
5
Kotlin
22
80
01107bbaad0e343d770b1e4124a5a9873b1bb5bd
3,181
Melijn
MIT License
src/main/kotlin/br/com/zupacademy/giovanna/Application.kt
giovanna-bernardi
394,647,420
true
{"Kotlin": 34299, "Smarty": 1902, "Dockerfile": 154}
package br.com.zupacademy.caico import io.micronaut.runtime.Micronaut.* fun main(args: Array<String>) { build() .args(*args) .packages("br.com.zupacademy.caico") .start() }
0
Kotlin
0
0
eb7ac9af8ebb473513c7a75e71c2133674d6e8f2
185
orange-talents-06-template-pix-keymanager-grpc
Apache License 2.0
app/src/main/java/fr/acinq/phoenix/settings/SeedSecurityFragment.kt
bitcoinuser
247,827,323
false
null
/* * Copyright 2019 ACINQ SAS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package fr.acinq.phoenix.settings import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.annotation.UiThread import androidx.biometric.BiometricManager import androidx.biometric.BiometricPrompt import androidx.lifecycle.* import androidx.navigation.fragment.findNavController import fr.acinq.phoenix.BaseFragment import fr.acinq.phoenix.R import fr.acinq.phoenix.databinding.FragmentSettingsSeedSecurityBinding import fr.acinq.phoenix.security.PinDialog import fr.acinq.phoenix.utils.* import fr.acinq.phoenix.utils.encrypt.EncryptedSeed import kotlinx.coroutines.* import org.slf4j.Logger import org.slf4j.LoggerFactory class SeedSecurityFragment : BaseFragment() { override val log: Logger = LoggerFactory.getLogger(this::class.java) private lateinit var mBinding: FragmentSettingsSeedSecurityBinding private lateinit var model: SeedSecurityViewModel private var promptPin: PinDialog? = null private var newPin: PinDialog? = null private var confirmPin: PinDialog? = null private var biometricPrompt: BiometricPrompt? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { mBinding = FragmentSettingsSeedSecurityBinding.inflate(inflater, container, false) mBinding.lifecycleOwner = this return mBinding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) model = ViewModelProvider(this).get(SeedSecurityViewModel::class.java) model.protectionState.observe(viewLifecycleOwner, Observer { state -> when (state!!) { SeedSecurityViewModel.ProtectionState.NONE -> { mBinding.pinSwitch.setChecked(false) mBinding.biometricsSwitch.setChecked(false) } SeedSecurityViewModel.ProtectionState.PIN_ONLY -> { mBinding.pinSwitch.setChecked(true) mBinding.biometricsSwitch.setChecked(false) } SeedSecurityViewModel.ProtectionState.PIN_AND_BIOMETRICS -> { mBinding.pinSwitch.setChecked(true) mBinding.biometricsSwitch.setChecked(true) } } }) model.protectionUpdateState.observe(viewLifecycleOwner, Observer { state -> when (state) { SeedSecurityViewModel.ProtectionUpdateState.SET_NEW_PIN -> promptNewPin() else -> Unit } }) model.messageEvent.observe(viewLifecycleOwner, Observer { it?.let { Toast.makeText(context, getString(it), Toast.LENGTH_SHORT).show() } }) mBinding.model = model } override fun onStart() { super.onStart() mBinding.actionBar.setOnBackAction(View.OnClickListener { findNavController().popBackStack() }) mBinding.pinSwitch.setOnClickListener { model.protectionUpdateState.value = SeedSecurityViewModel.ProtectionUpdateState.ENTER_PIN model.readSeed(context, Constants.DEFAULT_PIN) } mBinding.updatePinButton.setOnClickListener { model.protectionUpdateState.value = SeedSecurityViewModel.ProtectionUpdateState.ENTER_PIN promptExistingPin { pin: String -> model.readSeed(context, pin) } } mBinding.biometricsSwitch.setOnClickListener { context?.let { ctx -> when (BiometricManager.from(ctx).canAuthenticate()) { BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> Toast.makeText(context, R.string.seedsec_biometric_support_no_hw, Toast.LENGTH_SHORT).show() BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> Toast.makeText(context, R.string.seedsec_biometric_support_hw_unavailable, Toast.LENGTH_SHORT).show() BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> Toast.makeText(context, R.string.seedsec_biometric_support_none_enrolled, Toast.LENGTH_SHORT).show() BiometricManager.BIOMETRIC_SUCCESS -> if (mBinding.biometricsSwitch.isChecked()) { disableBiometrics(ctx) } else { enrollBiometrics(ctx) } } } } } override fun onResume() { super.onResume() checkState() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) biometricPrompt?.cancelAuthentication() } override fun onStop() { super.onStop() promptPin?.dismiss() newPin?.dismiss() confirmPin?.dismiss() model.protectionUpdateState.value = SeedSecurityViewModel.ProtectionUpdateState.IDLE } private fun checkState() { val isSeedEncrypted = context?.let { ctx -> Prefs.getIsSeedEncrypted(ctx) } ?: true val useBiometrics = context?.let { ctx -> Prefs.useBiometrics(ctx) } ?: false model.protectionState.value = if (isSeedEncrypted) { if (useBiometrics) { SeedSecurityViewModel.ProtectionState.PIN_AND_BIOMETRICS } else { SeedSecurityViewModel.ProtectionState.PIN_ONLY } } else { SeedSecurityViewModel.ProtectionState.NONE } } private fun disableBiometrics(context: Context) { biometricPrompt = getBiometricAuth(R.string.seedsec_disable_bio_prompt_title, R.string.seedsec_disable_bio_prompt_negative, R.string.seedsec_disable_bio_prompt_desc, { model.protectionUpdateState.postValue(SeedSecurityViewModel.ProtectionUpdateState.IDLE) }, { try { Prefs.useBiometrics(context, false) KeystoreHelper.deleteKeyForPin() model.protectionUpdateState.postValue(SeedSecurityViewModel.ProtectionUpdateState.IDLE) model.protectionState.postValue(SeedSecurityViewModel.ProtectionState.PIN_ONLY) model.messageEvent.postValue(R.string.seedsec_biometric_disabled) } catch (e: Exception) { log.error("could not disable bio: ", e) } }) } private fun enrollBiometrics(context: Context) { promptExistingPin { pin: String -> lifecycleScope.launch(CoroutineExceptionHandler { _, exception -> log.error("error when enrolling biometric: ", exception) model.protectionUpdateState.value = SeedSecurityViewModel.ProtectionUpdateState.IDLE model.messageEvent.value = R.string.seedsec_biometric_enrollment_error }) { model.protectionUpdateState.value = SeedSecurityViewModel.ProtectionUpdateState.ENROLLING_BIOMETRICS if (model.checkPIN(context, pin)) { // generate new key for pin code encryption (if necessary remove the old one) KeystoreHelper.deleteKeyForPin() KeystoreHelper.generateKeyForPin() biometricPrompt = getBiometricAuth(R.string.seedsec_bio_prompt_title, R.string.seedsec_bio_prompt_negative, null, { model.protectionUpdateState.postValue(SeedSecurityViewModel.ProtectionUpdateState.IDLE) }, { try { KeystoreHelper.encryptPin(context, pin) Prefs.useBiometrics(context, true) model.protectionUpdateState.postValue(SeedSecurityViewModel.ProtectionUpdateState.IDLE) model.protectionState.postValue(SeedSecurityViewModel.ProtectionState.PIN_AND_BIOMETRICS) model.messageEvent.postValue(R.string.seedsec_biometric_enabled) } catch (e: Exception) { log.error("could not encrypt pin in keystore: ", e) } }) } else { model.protectionUpdateState.value = SeedSecurityViewModel.ProtectionUpdateState.IDLE model.messageEvent.value = R.string.seedsec_error_wrong_pin } } } } private fun promptExistingPin(callback: (pin: String) -> Unit) { promptPin = getPinDialog(R.string.seedsec_pindialog_title_unlock, object : PinDialog.PinDialogCallback { override fun onPinConfirm(dialog: PinDialog, pinCode: String) { callback(pinCode) dialog.dismiss() } override fun onPinCancel(dialog: PinDialog) { model.protectionUpdateState.postValue(SeedSecurityViewModel.ProtectionUpdateState.IDLE) } }) promptPin?.reset() promptPin?.show() } private fun promptNewPin() { newPin = getPinDialog(R.string.seedsec_pindialog_title_set_new, object : PinDialog.PinDialogCallback { override fun onPinConfirm(dialog: PinDialog, pinCode: String) { confirmNewPin(pinCode) dialog.dismiss() } override fun onPinCancel(dialog: PinDialog) { model.protectionUpdateState.value = SeedSecurityViewModel.ProtectionUpdateState.IDLE } }) newPin?.reset() newPin?.show() } private fun confirmNewPin(firstPin: String) { confirmPin = getPinDialog(R.string.seedsec_pindialog_title_confirm_new, object : PinDialog.PinDialogCallback { override fun onPinConfirm(dialog: PinDialog, pinCode: String) { if (pinCode == firstPin) { model.encryptSeed(context, pinCode) } else { model.messageEvent.value = R.string.seedsec_error_pins_match model.protectionUpdateState.value = SeedSecurityViewModel.ProtectionUpdateState.IDLE } dialog.dismiss() } override fun onPinCancel(dialog: PinDialog) { model.protectionUpdateState.value = SeedSecurityViewModel.ProtectionUpdateState.IDLE } }) confirmPin?.reset() confirmPin?.show() } } class SeedSecurityViewModel : ViewModel() { enum class ProtectionUpdateState { ENTER_PIN, SET_NEW_PIN, ENCRYPTING, ENROLLING_BIOMETRICS, IDLE } enum class ProtectionState { NONE, PIN_ONLY, PIN_AND_BIOMETRICS } private val log = LoggerFactory.getLogger(DisplaySeedViewModel::class.java) private val seed = MutableLiveData<ByteArray>(null) val protectionState = MutableLiveData(ProtectionState.NONE) val protectionUpdateState = MutableLiveData(ProtectionUpdateState.IDLE) val messageEvent = SingleLiveEvent<Int>() /** * Check if the PIN is correct */ @UiThread suspend fun checkPIN(context: Context, pin: String): Boolean { return coroutineScope { async(Dispatchers.Default) { try { EncryptedSeed.readSeedFile(context, pin) true } catch (e: Exception) { log.error("pin is not valid: ", e) false } } }.await() } /** * Reads the seed from file and update state */ @UiThread fun readSeed(context: Context?, pin: String) { if (context != null) { viewModelScope.launch { withContext(Dispatchers.Default) { try { seed.postValue(EncryptedSeed.readSeedFile(context, pin)) protectionUpdateState.postValue(ProtectionUpdateState.SET_NEW_PIN) } catch (e: Exception) { log.error("could not read seed: ", e) if (pin == Constants.DEFAULT_PIN) { // preference pin status is probably obsolete Prefs.setIsSeedEncrypted(context) } messageEvent.postValue(R.string.seedsec_error_wrong_pin) protectionUpdateState.postValue(ProtectionUpdateState.IDLE) } } } } } /** * Write a seed to file with a synchronous coroutine */ @UiThread fun encryptSeed(context: Context?, pin: String) { viewModelScope.launch { withContext(Dispatchers.Default) { try { if (protectionUpdateState.value != ProtectionUpdateState.SET_NEW_PIN) { throw java.lang.RuntimeException("cannot encrypt seed in state ${protectionUpdateState.value}") } protectionUpdateState.postValue(ProtectionUpdateState.ENCRYPTING) EncryptedSeed.writeSeedToFile(context!!, seed.value ?: throw RuntimeException("empty seed"), pin) protectionUpdateState.postValue(ProtectionUpdateState.IDLE) protectionState.postValue(ProtectionState.PIN_ONLY) KeystoreHelper.deleteKeyForPin() Prefs.setIsSeedEncrypted(context) Prefs.useBiometrics(context, false) messageEvent.postValue(R.string.seedsec_pin_update_success) } catch (e: java.lang.Exception) { log.error("could not encrypt seed: ", e) messageEvent.postValue(R.string.seedsec_error_generic) protectionUpdateState.postValue(ProtectionUpdateState.IDLE) } } } } }
0
null
1
1
69ac18479c230bfb74ab3eabe6d0c0bd5af11f85
12,808
phoenix
Apache License 2.0
src/main/kotlin/nichrosia/nobreak/type/annotation/data/JsonReadable.kt
NiChrosia
376,650,996
false
null
package nichrosia.nobreak.type.annotation.data import kotlinx.serialization.json.JsonElement interface JsonReadable<R, T> where R : JsonWritable<T>, T : JsonElement { fun fromJson(json: T): R }
0
Kotlin
0
4
488ec8b41dcfa61aa746dc3eaa07ee263c959e4c
199
NoBreak
Creative Commons Zero v1.0 Universal
version-migrator/src/main/java/dylan/kwon/versionMigrator/datastore/VersionMigrationDataStore.kt
dylan-kwon
835,481,492
false
{"Kotlin": 15982}
@file:OptIn(ExperimentalCoroutinesApi::class) package dylan.kwon.versionMigrator.datastore import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.longPreferencesKey import androidx.datastore.preferences.preferencesDataStore import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.mapLatest /** * Data store for saving the version code of the most recently completed migration. (Internal use only) */ internal val Context.dataStore by preferencesDataStore("version-migration") /** * Default value if no migrations have been performed yet. */ internal const val UNINITIALIZED_VERSION_CODE = -1L /** * Data Store Keys. */ private object Key { val LATEST_VERSION_CODE = longPreferencesKey("latest_version_code") } /** * Version code of the last performed migration. */ internal val DataStore<Preferences>.latestVersionCode: Flow<Long> get() = data.mapLatest { it[Key.LATEST_VERSION_CODE] ?: UNINITIALIZED_VERSION_CODE } /** * Update [latestVersionCode]. */ internal suspend fun DataStore<Preferences>.updateLatestVersion(versionCode: Long) { edit { pref -> pref[Key.LATEST_VERSION_CODE] = versionCode } }
0
Kotlin
0
0
925b8607d09c04aad9e0fd998a91bcf99d64b827
1,379
android-version-migrator
Apache License 2.0
partiql-lang/src/main/kotlin/org/partiql/lang/syntax/impl/PartiQLPigVisitor.kt
partiql
186,474,394
false
null
/* * Copyright Amazon.com, Inc. or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at: * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package org.partiql.lang.syntax.impl import com.amazon.ion.Decimal import com.amazon.ionelement.api.DecimalElement import com.amazon.ionelement.api.FloatElement import com.amazon.ionelement.api.IntElement import com.amazon.ionelement.api.IntElementSize import com.amazon.ionelement.api.IonElement import com.amazon.ionelement.api.IonElementException import com.amazon.ionelement.api.MetaContainer import com.amazon.ionelement.api.StringElement import com.amazon.ionelement.api.SymbolElement import com.amazon.ionelement.api.emptyMetaContainer import com.amazon.ionelement.api.ionBool import com.amazon.ionelement.api.ionDecimal import com.amazon.ionelement.api.ionFloat import com.amazon.ionelement.api.ionInt import com.amazon.ionelement.api.ionNull import com.amazon.ionelement.api.ionString import com.amazon.ionelement.api.ionSymbol import com.amazon.ionelement.api.loadSingleElement import org.antlr.v4.runtime.ParserRuleContext import org.antlr.v4.runtime.Token import org.antlr.v4.runtime.tree.ErrorNode import org.antlr.v4.runtime.tree.RuleNode import org.antlr.v4.runtime.tree.TerminalNode import org.partiql.lang.ast.IsCountStarMeta import org.partiql.lang.ast.IsImplictJoinMeta import org.partiql.lang.ast.IsIonLiteralMeta import org.partiql.lang.ast.IsListParenthesizedMeta import org.partiql.lang.ast.IsPathIndexMeta import org.partiql.lang.ast.IsValuesExprMeta import org.partiql.lang.ast.LegacyLogicalNotMeta import org.partiql.lang.ast.SourceLocationMeta import org.partiql.lang.domains.PartiqlAst import org.partiql.lang.domains.metaContainerOf import org.partiql.lang.errors.ErrorCode import org.partiql.lang.errors.Property import org.partiql.lang.errors.PropertyValueMap import org.partiql.lang.eval.EvaluationException import org.partiql.lang.eval.time.MAX_PRECISION_FOR_TIME import org.partiql.lang.syntax.ParserException import org.partiql.lang.syntax.util.DateTimeUtils import org.partiql.lang.types.CustomType import org.partiql.lang.util.DATE_PATTERN_REGEX import org.partiql.lang.util.bigDecimalOf import org.partiql.lang.util.checkThreadInterrupted import org.partiql.lang.util.error import org.partiql.lang.util.getPrecisionFromTimeString import org.partiql.lang.util.unaryMinus import org.partiql.parser.antlr.PartiQLBaseVisitor import org.partiql.parser.antlr.PartiQLParser import org.partiql.pig.runtime.SymbolPrimitive import org.partiql.value.datetime.DateTimeException import org.partiql.value.datetime.TimeZone import java.math.BigInteger import java.time.LocalDate import java.time.LocalTime import java.time.OffsetTime import java.time.format.DateTimeFormatter import java.time.format.DateTimeParseException import kotlin.reflect.KClass import kotlin.reflect.cast /** * Extends ANTLR's generated [PartiQLBaseVisitor] to visit an ANTLR ParseTree and convert it into a PartiQL AST. This * class uses the [PartiqlAst.PartiqlAstNode] to represent all nodes within the new AST. */ internal class PartiQLPigVisitor( val customTypes: List<CustomType> = listOf(), private val parameterIndexes: Map<Int, Int> = mapOf() ) : PartiQLBaseVisitor<PartiqlAst.PartiqlAstNode>() { companion object { internal val TRIM_SPECIFICATION_KEYWORDS = setOf("both", "leading", "trailing") } private val customKeywords = customTypes.map { it.name.lowercase() } private val customTypeAliases = customTypes.map { customType -> customType.aliases.map { alias -> Pair(alias.lowercase(), customType.name.lowercase()) } }.flatten().toMap() /** * * TOP LEVEL * */ override fun visitQueryDql(ctx: PartiQLParser.QueryDqlContext) = visitDql(ctx.dql()) override fun visitQueryDml(ctx: PartiQLParser.QueryDmlContext): PartiqlAst.PartiqlAstNode = visit(ctx.dml()) override fun visitExprTermCurrentUser(ctx: PartiQLParser.ExprTermCurrentUserContext): PartiqlAst.Expr.SessionAttribute { val metas = ctx.CURRENT_USER().getSourceMetaContainer() return PartiqlAst.Expr.SessionAttribute( value = SymbolPrimitive(ctx.CURRENT_USER().text.toLowerCase(), metas), metas = metas ) } override fun visitRoot(ctx: PartiQLParser.RootContext) = when (ctx.EXPLAIN()) { null -> visit(ctx.statement()) as PartiqlAst.Statement else -> PartiqlAst.build { var type: String? = null var format: String? = null val metas = ctx.EXPLAIN().getSourceMetaContainer() ctx.explainOption().forEach { option -> val parameter = try { ExplainParameters.valueOf(option.param.text.toUpperCase()) } catch (ex: IllegalArgumentException) { throw option.param.error("Unknown EXPLAIN parameter.", ErrorCode.PARSE_UNEXPECTED_TOKEN, cause = ex) } when (parameter) { ExplainParameters.TYPE -> { type = parameter.getCompliantString(type, option.value) } ExplainParameters.FORMAT -> { format = parameter.getCompliantString(format, option.value) } } } explain( target = domain( statement = visit(ctx.statement()) as PartiqlAst.Statement, type = type, format = format, metas = metas ), metas = metas ) } } /** * * COMMON USAGES * */ override fun visitAsIdent(ctx: PartiQLParser.AsIdentContext) = visitSymbolPrimitive(ctx.symbolPrimitive()) override fun visitAtIdent(ctx: PartiQLParser.AtIdentContext) = visitSymbolPrimitive(ctx.symbolPrimitive()) override fun visitByIdent(ctx: PartiQLParser.ByIdentContext) = visitSymbolPrimitive(ctx.symbolPrimitive()) override fun visitSymbolPrimitive(ctx: PartiQLParser.SymbolPrimitiveContext) = PartiqlAst.build { val metas = ctx.ident.getSourceMetaContainer() when (ctx.ident.type) { PartiQLParser.IDENTIFIER_QUOTED -> id( ctx.IDENTIFIER_QUOTED().getStringValue(), caseSensitive(), unqualified(), metas ) PartiQLParser.IDENTIFIER -> id(ctx.IDENTIFIER().getStringValue(), caseInsensitive(), unqualified(), metas) else -> throw ParserException("Invalid symbol reference.", ErrorCode.PARSE_INVALID_QUERY) } } /** * * DATA DEFINITION LANGUAGE (DDL) * */ override fun visitQueryDdl(ctx: PartiQLParser.QueryDdlContext) = PartiqlAst.build { val op = visitDdl(ctx.ddl()) as PartiqlAst.DdlOp ddl(op, op.metas) } override fun visitDropTable(ctx: PartiQLParser.DropTableContext) = PartiqlAst.build { val id = visitSymbolPrimitive(ctx.tableName().symbolPrimitive()) dropTable(id.toIdentifier(), ctx.DROP().getSourceMetaContainer()) } override fun visitDropIndex(ctx: PartiQLParser.DropIndexContext) = PartiqlAst.build { val id = visitSymbolPrimitive(ctx.target) val key = visitSymbolPrimitive(ctx.on) dropIndex(key.toIdentifier(), id.toIdentifier(), ctx.DROP().getSourceMetaContainer()) } override fun visitCreateTable(ctx: PartiQLParser.CreateTableContext) = PartiqlAst.build { val name = visitSymbolPrimitive(ctx.tableName().symbolPrimitive()).name val def = ctx.tableDef()?.let { visitTableDef(it) } createTable_(name, def, ctx.CREATE().getSourceMetaContainer()) } override fun visitCreateIndex(ctx: PartiQLParser.CreateIndexContext) = PartiqlAst.build { val id = visitSymbolPrimitive(ctx.symbolPrimitive()) val fields = ctx.pathSimple().map { path -> visitPathSimple(path) } createIndex(id.toIdentifier(), fields, ctx.CREATE().getSourceMetaContainer()) } override fun visitTableDef(ctx: PartiQLParser.TableDefContext) = PartiqlAst.build { val parts = visitOrEmpty(ctx.tableDefPart(), PartiqlAst.TableDefPart::class) tableDef(parts) } override fun visitColumnDeclaration(ctx: PartiQLParser.ColumnDeclarationContext) = PartiqlAst.build { val name = visitSymbolPrimitive(ctx.columnName().symbolPrimitive()).name.text val type = visit(ctx.type(), PartiqlAst.Type::class) val constrs = ctx.columnConstraint().map { visitColumnConstraint(it) } columnDeclaration(name, type, constrs) } override fun visitColumnConstraint(ctx: PartiQLParser.ColumnConstraintContext) = PartiqlAst.build { val name = ctx.columnConstraintName()?.let { visitSymbolPrimitive(it.symbolPrimitive()).name.text } val def = visit(ctx.columnConstraintDef(), PartiqlAst.ColumnConstraintDef::class) columnConstraint(name, def) } override fun visitColConstrNotNull(ctx: PartiQLParser.ColConstrNotNullContext) = PartiqlAst.build { columnNotnull() } override fun visitColConstrNull(ctx: PartiQLParser.ColConstrNullContext) = PartiqlAst.build { columnNull() } /** * * EXECUTE * */ override fun visitQueryExec(ctx: PartiQLParser.QueryExecContext) = visitExecCommand(ctx.execCommand()) override fun visitExecCommand(ctx: PartiQLParser.ExecCommandContext) = PartiqlAst.build { val name = visitExpr(ctx.name).getStringValue(ctx.name.getStart()) val args = visitOrEmpty(ctx.args, PartiqlAst.Expr::class) exec_( SymbolPrimitive(name.lowercase(), emptyMetaContainer()), args, ctx.name.getStart().getSourceMetaContainer() ) } /** * * DATA MANIPULATION LANGUAGE (DML) * */ override fun visitDmlBaseWrapper(ctx: PartiQLParser.DmlBaseWrapperContext) = PartiqlAst.build { val sourceContext = when { ctx.updateClause() != null -> ctx.updateClause() ctx.fromClause() != null -> ctx.fromClause() else -> throw ParserException("Unable to deduce from source in DML", ErrorCode.PARSE_INVALID_QUERY) } val from = visitOrNull(sourceContext, PartiqlAst.FromSource::class) val where = visitOrNull(ctx.whereClause(), PartiqlAst.Expr::class) val returning = visitOrNull(ctx.returningClause(), PartiqlAst.ReturningExpr::class) val operations = ctx.dmlBaseCommand().map { command -> getCommandList(visit(command)) }.flatten() dml(dmlOpList(operations, operations[0].metas), from, where, returning, metas = operations[0].metas) } override fun visitDmlBase(ctx: PartiQLParser.DmlBaseContext) = PartiqlAst.build { val commands = getCommandList(visit(ctx.dmlBaseCommand())) dml(dmlOpList(commands, commands[0].metas), metas = commands[0].metas) } private fun getCommandList(command: PartiqlAst.PartiqlAstNode): List<PartiqlAst.DmlOp> { return when (command) { is PartiqlAst.DmlOpList -> command.ops is PartiqlAst.DmlOp -> listOf(command) else -> throw ParserException("Unable to grab DML operation.", ErrorCode.PARSE_INVALID_QUERY) } } override fun visitRemoveCommand(ctx: PartiQLParser.RemoveCommandContext) = PartiqlAst.build { val target = visitPathSimple(ctx.pathSimple()) remove(target, ctx.REMOVE().getSourceMetaContainer()) } override fun visitDeleteCommand(ctx: PartiQLParser.DeleteCommandContext) = PartiqlAst.build { val from = visit(ctx.fromClauseSimple(), PartiqlAst.FromSource::class) val where = visitOrNull(ctx.whereClause(), PartiqlAst.Expr::class) val returning = visitOrNull(ctx.returningClause(), PartiqlAst.ReturningExpr::class) dml( dmlOpList(delete(ctx.DELETE().getSourceMetaContainer()), metas = ctx.DELETE().getSourceMetaContainer()), from, where, returning, ctx.DELETE().getSourceMetaContainer() ) } override fun visitInsertStatementLegacy(ctx: PartiQLParser.InsertStatementLegacyContext) = PartiqlAst.build { val metas = ctx.INSERT().getSourceMetaContainer() val target = visitPathSimple(ctx.pathSimple()) val index = visitOrNull(ctx.pos, PartiqlAst.Expr::class) val onConflict = ctx.onConflictLegacy()?.let { visitOnConflictLegacy(it) } insertValue(target, visit(ctx.value, PartiqlAst.Expr::class), index, onConflict, metas) } override fun visitInsertStatement(ctx: PartiQLParser.InsertStatementContext) = PartiqlAst.build { insert( target = visitSymbolPrimitive(ctx.symbolPrimitive()), asAlias = visitOrNull(ctx.asIdent(), PartiqlAst.Expr.Id::class)?.name?.text, values = visit(ctx.value, PartiqlAst.Expr::class), conflictAction = ctx.onConflict()?.let { visitOnConflict(it) }, metas = ctx.INSERT().getSourceMetaContainer() ) } override fun visitReplaceCommand(ctx: PartiQLParser.ReplaceCommandContext) = PartiqlAst.build { insert( target = visitSymbolPrimitive(ctx.symbolPrimitive()), asAlias = visitOrNull(ctx.asIdent(), PartiqlAst.Expr.Id::class)?.name?.text, values = visit(ctx.value, PartiqlAst.Expr::class), conflictAction = doReplace(excluded()), metas = ctx.REPLACE().getSourceMetaContainer() ) } // Based on https://github.com/partiql/partiql-docs/blob/main/RFCs/0011-partiql-insert.md override fun visitUpsertCommand(ctx: PartiQLParser.UpsertCommandContext) = PartiqlAst.build { insert( target = visitSymbolPrimitive(ctx.symbolPrimitive()), asAlias = visitOrNull(ctx.asIdent(), PartiqlAst.Expr.Id::class)?.name?.text, values = visit(ctx.value, PartiqlAst.Expr::class), conflictAction = doUpdate(excluded()), metas = ctx.UPSERT().getSourceMetaContainer() ) } // Based on https://github.com/partiql/partiql-docs/blob/main/RFCs/0011-partiql-insert.md override fun visitInsertCommandReturning(ctx: PartiQLParser.InsertCommandReturningContext) = PartiqlAst.build { val metas = ctx.INSERT().getSourceMetaContainer() val target = visitPathSimple(ctx.pathSimple()) val index = visitOrNull(ctx.pos, PartiqlAst.Expr::class) val onConflictLegacy = ctx.onConflictLegacy()?.let { visitOnConflictLegacy(it) } val returning = visitOrNull(ctx.returningClause(), PartiqlAst.ReturningExpr::class) dml( dmlOpList( insertValue( target, visit(ctx.value, PartiqlAst.Expr::class), index = index, onConflict = onConflictLegacy, ctx.INSERT().getSourceMetaContainer() ), metas = metas ), returning = returning, metas = metas ) } override fun visitReturningClause(ctx: PartiQLParser.ReturningClauseContext) = PartiqlAst.build { val elements = visitOrEmpty(ctx.returningColumn(), PartiqlAst.ReturningElem::class) returningExpr(elements, ctx.RETURNING().getSourceMetaContainer()) } private fun getReturningMapping(status: Token, age: Token) = PartiqlAst.build { when { status.type == PartiQLParser.MODIFIED && age.type == PartiQLParser.NEW -> modifiedNew() status.type == PartiQLParser.MODIFIED && age.type == PartiQLParser.OLD -> modifiedOld() status.type == PartiQLParser.ALL && age.type == PartiQLParser.NEW -> allNew() status.type == PartiQLParser.ALL && age.type == PartiQLParser.OLD -> allOld() else -> throw status.err("Unable to get return mapping.", ErrorCode.PARSE_UNEXPECTED_TOKEN) } } override fun visitReturningColumn(ctx: PartiQLParser.ReturningColumnContext) = PartiqlAst.build { val column = when (ctx.ASTERISK()) { null -> returningColumn(visitExpr(ctx.expr())) else -> returningWildcard() } returningElem(getReturningMapping(ctx.status, ctx.age), column) } override fun visitOnConflict(ctx: PartiQLParser.OnConflictContext) = PartiqlAst.build { visit(ctx.conflictAction(), PartiqlAst.ConflictAction::class) } override fun visitOnConflictLegacy(ctx: PartiQLParser.OnConflictLegacyContext) = PartiqlAst.build { onConflict( expr = visitExpr(ctx.expr()), conflictAction = doNothing(), metas = ctx.ON().getSourceMetaContainer() ) } override fun visitConflictAction(ctx: PartiQLParser.ConflictActionContext) = PartiqlAst.build { when { ctx.NOTHING() != null -> doNothing() ctx.REPLACE() != null -> visitDoReplace(ctx.doReplace()) ctx.UPDATE() != null -> visitDoUpdate(ctx.doUpdate()) else -> TODO("ON CONFLICT only supports `DO REPLACE` and `DO NOTHING` actions at the moment.") } } override fun visitDoReplace(ctx: PartiQLParser.DoReplaceContext) = PartiqlAst.build { val value = when { ctx.EXCLUDED() != null -> excluded() else -> TODO("DO REPLACE doesn't support values other than `EXCLUDED` yet.") } val condition = visitOrNull(ctx.condition, PartiqlAst.Expr::class) doReplace(value, condition) } override fun visitDoUpdate(ctx: PartiQLParser.DoUpdateContext) = PartiqlAst.build { val value = when { ctx.EXCLUDED() != null -> excluded() else -> TODO("DO UPDATE doesn't support values other than `EXCLUDED` yet.") } val condition = visitOrNull(ctx.condition, PartiqlAst.Expr::class) doUpdate(value, condition) } override fun visitPathSimple(ctx: PartiQLParser.PathSimpleContext) = PartiqlAst.build { val root = visitSymbolPrimitive(ctx.symbolPrimitive()) if (ctx.pathSimpleSteps().isEmpty()) return@build root val steps = visitOrEmpty(ctx.pathSimpleSteps(), PartiqlAst.PathStep::class) path(root, steps, root.metas) } override fun visitPathSimpleLiteral(ctx: PartiQLParser.PathSimpleLiteralContext) = PartiqlAst.build { pathExpr(visit(ctx.literal()) as PartiqlAst.Expr, caseSensitive()) } override fun visitPathSimpleSymbol(ctx: PartiQLParser.PathSimpleSymbolContext) = PartiqlAst.build { pathExpr(visitSymbolPrimitive(ctx.symbolPrimitive()), caseSensitive()) } override fun visitPathSimpleDotSymbol(ctx: PartiQLParser.PathSimpleDotSymbolContext) = getSymbolPathExpr(ctx.symbolPrimitive()) override fun visitSetCommand(ctx: PartiQLParser.SetCommandContext) = PartiqlAst.build { val assignments = visitOrEmpty(ctx.setAssignment(), PartiqlAst.DmlOp.Set::class) val newSets = assignments.map { assignment -> assignment.copy(metas = ctx.SET().getSourceMetaContainer()) } dmlOpList(newSets, ctx.SET().getSourceMetaContainer()) } override fun visitSetAssignment(ctx: PartiQLParser.SetAssignmentContext) = PartiqlAst.build { set(assignment(visitPathSimple(ctx.pathSimple()), visitExpr(ctx.expr()))) } override fun visitUpdateClause(ctx: PartiQLParser.UpdateClauseContext) = visit(ctx.tableBaseReference(), PartiqlAst.FromSource::class) /** * * DATA QUERY LANGUAGE (DQL) * */ override fun visitDql(ctx: PartiQLParser.DqlContext) = PartiqlAst.build { val query = visit(ctx.expr(), PartiqlAst.Expr::class) query(query, query.metas) } override fun visitQueryBase(ctx: PartiQLParser.QueryBaseContext) = visit(ctx.exprSelect(), PartiqlAst.Expr::class) override fun visitSfwQuery(ctx: PartiQLParser.SfwQueryContext) = PartiqlAst.build { val projection = visit(ctx.select, PartiqlAst.Projection::class) val strategy = getSetQuantifierStrategy(ctx.select) val from = visitFromClause(ctx.from) val order = visitOrNull(ctx.order, PartiqlAst.OrderBy::class) val group = visitOrNull(ctx.group, PartiqlAst.GroupBy::class) val limit = visitOrNull(ctx.limit, PartiqlAst.Expr::class) val offset = visitOrNull(ctx.offset, PartiqlAst.Expr::class) val where = visitOrNull(ctx.where, PartiqlAst.Expr::class) val having = visitOrNull(ctx.having, PartiqlAst.Expr::class) val let = visitOrNull(ctx.let, PartiqlAst.Let::class) val metas = ctx.selectClause().getMetas() select( project = projection, from = from, setq = strategy, order = order, group = group, limit = limit, offset = offset, where = where, having = having, fromLet = let, metas = metas ) } /** * * SELECT & PROJECTIONS * */ override fun visitSetQuantifierStrategy(ctx: PartiQLParser.SetQuantifierStrategyContext?): PartiqlAst.SetQuantifier? = when { ctx == null -> null ctx.DISTINCT() != null -> PartiqlAst.SetQuantifier.Distinct() ctx.ALL() != null -> PartiqlAst.SetQuantifier.All() else -> null } override fun visitSelectAll(ctx: PartiQLParser.SelectAllContext) = PartiqlAst.build { projectStar(ctx.ASTERISK().getSourceMetaContainer()) } override fun visitSelectItems(ctx: PartiQLParser.SelectItemsContext) = convertProjectionItems(ctx.projectionItems(), ctx.SELECT().getSourceMetaContainer()) override fun visitSelectPivot(ctx: PartiQLParser.SelectPivotContext) = PartiqlAst.build { projectPivot(visitExpr(ctx.at), visitExpr(ctx.pivot)) } override fun visitSelectValue(ctx: PartiQLParser.SelectValueContext) = PartiqlAst.build { projectValue(visitExpr(ctx.expr())) } override fun visitProjectionItem(ctx: PartiQLParser.ProjectionItemContext) = PartiqlAst.build { val expr = visit(ctx.expr(), PartiqlAst.Expr::class) val alias = visitOrNull(ctx.symbolPrimitive(), PartiqlAst.Expr.Id::class)?.name if (expr is PartiqlAst.Expr.Path) convertPathToProjectionItem(expr, alias) else projectExpr_(expr, asAlias = alias, expr.metas) } /** * * SIMPLE CLAUSES * */ override fun visitLimitClause(ctx: PartiQLParser.LimitClauseContext): PartiqlAst.Expr = visit(ctx.arg, PartiqlAst.Expr::class) override fun visitExpr(ctx: PartiQLParser.ExprContext): PartiqlAst.Expr { checkThreadInterrupted() return visit(ctx.exprBagOp(), PartiqlAst.Expr::class) } override fun visitOffsetByClause(ctx: PartiQLParser.OffsetByClauseContext) = visit(ctx.arg, PartiqlAst.Expr::class) override fun visitWhereClause(ctx: PartiQLParser.WhereClauseContext) = visitExpr(ctx.arg) override fun visitWhereClauseSelect(ctx: PartiQLParser.WhereClauseSelectContext) = visit(ctx.arg, PartiqlAst.Expr::class) override fun visitHavingClause(ctx: PartiQLParser.HavingClauseContext) = visit(ctx.arg, PartiqlAst.Expr::class) /** * * LET CLAUSE * */ override fun visitLetClause(ctx: PartiQLParser.LetClauseContext) = PartiqlAst.build { val letBindings = visitOrEmpty(ctx.letBinding(), PartiqlAst.LetBinding::class) let(letBindings) } override fun visitLetBinding(ctx: PartiQLParser.LetBindingContext) = PartiqlAst.build { val expr = visit(ctx.expr(), PartiqlAst.Expr::class) val metas = ctx.symbolPrimitive().getSourceMetaContainer() letBinding_(expr, convertSymbolPrimitive(ctx.symbolPrimitive())!!, metas) } /** * * ORDER BY CLAUSE * */ override fun visitOrderByClause(ctx: PartiQLParser.OrderByClauseContext) = PartiqlAst.build { val sortSpecs = visitOrEmpty(ctx.orderSortSpec(), PartiqlAst.SortSpec::class) val metas = ctx.ORDER().getSourceMetaContainer() orderBy(sortSpecs, metas) } override fun visitOrderSortSpec(ctx: PartiQLParser.OrderSortSpecContext) = PartiqlAst.build { val expr = visit(ctx.expr(), PartiqlAst.Expr::class) val orderSpec = when { ctx.dir == null -> null ctx.dir.type == PartiQLParser.ASC -> asc() ctx.dir.type == PartiQLParser.DESC -> desc() else -> throw ctx.dir.err("Invalid query syntax", ErrorCode.PARSE_INVALID_QUERY) } val nullSpec = when { ctx.nulls == null -> null ctx.nulls.type == PartiQLParser.FIRST -> nullsFirst() ctx.nulls.type == PartiQLParser.LAST -> nullsLast() else -> throw ctx.dir.err("Invalid query syntax", ErrorCode.PARSE_INVALID_QUERY) } sortSpec(expr, orderingSpec = orderSpec, nullsSpec = nullSpec) } /** * * GROUP BY CLAUSE * */ override fun visitGroupClause(ctx: PartiQLParser.GroupClauseContext) = PartiqlAst.build { val strategy = if (ctx.PARTIAL() != null) groupPartial() else groupFull() val keys = visitOrEmpty(ctx.groupKey(), PartiqlAst.GroupKey::class) val keyList = groupKeyList(keys) val alias = visitOrNull(ctx.groupAlias(), PartiqlAst.Expr.Id::class).toPigSymbolPrimitive() groupBy_(strategy, keyList = keyList, groupAsAlias = alias, ctx.GROUP().getSourceMetaContainer()) } override fun visitGroupAlias(ctx: PartiQLParser.GroupAliasContext) = visitSymbolPrimitive(ctx.symbolPrimitive()) /** * Returns a GROUP BY key * TODO: Support ordinal case. Also, the conditional defining the exception is odd. 1 + 1 is allowed, but 2 is not. * This is to match the functionality of SqlParser, but this should likely be adjusted. */ override fun visitGroupKey(ctx: PartiQLParser.GroupKeyContext) = PartiqlAst.build { val expr = visit(ctx.key, PartiqlAst.Expr::class) val possibleLiteral = when (expr) { is PartiqlAst.Expr.Pos -> expr.expr is PartiqlAst.Expr.Neg -> expr.expr else -> expr } if ( (possibleLiteral is PartiqlAst.Expr.Lit && possibleLiteral.value != ionNull()) || possibleLiteral is PartiqlAst.Expr.LitTime || possibleLiteral is PartiqlAst.Expr.Date ) { throw ctx.key.getStart().err( "Literals (including ordinals) not supported in GROUP BY", ErrorCode.PARSE_UNSUPPORTED_LITERALS_GROUPBY ) } val alias = visitOrNull(ctx.symbolPrimitive(), PartiqlAst.Expr.Id::class).toPigSymbolPrimitive() groupKey_(expr, asAlias = alias, expr.metas) } /** * * BAG OPERATIONS * */ override fun visitIntersect(ctx: PartiQLParser.IntersectContext) = PartiqlAst.build { val lhs = visit(ctx.lhs, PartiqlAst.Expr::class) val rhs = visit(ctx.rhs, PartiqlAst.Expr::class) val quantifier = if (ctx.ALL() != null) all() else distinct() val (intersect, metas) = when (ctx.OUTER()) { null -> intersect() to ctx.INTERSECT().getSourceMetaContainer() else -> outerIntersect() to ctx.OUTER().getSourceMetaContainer() } bagOp(intersect, quantifier, listOf(lhs, rhs), metas) } override fun visitExcept(ctx: PartiQLParser.ExceptContext) = PartiqlAst.build { val lhs = visit(ctx.lhs, PartiqlAst.Expr::class) val rhs = visit(ctx.rhs, PartiqlAst.Expr::class) val quantifier = if (ctx.ALL() != null) all() else distinct() val (except, metas) = when (ctx.OUTER()) { null -> except() to ctx.EXCEPT().getSourceMetaContainer() else -> outerExcept() to ctx.OUTER().getSourceMetaContainer() } bagOp(except, quantifier, listOf(lhs, rhs), metas) } override fun visitUnion(ctx: PartiQLParser.UnionContext) = PartiqlAst.build { val lhs = visit(ctx.lhs, PartiqlAst.Expr::class) val rhs = visit(ctx.rhs, PartiqlAst.Expr::class) val quantifier = if (ctx.ALL() != null) all() else distinct() val (union, metas) = when (ctx.OUTER()) { null -> union() to ctx.UNION().getSourceMetaContainer() else -> outerUnion() to ctx.OUTER().getSourceMetaContainer() } bagOp(union, quantifier, listOf(lhs, rhs), metas) } /** * * GRAPH PATTERN MANIPULATION LANGUAGE (GPML) * */ override fun visitGpmlPattern(ctx: PartiQLParser.GpmlPatternContext) = PartiqlAst.build { val selector = visitOrNull(ctx.matchSelector(), PartiqlAst.GraphMatchSelector::class) val pattern = visitMatchPattern(ctx.matchPattern()) gpmlPattern(selector, listOf(pattern)) } override fun visitGpmlPatternList(ctx: PartiQLParser.GpmlPatternListContext) = PartiqlAst.build { val selector = visitOrNull(ctx.matchSelector(), PartiqlAst.GraphMatchSelector::class) val patterns = ctx.matchPattern().map { pattern -> visitMatchPattern(pattern) } gpmlPattern(selector, patterns) } override fun visitMatchPattern(ctx: PartiQLParser.MatchPatternContext) = PartiqlAst.build { val parts = visitOrEmpty(ctx.graphPart(), PartiqlAst.GraphMatchPatternPart::class) val restrictor = visitOrNull(ctx.restrictor, PartiqlAst.GraphMatchRestrictor::class) val variable = visitOrNull(ctx.variable, PartiqlAst.Expr.Id::class)?.name graphMatchPattern_(parts = parts, restrictor = restrictor, variable = variable) } override fun visitPatternPathVariable(ctx: PartiQLParser.PatternPathVariableContext) = visitSymbolPrimitive(ctx.symbolPrimitive()) override fun visitSelectorBasic(ctx: PartiQLParser.SelectorBasicContext) = PartiqlAst.build { val metas = ctx.mod.getSourceMetaContainer() when (ctx.mod.type) { PartiQLParser.ANY -> selectorAnyShortest(metas) PartiQLParser.ALL -> selectorAllShortest(metas) else -> throw ParserException("Unsupported match selector.", ErrorCode.PARSE_INVALID_QUERY) } } override fun visitSelectorAny(ctx: PartiQLParser.SelectorAnyContext) = PartiqlAst.build { val metas = ctx.ANY().getSourceMetaContainer() when (ctx.k) { null -> selectorAny(metas) else -> selectorAnyK(ctx.k.text.toLong(), metas) } } override fun visitSelectorShortest(ctx: PartiQLParser.SelectorShortestContext) = PartiqlAst.build { val k = ctx.k.text.toLong() val metas = ctx.k.getSourceMetaContainer() when (ctx.GROUP()) { null -> selectorShortestK(k, metas) else -> selectorShortestKGroup(k, metas) } } override fun visitPatternPartLabel(ctx: PartiQLParser.PatternPartLabelContext) = visitSymbolPrimitive(ctx.symbolPrimitive()) override fun visitPattern(ctx: PartiQLParser.PatternContext) = PartiqlAst.build { val restrictor = visitOrNull(ctx.restrictor, PartiqlAst.GraphMatchRestrictor::class) val variable = visitOrNull(ctx.variable, PartiqlAst.Expr.Id::class)?.name val prefilter = visitOrNull(ctx.where, PartiqlAst.Expr::class) val quantifier = visitOrNull(ctx.quantifier, PartiqlAst.GraphMatchQuantifier::class) val parts = visitOrEmpty(ctx.graphPart(), PartiqlAst.GraphMatchPatternPart::class) pattern( graphMatchPattern_( parts = parts, variable = variable, restrictor = restrictor, quantifier = quantifier, prefilter = prefilter ) ) } override fun visitEdgeAbbreviated(ctx: PartiQLParser.EdgeAbbreviatedContext) = PartiqlAst.build { val direction = visitEdgeAbbrev(ctx.edgeAbbrev()) val quantifier = visitOrNull(ctx.quantifier, PartiqlAst.GraphMatchQuantifier::class) edge(direction = direction, quantifier = quantifier) } override fun visitEdgeWithSpec(ctx: PartiQLParser.EdgeWithSpecContext) = PartiqlAst.build { val quantifier = visitOrNull(ctx.quantifier, PartiqlAst.GraphMatchQuantifier::class) val edge = visitOrNull(ctx.edgeWSpec(), PartiqlAst.GraphMatchPatternPart.Edge::class) edge!!.copy(quantifier = quantifier) } override fun visitEdgeSpec(ctx: PartiQLParser.EdgeSpecContext) = PartiqlAst.build { val placeholderDirection = edgeRight() val variable = visitOrNull(ctx.symbolPrimitive(), PartiqlAst.Expr.Id::class)?.name val prefilter = visitOrNull(ctx.whereClause(), PartiqlAst.Expr::class) val label = visitOrNull(ctx.patternPartLabel(), PartiqlAst.Expr.Id::class)?.name edge_( direction = placeholderDirection, variable = variable, prefilter = prefilter, label = listOfNotNull(label) ) } override fun visitEdgeSpecLeft(ctx: PartiQLParser.EdgeSpecLeftContext) = PartiqlAst.build { val edge = visitEdgeSpec(ctx.edgeSpec()) edge.copy(direction = edgeLeft()) } override fun visitEdgeSpecRight(ctx: PartiQLParser.EdgeSpecRightContext) = PartiqlAst.build { val edge = visitEdgeSpec(ctx.edgeSpec()) edge.copy(direction = edgeRight()) } override fun visitEdgeSpecBidirectional(ctx: PartiQLParser.EdgeSpecBidirectionalContext) = PartiqlAst.build { val edge = visitEdgeSpec(ctx.edgeSpec()) edge.copy(direction = edgeLeftOrRight()) } override fun visitEdgeSpecUndirectedBidirectional(ctx: PartiQLParser.EdgeSpecUndirectedBidirectionalContext) = PartiqlAst.build { val edge = visitEdgeSpec(ctx.edgeSpec()) edge.copy(direction = edgeLeftOrUndirectedOrRight()) } override fun visitEdgeSpecUndirected(ctx: PartiQLParser.EdgeSpecUndirectedContext) = PartiqlAst.build { val edge = visitEdgeSpec(ctx.edgeSpec()) edge.copy(direction = edgeUndirected()) } override fun visitEdgeSpecUndirectedLeft(ctx: PartiQLParser.EdgeSpecUndirectedLeftContext) = PartiqlAst.build { val edge = visitEdgeSpec(ctx.edgeSpec()) edge.copy(direction = edgeLeftOrUndirected()) } override fun visitEdgeSpecUndirectedRight(ctx: PartiQLParser.EdgeSpecUndirectedRightContext) = PartiqlAst.build { val edge = visitEdgeSpec(ctx.edgeSpec()) edge.copy(direction = edgeUndirectedOrRight()) } override fun visitEdgeAbbrev(ctx: PartiQLParser.EdgeAbbrevContext) = PartiqlAst.build { when { ctx.TILDE() != null && ctx.ANGLE_RIGHT() != null -> edgeUndirectedOrRight() ctx.TILDE() != null && ctx.ANGLE_LEFT() != null -> edgeLeftOrUndirected() ctx.TILDE() != null -> edgeUndirected() ctx.MINUS() != null && ctx.ANGLE_LEFT() != null && ctx.ANGLE_RIGHT() != null -> edgeLeftOrRight() ctx.MINUS() != null && ctx.ANGLE_LEFT() != null -> edgeLeft() ctx.MINUS() != null && ctx.ANGLE_RIGHT() != null -> edgeRight() ctx.MINUS() != null -> edgeLeftOrUndirectedOrRight() else -> throw ParserException("Unsupported edge type", ErrorCode.PARSE_INVALID_QUERY) } } override fun visitPatternQuantifier(ctx: PartiQLParser.PatternQuantifierContext) = PartiqlAst.build { when { ctx.quant == null -> graphMatchQuantifier(ctx.lower.text.toLong(), ctx.upper?.text?.toLong()) ctx.quant.type == PartiQLParser.PLUS -> graphMatchQuantifier(1L) ctx.quant.type == PartiQLParser.ASTERISK -> graphMatchQuantifier(0L) else -> throw ParserException("Unsupported quantifier", ErrorCode.PARSE_INVALID_QUERY) } } override fun visitNode(ctx: PartiQLParser.NodeContext) = PartiqlAst.build { val variable = visitOrNull(ctx.symbolPrimitive(), PartiqlAst.Expr.Id::class)?.name val prefilter = visitOrNull(ctx.whereClause(), PartiqlAst.Expr::class) val label = visitOrNull(ctx.patternPartLabel(), PartiqlAst.Expr.Id::class)?.name node_(variable = variable, prefilter = prefilter, label = listOfNotNull(label)) } override fun visitPatternRestrictor(ctx: PartiQLParser.PatternRestrictorContext) = PartiqlAst.build { val metas = ctx.restrictor.getSourceMetaContainer() when (ctx.restrictor.text.lowercase()) { "trail" -> restrictorTrail(metas) "acyclic" -> restrictorAcyclic(metas) "simple" -> restrictorSimple(metas) else -> throw ParserException("Unrecognized pattern restrictor", ErrorCode.PARSE_INVALID_QUERY) } } /** * * TABLE REFERENCES & JOINS & FROM CLAUSE * */ override fun visitFromClause(ctx: PartiQLParser.FromClauseContext) = visit(ctx.tableReference(), PartiqlAst.FromSource::class) override fun visitTableBaseRefClauses(ctx: PartiQLParser.TableBaseRefClausesContext) = PartiqlAst.build { val expr = visit(ctx.source, PartiqlAst.Expr::class) val (asAlias, atAlias, byAlias) = visitNullableItems( listOf(ctx.asIdent(), ctx.atIdent(), ctx.byIdent()), PartiqlAst.Expr.Id::class ) scan_( expr, asAlias = asAlias.toPigSymbolPrimitive(), byAlias = byAlias.toPigSymbolPrimitive(), atAlias = atAlias.toPigSymbolPrimitive(), metas = expr.metas ) } override fun visitTableBaseRefMatch(ctx: PartiQLParser.TableBaseRefMatchContext) = PartiqlAst.build { val expr = visit(ctx.source, PartiqlAst.Expr::class) val (asAlias, atAlias, byAlias) = visitNullableItems( listOf(ctx.asIdent(), ctx.atIdent(), ctx.byIdent()), PartiqlAst.Expr.Id::class ) scan_( expr, asAlias = asAlias.toPigSymbolPrimitive(), byAlias = byAlias.toPigSymbolPrimitive(), atAlias = atAlias.toPigSymbolPrimitive(), metas = expr.metas ) } override fun visitFromClauseSimpleExplicit(ctx: PartiQLParser.FromClauseSimpleExplicitContext) = PartiqlAst.build { val expr = visitPathSimple(ctx.pathSimple()) val (asAlias, atAlias, byAlias) = visitNullableItems( listOf(ctx.asIdent(), ctx.atIdent(), ctx.byIdent()), PartiqlAst.Expr.Id::class ) scan_( expr, asAlias = asAlias.toPigSymbolPrimitive(), byAlias = byAlias.toPigSymbolPrimitive(), atAlias = atAlias.toPigSymbolPrimitive(), metas = expr.metas ) } override fun visitTableUnpivot(ctx: PartiQLParser.TableUnpivotContext) = PartiqlAst.build { val expr = visitExpr(ctx.expr()) val metas = ctx.UNPIVOT().getSourceMetaContainer() val (asAlias, atAlias, byAlias) = visitNullableItems( listOf(ctx.asIdent(), ctx.atIdent(), ctx.byIdent()), PartiqlAst.Expr.Id::class ) unpivot_( expr, asAlias = asAlias.toPigSymbolPrimitive(), atAlias = atAlias.toPigSymbolPrimitive(), byAlias = byAlias.toPigSymbolPrimitive(), metas ) } override fun visitTableCrossJoin(ctx: PartiQLParser.TableCrossJoinContext) = PartiqlAst.build { val lhs = visit(ctx.lhs, PartiqlAst.FromSource::class) val joinType = visitJoinType(ctx.joinType()) val rhs = visit(ctx.rhs, PartiqlAst.FromSource::class) val metas = metaContainerOf(IsImplictJoinMeta.instance) + joinType.metas join(joinType, lhs, rhs, metas = metas) } override fun visitTableQualifiedJoin(ctx: PartiQLParser.TableQualifiedJoinContext) = PartiqlAst.build { val lhs = visit(ctx.lhs, PartiqlAst.FromSource::class) val joinType = visitJoinType(ctx.joinType()) val rhs = visit(ctx.rhs, PartiqlAst.FromSource::class) val condition = visitOrNull(ctx.joinSpec(), PartiqlAst.Expr::class) join(joinType, lhs, rhs, condition, metas = joinType.metas) } override fun visitTableBaseRefSymbol(ctx: PartiQLParser.TableBaseRefSymbolContext) = PartiqlAst.build { val expr = visit(ctx.source, PartiqlAst.Expr::class) val name = visitOrNull(ctx.symbolPrimitive(), PartiqlAst.Expr.Id::class) scan_(expr, name.toPigSymbolPrimitive(), metas = expr.metas) } override fun visitFromClauseSimpleImplicit(ctx: PartiQLParser.FromClauseSimpleImplicitContext) = PartiqlAst.build { val path = visitPathSimple(ctx.pathSimple()) val name = visitOrNull(ctx.symbolPrimitive(), PartiqlAst.Expr.Id::class)?.name scan_(path, name, metas = path.metas) } override fun visitTableWrapped(ctx: PartiQLParser.TableWrappedContext): PartiqlAst.PartiqlAstNode = visit(ctx.tableReference()) override fun visitJoinSpec(ctx: PartiQLParser.JoinSpecContext) = visitExpr(ctx.expr()) override fun visitJoinType(ctx: PartiQLParser.JoinTypeContext?) = PartiqlAst.build { if (ctx == null) return@build inner() val metas = ctx.mod.getSourceMetaContainer() when (ctx.mod.type) { PartiQLParser.LEFT -> left(metas) PartiQLParser.RIGHT -> right(metas) PartiQLParser.INNER -> inner(metas) PartiQLParser.FULL -> full(metas) PartiQLParser.OUTER -> full(metas) else -> inner(metas) } } override fun visitJoinRhsTableJoined(ctx: PartiQLParser.JoinRhsTableJoinedContext) = visit(ctx.tableReference(), PartiqlAst.FromSource::class) /** * SIMPLE EXPRESSIONS */ override fun visitOr(ctx: PartiQLParser.OrContext) = visitBinaryOperation(ctx.lhs, ctx.rhs, ctx.OR().symbol, null) override fun visitAnd(ctx: PartiQLParser.AndContext) = visitBinaryOperation(ctx.lhs, ctx.rhs, ctx.op, null) override fun visitNot(ctx: PartiQLParser.NotContext) = visitUnaryOperation(ctx.rhs, ctx.op, null) override fun visitMathOp00(ctx: PartiQLParser.MathOp00Context): PartiqlAst.PartiqlAstNode = visitBinaryOperation(ctx.lhs, ctx.rhs, ctx.op, ctx.parent) override fun visitMathOp01(ctx: PartiQLParser.MathOp01Context): PartiqlAst.PartiqlAstNode = visitBinaryOperation(ctx.lhs, ctx.rhs, ctx.op, ctx.parent) override fun visitMathOp02(ctx: PartiQLParser.MathOp02Context): PartiqlAst.PartiqlAstNode = visitBinaryOperation(ctx.lhs, ctx.rhs, ctx.op, ctx.parent) override fun visitValueExpr(ctx: PartiQLParser.ValueExprContext) = visitUnaryOperation(ctx.rhs, ctx.sign, ctx.parent) /** * * PREDICATES * */ override fun visitPredicateComparison(ctx: PartiQLParser.PredicateComparisonContext) = visitBinaryOperation(ctx.lhs, ctx.rhs, ctx.op) /** * Note: This predicate can take a wrapped expression on the RHS, and it will wrap it in a LIST. However, if the * expression is a SELECT or VALUES expression, it will NOT wrap it in a list. This is per SqlParser. */ override fun visitPredicateIn(ctx: PartiQLParser.PredicateInContext) = PartiqlAst.build { // Wrap Expression with LIST unless SELECT / VALUES val rhs = if (ctx.expr() != null) { val possibleRhs = visitExpr(ctx.expr()) if (possibleRhs is PartiqlAst.Expr.Select || possibleRhs.metas.containsKey(IsValuesExprMeta.TAG)) possibleRhs else list(possibleRhs, metas = possibleRhs.metas + metaContainerOf(IsListParenthesizedMeta)) } else { visit(ctx.rhs, PartiqlAst.Expr::class) } val lhs = visit(ctx.lhs, PartiqlAst.Expr::class) val args = listOf(lhs, rhs) val inCollection = inCollection(args, ctx.IN().getSourceMetaContainer()) if (ctx.NOT() == null) return@build inCollection not(inCollection, ctx.NOT().getSourceMetaContainer() + metaContainerOf(LegacyLogicalNotMeta.instance)) } override fun visitPredicateIs(ctx: PartiQLParser.PredicateIsContext) = PartiqlAst.build { val lhs = visit(ctx.lhs, PartiqlAst.Expr::class) val rhs = visit(ctx.type(), PartiqlAst.Type::class) val isType = isType(lhs, rhs, ctx.IS().getSourceMetaContainer()) if (ctx.NOT() == null) return@build isType not(isType, ctx.NOT().getSourceMetaContainer() + metaContainerOf(LegacyLogicalNotMeta.instance)) } override fun visitPredicateBetween(ctx: PartiQLParser.PredicateBetweenContext) = PartiqlAst.build { val args = visitOrEmpty(listOf(ctx.lhs, ctx.lower, ctx.upper), PartiqlAst.Expr::class) val between = between(args[0], args[1], args[2], ctx.BETWEEN().getSourceMetaContainer()) if (ctx.NOT() == null) return@build between not(between, ctx.NOT().getSourceMetaContainer() + metaContainerOf(LegacyLogicalNotMeta.instance)) } override fun visitPredicateLike(ctx: PartiQLParser.PredicateLikeContext) = PartiqlAst.build { val args = visitOrEmpty(listOf(ctx.lhs, ctx.rhs), PartiqlAst.Expr::class) val escape = visitOrNull(ctx.escape, PartiqlAst.Expr::class) val like = like(args[0], args[1], escape, ctx.LIKE().getSourceMetaContainer()) if (ctx.NOT() == null) return@build like not(like, metas = ctx.NOT().getSourceMetaContainer() + metaContainerOf(LegacyLogicalNotMeta.instance)) } /** * * PRIMARY EXPRESSIONS * */ override fun visitExprTermWrappedQuery(ctx: PartiQLParser.ExprTermWrappedQueryContext) = visit(ctx.expr(), PartiqlAst.Expr::class) override fun visitVariableIdentifier(ctx: PartiQLParser.VariableIdentifierContext): PartiqlAst.PartiqlAstNode = PartiqlAst.build { val metas = ctx.ident.getSourceMetaContainer() val qualifier = if (ctx.qualifier == null) unqualified() else localsFirst() val sensitivity = if (ctx.ident.type == PartiQLParser.IDENTIFIER) caseInsensitive() else caseSensitive() id(ctx.ident.getStringValue(), sensitivity, qualifier, metas) } override fun visitVariableKeyword(ctx: PartiQLParser.VariableKeywordContext): PartiqlAst.PartiqlAstNode = PartiqlAst.build { val keyword = ctx.nonReservedKeywords().start.text val metas = ctx.start.getSourceMetaContainer() val qualifier = ctx.qualifier?.let { localsFirst() } ?: unqualified() id(keyword, caseInsensitive(), qualifier, metas) } override fun visitParameter(ctx: PartiQLParser.ParameterContext) = PartiqlAst.build { val parameterIndex = parameterIndexes[ctx.QUESTION_MARK().symbol.tokenIndex] ?: throw ParserException("Unable to find index of parameter.", ErrorCode.PARSE_INVALID_QUERY) parameter(parameterIndex.toLong(), ctx.QUESTION_MARK().getSourceMetaContainer()) } override fun visitSequenceConstructor(ctx: PartiQLParser.SequenceConstructorContext) = PartiqlAst.build { val expressions = visitOrEmpty(ctx.expr(), PartiqlAst.Expr::class) val metas = ctx.datatype.getSourceMetaContainer() when (ctx.datatype.type) { PartiQLParser.LIST -> list(expressions, metas) PartiQLParser.SEXP -> sexp(expressions, metas) else -> throw ParserException("Unknown sequence", ErrorCode.PARSE_INVALID_QUERY) } } override fun visitExprPrimaryPath(ctx: PartiQLParser.ExprPrimaryPathContext) = PartiqlAst.build { val base = visit(ctx.exprPrimary()) as PartiqlAst.Expr val steps = ctx.pathStep().map { step -> visit(step) as PartiqlAst.PathStep } path(base, steps, base.metas) } override fun visitPathStepIndexExpr(ctx: PartiQLParser.PathStepIndexExprContext) = PartiqlAst.build { val expr = visit(ctx.key, PartiqlAst.Expr::class) val metas = expr.metas + metaContainerOf(IsPathIndexMeta.instance) pathExpr(expr, PartiqlAst.CaseSensitivity.CaseSensitive(), metas) } override fun visitPathStepDotExpr(ctx: PartiQLParser.PathStepDotExprContext) = getSymbolPathExpr(ctx.key) override fun visitPathStepIndexAll(ctx: PartiQLParser.PathStepIndexAllContext) = PartiqlAst.build { pathWildcard(metas = ctx.ASTERISK().getSourceMetaContainer()) } override fun visitPathStepDotAll(ctx: PartiQLParser.PathStepDotAllContext) = PartiqlAst.build { pathUnpivot() } override fun visitExprGraphMatchMany(ctx: PartiQLParser.ExprGraphMatchManyContext) = PartiqlAst.build { val graph = visit(ctx.exprPrimary()) as PartiqlAst.Expr val gpmlPattern = visitGpmlPatternList(ctx.gpmlPatternList()) graphMatch(graph, gpmlPattern, graph.metas) } override fun visitExprGraphMatchOne(ctx: PartiQLParser.ExprGraphMatchOneContext) = PartiqlAst.build { val graph = visit(ctx.exprPrimary()) as PartiqlAst.Expr val gpmlPattern = visitGpmlPattern(ctx.gpmlPattern()) graphMatch(graph, gpmlPattern, graph.metas) } override fun visitValues(ctx: PartiQLParser.ValuesContext) = PartiqlAst.build { val rows = visitOrEmpty(ctx.valueRow(), PartiqlAst.Expr.List::class) bag(rows, ctx.VALUES().getSourceMetaContainer() + metaContainerOf(IsValuesExprMeta.instance)) } override fun visitValueRow(ctx: PartiQLParser.ValueRowContext) = PartiqlAst.build { val expressions = visitOrEmpty(ctx.expr(), PartiqlAst.Expr::class) list(expressions, metas = ctx.PAREN_LEFT().getSourceMetaContainer() + metaContainerOf(IsListParenthesizedMeta)) } override fun visitValueList(ctx: PartiQLParser.ValueListContext) = PartiqlAst.build { val expressions = visitOrEmpty(ctx.expr(), PartiqlAst.Expr::class) list(expressions, metas = ctx.PAREN_LEFT().getSourceMetaContainer() + metaContainerOf(IsListParenthesizedMeta)) } /** * * FUNCTIONS * */ override fun visitNullIf(ctx: PartiQLParser.NullIfContext) = PartiqlAst.build { val lhs = visitExpr(ctx.expr(0)) val rhs = visitExpr(ctx.expr(1)) val metas = ctx.NULLIF().getSourceMetaContainer() nullIf(lhs, rhs, metas) } override fun visitCoalesce(ctx: PartiQLParser.CoalesceContext) = PartiqlAst.build { val expressions = visitOrEmpty(ctx.expr(), PartiqlAst.Expr::class) val metas = ctx.COALESCE().getSourceMetaContainer() coalesce(expressions, metas) } override fun visitCaseExpr(ctx: PartiQLParser.CaseExprContext) = PartiqlAst.build { val pairs = ctx.whens.indices.map { i -> exprPair(visitExpr(ctx.whens[i]), visitExpr(ctx.thens[i])) } val elseExpr = visitOrNull(ctx.else_, PartiqlAst.Expr::class) val caseMeta = ctx.CASE().getSourceMetaContainer() when (ctx.case_) { null -> searchedCase(exprPairList(pairs), elseExpr, metas = caseMeta) else -> simpleCase(visitExpr(ctx.case_), exprPairList(pairs), elseExpr, metas = caseMeta) } } override fun visitCast(ctx: PartiQLParser.CastContext) = PartiqlAst.build { val expr = visitExpr(ctx.expr()) val type = visit(ctx.type(), PartiqlAst.Type::class) val metas = ctx.CAST().getSourceMetaContainer() cast(expr, type, metas) } override fun visitCanCast(ctx: PartiQLParser.CanCastContext) = PartiqlAst.build { val expr = visitExpr(ctx.expr()) val type = visit(ctx.type(), PartiqlAst.Type::class) val metas = ctx.CAN_CAST().getSourceMetaContainer() canCast(expr, type, metas) } override fun visitCanLosslessCast(ctx: PartiQLParser.CanLosslessCastContext) = PartiqlAst.build { val expr = visitExpr(ctx.expr()) val type = visit(ctx.type(), PartiqlAst.Type::class) val metas = ctx.CAN_LOSSLESS_CAST().getSourceMetaContainer() canLosslessCast(expr, type, metas) } override fun visitFunctionCallIdent(ctx: PartiQLParser.FunctionCallIdentContext) = PartiqlAst.build { val name = ctx.name.getString().lowercase() val args = visitOrEmpty(ctx.expr(), PartiqlAst.Expr::class) val metas = ctx.name.getSourceMetaContainer() call(name, args = args, metas = metas) } override fun visitFunctionCallReserved(ctx: PartiQLParser.FunctionCallReservedContext) = PartiqlAst.build { val name = ctx.name.text.lowercase() val args = visitOrEmpty(ctx.expr(), PartiqlAst.Expr::class) val metas = ctx.name.getSourceMetaContainer() call(name, args = args, metas = metas) } override fun visitDateFunction(ctx: PartiQLParser.DateFunctionContext) = PartiqlAst.build { if (DateTimePart.safeValueOf(ctx.dt.text) == null) { throw ctx.dt.err("Expected one of: ${DateTimePart.values()}", ErrorCode.PARSE_EXPECTED_DATE_TIME_PART) } val datetimePart = lit(ionSymbol(ctx.dt.text)) val secondaryArgs = visitOrEmpty(ctx.expr(), PartiqlAst.Expr::class) val args = listOf(datetimePart) + secondaryArgs val metas = ctx.func.getSourceMetaContainer() call(ctx.func.text.lowercase(), args, metas) } override fun visitSubstring(ctx: PartiQLParser.SubstringContext) = PartiqlAst.build { val args = visitOrEmpty(ctx.expr(), PartiqlAst.Expr::class) val metas = ctx.SUBSTRING().getSourceMetaContainer() call(ctx.SUBSTRING().text.lowercase(), args, metas) } override fun visitPosition(ctx: PartiQLParser.PositionContext) = PartiqlAst.build { val args = visitOrEmpty(ctx.expr(), PartiqlAst.Expr::class) val metas = ctx.POSITION().getSourceMetaContainer() call(ctx.POSITION().text.lowercase(), args, metas) } override fun visitOverlay(ctx: PartiQLParser.OverlayContext) = PartiqlAst.build { val args = visitOrEmpty(ctx.expr(), PartiqlAst.Expr::class) val metas = ctx.OVERLAY().getSourceMetaContainer() call(ctx.OVERLAY().text.lowercase(), args, metas) } override fun visitCountAll(ctx: PartiQLParser.CountAllContext) = PartiqlAst.build { callAgg( all(), ctx.func.text.lowercase(), lit(ionInt(1)), ctx.COUNT().getSourceMetaContainer() + metaContainerOf(IsCountStarMeta.instance) ) } override fun visitExtract(ctx: PartiQLParser.ExtractContext) = PartiqlAst.build { if (DateTimePart.safeValueOf(ctx.IDENTIFIER().text) == null) { throw ctx.IDENTIFIER() .err("Expected one of: ${DateTimePart.values()}", ErrorCode.PARSE_EXPECTED_DATE_TIME_PART) } val datetimePart = lit(ionSymbol(ctx.IDENTIFIER().text)) val timeExpr = visit(ctx.rhs, PartiqlAst.Expr::class) val args = listOf(datetimePart, timeExpr) val metas = ctx.EXTRACT().getSourceMetaContainer() call(ctx.EXTRACT().text.lowercase(), args, metas) } /** * Note: This implementation is odd because the TRIM function contains keywords that are not keywords outside * of TRIM. Therefore, TRIM(<spec> <substring> FROM <target>) needs to be parsed as below. The <spec> needs to be * an identifier (according to SqlParser), but if the identifier is NOT a trim specification, and the <substring> is * null, we need to make the substring equal to the <spec> (and make <spec> null). */ override fun visitTrimFunction(ctx: PartiQLParser.TrimFunctionContext) = PartiqlAst.build { val possibleModText = if (ctx.mod != null) ctx.mod.text.lowercase() else null val isTrimSpec = TRIM_SPECIFICATION_KEYWORDS.contains(possibleModText) val (modifier, substring) = when { // if <spec> is not null and <substring> is null // then there are two possible cases trim(( BOTH | LEADING | TRAILING ) FROM <target> ) // or trim(<substring> FROM target), i.e., we treat what is recognized by parser as the modifier as <substring> ctx.mod != null && ctx.sub == null -> { if (isTrimSpec) ctx.mod.toSymbol() to null else null to id(possibleModText!!, caseInsensitive(), unqualified(), ctx.mod.getSourceMetaContainer()) } ctx.mod == null && ctx.sub != null -> { null to visitExpr(ctx.sub) } ctx.mod != null && ctx.sub != null -> { if (isTrimSpec) ctx.mod.toSymbol() to visitExpr(ctx.sub) // todo we need to decide if it should be an evaluator error or a parser error else { val errorContext = PropertyValueMap() errorContext[Property.TOKEN_STRING] = ctx.mod.text throw ctx.mod.err( "'${ctx.mod.text}' is an unknown trim specification, valid values: $TRIM_SPECIFICATION_KEYWORDS", ErrorCode.PARSE_INVALID_TRIM_SPEC, errorContext ) } } else -> null to null } val target = visitExpr(ctx.target) val args = listOfNotNull(modifier, substring, target) val metas = ctx.func.getSourceMetaContainer() call(ctx.func.text.lowercase(), args, metas) } override fun visitAggregateBase(ctx: PartiQLParser.AggregateBaseContext) = PartiqlAst.build { val strategy = getStrategy(ctx.setQuantifierStrategy(), default = all()) val arg = visitExpr(ctx.expr()) val metas = ctx.func.getSourceMetaContainer() callAgg(strategy, ctx.func.text.lowercase(), arg, metas) } /** * * Window Functions * TODO: Remove from experimental once https://github.com/partiql/partiql-docs/issues/31 is resolved and a RFC is approved * */ override fun visitLagLeadFunction(ctx: PartiQLParser.LagLeadFunctionContext) = PartiqlAst.build { val args = visitOrEmpty(ctx.expr(), PartiqlAst.Expr::class) val over = visitOver(ctx.over()) // LAG and LEAD will require a Window ORDER BY if (over.orderBy == null) { val errorContext = PropertyValueMap() errorContext[Property.TOKEN_STRING] = ctx.func.text.lowercase() throw ctx.func.err( "${ctx.func.text} requires Window ORDER BY", ErrorCode.PARSE_EXPECTED_WINDOW_ORDER_BY, errorContext ) } val metas = ctx.func.getSourceMetaContainer() callWindow(ctx.func.text.lowercase(), over, args, metas) } override fun visitOver(ctx: PartiQLParser.OverContext) = PartiqlAst.build { val windowPartitionList = if (ctx.windowPartitionList() != null) visitWindowPartitionList(ctx.windowPartitionList()) else null val windowSortSpecList = if (ctx.windowSortSpecList() != null) visitWindowSortSpecList(ctx.windowSortSpecList()) else null val metas = ctx.OVER().getSourceMetaContainer() over(windowPartitionList, windowSortSpecList, metas) } override fun visitWindowPartitionList(ctx: PartiQLParser.WindowPartitionListContext) = PartiqlAst.build { val args = visitOrEmpty(ctx.expr(), PartiqlAst.Expr::class) val metas = ctx.PARTITION().getSourceMetaContainer() windowPartitionList(args, metas) } override fun visitWindowSortSpecList(ctx: PartiQLParser.WindowSortSpecListContext) = PartiqlAst.build { val sortSpecList = visitOrEmpty(ctx.orderSortSpec(), PartiqlAst.SortSpec::class) val metas = ctx.ORDER().getSourceMetaContainer() windowSortSpecList(sortSpecList, metas) } /** * * LITERALS * */ override fun visitBag(ctx: PartiQLParser.BagContext) = PartiqlAst.build { val exprList = visitOrEmpty(ctx.expr(), PartiqlAst.Expr::class) bag(exprList, ctx.ANGLE_DOUBLE_LEFT().getSourceMetaContainer()) } override fun visitLiteralDecimal(ctx: PartiQLParser.LiteralDecimalContext) = PartiqlAst.build { val decimal = try { ionDecimal(Decimal.valueOf(bigDecimalOf(ctx.LITERAL_DECIMAL().text))) } catch (e: NumberFormatException) { val errorContext = PropertyValueMap() errorContext[Property.TOKEN_STRING] = ctx.LITERAL_DECIMAL().text throw ctx.LITERAL_DECIMAL().err("Invalid decimal literal", ErrorCode.LEXER_INVALID_LITERAL, errorContext) } lit( decimal, ctx.LITERAL_DECIMAL().getSourceMetaContainer() ) } override fun visitArray(ctx: PartiQLParser.ArrayContext) = PartiqlAst.build { val metas = ctx.BRACKET_LEFT().getSourceMetaContainer() list(visitOrEmpty(ctx.expr(), PartiqlAst.Expr::class), metas) } override fun visitLiteralNull(ctx: PartiQLParser.LiteralNullContext) = PartiqlAst.build { lit(ionNull(), ctx.NULL().getSourceMetaContainer()) } override fun visitLiteralMissing(ctx: PartiQLParser.LiteralMissingContext) = PartiqlAst.build { missing(ctx.MISSING().getSourceMetaContainer()) } override fun visitLiteralTrue(ctx: PartiQLParser.LiteralTrueContext) = PartiqlAst.build { lit(ionBool(true), ctx.TRUE().getSourceMetaContainer()) } override fun visitLiteralFalse(ctx: PartiQLParser.LiteralFalseContext) = PartiqlAst.build { lit(ionBool(false), ctx.FALSE().getSourceMetaContainer()) } override fun visitLiteralIon(ctx: PartiQLParser.LiteralIonContext) = PartiqlAst.build { val ionValue = try { loadSingleElement(ctx.ION_CLOSURE().getStringValue()) } catch (e: IonElementException) { throw ParserException("Unable to parse Ion value.", ErrorCode.PARSE_UNEXPECTED_TOKEN, cause = e) } lit( ionValue, ctx.ION_CLOSURE().getSourceMetaContainer() + metaContainerOf(IsIonLiteralMeta.instance) ) } override fun visitLiteralString(ctx: PartiQLParser.LiteralStringContext) = PartiqlAst.build { lit(ionString(ctx.LITERAL_STRING().getStringValue()), ctx.LITERAL_STRING().getSourceMetaContainer()) } override fun visitLiteralInteger(ctx: PartiQLParser.LiteralIntegerContext): PartiqlAst.Expr.Lit = PartiqlAst.build { lit(parseToIntElement(ctx.LITERAL_INTEGER().text), ctx.LITERAL_INTEGER().getSourceMetaContainer()) } override fun visitLiteralDate(ctx: PartiQLParser.LiteralDateContext) = PartiqlAst.build { val dateString = ctx.LITERAL_STRING().getStringValue() if (DATE_PATTERN_REGEX.matches(dateString).not()) { throw ctx.LITERAL_STRING() .err("Expected DATE string to be of the format yyyy-MM-dd", ErrorCode.PARSE_INVALID_DATE_STRING) } try { LocalDate.parse(dateString, DateTimeFormatter.ISO_LOCAL_DATE) val (year, month, day) = dateString.split("-") date(year.toLong(), month.toLong(), day.toLong(), ctx.DATE().getSourceMetaContainer()) } catch (e: DateTimeParseException) { throw ctx.LITERAL_STRING().err(e.localizedMessage, ErrorCode.PARSE_INVALID_DATE_STRING, cause = e) } catch (e: IndexOutOfBoundsException) { throw ctx.LITERAL_STRING().err(e.localizedMessage, ErrorCode.PARSE_INVALID_DATE_STRING, cause = e) } } override fun visitLiteralTime(ctx: PartiQLParser.LiteralTimeContext) = PartiqlAst.build { val (timeString, precision) = getTimeStringAndPrecision(ctx.LITERAL_STRING(), ctx.LITERAL_INTEGER()) when (ctx.WITH()) { null -> getLocalTime(timeString, false, precision, ctx.LITERAL_STRING(), ctx.TIME(0)) else -> getOffsetTime(timeString, precision, ctx.LITERAL_STRING(), ctx.TIME(0)) } } override fun visitLiteralTimestamp(ctx: PartiQLParser.LiteralTimestampContext): PartiqlAst.PartiqlAstNode { val (timestamp, precision) = getTimestampStringAndPrecision(ctx.LITERAL_STRING(), ctx.LITERAL_INTEGER()) return when (ctx.WITH()) { null -> getTimestampDynamic(timestamp, precision, ctx.LITERAL_STRING()) else -> getTimestampWithTimezone(timestamp, precision, ctx.LITERAL_STRING()) } } override fun visitTuple(ctx: PartiQLParser.TupleContext) = PartiqlAst.build { val pairs = visitOrEmpty(ctx.pair(), PartiqlAst.ExprPair::class) val metas = ctx.BRACE_LEFT().getSourceMetaContainer() struct(pairs, metas) } override fun visitPair(ctx: PartiQLParser.PairContext) = PartiqlAst.build { val lhs = visitExpr(ctx.lhs) val rhs = visitExpr(ctx.rhs) exprPair(lhs, rhs) } /** * * TYPES * */ override fun visitTypeAtomic(ctx: PartiQLParser.TypeAtomicContext) = PartiqlAst.build { val metas = ctx.datatype.getSourceMetaContainer() when (ctx.datatype.type) { PartiQLParser.NULL -> nullType(metas) PartiQLParser.BOOL -> booleanType(metas) PartiQLParser.BOOLEAN -> booleanType(metas) PartiQLParser.SMALLINT -> smallintType(metas) PartiQLParser.INT2 -> smallintType(metas) PartiQLParser.INTEGER2 -> smallintType(metas) PartiQLParser.INT -> integerType(metas) PartiQLParser.INTEGER -> integerType(metas) PartiQLParser.INT4 -> integer4Type(metas) PartiQLParser.INTEGER4 -> integer4Type(metas) PartiQLParser.INT8 -> integer8Type(metas) PartiQLParser.INTEGER8 -> integer8Type(metas) PartiQLParser.BIGINT -> integer8Type(metas) PartiQLParser.REAL -> realType(metas) PartiQLParser.DOUBLE -> doublePrecisionType(metas) PartiQLParser.CHAR -> characterType(metas = metas) PartiQLParser.CHARACTER -> characterType(metas = metas) PartiQLParser.MISSING -> missingType(metas) PartiQLParser.STRING -> stringType(metas) PartiQLParser.SYMBOL -> symbolType(metas) PartiQLParser.BLOB -> blobType(metas) PartiQLParser.CLOB -> clobType(metas) PartiQLParser.DATE -> dateType(metas) PartiQLParser.STRUCT -> structType(metas) PartiQLParser.TUPLE -> tupleType(metas) PartiQLParser.LIST -> listType(metas) PartiQLParser.BAG -> bagType(metas) PartiQLParser.SEXP -> sexpType(metas) PartiQLParser.ANY -> anyType(metas) else -> throw ParserException("Unsupported type.", ErrorCode.PARSE_INVALID_QUERY) } } override fun visitTypeVarChar(ctx: PartiQLParser.TypeVarCharContext) = PartiqlAst.build { val arg0 = if (ctx.arg0 != null) parseToIntElement(ctx.arg0.text) else null val metas = ctx.CHARACTER().getSourceMetaContainer() assertIntegerElement(ctx.arg0, arg0) characterVaryingType(arg0?.longValue, metas) } override fun visitTypeArgSingle(ctx: PartiQLParser.TypeArgSingleContext) = PartiqlAst.build { val arg0 = if (ctx.arg0 != null) parseToIntElement(ctx.arg0.text) else null assertIntegerElement(ctx.arg0, arg0) val metas = ctx.datatype.getSourceMetaContainer() when (ctx.datatype.type) { PartiQLParser.FLOAT -> floatType(arg0?.longValue, metas) PartiQLParser.CHAR, PartiQLParser.CHARACTER -> characterType(arg0?.longValue, metas) PartiQLParser.VARCHAR -> characterVaryingType(arg0?.longValue, metas) else -> throw ParserException("Unknown datatype", ErrorCode.PARSE_UNEXPECTED_TOKEN, PropertyValueMap()) } } override fun visitTypeArgDouble(ctx: PartiQLParser.TypeArgDoubleContext) = PartiqlAst.build { val arg0 = if (ctx.arg0 != null) parseToIntElement(ctx.arg0.text) else null val arg1 = if (ctx.arg1 != null) parseToIntElement(ctx.arg1.text) else null assertIntegerElement(ctx.arg0, arg0) assertIntegerElement(ctx.arg1, arg1) val metas = ctx.datatype.getSourceMetaContainer() when (ctx.datatype.type) { PartiQLParser.DECIMAL, PartiQLParser.DEC -> decimalType(arg0?.longValue, arg1?.longValue, metas) PartiQLParser.NUMERIC -> numericType(arg0?.longValue, arg1?.longValue, metas) else -> throw ParserException("Unknown datatype", ErrorCode.PARSE_UNEXPECTED_TOKEN, PropertyValueMap()) } } override fun visitTypeTimeZone(ctx: PartiQLParser.TypeTimeZoneContext) = PartiqlAst.build { val precision = if (ctx.precision != null) ctx.precision.text.toInteger().toLong() else null if (precision != null && (precision < 0 || precision > MAX_PRECISION_FOR_TIME)) { throw ctx.precision.err("Unsupported precision", ErrorCode.PARSE_INVALID_PRECISION_FOR_TIME) } val hasTimeZone = ctx.WITH() != null when (ctx.datatype.type) { PartiQLParser.TIME -> if (hasTimeZone) timeWithTimeZoneType(precision) else timeType(precision) PartiQLParser.TIMESTAMP -> if (hasTimeZone) timestampWithTimeZoneType(precision) else timestampType( precision ) else -> throw ParserException("Unknown datatype", ErrorCode.PARSE_UNEXPECTED_TOKEN, PropertyValueMap()) } } override fun visitTypeCustom(ctx: PartiQLParser.TypeCustomContext) = PartiqlAst.build { val metas = ctx.symbolPrimitive().getSourceMetaContainer() val customName: String = when (val name = ctx.symbolPrimitive().getString().lowercase()) { in customKeywords -> name in customTypeAliases.keys -> customTypeAliases.getOrDefault(name, name) else -> throw ParserException("Invalid custom type name: $name", ErrorCode.PARSE_INVALID_QUERY) } customType_(SymbolPrimitive(customName, metas), metas) } /** * NOT OVERRIDDEN * Explicitly defining the override helps by showing the user (via the IDE) which methods remain to be overridden. */ override fun visitTerminal(node: TerminalNode?): PartiqlAst.PartiqlAstNode = super.visitTerminal(node) override fun shouldVisitNextChild(node: RuleNode?, currentResult: PartiqlAst.PartiqlAstNode?) = super.shouldVisitNextChild(node, currentResult) override fun visitErrorNode(node: ErrorNode?): PartiqlAst.PartiqlAstNode = super.visitErrorNode(node) override fun visitChildren(node: RuleNode?): PartiqlAst.PartiqlAstNode = super.visitChildren(node) override fun visitExprPrimaryBase(ctx: PartiQLParser.ExprPrimaryBaseContext?): PartiqlAst.PartiqlAstNode = super.visitExprPrimaryBase(ctx) override fun visitExprTermBase(ctx: PartiQLParser.ExprTermBaseContext?): PartiqlAst.PartiqlAstNode = super.visitExprTermBase(ctx) override fun visitCollection(ctx: PartiQLParser.CollectionContext?): PartiqlAst.PartiqlAstNode = super.visitCollection(ctx) override fun visitPredicateBase(ctx: PartiQLParser.PredicateBaseContext?): PartiqlAst.PartiqlAstNode = super.visitPredicateBase(ctx) override fun visitTableNonJoin(ctx: PartiQLParser.TableNonJoinContext?): PartiqlAst.PartiqlAstNode = super.visitTableNonJoin(ctx) override fun visitTableRefBase(ctx: PartiQLParser.TableRefBaseContext?): PartiqlAst.PartiqlAstNode = super.visitTableRefBase(ctx) override fun visitJoinRhsBase(ctx: PartiQLParser.JoinRhsBaseContext?): PartiqlAst.PartiqlAstNode = super.visitJoinRhsBase(ctx) override fun visitConflictTarget(ctx: PartiQLParser.ConflictTargetContext?): PartiqlAst.PartiqlAstNode = super.visitConflictTarget(ctx) /** * * HELPER METHODS * */ private fun <T : PartiqlAst.PartiqlAstNode> visitOrEmpty(ctx: List<ParserRuleContext>?, clazz: KClass<T>): List<T> = when { ctx.isNullOrEmpty() -> emptyList() else -> ctx.map { clazz.cast(visit(it)) } } private fun <T : PartiqlAst.PartiqlAstNode> visitNullableItems( ctx: List<ParserRuleContext>?, clazz: KClass<T> ): List<T?> = when { ctx.isNullOrEmpty() -> emptyList() else -> ctx.map { visitOrNull(it, clazz) } } private fun <T : PartiqlAst.PartiqlAstNode> visitOrNull(ctx: ParserRuleContext?, clazz: KClass<T>): T? = when (ctx) { null -> null else -> clazz.cast(visit(ctx)) } private fun <T : PartiqlAst.PartiqlAstNode> visit(ctx: ParserRuleContext, clazz: KClass<T>): T = clazz.cast(visit(ctx)) private fun TerminalNode?.getSourceMetaContainer(): MetaContainer { if (this == null) return emptyMetaContainer() val metas = this.getSourceMetas() return com.amazon.ionelement.api.metaContainerOf(Pair(metas.tag, metas)) } private fun Token?.getSourceMetaContainer(): MetaContainer { if (this == null) return emptyMetaContainer() val metas = this.getSourceMetas() return com.amazon.ionelement.api.metaContainerOf(Pair(metas.tag, metas)) } private fun TerminalNode.getSourceMetas(): SourceLocationMeta = this.symbol.getSourceMetas() private fun Token.getSourceMetas(): SourceLocationMeta { val length = this.stopIndex - this.startIndex + 1 return SourceLocationMeta(this.line.toLong(), this.charPositionInLine.toLong() + 1, length.toLong()) } private fun visitBinaryOperation( lhs: ParserRuleContext?, rhs: ParserRuleContext?, op: Token?, parent: ParserRuleContext? = null ) = PartiqlAst.build { if (parent != null) return@build visit(parent, PartiqlAst.Expr::class) val args = visitOrEmpty(listOf(lhs!!, rhs!!), PartiqlAst.Expr::class) val metas = op.getSourceMetaContainer() when (op!!.type) { PartiQLParser.AND -> and(args, metas) PartiQLParser.OR -> or(args, metas) PartiQLParser.ASTERISK -> times(args, metas) PartiQLParser.SLASH_FORWARD -> divide(args, metas) PartiQLParser.PLUS -> plus(args, metas) PartiQLParser.MINUS -> minus(args, metas) PartiQLParser.PERCENT -> modulo(args, metas) PartiQLParser.CONCAT -> concat(args, metas) PartiQLParser.ANGLE_LEFT -> lt(args, metas) PartiQLParser.LT_EQ -> lte(args, metas) PartiQLParser.ANGLE_RIGHT -> gt(args, metas) PartiQLParser.GT_EQ -> gte(args, metas) PartiQLParser.NEQ -> ne(args, metas) PartiQLParser.EQ -> eq(args, metas) else -> throw ParserException("Unknown binary operator", ErrorCode.PARSE_INVALID_QUERY) } } private fun visitUnaryOperation(operand: ParserRuleContext?, op: Token?, parent: ParserRuleContext? = null) = PartiqlAst.build { if (parent != null) return@build visit(parent, PartiqlAst.Expr::class) val arg = visit(operand!!, PartiqlAst.Expr::class) val metas = op.getSourceMetaContainer() when (op!!.type) { PartiQLParser.PLUS -> { when { arg !is PartiqlAst.Expr.Lit -> pos(arg, metas) arg.value is IntElement -> arg arg.value is FloatElement -> arg arg.value is DecimalElement -> arg else -> pos(arg, metas) } } PartiQLParser.MINUS -> { when { arg !is PartiqlAst.Expr.Lit -> neg(arg, metas) arg.value is IntElement -> { val intValue = when (arg.value.integerSize) { IntElementSize.LONG -> ionInt(-arg.value.longValue) IntElementSize.BIG_INTEGER -> when (arg.value.bigIntegerValue) { Long.MAX_VALUE.toBigInteger() + (1L).toBigInteger() -> ionInt(Long.MIN_VALUE) else -> ionInt(arg.value.bigIntegerValue * BigInteger.valueOf(-1L)) } } arg.copy(value = intValue.asAnyElement()) } arg.value is FloatElement -> arg.copy(value = ionFloat(-(arg.value.doubleValue)).asAnyElement()) arg.value is DecimalElement -> arg.copy(value = ionDecimal(-(arg.value.decimalValue)).asAnyElement()) else -> neg(arg, metas) } } PartiQLParser.NOT -> not(arg, metas) else -> throw ParserException("Unknown unary operator", ErrorCode.PARSE_INVALID_QUERY) } } private fun PartiQLParser.SymbolPrimitiveContext.getSourceMetaContainer() = when (this.ident.type) { PartiQLParser.IDENTIFIER -> this.IDENTIFIER().getSourceMetaContainer() PartiQLParser.IDENTIFIER_QUOTED -> this.IDENTIFIER_QUOTED().getSourceMetaContainer() else -> throw ParserException( "Unable to get identifier's source meta-container.", ErrorCode.PARSE_INVALID_QUERY ) } private fun PartiqlAst.Expr.getStringValue(token: Token? = null): String = when (this) { is PartiqlAst.Expr.Id -> this.name.text.lowercase() is PartiqlAst.Expr.Lit -> { when (this.value) { is SymbolElement -> this.value.symbolValue.lowercase() is StringElement -> this.value.stringValue.lowercase() else -> this.value.stringValueOrNull ?: throw token.err( "Unable to pass the string value", ErrorCode.PARSE_UNEXPECTED_TOKEN ) } } else -> throw token.err("Unable to get value", ErrorCode.PARSE_UNEXPECTED_TOKEN) } private fun PartiqlAst.Expr.Id?.toPigSymbolPrimitive(): SymbolPrimitive? = when (this) { null -> null else -> this.name.copy(metas = this.metas) } private fun PartiqlAst.Expr.Id.toIdentifier(): PartiqlAst.Identifier { val name = this.name.text val case = this.case return PartiqlAst.build { identifier(name, case) } } /** * With the <string> and <int> nodes of a literal time expression, returns the parsed string and precision. * TIME (<int>)? (WITH TIME ZONE)? <string> */ private fun getTimeStringAndPrecision(stringNode: TerminalNode, integerNode: TerminalNode?): Pair<String, Long> { val timeString = stringNode.getStringValue() val precision = when (integerNode) { null -> try { getPrecisionFromTimeString(timeString).toLong() } catch (e: EvaluationException) { throw stringNode.err( "Unable to parse precision.", ErrorCode.PARSE_INVALID_TIME_STRING, cause = e ) } else -> integerNode.text.toInteger().toLong() } if (precision < 0 || precision > MAX_PRECISION_FOR_TIME) { throw integerNode.err("Precision out of bounds", ErrorCode.PARSE_INVALID_PRECISION_FOR_TIME) } return timeString to precision } /** * Parses a [timeString] using [OffsetTime] and converts to a [PartiqlAst.Expr.LitTime]. If unable to parse, parses * using [getLocalTime]. */ private fun getOffsetTime(timeString: String, precision: Long, stringNode: TerminalNode, timeNode: TerminalNode) = PartiqlAst.build { try { val time: OffsetTime = OffsetTime.parse(timeString) litTime( timeValue( time.hour.toLong(), time.minute.toLong(), time.second.toLong(), time.nano.toLong(), precision, true, (time.offset.totalSeconds / 60).toLong() ) ) } catch (e: DateTimeParseException) { getLocalTime(timeString, true, precision, stringNode, timeNode) } } /** * Parses a [timeString] using [LocalTime] and converts to a [PartiqlAst.Expr.LitTime] */ private fun getLocalTime( timeString: String, withTimeZone: Boolean, precision: Long, stringNode: TerminalNode, timeNode: TerminalNode ) = PartiqlAst.build { val time: LocalTime val formatter = when (withTimeZone) { false -> DateTimeFormatter.ISO_TIME else -> DateTimeFormatter.ISO_LOCAL_TIME } try { time = LocalTime.parse(timeString, formatter) } catch (e: DateTimeParseException) { throw stringNode.err("Unable to parse time", ErrorCode.PARSE_INVALID_TIME_STRING, cause = e) } litTime( timeValue( time.hour.toLong(), time.minute.toLong(), time.second.toLong(), time.nano.toLong(), precision, withTimeZone, null, stringNode.getSourceMetaContainer() ), timeNode.getSourceMetaContainer() ) } private fun getTimestampStringAndPrecision( stringNode: TerminalNode, integerNode: TerminalNode? ): Pair<String, Long?> { val timestampString = stringNode.getStringValue() val precision = when (integerNode) { null -> return timestampString to null else -> integerNode.text.toInteger().toLong() } if (precision < 0) { throw integerNode.err("Precision out of bounds", ErrorCode.PARSE_INVALID_PRECISION_FOR_TIMESTAMP) } return timestampString to precision } /** * Parse Timestamp based on the existence of Time zone */ private fun getTimestampDynamic( timestampString: String, precision: Long?, node: TerminalNode ) = PartiqlAst.build { val timestamp = try { DateTimeUtils.parseTimestamp(timestampString) } catch (e: DateTimeException) { throw node.err("Invalid Date Time Literal", ErrorCode.PARSE_INVALID_DATETIME_STRING, cause = e) } val timeZone = timestamp.timeZone?.let { getTimeZone(it) } timestamp( timestampValue( timestamp.year.toLong(), timestamp.month.toLong(), timestamp.day.toLong(), timestamp.hour.toLong(), timestamp.minute.toLong(), ionDecimal(Decimal.valueOf(timestamp.decimalSecond)), timeZone, precision ) ) } private fun getTimestampWithTimezone( timestampString: String, precision: Long?, node: TerminalNode ) = PartiqlAst.build { val timestamp = try { DateTimeUtils.parseTimestamp(timestampString) } catch (e: DateTimeException) { throw node.err("Invalid Date Time Literal", ErrorCode.PARSE_INVALID_DATETIME_STRING, cause = e) } if (timestamp.timeZone == null) throw node.err( "Invalid Date Time Literal, expect Time Zone for Type Timestamp With Time Zone", ErrorCode.PARSE_INVALID_DATETIME_STRING ) val timeZone = timestamp.timeZone?.let { getTimeZone(it) } timestamp( timestampValue( timestamp.year.toLong(), timestamp.month.toLong(), timestamp.day.toLong(), timestamp.hour.toLong(), timestamp.minute.toLong(), ionDecimal(Decimal.valueOf(timestamp.decimalSecond)), timeZone, precision ) ) } private fun getTimeZone(timeZone: TimeZone) = PartiqlAst.build { when (timeZone) { TimeZone.UnknownTimeZone -> unknownTimezone() is TimeZone.UtcOffset -> utcOffset(timeZone.totalOffsetMinutes.toLong()) } } private fun convertSymbolPrimitive(sym: PartiQLParser.SymbolPrimitiveContext?): SymbolPrimitive? = when (sym) { null -> null else -> SymbolPrimitive(sym.getString(), sym.getSourceMetaContainer()) } private fun convertProjectionItems(ctx: PartiQLParser.ProjectionItemsContext, metas: MetaContainer) = PartiqlAst.build { val projections = visitOrEmpty(ctx.projectionItem(), PartiqlAst.ProjectItem::class) projectList(projections, metas) } private fun PartiQLParser.SelectClauseContext.getMetas(): MetaContainer = when (this) { is PartiQLParser.SelectAllContext -> this.SELECT().getSourceMetaContainer() is PartiQLParser.SelectItemsContext -> this.SELECT().getSourceMetaContainer() is PartiQLParser.SelectValueContext -> this.SELECT().getSourceMetaContainer() is PartiQLParser.SelectPivotContext -> this.PIVOT().getSourceMetaContainer() else -> throw ParserException("Unknown meta location.", ErrorCode.PARSE_INVALID_QUERY) } /** * Converts a Path expression into a Projection Item (either ALL or EXPR). Note: A Projection Item only allows a * subset of a typical Path expressions. See the following examples. * * Examples of valid projections are: * * ```sql * SELECT * FROM foo * SELECT foo.* FROM foo * SELECT f.* FROM foo as f * SELECT foo.bar.* FROM foo * SELECT f.bar.* FROM foo as f * ``` * Also validates that the expression is valid for select list context. It does this by making * sure that expressions looking like the following do not appear: * * ```sql * SELECT foo[*] FROM foo * SELECT f.*.bar FROM foo as f * SELECT foo[1].* FROM foo * SELECT foo.*.bar FROM foo * ``` */ protected fun convertPathToProjectionItem(path: PartiqlAst.Expr.Path, alias: SymbolPrimitive?) = PartiqlAst.build { val steps = mutableListOf<PartiqlAst.PathStep>() var containsIndex = false path.steps.forEachIndexed { index, step -> // Only last step can have a '.*' if (step is PartiqlAst.PathStep.PathUnpivot && index != path.steps.lastIndex) { throw ParserException("Projection item cannot unpivot unless at end.", ErrorCode.PARSE_INVALID_QUERY) } // No step can have an indexed wildcard: '[*]' if (step is PartiqlAst.PathStep.PathWildcard) { throw ParserException("Projection item cannot index using wildcard.", ErrorCode.PARSE_INVALID_QUERY) } // If the last step is '.*', no indexing is allowed if (step.metas.containsKey(IsPathIndexMeta.TAG)) { containsIndex = true } if (step !is PartiqlAst.PathStep.PathUnpivot) { steps.add(step) } } if (path.steps.last() is PartiqlAst.PathStep.PathUnpivot && containsIndex) { throw ParserException("Projection item use wildcard with any indexing.", ErrorCode.PARSE_INVALID_QUERY) } when { path.steps.last() is PartiqlAst.PathStep.PathUnpivot && steps.isEmpty() -> projectAll(path.root, path.metas) path.steps.last() is PartiqlAst.PathStep.PathUnpivot -> projectAll( path(path.root, steps, path.metas), path.metas ) else -> projectExpr_(path, asAlias = alias, path.metas) } } private fun TerminalNode.getStringValue(): String = this.symbol.getStringValue() private fun Token.getStringValue(): String = when (this.type) { PartiQLParser.IDENTIFIER -> this.text PartiQLParser.IDENTIFIER_QUOTED -> this.text.removePrefix("\"").removeSuffix("\"").replace("\"\"", "\"") PartiQLParser.LITERAL_STRING -> this.text.removePrefix("'").removeSuffix("'").replace("''", "'") PartiQLParser.ION_CLOSURE -> this.text.removePrefix("`").removeSuffix("`") else -> throw this.err("Unsupported token for grabbing string value.", ErrorCode.PARSE_INVALID_QUERY) } private fun getStrategy(strategy: PartiQLParser.SetQuantifierStrategyContext?, default: PartiqlAst.SetQuantifier) = PartiqlAst.build { when { strategy == null -> default strategy.DISTINCT() != null -> distinct() strategy.ALL() != null -> all() else -> default } } private fun getStrategy(strategy: PartiQLParser.SetQuantifierStrategyContext?): PartiqlAst.SetQuantifier? { return when { strategy == null -> null strategy.DISTINCT() != null -> PartiqlAst.build { distinct() } else -> null } } private fun getSetQuantifierStrategy(ctx: PartiQLParser.SelectClauseContext): PartiqlAst.SetQuantifier? { return when (ctx) { is PartiQLParser.SelectAllContext -> getStrategy(ctx.setQuantifierStrategy()) is PartiQLParser.SelectItemsContext -> getStrategy(ctx.setQuantifierStrategy()) is PartiQLParser.SelectValueContext -> getStrategy(ctx.setQuantifierStrategy()) is PartiQLParser.SelectPivotContext -> null else -> null } } private fun PartiQLParser.SymbolPrimitiveContext.getString(): String { return when { this.IDENTIFIER_QUOTED() != null -> this.IDENTIFIER_QUOTED().getStringValue() this.IDENTIFIER() != null -> this.IDENTIFIER().text else -> throw ParserException("Unable to get symbol's text.", ErrorCode.PARSE_INVALID_QUERY) } } private fun getSymbolPathExpr(ctx: PartiQLParser.SymbolPrimitiveContext) = PartiqlAst.build { when { ctx.IDENTIFIER_QUOTED() != null -> pathExpr( lit(ionString(ctx.IDENTIFIER_QUOTED().getStringValue())), caseSensitive(), metas = ctx.IDENTIFIER_QUOTED().getSourceMetaContainer() ) ctx.IDENTIFIER() != null -> pathExpr( lit(ionString(ctx.IDENTIFIER().text)), caseInsensitive(), metas = ctx.IDENTIFIER().getSourceMetaContainer() ) else -> throw ParserException("Unable to get symbol's text.", ErrorCode.PARSE_INVALID_QUERY) } } private fun String.toInteger() = BigInteger(this, 10) private fun Token.toSymbol(): PartiqlAst.Expr.Lit { val str = this.text val metas = this.getSourceMetaContainer() return PartiqlAst.build { lit(ionSymbol(str), metas) } } private fun parseToIntElement(text: String): IntElement = try { ionInt(text.toLong()) } catch (e: NumberFormatException) { ionInt(text.toBigInteger()) } private fun assertIntegerElement(token: Token?, value: IonElement?) { if (value == null) return if (value !is IntElement) throw token.err("Expected an integer value.", ErrorCode.PARSE_MALFORMED_PARSE_TREE) if (value.integerSize == IntElementSize.BIG_INTEGER || value.longValue > Int.MAX_VALUE || value.longValue < Int.MIN_VALUE) throw token.err( "Type parameter exceeded maximum value", ErrorCode.PARSE_TYPE_PARAMETER_EXCEEDED_MAXIMUM_VALUE ) } private enum class ExplainParameters { TYPE, FORMAT; fun getCompliantString(target: String?, input: Token): String = when (target) { null -> input.text!! else -> throw input.error( "Cannot set EXPLAIN parameter ${this.name} multiple times.", ErrorCode.PARSE_UNEXPECTED_TOKEN ) } } private fun TerminalNode?.err( msg: String, code: ErrorCode, ctx: PropertyValueMap = PropertyValueMap(), cause: Throwable? = null ) = this.error(msg, code, ctx, cause) private fun Token?.err( msg: String, code: ErrorCode, ctx: PropertyValueMap = PropertyValueMap(), cause: Throwable? = null ) = this.error(msg, code, ctx, cause) }
256
null
61
526
f7bff3d196c0b4ebd03331c13c524ec62145956a
92,878
partiql-lang-kotlin
Apache License 2.0
2020/src/main/kotlin/org/suggs/adventofcode/Day03TobogganTrajectory.kt
suggitpe
321,028,552
false
{"Kotlin": 151090}
package org.suggs.adventofcode import org.slf4j.LoggerFactory /** * @see https://adventofcode.com/2020/day/3 */ class Day03TobogganTrajectory(hillMap: List<String>) { private val widthOfHillMap: Int = hillMap[0].length private val sizeOfHill: Int = hillMap.size private val treeCoordinates: List<List<Int>> = hillMap.map { Regex("#").findAll(it).map { it.range.first }.toList() } companion object { private val log = LoggerFactory.getLogger(this::class.java) fun buildHillFrom(hill: List<String>): Day03TobogganTrajectory { return Day03TobogganTrajectory(hill) } } fun isATree(coordinates: Pair<Int, Int>): Boolean { return treeCoordinates[coordinates.second].contains(coordinates.first % widthOfHillMap) } fun countTheTreesAsYouTobogganOnPathOf(direction: Pair<Int, Int>): Long { fun countTheTreesAsYouTobogganOnPathOf(currentLocation: Pair<Int, Int>, direction: Pair<Int, Int>, treeCount: Long): Long { return if (currentLocation.second + direction.second > sizeOfHill) { log.info("For the direction $direction we bumped into $treeCount trees") treeCount } else { countTheTreesAsYouTobogganOnPathOf(Pair(currentLocation.first + direction.first, currentLocation.second + direction.second), direction, treeCount + isATree(currentLocation).compareTo(false)) } } return countTheTreesAsYouTobogganOnPathOf(Pair(0, 0), direction, 0) } }
0
Kotlin
0
0
89a98a448a24851ccc114330672eff3636f4f239
1,541
advent-of-code
Apache License 2.0
year2021/day02/part1/src/main/kotlin/com/curtislb/adventofcode/year2021/day02/part1/Year2021Day02Part1.kt
curtislb
226,797,689
false
{"Kotlin": 2014224}
/* --- Day 2: Dive! --- Now, you need to figure out how to pilot this thing. It seems like the submarine can take a series of commands like `forward 1`, `down 2`, or `up 3`: - `forward X` increases the horizontal position by X units. - `down X` increases the depth by X units. - `up X` decreases the depth by X units. Note that since you're on a submarine, `down` and `up` affect your depth, and so they have the opposite result of what you might expect. The submarine seems to already have a planned course (your puzzle input). You should probably figure out where it's going. For example: ``` forward 5 down 5 forward 8 up 3 down 8 forward 2 ``` Your horizontal position and depth both start at 0. The steps above would then modify them as follows: - `forward 5` adds 5 to your horizontal position, a total of 5. - `down 5` adds 5 to your depth, resulting in a value of 5. - `forward 8` adds 8 to your horizontal position, a total of 13. - `up 3` decreases your depth by 3, resulting in a value of 2. - `down 8` adds 8 to your depth, resulting in a value of 10. - `forward 2` adds 2 to your horizontal position, a total of 15. After following these instructions, you would have a horizontal position of 15 and a depth of 10. (Multiplying these together produces 150.) Calculate the horizontal position and depth you would have after following the planned course. What do you get if you multiply your final horizontal position by your final depth? */ package com.curtislb.adventofcode.year2021.day02.part1 import com.curtislb.adventofcode.year2021.day02.submarine.SimpleSubmarine import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2021, day 2, part 1. * * @param inputPath The path to the input file for this puzzle. * @param initialPosition The horizontal position of the submarine before running any commands. * @param initialDepth The depth of the submarine before running any commands. */ fun solve( inputPath: Path = Paths.get("..", "input", "input.txt"), initialPosition: Int = 0, initialDepth: Int = 0 ): Int { val submarine = SimpleSubmarine(initialPosition, initialDepth) inputPath.toFile().forEachLine { submarine.runCommand(it) } return submarine.horizontalPosition * submarine.depth } fun main() { println(solve()) }
0
Kotlin
1
1
a55341d18b4a44f05efbc9b0b9583e11d9528285
2,325
AdventOfCode
MIT License
feature/profile/src/main/java/com/redpine/profile/presentation/profile/ProfileViewModel.kt
maiow
600,207,272
false
null
package com.redpine.profile.presentation.profile import androidx.lifecycle.viewModelScope import com.redpine.core.base.BaseViewModel import com.redpine.core.domain.AuthDialogPrefs import com.redpine.profile.domain.usecase.DeleteAccountUseCase import com.redpine.profile.domain.usecase.LogoutUseCase import com.redpine.profile.domain.usecase.ProfileInfoUseCase import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import javax.inject.Inject class ProfileViewModel @Inject constructor( private val profileInfoUseCase: ProfileInfoUseCase, private val deleteAccountUseCase: DeleteAccountUseCase, private val logoutUseCase: LogoutUseCase, private val authDialogPrefs: AuthDialogPrefs ) : BaseViewModel() { private val _isAuth = MutableStateFlow(false) val isAuth = _isAuth.asStateFlow() var authDialogIsShown = authDialogPrefs.isShown() private val _email = MutableStateFlow("") val email = _email.asStateFlow() private val _actionResult = MutableSharedFlow<UserActionResult>() val actionResult = _actionResult.asSharedFlow() fun onRetryButtonClick() = checkAuth() fun checkAuth() { viewModelScope.launch(Dispatchers.IO) { _isAuth.value = profileInfoUseCase.isUserAuthorized() authDialogIsShown = authDialogPrefs.isShown() if (_isAuth.value) { _email.value = profileInfoUseCase.getEmail() } } } fun resetAuthCheck() { _isAuth.value = false } fun rememberAuthDialogIsShown() = authDialogPrefs.rememberAuthDialogIsShown() fun logout() { viewModelScope.launch(Dispatchers.IO) { if (logoutUseCase.logout()) { _actionResult.emit(UserActionResult.LOGOUT) _email.value = LOGGED_OUT _isAuth.value = false } } } fun deleteAccount(password: String) { viewModelScope.launch(Dispatchers.IO) { if (!deleteAccountUseCase.reauthenticateUser(password)) _actionResult.emit(UserActionResult.REAUTH_FAILED) else if (deleteAccountUseCase.deleteAccount()) { _actionResult.emit(UserActionResult.ACCOUNT_DELETED) _isAuth.value = false } else _actionResult.emit(UserActionResult.ERROR) } } enum class UserActionResult { LOGOUT, REAUTH_FAILED, ACCOUNT_DELETED, ERROR } companion object { const val LOGGED_OUT = "You have logged out" } }
5
null
1
5
483c2af3380e45053fbbede964365a0a7a649dfa
2,738
dog-shelter
MIT License
app/src/main/java/com/vipulasri/jetinstagram/model/Favourite.kt
vldtc
630,199,689
false
null
package com.vipulasri.jetinstagram.model data class Favourite( val id: Int, val user: User )
0
Kotlin
0
0
38df85fd83d6204c9000dd6a143937f7116e868b
101
InstagramKnockoff
Apache License 2.0
shared/src/commonMain/kotlin/com/petros/efthymiou/dailypulse/articles/data/ArticlesDataSource.kt
ricodroid404
779,098,721
false
{"Kotlin": 24351, "Swift": 9122}
package com.petros.efthymiou.dailypulse.articles.data import petros.efthymiou.dailypulse.db.DailyPulseDatabase class ArticlesDataSource(private val database: DailyPulseDatabase) { fun getAllArticles(): List<ArticleRaw> = database.dailyPulseDatabaseQueries.selectAllArticles(::mapToArticleRaw).executeAsList() fun insertArticles(articles: List<ArticleRaw>) { database.dailyPulseDatabaseQueries.transaction { articles.forEach { articleRaw -> insertArticle(articleRaw) } } } fun clearArticles() = database.dailyPulseDatabaseQueries.removeAllArticles() private fun insertArticle(articleRaw: ArticleRaw) { database.dailyPulseDatabaseQueries.insertArticle( articleRaw.title, articleRaw.desc, articleRaw.date, articleRaw.imageUrl ) } private fun mapToArticleRaw( title: String, desc: String?, date: String, url: String? ): ArticleRaw = ArticleRaw( title, desc, date, url ) }
0
Kotlin
0
0
67a41ec61ff4d612bdd8e88a672996ec0b6915e4
1,138
kmp_ls2
Apache License 2.0
walletconnectv2/src/main/kotlin/org/walletconnect/walletconnectv2/crypto/Codec.kt
WalletConnect-Labs
397,808,009
false
null
package org.walletconnect.walletconnectv2.crypto import org.walletconnect.walletconnectv2.crypto.data.EncryptionPayload import org.walletconnect.walletconnectv2.crypto.data.PublicKey interface Codec { fun encrypt(message: String, sharedKey: String, publicKey: PublicKey): EncryptionPayload fun decrypt(payload: EncryptionPayload, sharedKey: String): String }
1
Kotlin
2
11
b05a1990cfbfc43b3380274183c33b0b7b307dc2
369
WalletConnectKotlinV2
Apache License 2.0
app/src/main/java/dev/vengateshm/composableshub/tabs/TabScreen.kt
vengateshm
667,731,144
false
null
package dev.vengateshm.composableshub.tabs import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.material3.Icon import androidx.compose.material3.ScrollableTabRow import androidx.compose.material3.Tab import androidx.compose.material3.TabRow import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlinx.coroutines.launch @OptIn(ExperimentalFoundationApi::class) @Composable fun TabLayoutSample() { val tabItems = remember { listOf( TabItem(title = "Dashboard", icon = TabIcons.Dashboard), TabItem(title = "Bookmarks", icon = TabIcons.Bookmarks), TabItem(title = "Settings", icon = TabIcons.Settings), TabItem(title = "Cloud Sync", icon = TabIcons.CloudSync), ) /*listOf( TabItem(title = "Dashboard", icon = null), TabItem(title = "Bookmarks", icon =null), TabItem(title = "Settings", icon = null), TabItem(title = "Cloud Sync", icon = null), )*/ } val pagerState = rememberPagerState( initialPage = 0, initialPageOffsetFraction = 0f, pageCount = { tabItems.size } ) val scope = rememberCoroutineScope() Column { // TabRow(selectedTabIndex = pagerState.currentPage) { ScrollableTabRow(selectedTabIndex = pagerState.currentPage, edgePadding = 0.dp) { tabItems.forEachIndexed { index, item -> TabView( title = item.title, icon = item.icon, isSelected = pagerState.currentPage == index, onClicked = { scope.launch { pagerState.animateScrollToPage(index) } } ) } } HorizontalPager(state = pagerState) { currentPage -> TabScreen(title = tabItems[currentPage].title) } } } @Composable fun TabView( title: String, icon: ImageVector?, isSelected: Boolean, onClicked: () -> Unit, ) { Tab( selected = isSelected, onClick = onClicked, text = { Text(text = title) }, icon = if (icon != null) { { Icon(imageVector = icon, contentDescription = "$title tab icon") } } else null ) } @Composable fun TabScreen(title: String) { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { Text( text = title, fontSize = 32.sp ) } }
0
Kotlin
0
0
820d1f89faaa803d50b3442539115fd1ae1e7690
3,199
ComposablesHub
Apache License 2.0
common/src/jvmMain/kotlin/com/monta/ocpp/emulator/common/WindowExtensions.kt
monta-app
789,343,716
false
{"Kotlin": 373123}
package com.monta.ocpp.emulator.common import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.DisposableEffect import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.window.ApplicationScope import androidx.compose.ui.window.FrameWindowScope import androidx.compose.ui.window.LocalWindowExceptionHandlerFactory import androidx.compose.ui.window.Window import androidx.compose.ui.window.WindowExceptionHandler import androidx.compose.ui.window.WindowExceptionHandlerFactory import androidx.compose.ui.window.WindowState import io.sentry.Sentry import mu.KotlinLogging import java.awt.event.WindowEvent import java.awt.event.WindowFocusListener private val logger = KotlinLogging.logger {} @OptIn(ExperimentalComposeUiApi::class) @Composable fun ApplicationScope.BaseMontaWindow( title: String, state: WindowState, windowGainedFocus: () -> Unit = {}, windowLostFocus: () -> Unit = {}, block: @Composable FrameWindowScope.() -> Unit ) { CompositionLocalProvider( LocalWindowExceptionHandlerFactory.provides( WindowExceptionHandlerFactory { window -> WindowExceptionHandler { throwable -> Sentry.captureException(throwable) logger.error("Window Exception", throwable) window.dispatchEvent(WindowEvent(window, WindowEvent.WINDOW_CLOSING)) throw throwable } } ) ) { Window( title = title, state = state, focusable = true, onCloseRequest = { this.exitApplication() } ) { DisposableEffect(Unit) { window.addWindowFocusListener(object : WindowFocusListener { override fun windowGainedFocus( e: WindowEvent ) { windowGainedFocus() } override fun windowLostFocus( e: WindowEvent ) { windowLostFocus() } }) onDispose {} } block() } } }
7
Kotlin
4
89
3ec9445ca517e97a0dba2f0a05b7ed38ac37faf5
2,312
ocpp-emulator
Apache License 2.0
lib/src/main/kotlin/be/zvz/klover/track/playback/TerminatorAudioFrame.kt
organization
673,130,266
false
null
package be.zvz.klover.track.playback import be.zvz.klover.format.AudioDataFormat /** * Audio frame where [.isTerminator] is `true`. */ class TerminatorAudioFrame : AudioFrame { override val timecode: Long get() { throw UnsupportedOperationException() } override val volume: Int get() { throw UnsupportedOperationException() } override val dataLength: Int get() { throw UnsupportedOperationException() } override val data: ByteArray? get() { throw UnsupportedOperationException() } override fun getData(buffer: ByteArray?, offset: Int) { throw UnsupportedOperationException() } override val format: AudioDataFormat? get() { throw UnsupportedOperationException() } override val isTerminator: Boolean get() = true companion object { val INSTANCE = TerminatorAudioFrame() } }
1
Kotlin
0
2
06e801808933ff8c627543d579c4be00061eb305
983
Klover
Apache License 2.0
app/src/main/java/com/engineerfred/kotlin/ktor/ui/screens/admin/login/AdminLoginScreenState.kt
EngFred
763,078,300
false
{"Kotlin": 375304}
package com.engineerfred.kotlin.ktor.ui.screens.admin.login import com.engineerfred.kotlin.ktor.domain.model.Admin data class AdminLoginScreenState( val loginInProgress: Boolean = false, val emailValue: String = "", val passwordValue: String = "", val lastNameValue: String = "", val firstNameValue: String = "", val emailValueError: String? = null, val loginError: String? = null, val admin: Admin? = null, val changingUser: Boolean = false, val notAdminClickSuccess: Boolean = false, val notAdminClickError: String? = null, )
0
Kotlin
0
0
bf9031db3581709d5de44181361e1246850b6092
579
quiz-quest
MIT License
presentation/src/main/kotlin/io/mateam/playground/presentation/details/viewModel/MovieDetailsViewModel.kt
AndZp
198,453,114
false
null
package io.mateam.playground.presentation.details.viewModel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import io.mateam.playground.presentation.details.entity.ReviewUiModel import io.mateam.playground.presentation.details.mapper.MoviesDetailsUiMapper import io.mateam.playground.presentation.popular.paginator.PaginationHelper import io.mateam.playground2.domain.entity.movie.Genre import io.mateam.playground2.domain.entity.movie.MovieFullDetails import io.mateam.playground2.domain.entity.movie.MovieReviews import io.mateam.playground2.domain.entity.movie.Review import io.mateam.playground2.domain.entity.result.Failure import io.mateam.playground2.domain.useCase.GetMovieReview import io.mateam.playground2.domain.useCase.GetMoviesFullDetails import io.mateam.playground2.domain.utils.logDebug import io.mateam.playground2.domain.utils.logWarning class MovieDetailsViewModel( private val movieId: Int, private val getReviews: GetMovieReview, private val getMoviesFullDetails: GetMoviesFullDetails, private val uiMapper: MoviesDetailsUiMapper, private val reviewsPaginationHelper: PaginationHelper<Review> ) : ViewModel() { val reviewState = MutableLiveData<MoviesReviewState>() val genersTags = MutableLiveData<List<String>>() init { loadFullDetails() loadMoreReview() } private fun loadFullDetails() { logDebug("loadFullDetails: movieId [$movieId]") val params = GetMoviesFullDetails.Param(movieId) getMoviesFullDetails(viewModelScope, params) { it.either(::handleDetailsFailure, ::handleDetailsSuccess) } } fun loadMoreReview() { logDebug("loadMoreReview: paginationHelper.nextPage [${reviewsPaginationHelper.nextPage}]") reviewState.postValue(MoviesReviewState.Loading) val params = GetMovieReview.Param(movieId, reviewsPaginationHelper.nextPage) getReviews(viewModelScope, params) { it.either(::handleReviewFailure, ::handleReviewSuccess) } } private fun handleDetailsFailure(failure: Failure) { logDebug("handleDetailsFailure: [${failure.javaClass.simpleName}]") when (failure) { is GetMoviesFullDetails.GetMovieFailure.LoadError -> reviewState.postValue(MoviesReviewState.LoadingError) else -> logWarning("handleReviewFailure: Unexpected failure [$failure]") } } private fun handleDetailsSuccess(movieFullDetails: MovieFullDetails) { logDebug("handleDetailsSuccess, movie id = [${movieFullDetails.id}, title [${movieFullDetails.title}") movieFullDetails.genres?.let { postGenres(it) } } private fun handleReviewFailure(failure: Failure) { logDebug("handleReviewFailure: [${failure.javaClass.simpleName}]") when (failure) { is GetMoviesFullDetails.GetMovieFailure.LoadError -> reviewState.postValue(MoviesReviewState.LoadingError) else -> logWarning("handleReviewFailure: Unexpected failure [$failure]") } } private fun handleReviewSuccess(movieReviews: MovieReviews) { logDebug("handleReviewSuccess, movie revies = id = [${movieReviews.id}, page [${movieReviews.page}, reviews size = [${movieReviews.reviews.size}") reviewsPaginationHelper.onSuccessLoad(movieReviews.reviews) postPopularMovies(reviewsPaginationHelper.allItems) } private fun postPopularMovies(reviews: List<Review>) { val uiMoviesModels = uiMapper.mapReview(reviews) reviewState.postValue(MoviesReviewState.Success(uiMoviesModels)) } private fun postGenres(genres: List<Genre>) { val genresTags = genres.map { it.name } genersTags.postValue(genresTags) } } sealed class MoviesReviewState { object Loading : MoviesReviewState() object LoadingError : MoviesReviewState() data class Success(val reviews: List<ReviewUiModel>) : MoviesReviewState() }
0
Kotlin
2
1
e369ce8d2c65e1ba3915ebfea060bf6efdc1e9b9
3,967
Clean-MVVM-Coroutines
Do What The F*ck You Want To Public License
utils/extensions/src/main/java/com/steleot/jetpackcompose/playground/utils/StringExtensions.kt
Vivecstel
338,792,534
false
{"Kotlin": 1538487}
package com.steleot.jetpackcompose.playground.utils import java.util.* fun String.capitalizeFirstLetter(): String { return this.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() } }
1
Kotlin
46
346
0161d9c7bf2eee53270ba2227a61d71ba8292ad0
231
Jetpack-Compose-Playground
Apache License 2.0
app/src/main/java/com/example/yzrsunnyweather/ui/weather/WeatherViewModel.kt
ycookiee
505,773,390
false
null
package com.example.yzrsunnyweather.ui.weather import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import androidx.lifecycle.ViewModel import com.example.yzrsunnyweather.logic.Repository import com.example.yzrsunnyweather.logic.model.PlaceResponse class WeatherViewModel : ViewModel() { private val locationLiveData = MutableLiveData<PlaceResponse.Location>() var locationLng = "" var locationLat = "" var placeName = "" val weatherLiveData = Transformations.switchMap(locationLiveData) { location -> Repository.refreshWeather(location.lng, location.lat) } fun refreshWeather(lng: String, lat: String) { locationLiveData.value = PlaceResponse.Location(lng, lat) } }
0
Kotlin
0
0
26b5cd6603aee2714790a5f24771d0de8da416df
752
YzrSunnyWeather
Apache License 2.0
src/rider/main/kotlin/com/github/rafaelldi/diagnosticsclientplugin/actions/counters/StartLiveCounterSessionAction.kt
rafaelldi
487,741,199
false
null
package com.github.rafaelldi.diagnosticsclientplugin.actions.counters import com.github.rafaelldi.diagnosticsclientplugin.actions.common.StartLiveSessionAction import com.github.rafaelldi.diagnosticsclientplugin.dialogs.CountersDialog import com.github.rafaelldi.diagnosticsclientplugin.generated.LiveCounterSession import com.github.rafaelldi.diagnosticsclientplugin.generated.diagnosticsHostModel import com.github.rafaelldi.diagnosticsclientplugin.services.counters.LiveCounterSessionController import com.github.rafaelldi.diagnosticsclientplugin.services.counters.CounterSettings import com.github.rafaelldi.diagnosticsclientplugin.utils.DotNetProcess import com.intellij.openapi.project.Project import com.jetbrains.rider.projectView.solution class StartLiveCounterSessionAction : StartLiveSessionAction<LiveCounterSession>() { override fun startSession(selected: DotNetProcess, processes: List<DotNetProcess>, project: Project) { val dialog = CountersDialog(project, selected, processes, false) if (dialog.showAndGet()) { val model = dialog.getModel() CounterSettings.getInstance(project).update(model, false) LiveCounterSessionController.getInstance(project).startSession(model) } } override fun getSession(selected: DotNetProcess, project: Project) = project.solution.diagnosticsHostModel.liveCounterSessions[selected.pid] }
3
Kotlin
0
4
8d4cfd9f4992ad10010d80c2359158399f4846aa
1,415
diagnostics-client-plugin
MIT License
src/main/kotlin/org/scofield/claims/ext/PlayerIsOpExt.kt
mscofield0
306,871,622
false
null
package org.scofield.claims.ext import net.minecraft.server.network.ServerPlayerEntity fun ServerPlayerEntity.isOp() = this.server.playerManager.isOperator(this.gameProfile)
0
Kotlin
0
0
ec0e529d39f705729c11f51a491a01c43c90b0a8
175
claims
Creative Commons Zero v1.0 Universal
kotlin-electron/src/jsMain/generated/electron/common/TouchBarPopoverConstructorOptions.kt
JetBrains
93,250,841
false
{"Kotlin": 11400167, "JavaScript": 146545}
package electron.common typealias TouchBarPopoverConstructorOptions = electron.core.TouchBarPopoverConstructorOptions
28
Kotlin
173
1,250
d1f8f5d805ffa18431dfefb7a1aa2f67f48915f6
120
kotlin-wrappers
Apache License 2.0
libraries/stdlib/coroutines/jvm/src/kotlin/coroutines/experimental/migration/CoroutinesMigration.kt
latheesh123
141,489,330
true
{"Kotlin": 28539168, "Java": 7544965, "JavaScript": 153376, "HTML": 65245, "Lex": 18269, "ANTLR": 9797, "IDL": 8755, "Shell": 6769, "CSS": 4679, "Batchfile": 4437, "Groovy": 4358}
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ package kotlin.coroutines.experimental.migration import kotlin.coroutines.experimental.Continuation as ExperimentalContinuation import kotlin.coroutines.experimental.CoroutineContext as ExperimentalCoroutineContext import kotlin.coroutines.experimental.AbstractCoroutineContextElement as ExperimentalAbstractCoroutineContextElement import kotlin.coroutines.experimental.EmptyCoroutineContext as ExperimentalEmptyCoroutineContext import kotlin.coroutines.experimental.ContinuationInterceptor as ExperimentalContinuationInterceptor import kotlin.coroutines.experimental.intrinsics.COROUTINE_SUSPENDED as EXPERIMENTAL_COROUTINE_SUSPENDED import kotlin.coroutines.* import kotlin.coroutines.intrinsics.* /** * Adapter to invoke experimental suspending function. * * To invoke experimental suspending function `foo(args)` that returns value of some type `Result` * from Kotlin 1.3 use the following code: * * ``` * invokeExperimentalSuspend<Result> { foo(args, it) } * ``` */ @SinceKotlin("1.3") public suspend inline fun <T> invokeExperimentalSuspend(crossinline invocation: (ExperimentalContinuation<T>) -> Any?): T = suspendCoroutineUninterceptedOrReturn { continuation -> val result = invocation(continuation.toExperimentalContinuation()) @Suppress("UNCHECKED_CAST") if (result === EXPERIMENTAL_COROUTINE_SUSPENDED) COROUTINE_SUSPENDED else result as T } /** * Coverts reference to suspending function to experimental suspending function. */ @SinceKotlin("1.3") public fun <T> (suspend () -> T).toExperimentalSuspendFunction(): (ExperimentalContinuation<T>) -> Any? = ExperimentalSuspendFunction0Migration(this) /** * Coverts reference to experimental suspending function to suspending function. */ @SinceKotlin("1.3") public fun <T> ((ExperimentalContinuation<T>) -> Any?).toSuspendFunction(): suspend () -> T = (this as? ExperimentalSuspendFunction0Migration)?.function ?: SuspendFunction0Migration(this)::invoke /** * Coverts reference to suspending function with receiver to experimental suspending function. */ @SinceKotlin("1.3") public fun <R, T> (suspend (R) -> T).toExperimentalSuspendFunction(): (R, ExperimentalContinuation<T>) -> Any? = ExperimentalSuspendFunction1Migration(this) /** * Coverts reference to experimental suspending function with receiver to suspending function. */ @SinceKotlin("1.3") public fun <R, T> ((R, ExperimentalContinuation<T>) -> Any?).toSuspendFunction(): suspend (R) -> T = (this as? ExperimentalSuspendFunction1Migration)?.function ?: SuspendFunction1Migration(this)::invoke /** * Converts [Continuation] to [ExperimentalContinuation]. */ @SinceKotlin("1.3") public fun <T> Continuation<T>.toExperimentalContinuation(): ExperimentalContinuation<T> = (this as? ContinuationMigration<T>)?.continuation ?: ExperimentalContinuationMigration(this) /** * Converts [ExperimentalContinuation] to [Continuation]. */ @SinceKotlin("1.3") public fun <T> ExperimentalContinuation<T>.toContinuation(): Continuation<T> = (this as? ExperimentalContinuationMigration<T>)?.continuation ?: ContinuationMigration(this) /** * Converts [CoroutineContext] to [ExperimentalCoroutineContext]. */ @SinceKotlin("1.3") public fun CoroutineContext.toExperimentalCoroutineContext(): ExperimentalCoroutineContext { val interceptor = get(ContinuationInterceptor.Key) val migration = get(ContextMigration.Key) val remainder = minusKey(ContinuationInterceptor.Key).minusKey(ContextMigration.Key) val original = migration?.context ?: ExperimentalEmptyCoroutineContext val result = if (remainder === EmptyCoroutineContext) original else original + ExperimentalContextMigration(remainder) return if (interceptor == null) result else result + interceptor.toExperimentalContinuationInterceptor() } /** * Converts [ExperimentalCoroutineContext] to [CoroutineContext]. */ @SinceKotlin("1.3") public fun ExperimentalCoroutineContext.toCoroutineContext(): CoroutineContext { val interceptor = get(ExperimentalContinuationInterceptor.Key) val migration = get(ExperimentalContextMigration.Key) val remainder = minusKey(ExperimentalContinuationInterceptor.Key).minusKey(ExperimentalContextMigration.Key) val original = migration?.context ?: EmptyCoroutineContext val result = if (remainder === ExperimentalEmptyCoroutineContext) original else original + ContextMigration(remainder) return if (interceptor == null) result else result + interceptor.toContinuationInterceptor() } /** * Converts [ContinuationInterceptor] to [ExperimentalContinuationInterceptor]. */ @SinceKotlin("1.3") public fun ContinuationInterceptor.toExperimentalContinuationInterceptor(): ExperimentalContinuationInterceptor = (this as? ContinuationInterceptorMigration)?.interceptor ?: ExperimentalContinuationInterceptorMigration(this) /** * Converts [ExperimentalContinuationInterceptor] to [ContinuationInterceptor]. */ @SinceKotlin("1.3") public fun ExperimentalContinuationInterceptor.toContinuationInterceptor(): ContinuationInterceptor = (this as? ExperimentalContinuationInterceptorMigration)?.interceptor ?: ContinuationInterceptorMigration(this) // ------------------ converter classes ------------------ // Their name starts with "Experimental" if they implement the corresponding Experimental interfaces private class ExperimentalSuspendFunction0Migration<T>(val function: suspend () -> T) : (ExperimentalContinuation<T>) -> Any? { override fun invoke(continuation: ExperimentalContinuation<T>): Any? { val result = function.startCoroutineUninterceptedOrReturn(continuation.toContinuation()) return if (result === COROUTINE_SUSPENDED) EXPERIMENTAL_COROUTINE_SUSPENDED else result } } private class SuspendFunction0Migration<T>(val function: (ExperimentalContinuation<T>) -> Any?) { suspend fun invoke(): T = suspendCoroutineUninterceptedOrReturn { continuation -> val result = function(continuation.toExperimentalContinuation()) if (result === EXPERIMENTAL_COROUTINE_SUSPENDED) COROUTINE_SUSPENDED else result } } private class ExperimentalSuspendFunction1Migration<R, T>(val function: suspend (R) -> T) : (R, ExperimentalContinuation<T>) -> Any? { override fun invoke(receiver: R, continuation: ExperimentalContinuation<T>): Any? { val result = function.startCoroutineUninterceptedOrReturn(receiver, continuation.toContinuation()) return if (result === COROUTINE_SUSPENDED) EXPERIMENTAL_COROUTINE_SUSPENDED else result } } private class SuspendFunction1Migration<R, T>(val function: (R, ExperimentalContinuation<T>) -> Any?) { suspend fun invoke(receiver: R): T = suspendCoroutineUninterceptedOrReturn { continuation -> val result = function(receiver, continuation.toExperimentalContinuation()) if (result === EXPERIMENTAL_COROUTINE_SUSPENDED) COROUTINE_SUSPENDED else result } } private class ExperimentalContinuationMigration<T>(val continuation: Continuation<T>): ExperimentalContinuation<T> { override val context = continuation.context.toExperimentalCoroutineContext() override fun resume(value: T) = continuation.resume(value) override fun resumeWithException(exception: Throwable) = continuation.resumeWithException(exception) } private class ContinuationMigration<T>(val continuation: ExperimentalContinuation<T>): Continuation<T> { override val context: CoroutineContext = continuation.context.toCoroutineContext() override fun resumeWith(result: SuccessOrFailure<T>) { result .onSuccess { continuation.resume(it) } .onFailure { continuation.resumeWithException(it) } } } private class ExperimentalContextMigration(val context: CoroutineContext): ExperimentalAbstractCoroutineContextElement(Key) { companion object Key : ExperimentalCoroutineContext.Key<ExperimentalContextMigration> } private class ContextMigration(val context: ExperimentalCoroutineContext): AbstractCoroutineContextElement(Key) { companion object Key : CoroutineContext.Key<ContextMigration> } private class ExperimentalContinuationInterceptorMigration(val interceptor: ContinuationInterceptor) : ExperimentalContinuationInterceptor { override val key: ExperimentalCoroutineContext.Key<*> get() = ExperimentalContinuationInterceptor.Key override fun <T> interceptContinuation(continuation: ExperimentalContinuation<T>): ExperimentalContinuation<T> = interceptor.interceptContinuation(continuation.toContinuation()).toExperimentalContinuation() } private class ContinuationInterceptorMigration(val interceptor: ExperimentalContinuationInterceptor) : ContinuationInterceptor { override val key: CoroutineContext.Key<*> get() = ContinuationInterceptor.Key override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> = interceptor.interceptContinuation(continuation.toExperimentalContinuation()).toContinuation() }
0
Kotlin
0
0
094cb6be1d351022a1d6a8cdcd1c30f74a6c82e3
9,136
kotlin
Apache License 2.0
opendc-experiments/opendc-experiments-serverless20/src/main/kotlin/org/opendc/experiments/serverless/trace/ServerlessTraceReader.kt
atlarge-research
79,902,234
false
null
/* * Copyright (c) 2021 AtLarge Research * * 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 org.opendc.experiments.serverless.trace import mu.KotlinLogging import java.io.File import kotlin.math.max /** * A trace reader for the serverless workload trace used in the OpenDC Serverless thesis. */ public class ServerlessTraceReader { /** * The logger for this portfolio instance. */ private val logger = KotlinLogging.logger {} /** * Parse the traces at the specified [path]. */ public fun parse(path: File): List<FunctionTrace> { return if (path.isFile) { listOf(parseSingle(path)) } else { path.walk() .filterNot { it.isDirectory } .map { file -> logger.info { "Parsing $file" } parseSingle(file) } .toList() } } /** * Parse a single trace. */ private fun parseSingle(path: File): FunctionTrace { val samples = mutableListOf<FunctionSample>() val id = path.nameWithoutExtension var idx = 0 var timestampCol = 0 var invocationsCol = 0 var execTimeCol = 0 var provCpuCol = 0 var provMemCol = 0 var cpuUsageCol = 0 var memoryUsageCol = 0 var maxMemory = 0 path.forEachLine { line -> if (line.startsWith("#") && line.isNotBlank()) { return@forEachLine } val values = line.split(",") /* Header parsing */ if (idx++ == 0) { val header = values.mapIndexed { col, name -> Pair(name.trim(), col) }.toMap() timestampCol = header["Timestamp [ms]"]!! invocationsCol = header["Invocations"]!! execTimeCol = header["Avg Exec time per Invocation"]!! provCpuCol = header["Provisioned CPU [Mhz]"]!! provMemCol = header["Provisioned Memory [mb]"]!! cpuUsageCol = header["Avg cpu usage per Invocation [Mhz]"]!! memoryUsageCol = header["Avg mem usage per Invocation [mb]"]!! return@forEachLine } val timestamp = values[timestampCol].trim().toLong() val invocations = values[invocationsCol].trim().toInt() val execTime = values[execTimeCol].trim().toLong() val provisionedCpu = values[provCpuCol].trim().toInt() val provisionedMemory = values[provMemCol].trim().toInt() val cpuUsage = values[cpuUsageCol].trim().toDouble() val memoryUsage = values[memoryUsageCol].trim().toDouble() maxMemory = max(maxMemory, provisionedMemory) samples.add(FunctionSample(timestamp, execTime, invocations, provisionedCpu, provisionedMemory, cpuUsage, memoryUsage)) } return FunctionTrace(id, maxMemory, samples) } }
9
Kotlin
14
41
578394adfb5f1f835b7d8e24f68094968706dfaa
3,996
opendc
MIT License
libs/saksbehandling-common/src/main/kotlin/ShutdownHook.kt
navikt
417,041,535
false
{"Kotlin": 7287681, "TypeScript": 1786181, "Handlebars": 27910, "Shell": 12680, "PLpgSQL": 1891, "HTML": 1734, "CSS": 598, "Dockerfile": 547}
package no.nav.etterlatte import org.slf4j.LoggerFactory import java.util.Timer import java.util.concurrent.atomic.AtomicBoolean val shuttingDown: AtomicBoolean = AtomicBoolean(false) val logger = LoggerFactory.getLogger("shutdownhookLogger") fun addShutdownHook(timers: Collection<Timer>) = addShutdownHook(*timers.toTypedArray()) fun addShutdownHook(vararg timer: Timer) { try { Runtime.getRuntime().addShutdownHook( Thread { shuttingDown.set(true) timer.forEach { it.cancel() } }, ) } catch (e: IllegalStateException) { try { logger.warn("App er på vei ned allerede, kan ikke legge til shutdownhooks", e) } catch (e: Exception) { // Ignorer at vi ikke får logget på grunn av shutdown, da er det ikke noe å gjøre uansett } } }
8
Kotlin
0
6
5d27be4daf95f7e48f7c4eec8645c621d35bb60a
867
pensjon-etterlatte-saksbehandling
MIT License
app/src/main/java/datlowashere/project/rcoffee/data/model/response/ApiResponse.kt
SUMMER24-R-Coffee
801,556,779
false
{"Kotlin": 273830, "Java": 10931}
package datlowashere.project.rcoffee.data.model.response data class ApiResponse( val status: String, val message: String )
0
Kotlin
0
1
dbe25b6c2c22d376d30a21e8d11a0b0b6b0ca287
131
R-Coffee_App
MIT License
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsassessrisksandneedshandoverservice/integration/HandoverControllerTest.kt
ministryofjustice
803,229,302
false
{"Kotlin": 111890, "Dockerfile": 1126, "JavaScript": 743, "Makefile": 661}
package uk.gov.justice.digital.hmpps.hmppsassessrisksandneedshandoverservice.integration import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Value import org.springframework.http.HttpStatus import org.springframework.test.web.reactive.server.expectBody import uk.gov.justice.digital.hmpps.hmppsassessrisksandneedshandoverservice.config.AppConfiguration import uk.gov.justice.digital.hmpps.hmppsassessrisksandneedshandoverservice.context.entity.Location import uk.gov.justice.digital.hmpps.hmppsassessrisksandneedshandoverservice.context.entity.SubjectDetails import uk.gov.justice.digital.hmpps.hmppsassessrisksandneedshandoverservice.handlers.exceptions.ErrorResponse import uk.gov.justice.digital.hmpps.hmppsassessrisksandneedshandoverservice.handover.entity.HandoverToken import uk.gov.justice.digital.hmpps.hmppsassessrisksandneedshandoverservice.handover.repository.HandoverTokenRepository import uk.gov.justice.digital.hmpps.hmppsassessrisksandneedshandoverservice.handover.request.CreateHandoverLinkRequest import uk.gov.justice.digital.hmpps.hmppsassessrisksandneedshandoverservice.handover.response.CreateHandoverLinkResponse import uk.gov.justice.digital.hmpps.hmppsassessrisksandneedshandoverservice.handover.service.HandoverService import uk.gov.justice.digital.hmpps.hmppsassessrisksandneedshandoverservice.testUtils.TestUtils import uk.gov.justice.digital.hmpps.hmppsassessrisksandneedshandoverservice.testUtils.WireMockExtension import java.time.LocalDate import java.util.* @ExtendWith(WireMockExtension::class) class HandoverControllerTest : IntegrationTestBase() { @Autowired lateinit var handoverTokenRepository: HandoverTokenRepository @Autowired lateinit var appConfiguration: AppConfiguration @Autowired lateinit var handoverService: HandoverService @Value("\${server.servlet.session.cookie.name}") lateinit var sessionCookieName: String @Nested @DisplayName("createHandoverLink") inner class CreateHandoverLink { @Test fun `should return okay when authenticated`() { val handoverRequest = TestUtils.createHandoverRequest() val response = webTestClient.post().uri(appConfiguration.self.endpoints.handover) .bodyValue(handoverRequest) .header("Content-Type", "application/json") .header("Authorization", "Bearer ${jwtHelper.generateAuthToken()}") .exchange() .expectStatus().isOk .expectBody(CreateHandoverLinkResponse::class.java) .returnResult() .responseBody assertThat(response.handoverLink).startsWith(appConfiguration.self.externalUrl) assertThat(response.handoverSessionId).toString().isNotEmpty() } @Test fun `should return bad request when invalid request`() { val handoverRequest = CreateHandoverLinkRequest( user = TestUtils.createPrincipal(), subjectDetails = SubjectDetails( crn = "12345", pnc = "12345", nomisId = "", givenName = "", familyName = "Jenkins", dateOfBirth = LocalDate.of(1990, 1, 1), gender = 1, location = Location.PRISON, sexuallyMotivatedOffenceHistory = "invalid_answer", ), oasysAssessmentPk = "123", assessmentVersion = 1, planVersion = 1, ) val response = webTestClient.post().uri(appConfiguration.self.endpoints.handover) .bodyValue(handoverRequest) .header("Content-Type", "application/json") .header("Authorization", "Bearer ${jwtHelper.generateAuthToken()}") .exchange() .expectStatus().isBadRequest .expectBody(ErrorResponse::class.java) .returnResult() .responseBody assertThat(response.userMessage).contains("subjectDetails.sexuallyMotivatedOffenceHistory: must be either 'YES' or 'NO'") assertThat(response.userMessage).contains("subjectDetails.givenName: size must be between 1 and 25") } @Test fun `should return forbidden when unauthorized`() { val handoverRequest = TestUtils.createHandoverRequest() val response = webTestClient.post().uri(appConfiguration.self.endpoints.handover) .bodyValue(handoverRequest) .header("Content-Type", "application/json") .header("Authorization", "Bearer ${jwtHelper.generateHandoverToken(UUID.randomUUID())}") .exchange() .expectStatus().isForbidden .expectBody(ErrorResponse::class.java) .returnResult() .responseBody assertThat(response!!.developerMessage).isEqualTo("Token needs to be issued by HMPPS Auth") } @Test fun `should return forbidden when unauthenticated`() { val handoverRequest = TestUtils.createHandoverRequest() webTestClient.post().uri(appConfiguration.self.endpoints.handover) .bodyValue(handoverRequest) .header("Content-Type", "application/json") .exchange() .expectStatus().isUnauthorized } } @Nested @DisplayName("useHandoverLink") inner class UseHandoverLink { @Test fun `should return found when using handover link with valid code `() { val clientId = "test-client" val client: AppConfiguration.Client = appConfiguration.clients[clientId] ?: throw IllegalStateException() val handoverToken = handoverTokenRepository.save( HandoverToken( handoverSessionId = UUID.randomUUID(), principal = TestUtils.createPrincipal(), ), ) webTestClient.get().uri("/handover/${handoverToken.code}?clientId=$clientId") .exchange() .expectStatus().isFound .expectHeader().valueEquals("Location", client.handoverRedirectUri) .expectCookie().exists(sessionCookieName) } @Test fun `should return not found when using handover link with invalid code `() { val clientId = "test-client" val handoverCode = UUID.randomUUID().toString() val response = webTestClient.get().uri("/handover/$handoverCode?clientId=$clientId") .exchange() .expectStatus().isNotFound .expectBody(String::class.java) .returnResult() .responseBody assertThat(response).isEqualTo("Handover link expired or not found") } @Test fun `should return conflict when using handover link with already used code`() { val clientId = "test-client" val handoverToken = handoverTokenRepository.save( HandoverToken( handoverSessionId = UUID.randomUUID(), principal = TestUtils.createPrincipal(), ), ) handoverService.consumeAndExchangeHandover(handoverToken.code) val response = webTestClient.get().uri("/handover/${handoverToken.code}?clientId=$clientId") .exchange() .expectStatus().isEqualTo(HttpStatus.CONFLICT) .expectBody(String::class.java) .returnResult() .responseBody assertThat(response).isEqualTo("Handover link has already been used") } } }
5
Kotlin
0
1
3b809c94a363589a19283771a69a6620cd189bba
7,258
hmpps-assess-risks-and-needs-handover-service
MIT License
src/main/kotlin/com/salesforce/revoman/internal/exe/UnmarshallRequest.kt
salesforce-misc
677,000,343
false
{"Kotlin": 110471, "Java": 35697, "HTML": 720, "Starlark": 283}
package com.salesforce.revoman.internal.exe import arrow.core.Either import com.salesforce.revoman.input.config.Kick import com.salesforce.revoman.internal.asA import com.salesforce.revoman.internal.postman.pm import com.salesforce.revoman.output.Rundown import com.salesforce.revoman.output.Rundown.StepReport import com.salesforce.revoman.output.Rundown.StepReport.RequestFailure.UnmarshallRequestFailure import com.salesforce.revoman.output.Rundown.StepReport.TxInfo import java.lang.reflect.Type import org.http4k.core.Request import org.http4k.format.ConfigurableMoshi internal fun unmarshallRequest( stepName: String, pmRequest: com.salesforce.revoman.internal.postman.state.Request, kick: Kick, moshiReVoman: ConfigurableMoshi, stepNameToReport: Map<String, StepReport> ): Either<UnmarshallRequestFailure, TxInfo<Request>> { val httpRequest = pmRequest.toHttpRequest() val requestType: Type = (getRequestConfigForStepName(stepName, kick.stepNameToRequestConfig()) ?: pickRequestConfig( kick.pickToRequestConfig(), stepName, TxInfo(null, null, httpRequest), Rundown(stepNameToReport, pm.environment, kick.haltOnAnyFailureExceptForSteps()) )) ?.requestType ?: Any::class.java return when { isContentTypeApplicationJson(httpRequest) -> runChecked<Any?>(stepName, StepReport.ExeType.UNMARSHALL_REQUEST) { pmRequest.body?.let { body -> moshiReVoman.asA(body.raw, requestType) } } .mapLeft { UnmarshallRequestFailure(it, TxInfo(requestType, null, httpRequest)) } else -> Either.Right(null) // ! TODO 15/10/23 gopala.akshintala: xml2Json }.map { TxInfo(requestType, it, pmRequest.toHttpRequest()) } }
7
Kotlin
3
5
223bd35d2597a79645c359346f988b32ca1e7396
1,727
ReVoman
Apache License 2.0
app/src/main/java/com/serma/dionysus/common/ui/CommonTab.kt
asuka1211
350,113,092
false
null
package com.serma.dionysus.common.ui import androidx.compose.material.TabRow import androidx.compose.material.TabRowDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import com.google.accompanist.pager.ExperimentalPagerApi import com.google.accompanist.pager.PagerState import com.google.accompanist.pager.pagerTabIndicatorOffset @Deprecated("Used instead default") @ExperimentalPagerApi @Composable fun CommonTabRow( modifier: Modifier = Modifier, backgroundColor: Color, selectedPos: Int = 0, pagerState: PagerState, tabs: @Composable () -> Unit ) { TabRow( selectedPos, backgroundColor = backgroundColor, modifier = modifier, indicator = { tabPos -> TabRowDefaults.Indicator( Modifier.pagerTabIndicatorOffset(pagerState, tabPos) ) } ) { tabs() } } @Deprecated("Used instead default") @ExperimentalPagerApi @Composable fun <S, T : BaseTabItem<S>> CommonAutoTabRow( modifier: Modifier = Modifier, selectedPos: Int = 0, backgroundColor: Color, pagerState: PagerState, data: List<T>, tabView: @Composable (T, Int) -> Unit, ) { CommonTabRow( modifier = modifier, selectedPos = selectedPos, pagerState = pagerState, backgroundColor = backgroundColor ) { data.forEachIndexed { index, item -> tabView(item, index) } } } interface BaseTabItem<T> { val pos: Int val type: T }
0
Kotlin
0
0
92c1a65d5b52e4d14907f32a3d7d10028aca783e
1,578
DionysusProject
Apache License 2.0
common/src/iosMain/kotlin/com/outsidesource/oskitExample/common/SwiftInterop.kt
outsidesource
597,072,965
false
{"Kotlin": 100717, "Ruby": 2403, "Swift": 1884}
package com.outsidesource.oskitExample.common import com.outsidesource.oskitkmp.outcome.Outcome import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.channels.ProducerScope import kotlinx.coroutines.flow.* import kotlinx.coroutines.isActive import kotlin.coroutines.cancellation.CancellationException sealed class SwiftOutcome<out V, out E>(private val outcome: Outcome<V, E>) { data class Ok<out V, out E>(val value: V) : SwiftOutcome<V, E>(outcome = Outcome.Ok(value)) data class Error<out V, out E>(val error: E) : SwiftOutcome<V, E>(outcome = Outcome.Error(error)) fun unwrap() = outcome } // TODO: Might be able to add a heartbeat or something to check if the flow is still active /** * SwiftFlow * * Allows creation of a cold flow in Swift. Supports cancellation but is only checked when trying to emit or by calling * ensureActive() */ abstract class SwiftFlow<T : Any> { private var scope: ProducerScope<T>? = null @Throws(SwiftFlowCancellationException::class, CancellationException::class) protected suspend fun emit(value: T) { if (scope?.isActive == false) throw SwiftFlowCancellationException() scope?.send(value) } @Throws(SwiftFlowCancellationException::class, CancellationException::class) protected suspend fun ensureActive() { if (scope?.isActive == false) throw SwiftFlowCancellationException() } abstract suspend fun create() fun unwrap(): Flow<T> = channelFlow { scope = this try { create() } catch (e: SwiftFlowCancellationException) { // Do nothing } }.onCompletion { scope = null } } class SwiftMutableSharedFlow<T : Any>( replay: Int = 0, extraBufferCapacity: Int = 0, onBufferOverflow: BufferOverflow = BufferOverflow.SUSPEND ) { private val flow = MutableSharedFlow<T>(replay, extraBufferCapacity, onBufferOverflow) fun unwrap(): MutableSharedFlow<T> = flow } class SwiftMutableStateFlow<T : Any>(value: T) { private val flow = MutableStateFlow(value) fun unwrap(): MutableStateFlow<T> = flow } class SwiftFlowCancellationException : CancellationException("SwiftFlow has been cancelled")
0
Kotlin
0
0
b0106a0bc856cbade9f4d87cdcc8b822ee9567c9
2,226
OSKit-Example-App-KMP
MIT License
app/src/testDemo/kotlin/com/google/samples/apps/nowinandroid/ui/InterestsListDetailScreenTest.kt
android
483,402,734
false
{"Kotlin": 1043259, "Shell": 15315}
/* * Copyright 2024 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. */ package com.google.samples.apps.nowinandroid.ui import androidx.activity.compose.BackHandler import androidx.annotation.StringRes import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertIsNotDisplayed import androidx.compose.ui.test.junit4.AndroidComposeTestRule import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.test.espresso.Espresso import com.google.samples.apps.nowinandroid.core.data.repository.TopicsRepository import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme import com.google.samples.apps.nowinandroid.core.model.data.Topic import com.google.samples.apps.nowinandroid.ui.interests2pane.InterestsListDetailScreen import com.google.samples.apps.nowinandroid.uitesthiltmanifest.HiltComponentActivity import dagger.hilt.android.testing.HiltAndroidRule import dagger.hilt.android.testing.HiltAndroidTest import dagger.hilt.android.testing.HiltTestApplication import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import javax.inject.Inject import kotlin.properties.ReadOnlyProperty import kotlin.test.assertTrue import com.google.samples.apps.nowinandroid.feature.topic.R as FeatureTopicR private const val EXPANDED_WIDTH = "w1200dp-h840dp" private const val COMPACT_WIDTH = "w412dp-h915dp" @HiltAndroidTest @RunWith(RobolectricTestRunner::class) @Config(application = HiltTestApplication::class) class InterestsListDetailScreenTest { @get:Rule(order = 0) val hiltRule = HiltAndroidRule(this) @get:Rule(order = 1) val composeTestRule = createAndroidComposeRule<HiltComponentActivity>() @Inject lateinit var topicsRepository: TopicsRepository /** Convenience function for getting all topics during tests, */ private fun getTopics(): List<Topic> = runBlocking { topicsRepository.getTopics().first().sortedBy { it.name } } // The strings used for matching in these tests. private val placeholderText by composeTestRule.stringResource(FeatureTopicR.string.feature_topic_select_an_interest) private val listPaneTag = "interests:topics" private val Topic.testTag get() = "topic:${this.id}" @Before fun setup() { hiltRule.inject() } @Test @Config(qualifiers = EXPANDED_WIDTH) fun expandedWidth_initialState_showsTwoPanesWithPlaceholder() { composeTestRule.apply { setContent { NiaTheme { InterestsListDetailScreen() } } onNodeWithTag(listPaneTag).assertIsDisplayed() onNodeWithText(placeholderText).assertIsDisplayed() } } @Test @Config(qualifiers = COMPACT_WIDTH) fun compactWidth_initialState_showsListPane() { composeTestRule.apply { setContent { NiaTheme { InterestsListDetailScreen() } } onNodeWithTag(listPaneTag).assertIsDisplayed() onNodeWithText(placeholderText).assertIsNotDisplayed() } } @Test @Config(qualifiers = EXPANDED_WIDTH) fun expandedWidth_topicSelected_updatesDetailPane() { composeTestRule.apply { setContent { NiaTheme { InterestsListDetailScreen() } } val firstTopic = getTopics().first() onNodeWithText(firstTopic.name).performClick() onNodeWithTag(listPaneTag).assertIsDisplayed() onNodeWithText(placeholderText).assertIsNotDisplayed() onNodeWithTag(firstTopic.testTag).assertIsDisplayed() } } @Test @Config(qualifiers = COMPACT_WIDTH) fun compactWidth_topicSelected_showsTopicDetailPane() { composeTestRule.apply { setContent { NiaTheme { InterestsListDetailScreen() } } val firstTopic = getTopics().first() onNodeWithText(firstTopic.name).performClick() onNodeWithTag(listPaneTag).assertIsNotDisplayed() onNodeWithText(placeholderText).assertIsNotDisplayed() onNodeWithTag(firstTopic.testTag).assertIsDisplayed() } } @Test @Config(qualifiers = EXPANDED_WIDTH) fun expandedWidth_backPressFromTopicDetail_leavesInterests() { var unhandledBackPress = false composeTestRule.apply { setContent { NiaTheme { // Back press should not be handled by the two pane layout, and thus // "fall through" to this BackHandler. BackHandler { unhandledBackPress = true } InterestsListDetailScreen() } } val firstTopic = getTopics().first() onNodeWithText(firstTopic.name).performClick() waitForIdle() Espresso.pressBack() assertTrue(unhandledBackPress) } } @Test @Config(qualifiers = COMPACT_WIDTH) fun compactWidth_backPressFromTopicDetail_showsListPane() { composeTestRule.apply { setContent { NiaTheme { InterestsListDetailScreen() } } val firstTopic = getTopics().first() onNodeWithText(firstTopic.name).performClick() waitForIdle() Espresso.pressBack() onNodeWithTag(listPaneTag).assertIsDisplayed() onNodeWithText(placeholderText).assertIsNotDisplayed() onNodeWithTag(firstTopic.testTag).assertIsNotDisplayed() } } } private fun AndroidComposeTestRule<*, *>.stringResource( @StringRes resId: Int, ): ReadOnlyProperty<Any, String> = ReadOnlyProperty { _, _ -> activity.getString(resId) }
237
Kotlin
3060
16,829
489aebf6294891bee0d9d0d60445b36417d96e86
6,848
nowinandroid
Apache License 2.0
src/main/kotlin/one/digitalinnovation/collections/TesteDoubleArray.kt
clovisdanielcosta
353,433,962
false
null
package one.digitalinnovation.collections fun main() { val salarios = DoubleArray(3) salarios[0] = 1099.12 salarios[1] = 2035.20 salarios[2] = 1000.30 salarios.forEach { println(it) } println("---------------------------") salarios.forEachIndexed { index, salario -> salarios[index] = salario * 1.1 } salarios.forEach { println(it) } println("---------------------------") val salarios2 = doubleArrayOf(11000.00, 2500.15, 5000.11) salarios2.sort() salarios2.forEach { println(it) } }
0
Kotlin
0
0
d0ddd06f5d01bd4897e8d9d31f8dd84f20972ab6
551
kotlin-collections
MIT License
app/src/main/java/me/cyber/nukleos/dagger/ChartsViewModule.kt
fossabot
161,150,256
true
{"Kotlin": 103020}
package me.cyber.nukleos.dagger import dagger.Binds import dagger.Module import me.cyber.nukleos.ui.charts.ChartInterface import me.cyber.nukleos.ui.charts.ChartsFragment @Module abstract class ChartsViewModule { @Binds abstract fun provideChartsView(exportFragment: ChartsFragment): ChartInterface.View }
0
Kotlin
0
0
8fdb9c6f3af47efca5dc8f4fc271445958da5d23
316
nukleos
Apache License 2.0
app/src/main/java/com/angelo/destinystatusapp/presentation/viewmodel/PhotoDetailsViewModel.kt
angelorohit
777,418,508
false
{"Kotlin": 133311, "Shell": 455}
package com.angelo.destinystatusapp.presentation.viewmodel import androidx.lifecycle.ViewModel import com.angelo.destinystatusapp.domain.model.BungieChannelType import com.angelo.destinystatusapp.domain.repository.BungieChannelPostsCacheRepository import org.koin.core.component.KoinComponent import org.koin.core.component.inject class PhotoDetailsViewModel( channelType: BungieChannelType, postId: String, mediaId: String, ) : ViewModel(), KoinComponent { private val cacheRepository: BungieChannelPostsCacheRepository by inject() var title: String private set var photoUrl: String private set var photoAspectRatio: Float private set init { val bungiePost = cacheRepository.getPosts(channelType).find { bungiePost -> bungiePost.id == postId } val bungiePostMedia = bungiePost?.media?.find { bungiePostMedia -> bungiePostMedia.id == mediaId } title = bungiePost?.text.orEmpty() photoUrl = bungiePostMedia?.sizes?.large?.imageUrl.orEmpty() photoAspectRatio = bungiePostMedia?.sizes?.large?.aspectRatio ?: 1f } }
0
Kotlin
0
0
ef914daf44059da618f95e5668408c6472c3c917
1,093
DestinyStatusApp
MIT License
app/src/main/java/cn/ijero/scaffold/fragment/DemoFragment.kt
ijero
382,867,885
false
null
package cn.ijero.scaffold.fragment import android.os.Bundle import androidx.fragment.app.viewModels import cn.ijero.scaffold.R import cn.ijero.scaffold.ScaffoldFragment import cn.ijero.scaffold.databinding.FragmentDemoBinding class DemoFragment : ScaffoldFragment<FragmentDemoBinding>() { companion object { fun newInstance(): DemoFragment { val args = Bundle() val fragment = DemoFragment() fragment.arguments = args return fragment } } private val viewModel by viewModels<DemoFragmentViewModel>() override fun initObserver() { viewModel.randomFood.observe(this) { binding.textView.text = getString(R.string.format_i_like_eat, it) } } override fun initViewListener() { binding.serveButton.setOnClickListener { viewModel.randomFood() } } }
0
Kotlin
0
0
6e366ad2fba2c3370a597b6029bb7a9d1ac58476
894
jero-scaffold
Apache License 2.0
packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/FileUtils.kt
hramos
114,177,219
true
{"JavaScript": 4994135, "Java": 3069761, "Objective-C": 1807824, "C++": 1549813, "Objective-C++": 451195, "Python": 200755, "Shell": 60072, "Ruby": 43285, "C": 27646, "HTML": 25212, "Assembly": 14912, "Makefile": 9237, "IDL": 2656, "CSS": 1306, "Prolog": 465, "Batchfile": 270}
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.utils import java.io.File internal fun File.moveTo(destination: File) { copyTo(destination, overwrite = true) delete() } internal fun File.recreateDir() { deleteRecursively() mkdirs() }
0
JavaScript
1
2
084a8b5f03d100a9d775a676ede08e26ed25d0c4
413
react-native
MIT License
app/src/main/java/com/botigocontigo/alfred/foda/Dimension.kt
UTN-FRBA-Mobile
146,629,720
false
null
package com.botigocontigo.alfred.foda data class Dimension (var id: Int,var type:String,var userId: String,var descriptions: Array<String>)
0
Kotlin
4
1
558eb3967b3026bf66ae12d25b98c8055b3a9949
140
Alfred
MIT License
base/build-system/integration-test/application/src/test/java/com/android/build/gradle/integration/annotationprocessor/AutoServiceTest.kt
qiangxu1996
301,210,525
false
{"Gradle Kotlin DSL": 2, "Shell": 29, "Markdown": 39, "Batchfile": 10, "Text": 287, "Ignore List": 47, "Java": 4790, "INI": 19, "XML": 1725, "Gradle": 543, "Starlark": 149, "JAR Manifest": 3, "Kotlin": 1462, "Ant Build System": 3, "HTML": 6, "Makefile": 12, "XSLT": 6, "CSS": 10, "Git Attributes": 2, "Protocol Buffer": 35, "Java Properties": 43, "C++": 479, "RenderScript": 32, "C": 32, "Proguard": 29, "JavaScript": 2, "Checksums": 8, "Filterscript": 11, "Prolog": 1, "CMake": 3, "GLSL": 2, "AIDL": 6, "JSON": 53, "PureBasic": 1, "SVG": 201, "YAML": 4, "Python": 9, "Dockerfile": 2, "Emacs Lisp": 1, "FreeMarker": 173, "Fluent": 314}
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.build.gradle.integration.annotationprocessor import com.android.build.gradle.integration.common.truth.TruthHelper.assertThat import com.android.build.gradle.integration.common.fixture.GradleTestProject import com.android.build.gradle.integration.common.fixture.app.HelloWorldApp import com.android.build.gradle.integration.common.utils.TestFileUtils import com.google.common.collect.ImmutableList import java.nio.charset.StandardCharsets import java.nio.file.Files import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import java.util.function.Consumer @RunWith(Parameterized::class) class AutoServiceTest(private val pluginName: String) { @get:Rule val project: GradleTestProject = GradleTestProject.builder() .fromTestApp(HelloWorldApp.forPlugin(pluginName)) .create() @Before fun addAutoService() { TestFileUtils.appendToFile( project.buildFile, """ |dependencies { | compileOnly 'com.google.auto.service:auto-service:1.0-rc2' | annotationProcessor 'com.google.auto.service:auto-service:1.0-rc2' |} |""".trimMargin("|") ) Files.write( project.file("src/main/java/com/example/helloworld/MyService.java").toPath(), listOf( "package com.example.helloworld;", "", "public interface MyService {", " void doSomething();", "}", "" ), StandardCharsets.UTF_8 ) Files.write( project.file("src/main/java/com/example/helloworld/MyServiceImpl.java").toPath(), listOf( "package com.example.helloworld;", "", "@com.google.auto.service.AutoService(MyService.class)", "public class MyServiceImpl implements MyService {", " public void doSomething() {}", "}", "" ), StandardCharsets.UTF_8 ) } @Test fun checkAutoServiceResourceIncluded() { project.executor().run("assembleDebug") if (pluginName == "com.android.application") { assertThat(project.getApk(GradleTestProject.ApkType.DEBUG)) .containsJavaResource("META-INF/services/com.example.helloworld.MyService") } else { project.assertThatAar("debug") { containsJavaResource("META-INF/services/com.example.helloworld.MyService") } } } companion object { @JvmStatic @Parameterized.Parameters(name = "{0}") fun plugin(): List<String> { return ImmutableList.of("com.android.application", "com.android.library") } } }
1
null
1
1
3411c5436d0d34e6e2b84cbf0e9395ac8c55c9d4
3,574
vmtrace
Apache License 2.0
src/test/kotlin/com/leetcode/P1237Test.kt
antop-dev
229,558,170
false
{"Kotlin": 731829, "Java": 217825, "Python": 4406}
package com.leetcode import com.leetcode.P1237.CustomFunction import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.`is` import org.junit.jupiter.api.Test class P1237Test { val sut = P1237() @Test fun `example 1`() { val function1 = object : CustomFunction { override fun f(x: Int, y: Int) = x + y } assertThat( sut.findSolution(function1, 5), `is`( listOf( listOf(1, 4), listOf(2, 3), listOf(3, 2), listOf(4, 1) ) ) ) } @Test fun `example 2`() { val function2 = object : CustomFunction { override fun f(x: Int, y: Int) = x * y } assertThat( sut.findSolution(function2, 5), `is`( listOf( listOf(1, 5), listOf(5, 1) ) ) ) } }
3
Kotlin
0
0
a9dd7cfa4f6cfc5186a86f6e2c8aefc489f5c028
1,023
algorithm
MIT License
pushlib/src/main/java/com/saint/pushlib/util/PushUtil.kt
saint-li
263,572,354
false
null
package com.saint.pushlib.util import android.app.ActivityManager import android.content.Context import android.content.pm.PackageManager import android.os.Process object PushUtil { /** * 获取Manifest 里面的meta-data * * @param context * @param key * @return */ @JvmStatic fun getMetaData(context: Context, key: String): String? { return try { val appInfo = context.packageManager .getApplicationInfo(context.packageName, PackageManager.GET_META_DATA) appInfo.metaData.getString(key) } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() "" } } /** * 包名判断是否为主进程 * * @param * @return */ fun isMainProcess(context: Context): Boolean { return context.applicationContext.packageName == getCurrentProcessName(context) } /** * 获取当前进程名 */ fun getCurrentProcessName(context: Context): String { val pid = Process.myPid() var processName = "" val manager = context.applicationContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager for (process in manager.runningAppProcesses) { if (process.pid == pid) { processName = process.processName } } return processName } }
1
null
1
4
696c7883267096176ca91f351785d2789a91c3fe
1,388
push
Apache License 2.0
src/test/kotlin/me/serce/solidity/lang/completion/SolNatSpecCompletionTest.kt
intellij-solidity
82,682,728
false
null
package me.serce.solidity.lang.completion class SolNatSpecCompletionTest : SolCompletionTestBase() { fun testNatSpecCommentCompletion() = checkCompletion(hashSetOf("@author", "@title", "@return", "@notice"), """ /// /*caret*/ contract A {} """, strict = false) fun testNatSpecTagCompletion() = checkCompletion(hashSetOf("author"), """ /** * @/*caret*/ */ contract A {} """, strict = false) }
65
null
87
990
e417a9f279b8d39bec8d9c68cb19fb23d4c3cddb
453
intellij-solidity
MIT License
kotlin/semlang-api/src/main/kotlin/language.kt
AlexLandau
67,669,978
false
null
package net.semlang.api import java.util.Objects import net.semlang.api.parser.Location // An EntityId uniquely identifies an entity within a module. An EntityRef refers to an entity that may be in this // module or another, and may or may not have hints pointing to a particular module. data class EntityId(val namespacedName: List<String>) { init { if (namespacedName.isEmpty()) { error("Entity IDs must have at least one name component") } for (namePart in namespacedName) { if (namePart.isEmpty()) { error("Entity IDs may not have empty name components") } var foundNonUnderscore = false for (character in namePart) { if (character in 'a'..'z' || character in 'A'..'Z' || character in '0'..'9') { foundNonUnderscore = true } else if (character == '_') { // Do nothing } else { error("Invalid character '$character' (code: ${character.toInt()}) in entity ID with components $namespacedName") } } if (!foundNonUnderscore) { error("Name components must contain non-underscore characters; bad entity ID components: $namespacedName") } } } companion object { fun of(vararg names: String): EntityId { return EntityId(names.toList()) } /** * Parses the components of an entity ID expressed as a period-delimited string. In particular, this reverses * the [EntityId.toString] operation. */ fun parse(periodDelimitedNames: String): EntityId { return EntityId(periodDelimitedNames.split(".")) } } override fun toString(): String { return namespacedName.joinToString(".") } /** * Returns an EntityRef with this identity and no module hints. */ fun asRef(): EntityRef { return EntityRef(null, this) } } /** * Note: These should usually not be used as keys in a map; use ResolvedEntityRefs from an EntityResolver instead. */ data class EntityRef(val moduleRef: ModuleRef?, val id: EntityId) { companion object { fun of(vararg names: String): EntityRef { return EntityRef(null, EntityId.of(*names)) } } override fun toString(): String { if (moduleRef != null) { return moduleRef.toString() + ":" + id.toString() } else { return id.toString() } } } data class ResolvedEntityRef(val module: ModuleUniqueId, val id: EntityId) { override fun toString(): String { return "${module.name}:\"${ModuleUniqueId.UNIQUE_VERSION_SCHEME_PREFIX}${module.fake0Version}\":$id" } fun toUnresolvedRef(): EntityRef { val moduleRef = ModuleRef(module.name.group, module.name.module, ModuleUniqueId.UNIQUE_VERSION_SCHEME_PREFIX + module.fake0Version) return EntityRef(moduleRef, id) } } // TODO: It would be really nice to have a TypeId or something that didn't have a location, vs. UnvalidatedType sealed class UnvalidatedType { abstract val location: Location? abstract protected fun getTypeString(): String abstract fun isReference(): Boolean abstract fun replacingNamedParameterTypes(parameterReplacementMap: Map<String, UnvalidatedType>): UnvalidatedType abstract fun equalsIgnoringLocation(other: UnvalidatedType?): Boolean override fun toString(): String { return getTypeString() } data class FunctionType(private val isReference: Boolean, val typeParameters: List<TypeParameter>, val argTypes: List<UnvalidatedType>, val outputType: UnvalidatedType, override val location: Location? = null): UnvalidatedType() { override fun isReference(): Boolean { return isReference } override fun replacingNamedParameterTypes(parameterReplacementMap: Map<String, UnvalidatedType>): FunctionType { return FunctionType( isReference, typeParameters.filter { !parameterReplacementMap.containsKey(it.name) }, this.argTypes.map { it.replacingNamedParameterTypes(parameterReplacementMap) }, this.outputType.replacingNamedParameterTypes(parameterReplacementMap), location) } override fun equalsIgnoringLocation(other: UnvalidatedType?): Boolean { return other is FunctionType && isReference == other.isReference && typeParameters == other.typeParameters && argTypes.size == other.argTypes.size && argTypes.zip(other.argTypes).all { it.first.equalsIgnoringLocation(it.second) } && outputType.equalsIgnoringLocation(other.outputType) } override fun getTypeString(): String { val referenceString = if (isReference) "&" else "" val typeParametersString = if (typeParameters.isEmpty()) { "" } else { "<" + typeParameters.joinToString(", ") + ">" } return referenceString + typeParametersString + "(" + argTypes.joinToString(", ") + ") -> " + outputType.toString() } override fun toString(): String { return getTypeString() } fun getNumArguments(): Int { return argTypes.size } } data class NamedType(val ref: EntityRef, private val isReference: Boolean, val parameters: List<UnvalidatedType> = listOf(), override val location: Location? = null): UnvalidatedType() { override fun isReference(): Boolean { return isReference } override fun replacingNamedParameterTypes(parameterReplacementMap: Map<String, UnvalidatedType>): UnvalidatedType { if (ref.moduleRef == null && ref.id.namespacedName.size == 1) { val replacement = parameterReplacementMap[ref.id.namespacedName[0]] if (replacement != null) { return replacement } } return NamedType( ref, isReference, parameters.map { it.replacingNamedParameterTypes(parameterReplacementMap) }, location) } companion object { fun forParameter(parameter: TypeParameter, location: Location? = null): NamedType { return NamedType(EntityRef(null, EntityId(listOf(parameter.name))), false, listOf(), location) } } override fun equalsIgnoringLocation(other: UnvalidatedType?): Boolean { return other is NamedType && ref == other.ref && isReference == other.isReference && parameters.size == other.parameters.size && parameters.zip(other.parameters).all { it.first.equalsIgnoringLocation(it.second) } } override fun getTypeString(): String { // TODO: This might be wrong if the ref includes a module... return (if (isReference) "&" else "") + ref.toString() + if (parameters.isEmpty()) { "" } else { "<" + parameters.joinToString(", ") + ">" } } override fun toString(): String { return getTypeString() } } } /** * Note: The hashCode() and equals() methods for [Type.NamedType] ignore [Type.NamedType.originalRef], which is provided for a narrow * range of reasons -- primarily, converting back to the original unvalidated code. This may cause odd behavior if * you put Types in a set or as the key of a map, but it makes equality checking correct for the purposes of checking * that types agree with one another. */ sealed class Type { protected abstract fun replacingInternalParametersInternal(chosenParameters: List<Type?>): Type abstract fun getTypeString(): String abstract fun isReference(): Boolean override fun toString(): String { return getTypeString() } abstract fun replacingExternalParameters(parametersMap: Map<ParameterType, Type>): Type /** * Some types are not bindable -- that is, if they are arguments of a function type, they cannot immediately accept * an argument in a function binding. This happens when they contain references to internal parameter types external * to the type itself. */ fun isBindable(): Boolean { return isBindableInternal(0) } abstract protected fun isBindableInternal(numAllowedIndices: Int): Boolean sealed class FunctionType: Type() { abstract fun getNumArguments(): Int abstract fun rebindTypeParameters(boundTypeParameters: List<Type?>): FunctionType abstract fun rebindArguments(bindingTypes: List<Type?>): FunctionType /** * This returns a list of argument types in which any argument type that is not currently bindable (because its type * contains an internal parameter type that is not bound) is replaced with null. */ abstract fun getBindableArgumentTypes(): List<Type?> // This is usually used for things like printing the types for the user abstract fun getDefaultGrounding(): Ground abstract fun groundWithTypeParameters(chosenTypeParameters: List<Type>): Ground abstract val typeParameters: List<TypeParameter> companion object { fun create(isReference: Boolean, typeParameters: List<TypeParameter>, argTypes: List<Type>, outputType: Type): FunctionType { if (typeParameters.isEmpty()) { return Ground(isReference, argTypes, outputType) } else { return Parameterized(isReference, typeParameters, argTypes, outputType) } } } data class Ground(private val isReference: Boolean, val argTypes: List<Type>, val outputType: Type) : FunctionType() { override val typeParameters = listOf<TypeParameter>() override fun groundWithTypeParameters(chosenTypeParameters: List<Type>): Ground { if (chosenTypeParameters.isNotEmpty()) { error("Tried to rebind a ground function type $this with parameters $chosenTypeParameters") } return this } override fun getDefaultGrounding(): Ground { return this } override fun isBindableInternal(numAllowedIndices: Int): Boolean { return argTypes.all { it.isBindableInternal(numAllowedIndices) } && outputType.isBindableInternal(numAllowedIndices) } override fun getBindableArgumentTypes(): List<Type?> { return argTypes } override fun rebindTypeParameters(boundTypeParameters: List<Type?>): Ground { if (boundTypeParameters.isNotEmpty()) { error("Tried to rebind a ground function type $this with parameters $boundTypeParameters") } return this } /** * Returns the type that would result if a binding were performed with the given types for passed-in bindings. */ override fun rebindArguments(bindingTypes: List<Type?>): Ground { if (bindingTypes.size != argTypes.size) { error("Wrong number of binding types") } val willBeReference = this.isReference || bindingTypes.any { it != null && it.isReference() } return Ground( willBeReference, argTypes.zip(bindingTypes).filter { it.second == null }.map { it.first }, outputType) } override fun getNumArguments(): Int { return argTypes.size } override fun isReference(): Boolean { return this.isReference } override fun replacingInternalParametersInternal(chosenParameters: List<Type?>): Ground { val argTypes = argTypes.map { it.replacingInternalParametersInternal(chosenParameters) } val outputType = outputType.replacingInternalParametersInternal(chosenParameters) return Ground(isReference, argTypes, outputType) } override fun getTypeString(): String { val referenceString = if (isReference) "&" else "" return referenceString + "(" + argTypes.joinToString(", ") + ") -> " + outputType.toString() } override fun replacingExternalParameters(parametersMap: Map<ParameterType, Type>): Type { return Ground( isReference, argTypes.map { it.replacingExternalParameters(parametersMap) }, outputType.replacingExternalParameters(parametersMap) ) } } //TODO: Figure out if we can return argTypes and outputType to private class Parameterized(private val isReference: Boolean, override val typeParameters: List<TypeParameter>, val argTypes: List<Type>, val outputType: Type) : FunctionType() { override fun groundWithTypeParameters(chosenTypeParameters: List<Type>): Ground { if (chosenTypeParameters.size != typeParameters.size) { error("Wrong number of type parameters") } val newArgTypes = getArgTypes(chosenTypeParameters) val newOutputType = getOutputType(chosenTypeParameters) return Ground(isReference, newArgTypes, newOutputType) } override fun getDefaultGrounding(): Ground { val substitution = this.getDefaultTypeParameterNameSubstitution() return rebindTypeParameters(substitution) as Ground } override fun isBindableInternal(incomingNumAllowedIndices: Int): Boolean { val newNumAllowedIndices = incomingNumAllowedIndices + typeParameters.size return argTypes.all { it.isBindableInternal(newNumAllowedIndices) } && outputType.isBindableInternal(newNumAllowedIndices) } override fun getBindableArgumentTypes(): List<Type?> { return argTypes.map { if (it.isBindable()) { it } else { null } } } override fun rebindTypeParameters(boundTypeParameters: List<Type?>): FunctionType { if (boundTypeParameters.size != typeParameters.size) { error("Wrong number of type parameters") } val newArgTypes = getArgTypes(boundTypeParameters) val newOutputType = getOutputType(boundTypeParameters) return create( this.isReference, typeParameters.zip(boundTypeParameters).filter { it.second == null }.map { it.first }, newArgTypes, newOutputType) } /** * Returns the type that would result if a binding were performed with the given types for passed-in bindings. */ override fun rebindArguments(bindingTypes: List<Type?>): FunctionType { if (bindingTypes.size != argTypes.size) { error("Wrong number of binding types") } for ((bindingType, argType) in bindingTypes.zip(argTypes)) { if (bindingType != null && !argType.isBindable()) { error("Passed in a binding type for a non-bindable argument type $argType; type is $this, bindingTypes are $bindingTypes") } } val willBeReference = this.isReference || bindingTypes.any { it != null && it.isReference() } return create( willBeReference, typeParameters, argTypes.zip(bindingTypes).filter { it.second == null }.map { it.first }, outputType) } init { if (typeParameters.isEmpty()) { error("Should be making a FunctionType.Ground instead; argTypes: $argTypes, outputType: $outputType") } } override fun getNumArguments(): Int { return argTypes.size } override fun isReference(): Boolean { return this.isReference } private fun getDefaultTypeParameterNameSubstitution(): List<Type> { return typeParameters.map(Type::ParameterType) } private fun getArgTypes(chosenParameters: List<Type?>): List<Type> { if (chosenParameters.size != typeParameters.size) { error("Incorrect size of chosen parameters") } val replaced = replacingInternalParameters(chosenParameters) return when (replaced) { is Ground -> replaced.argTypes is Parameterized -> replaced.argTypes } } private fun getOutputType(chosenParameters: List<Type?>): Type { if (chosenParameters.size != typeParameters.size) { error("Incorrect size of chosen parameters") } val replaced = replacingInternalParameters(chosenParameters) return when (replaced) { is Ground -> replaced.outputType is Parameterized -> replaced.outputType } } override fun hashCode(): Int { return Objects.hash( isReference, typeParameters.map { it.typeClass }, argTypes, outputType ) } override fun equals(other: Any?): Boolean { if (other !is Parameterized) { return false } return isReference == other.isReference && typeParameters.map { it.typeClass } == other.typeParameters.map { it.typeClass } && argTypes == other.argTypes && outputType == other.outputType } private fun replacingInternalParameters(chosenParameters: List<Type?>): FunctionType { // The chosenParameters should be correct at this point return create( isReference, // Keep type parameters that aren't getting defined typeParameters.filterIndexed { index, typeParameter -> chosenParameters[index] == null }, argTypes.map { type -> type.replacingInternalParametersInternal(chosenParameters) }, outputType.replacingInternalParametersInternal(chosenParameters) ) } override fun replacingInternalParametersInternal(chosenParameters: List<Type?>): FunctionType { val adjustedChosenParameters = typeParameters.map { null } + chosenParameters return replacingInternalParameters(adjustedChosenParameters) } override fun replacingExternalParameters(parametersMap: Map<ParameterType, Type>): Type { return Parameterized( isReference, typeParameters, argTypes.map { it.replacingExternalParameters(parametersMap) }, outputType.replacingExternalParameters(parametersMap) ) } override fun getTypeString(): String { val referenceString = if (isReference) "&" else "" val typeParametersString = if (typeParameters.isEmpty()) { "" } else { "<" + typeParameters.joinToString(", ") + ">" } return referenceString + typeParametersString + "(" + argTypes.joinToString(", ") + ") -> " + outputType.toString() } override fun toString(): String { return getTypeString() } } } /** * This class represents a type parameter that is defined elsewhere in either this type or a type containing this * one. In the latter case, this should not be exposed to clients directly; instead, the type defining the type * parameter should require clients to pass in type parameters in order to instantiate them. * * This deals with the fact that we don't want the name of the type parameter to be meaningful; in particular, if * we have a function parameterized in terms of T in its definition, we want to be able to call it and ignore the * name "T", which we might be using locally, without having to worry about name shadowing. * * TODO: Document index ordering. */ data class InternalParameterType(val index: Int): Type() { override fun isBindableInternal(numAllowedIndices: Int): Boolean { return index < numAllowedIndices } override fun isReference(): Boolean { return false } override fun replacingInternalParametersInternal(chosenParameters: List<Type?>): Type { val replacement = chosenParameters[index] if (replacement != null) { return replacement } else { // New index: number of null values preceding this index in the chosenParameters array val newIndex = chosenParameters.subList(0, index).count { it == null } return InternalParameterType(newIndex) } } override fun replacingExternalParameters(parametersMap: Map<ParameterType, Type>): Type { return this } override fun getTypeString(): String { error("This internal parameter type should be replaced in the type before being converted to a string") } } /** * This represents type parameter types where the type parameter is defined in places other than within the same * type definition. For example, a struct with a type parameter T may have a member of type T, or a function with * type parameter T may have a variable in its code with type T. These would use ParameterType as opposed to * [InternalParameterType]. */ data class ParameterType(val parameter: TypeParameter): Type() { override fun isBindableInternal(numAllowedIndices: Int): Boolean { return true } override fun isReference(): Boolean { return false } override fun replacingInternalParametersInternal(chosenParameters: List<Type?>): Type { return this } override fun replacingExternalParameters(parametersMap: Map<ParameterType, Type>): Type { val replacement = parametersMap[this] return if (replacement != null) { replacement } else { this } } override fun getTypeString(): String { return parameter.name } override fun toString(): String { return parameter.name } } /** * Note: The hashCode() and equals() methods for this class ignore [originalRef], which is provided for a narrow * range of reasons -- primarily, converting back to the original unvalidated code. This may cause odd behavior if * you put Types in a set or as the key of a map, but it makes equality checking correct for the purposes of checking * that types agree with one another. */ // TODO: Should "ref" be an EntityResolution? Either way, stop passing originalRef to resolvers data class NamedType(val ref: ResolvedEntityRef, val originalRef: EntityRef, private val isReference: Boolean, val parameters: List<Type> = listOf()): Type() { override fun isBindableInternal(numAllowedIndices: Int): Boolean { return parameters.all { it.isBindableInternal(numAllowedIndices) } } override fun isReference(): Boolean { return isReference } override fun replacingInternalParametersInternal(chosenParameters: List<Type?>): Type { return this.copy(parameters = parameters.map { it.replacingInternalParametersInternal(chosenParameters) }) } override fun replacingExternalParameters(parametersMap: Map<ParameterType, Type>): Type { return this.copy(parameters = parameters.map { it.replacingExternalParameters(parametersMap) }) } override fun getTypeString(): String { // TODO: This might be wrong if the ref includes a module... return (if (isReference) "&" else "") + ref.toString() + if (parameters.isEmpty()) { "" } else { "<" + parameters.joinToString(", ") + ">" } } override fun toString(): String { return getTypeString() } /** * Ignores the value of [originalRef]. */ override fun equals(other: Any?): Boolean { if (this === other) { return true } if (other == null) { return false } if (other !is NamedType) { return false } return Objects.equals(ref, other.ref) && isReference == other.isReference && Objects.equals(parameters, other.parameters) } /** * Ignores the value of [originalRef]. */ override fun hashCode(): Int { return Objects.hash(ref, isReference, parameters) } } } enum class TypeClass { Data, } data class TypeParameter(val name: String, val typeClass: TypeClass?) { override fun toString(): String { if (typeClass == null) { return name } else { return "$name: $typeClass" } } } data class UnvalidatedFunctionSignature(override val id: EntityId, val argumentTypes: List<UnvalidatedType>, val outputType: UnvalidatedType, val typeParameters: List<TypeParameter> = listOf()): HasId { fun getFunctionType(): UnvalidatedType.FunctionType { return UnvalidatedType.FunctionType(false, typeParameters, argumentTypes, outputType) } } data class FunctionSignature private constructor(override val id: EntityId, val argumentTypes: List<Type>, val outputType: Type, val typeParameters: List<TypeParameter> = listOf()): HasId { companion object { /** * Note: This converts instances of the given type parameters into internal parameters in the argument and output types. */ fun create(id: EntityId, argumentTypes: List<Type>, outputType: Type, typeParameters: List<TypeParameter> = listOf()): FunctionSignature { val newParameterIndices = HashMap<String, Int>() typeParameters.mapIndexed { index, typeParameter -> newParameterIndices.put(typeParameter.name, index) } val newArgTypes = argumentTypes.map { it.internalizeParameters(newParameterIndices, 0) } val newOutputType = outputType.internalizeParameters(newParameterIndices, 0) return FunctionSignature(id, newArgTypes, newOutputType, typeParameters) } } fun getFunctionType(): Type.FunctionType { return Type.FunctionType.create(false, typeParameters, argumentTypes, outputType) } } data class Annotation(val name: EntityId, val values: List<AnnotationArgument>) sealed class AnnotationArgument { data class Literal(val value: String): AnnotationArgument() data class List(val values: kotlin.collections.List<AnnotationArgument>): AnnotationArgument() } // Pre-type-analysis sealed class Expression { abstract val location: Location? data class Variable(val name: String, override val location: Location? = null): Expression() data class IfThen(val condition: Expression, val thenBlock: Block, val elseBlock: Block, override val location: Location? = null): Expression() data class NamedFunctionCall(val functionRef: EntityRef, val arguments: List<Expression>, val chosenParameters: List<UnvalidatedType>, override val location: Location? = null, val functionRefLocation: Location? = null): Expression() data class ExpressionFunctionCall(val functionExpression: Expression, val arguments: List<Expression>, val chosenParameters: List<UnvalidatedType>, override val location: Location? = null): Expression() data class Literal(val type: UnvalidatedType, val literal: String, override val location: Location? = null): Expression() data class ListLiteral(val contents: List<Expression>, val chosenParameter: UnvalidatedType, override val location: Location? = null): Expression() data class NamedFunctionBinding(val functionRef: EntityRef, val bindings: List<Expression?>, val chosenParameters: List<UnvalidatedType?>, override val location: Location? = null, val functionRefLocation: Location? = null): Expression() data class ExpressionFunctionBinding(val functionExpression: Expression, val bindings: List<Expression?>, val chosenParameters: List<UnvalidatedType?>, override val location: Location? = null): Expression() data class Follow(val structureExpression: Expression, val name: String, override val location: Location? = null): Expression() data class InlineFunction(val arguments: List<UnvalidatedArgument>, val returnType: UnvalidatedType, val block: Block, override val location: Location? = null): Expression() } // Post-type-analysis enum class AliasType { /** * Indicates that the expression represents a reference or value without an existing alias, and thus can be assigned * to a variable if it's a reference type. */ NotAliased, /** * Indicates that the expression represents a reference or value that either is guaranteed to have * or conditionally may have an existing alias, and thus cannot be assigned to a variable if it's a reference type. * * Note that this category includes expressions that may be "definitely aliased", but there's no need to distinguish * them from expressions that are "possibly aliased" (such as may result from an if-expression where one possible * result is aliased and the other is not). */ PossiblyAliased, ; companion object { // I'd really rather this be named "for", but that's not an option fun of(possiblyAliased: Boolean): AliasType { if (possiblyAliased) { return PossiblyAliased } else { return NotAliased } } } } sealed class TypedExpression { abstract val type: Type // TODO: Consider auto-setting some alias types; i.e. always aliased for Variable, never aliased for Literal/ListLiteral/maybe FunctionCalls // (Non-obvious correction: Follows wouldn't be aliased if their structure expressions are unaliased, e.g. foo()->bar) abstract val aliasType: AliasType data class Variable(override val type: Type, override val aliasType: AliasType, val name: String): TypedExpression() data class IfThen(override val type: Type, override val aliasType: AliasType, val condition: TypedExpression, val thenBlock: TypedBlock, val elseBlock: TypedBlock): TypedExpression() data class NamedFunctionCall(override val type: Type, override val aliasType: AliasType, val functionRef: EntityRef, val resolvedFunctionRef: ResolvedEntityRef, val arguments: List<TypedExpression>, val chosenParameters: List<Type>, val originalChosenParameters: List<Type>): TypedExpression() data class ExpressionFunctionCall(override val type: Type, override val aliasType: AliasType, val functionExpression: TypedExpression, val arguments: List<TypedExpression>, val chosenParameters: List<Type>, val originalChosenParameters: List<Type>): TypedExpression() data class Literal(override val type: Type, override val aliasType: AliasType, val literal: String): TypedExpression() data class ListLiteral(override val type: Type, override val aliasType: AliasType, val contents: List<TypedExpression>, val chosenParameter: Type): TypedExpression() data class NamedFunctionBinding(override val type: Type.FunctionType, override val aliasType: AliasType, val functionRef: EntityRef, val resolvedFunctionRef: ResolvedEntityRef, val bindings: List<TypedExpression?>, val chosenParameters: List<Type?>, val originalChosenParameters: List<Type?>) : TypedExpression() data class ExpressionFunctionBinding(override val type: Type.FunctionType, override val aliasType: AliasType, val functionExpression: TypedExpression, val bindings: List<TypedExpression?>, val chosenParameters: List<Type?>, val originalChosenParameters: List<Type?>) : TypedExpression() data class Follow(override val type: Type, override val aliasType: AliasType, val structureExpression: TypedExpression, val name: String): TypedExpression() data class InlineFunction(override val type: Type, override val aliasType: AliasType, val arguments: List<Argument>, val boundVars: List<Argument>, val returnType: Type, val block: TypedBlock): TypedExpression() } // Note: Currently Statements can refer to either assignments (if name is non-null) or "plain" statements with imperative // effects (otherwise). If we introduce a third statement type, we should probably switch this to be a sealed class. sealed class Statement { abstract val location: Location? data class Assignment(val name: String, val type: UnvalidatedType?, val expression: Expression, override val location: Location? = null, val nameLocation: Location? = null): Statement() data class Bare(val expression: Expression): Statement() { override val location: Location? get() = expression.location } } sealed class ValidatedStatement { data class Assignment(val name: String, val type: Type, val expression: TypedExpression): ValidatedStatement() // TODO: Is the type here necessary? data class Bare(val type: Type, val expression: TypedExpression): ValidatedStatement() } data class UnvalidatedArgument(val name: String, val type: UnvalidatedType, val location: Location? = null) data class Argument(val name: String, val type: Type) data class Block(val statements: List<Statement>, val location: Location? = null) // TODO: Rename to standardize // TODO: Probably do something different about the lastStatementAliasType data class TypedBlock(val type: Type, val statements: List<ValidatedStatement>, val lastStatementAliasType: AliasType) { init { if (statements.isEmpty()) { error("The list of statements in a TypedBlock should not be empty; this should have already failed validation") } } } data class Function(override val id: EntityId, val typeParameters: List<TypeParameter>, val arguments: List<UnvalidatedArgument>, val returnType: UnvalidatedType, val block: Block, override val annotations: List<Annotation>, val idLocation: Location? = null, val returnTypeLocation: Location? = null) : TopLevelEntity { fun getType(): UnvalidatedType.FunctionType { return UnvalidatedType.FunctionType( false, typeParameters, arguments.map(UnvalidatedArgument::type), returnType ) } } data class ValidatedFunction(override val id: EntityId, val typeParameters: List<TypeParameter>, val arguments: List<Argument>, val returnType: Type, val block: TypedBlock, override val annotations: List<Annotation>) : TopLevelEntity { fun getTypeSignature(): FunctionSignature { return FunctionSignature.create(id, arguments.map(Argument::type), returnType, typeParameters) } } data class UnvalidatedStruct(override val id: EntityId, val typeParameters: List<TypeParameter>, val members: List<UnvalidatedMember>, val requires: Block?, override val annotations: List<Annotation>, val idLocation: Location? = null) : TopLevelEntity { fun getConstructorSignature(): UnvalidatedFunctionSignature { val argumentTypes = members.map(UnvalidatedMember::type) val typeParameters = typeParameters.map { UnvalidatedType.NamedType.forParameter(it, idLocation) } val outputType = if (requires == null) { UnvalidatedType.NamedType(id.asRef(), false, typeParameters, idLocation) } else { UnvalidatedType.NamedType(NativeOpaqueType.MAYBE.resolvedRef.toUnresolvedRef(), false, listOf( UnvalidatedType.NamedType(id.asRef(), false, typeParameters, idLocation) ), idLocation) } return UnvalidatedFunctionSignature(id, argumentTypes, outputType, this.typeParameters) } } data class Struct(override val id: EntityId, val moduleId: ModuleUniqueId, val typeParameters: List<TypeParameter>, val members: List<Member>, val requires: TypedBlock?, override val annotations: List<Annotation>) : TopLevelEntity { val resolvedRef = ResolvedEntityRef(moduleId, id) fun getIndexForName(name: String): Int { return members.indexOfFirst { member -> member.name == name } } fun getType(vararg chosenParameters: Type = arrayOf()): Type.NamedType { if (chosenParameters.size != typeParameters.size) { error("Incorrect number of type parameters") } return Type.NamedType(resolvedRef, id.asRef(), false, chosenParameters.toList()) } // TODO: Deconflict with UnvalidatedStruct version fun getConstructorSignature(): FunctionSignature { val argumentTypes = members.map(Member::type) val typeParameters = typeParameters.map(Type::ParameterType) val outputType = if (requires == null) { Type.NamedType(resolvedRef, id.asRef(), false, typeParameters) } else { NativeOpaqueType.MAYBE.getType(Type.NamedType(resolvedRef, id.asRef(), false, typeParameters)) } return FunctionSignature.create(id, argumentTypes, outputType, this.typeParameters) } } interface HasId { val id: EntityId } interface TopLevelEntity: HasId { val annotations: List<Annotation> } data class UnvalidatedMember(val name: String, val type: UnvalidatedType) data class Member(val name: String, val type: Type) data class UnvalidatedUnion(override val id: EntityId, val typeParameters: List<TypeParameter>, val options: List<UnvalidatedOption>, override val annotations: List<Annotation>, val idLocation: Location? = null): TopLevelEntity { private fun getType(): UnvalidatedType { val functionParameters = typeParameters.map { UnvalidatedType.NamedType.forParameter(it) } return UnvalidatedType.NamedType(id.asRef(), false, functionParameters) } fun getConstructorSignature(option: UnvalidatedOption): UnvalidatedFunctionSignature { if (!options.contains(option)) { error("Invalid option $option") } val optionId = EntityId(id.namespacedName + option.name) val argumentTypes = if (option.type == null) { listOf() } else { listOf(option.type) } return UnvalidatedFunctionSignature(optionId, argumentTypes, getType(), typeParameters) } fun getWhenSignature(): UnvalidatedFunctionSignature { val whenId = EntityId(id.namespacedName + "when") val outputParameterName = getUnusedTypeParameterName(typeParameters) val outputParameterType = UnvalidatedType.NamedType(EntityId.of(outputParameterName).asRef(), false) val outputTypeParameter = TypeParameter(outputParameterName, null) val whenTypeParameters = typeParameters + outputTypeParameter val argumentTypes = listOf(getType()) + options.map { option -> val optionArgTypes = if (option.type == null) { listOf() } else { listOf(option.type) } UnvalidatedType.FunctionType(false, listOf(), optionArgTypes, outputParameterType) } return UnvalidatedFunctionSignature(whenId, argumentTypes, outputParameterType, whenTypeParameters) } } data class Union(override val id: EntityId, val moduleId: ModuleUniqueId, val typeParameters: List<TypeParameter>, val options: List<Option>, override val annotations: List<Annotation>): TopLevelEntity { val resolvedRef = ResolvedEntityRef(moduleId, id) val whenId = EntityId(id.namespacedName + "when") private val optionIndexLookup: Map<EntityId, Int> = { val map = HashMap<EntityId, Int>() options.forEachIndexed { index, option -> val optionId = EntityId(id.namespacedName + option.name) map.put(optionId, index) } map }() fun getOptionIndexById(functionId: EntityId): Int? { return optionIndexLookup[functionId] } fun getType(): Type { return Type.NamedType(resolvedRef, this.id.asRef(), false, typeParameters.map { name -> Type.ParameterType(name) }) } fun getOptionConstructorSignatureForId(optionId: EntityId): FunctionSignature { val optionIndex = optionIndexLookup[optionId] ?: error("The union ${id} has no option with ID $optionId") val option = options[optionIndex] val optionType = option.type if (optionType != null) { return FunctionSignature.create(optionId, listOf(optionType), this.getType(), typeParameters) } else { return FunctionSignature.create(optionId, listOf(), this.getType(), typeParameters) } } } data class UnvalidatedOption(val name: String, val type: UnvalidatedType?, val idLocation: Location? = null) data class Option(val name: String, val type: Type?) private fun getUnusedTypeParameterName(explicitTypeParameters: List<TypeParameter>): String { val typeParameterNames = explicitTypeParameters.map(TypeParameter::name) if (!typeParameterNames.contains("A")) { return "A" } var index = 2 while (true) { val name = "A" + index if (!typeParameterNames.contains(name)) { return name } index++ } } data class OpaqueType(val id: EntityId, val moduleId: ModuleUniqueId, val typeParameters: List<TypeParameter>, val isReference: Boolean) { val resolvedRef = ResolvedEntityRef(moduleId, id) fun getType(vararg chosenParameters: Type = arrayOf()): Type.NamedType { if (chosenParameters.size != typeParameters.size) { error("Passed in the wrong number of type parameters to type $this; passed in $chosenParameters") } return Type.NamedType(resolvedRef, id.asRef(), isReference, chosenParameters.toList()) } } private fun Type.internalizeParameters(newParameterIndices: HashMap<String, Int>, indexOffset: Int): Type { return when (this) { is Type.FunctionType.Ground -> { val newArgTypes = argTypes.map { it.internalizeParameters(newParameterIndices, indexOffset) } val newOutputType = outputType.internalizeParameters(newParameterIndices, indexOffset) Type.FunctionType.Ground(this.isReference(), newArgTypes, newOutputType) } is Type.FunctionType.Parameterized -> { val newIndexOffset = indexOffset + this.typeParameters.size val newArgTypes = argTypes.map { it.internalizeParameters(newParameterIndices, newIndexOffset) } val newOutputType = outputType.internalizeParameters(newParameterIndices, newIndexOffset) Type.FunctionType.Parameterized(this.isReference(), typeParameters, newArgTypes, newOutputType) } is Type.InternalParameterType -> this is Type.ParameterType -> { val index = newParameterIndices[this.parameter.name]?.plus(indexOffset) if (index != null) { Type.InternalParameterType(index) } else { this } } is Type.NamedType -> { val newParameters = parameters.map { it.internalizeParameters(newParameterIndices, indexOffset) } return this.copy(parameters = newParameters) } } }
3
null
1
1
045d3317fe35e7bcdaaa90e343cb7d067b6e4111
45,364
semlang
Apache License 2.0
packages/react-native/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableMapKeySetIterator.kt
react-native-tvos
177,633,560
false
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.bridge import com.facebook.proguard.annotations.DoNotStrip /** Interface of a iterator for a [NativeMap]'s key set. */ @DoNotStrip public interface ReadableMapKeySetIterator { public fun hasNextKey(): Boolean public fun nextKey(): String }
7
null
147
942
692bc66a98c8928c950bece9a22d04c13f0c579d
465
react-native-tvos
MIT License
GithubApi/app/src/main/java/com/achmadabrar/githubapi/presentation/fragment/TimePicker.kt
achmadabrar
316,360,868
false
null
package com.achmadabrar.githubapi.presentation.fragment class TimePicker { }
1
null
1
1
707d75bba3461130b977f476de594a566b96f929
77
test_scanner_java
Creative Commons Attribution 4.0 International
clients/kotlin/generated/src/test/kotlin/org/openapitools/client/models/AssistantToolsRetrievalTest.kt
oapicf
529,246,487
false
{"Markdown": 6348, "YAML": 73, "Text": 16, "Ignore List": 52, "JSON": 1138, "Makefile": 3, "JavaScript": 1042, "F#": 585, "XML": 468, "Shell": 47, "Batchfile": 10, "Scala": 2313, "INI": 31, "Dockerfile": 17, "Maven POM": 22, "Java": 6356, "Emacs Lisp": 1, "Haskell": 39, "Swift": 263, "Ruby": 555, "OASv3-yaml": 19, "Cabal Config": 2, "Go": 1036, "Go Checksums": 1, "Go Module": 4, "CMake": 11, "C++": 3617, "TOML": 5, "Rust": 268, "Nim": 253, "Perl": 252, "Microsoft Visual Studio Solution": 2, "C#": 778, "HTML": 257, "Xojo": 507, "Gradle": 20, "R": 503, "JSON with Comments": 8, "QMake": 1, "Kotlin": 1548, "Python": 1600, "Crystal": 486, "ApacheConf": 2, "PHP": 1715, "Gradle Kotlin DSL": 1, "Protocol Buffer": 250, "C": 752, "Ada": 16, "Objective-C": 522, "Java Properties": 2, "Erlang": 521, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 501, "SQL": 242, "AsciiDoc": 1, "CSS": 3, "PowerShell": 507, "Elixir": 5, "Apex": 426, "Gemfile.lock": 1, "Option List": 2, "Eiffel": 277, "Gherkin": 1, "Dart": 500, "Groovy": 251, "Elm": 13}
/** * * 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 org.openapitools.client.models import io.kotlintest.shouldBe import io.kotlintest.specs.ShouldSpec import org.openapitools.client.models.AssistantToolsRetrieval class AssistantToolsRetrievalTest : ShouldSpec() { init { // uncomment below to create an instance of AssistantToolsRetrieval //val modelInstance = AssistantToolsRetrieval() // to test the property `type` - The type of tool being defined: `retrieval` should("test type") { // uncomment below to test the property //modelInstance.type shouldBe ("TODO") } } }
2
Java
0
4
c04dc03fa17b816be6e9a262c047840301c084b6
876
openapi-openai
MIT License
soapui-streams-executor/src/main/kotlin/eu/k5/soapui/executor/Executor.kt
denninger-eu
244,302,123
false
null
package eu.k5.soapui.executor class Executor { }
5
Kotlin
0
0
665e54e4ac65d6c7e9805bb1b44f30f9ec702ce3
50
soapui-utils
Apache License 2.0
src/main/kotlin/cc/mcyx/paimon/common/command/PaimonSubCommand.kt
xiaocheng168
693,567,613
false
{"Java": 49927, "Kotlin": 45331}
package cc.mcyx.paimon.common.command import cc.mcyx.paimon.common.plugin.Paimon /** * 子命令批处理类 * @param paimon 插件主体 * @param command 命令头 */ class PaimonSubCommand(paimon: Paimon, command: String, permissionNode: String = "") : PaimonCommand(paimon, command, permissionNode)
1
Kotlin
0
0
0788cb7b7f0c33badb6df3d79e73fcc0d494c65f
283
Paimon
MIT License
fuzzer/fuzzing_output/crashing_tests/verified/minimized/withNullability.kt247254179.kt_minimized.kt
ItsLastDay
102,885,402
false
null
fun box(): String { val nonNull = ((::nonNull))!!!!.returnType }
1
null
1
6
bb80db8b1383a6c7f186bea95c53faff4c0e0281
64
KotlinFuzzer
MIT License
app/src/main/java/com/jordandroid/aac/Trajets.kt
jordandroid
380,593,218
false
{"Gradle": 3, "Markdown": 1, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "XML": 26, "Kotlin": 12, "Java": 1}
package com.jordandroid.aac import android.content.ContentValues.TAG import android.content.SharedPreferences import android.provider.Settings import android.util.Log import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import com.google.gson.Gson import java.util.* import kotlin.collections.ArrayList import android.content.Context as Context1 import android.widget.Toast import com.google.firebase.FirebaseApp import com.google.firebase.appcheck.FirebaseAppCheck import com.google.firebase.appcheck.safetynet.SafetyNetAppCheckProviderFactory class Trajets{ var listOfTrajets : ArrayList<Trajet> = ArrayList<Trajet>() var randomInt = "" fun addATrajet(trajet: Trajet){ listOfTrajets.add(trajet) listOfTrajets.sortDescending() } fun toPrint(): String { var text = "" for (trajet in listOfTrajets){ text += trajet.toPrint() + "<br> \n" } return text } fun toPrintTotal(context: Context1): String { var distMadeInt = 0 listOfTrajets.forEach { x ->distMadeInt += x.distance.toInt() } if (listOfTrajets.size >= 1){ return "$distMadeInt ${CustomSettings.unit}" } else{ return context.getString(R.string.no_trajet) } } override fun toString(): String { var text = "" if (listOfTrajets.size < 10000) { for (trajet in listOfTrajets) { text += trajet.toString() + "\n" } } else { var step = 0 for (trajet in listOfTrajets) { if (step < 100000) { text += trajet.toString() + "\n" step+=1 } } } return text } fun toJson(id_s: String): String { val gson = Gson() println("Trajets JSON : ${gson.toJson(this)}") val json = AESUtils.encrypt(gson.toJson(this), id_s) println("jsonessai" + json) return json } fun saveFromExternalDB(sharedPreferences: SharedPreferences, id_text : String, id_s : String, context: android.content.Context) { CustomSettings.getValues(sharedPreferences) val database = FirebaseDatabase.getInstance().reference // Do network action in this function val gson = Gson() val dbManager = TrajetsDB(context) println("id_text : "+ id_text) val valueEventListener = object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val json = dataSnapshot.child(id_text).getValue(String::class.java) println("Return SaveFromExternalDB : ${json}") try { val readed = gson.fromJson(AESUtils.decrypt(json, id_s), Trajets::class.java) println("Trajets coucou " + readed.toPrintTotal(context)) for (trajet in readed.listOfTrajets) { println("Trajets add : $trajet") dbManager.Insert(trajet) } } catch (e: Exception){ Toast.makeText(context, "Invalid key", Toast.LENGTH_LONG).show() } } override fun onCancelled(databaseError: DatabaseError) { Log.d(TAG, databaseError.getMessage()) //Don't ignore errors! println("Error : "+databaseError.getMessage()) Log.d(TAG, "Return SaveFromExternalDB : Error") } } database.addListenerForSingleValueEvent(valueEventListener) // Write a message to the database /* lateinit var database: DatabaseReference database = Firebase.database.getReferenceFromUrl("LINK FIREBASE") database.child("StockedJSON").child(randomInt.toString())*/ } fun saveToExternalDB(sharedPreferences: SharedPreferences, context : Context1){ FirebaseApp.initializeApp(/*context=*/ context) val firebaseAppCheck = FirebaseAppCheck.getInstance() firebaseAppCheck.installAppCheckProviderFactory(SafetyNetAppCheckProviderFactory.getInstance()) val database = FirebaseDatabase.getInstance() CustomSettings.getValues(sharedPreferences) if (CustomSettings.id == "-1") { val random = Random(System.nanoTime() % 10000000) val time : Long = System.currentTimeMillis()/(1000*3600) randomInt = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID) + time.toString(16) val myRand = random.nextInt(1000000000).toString(16) println("number bytes : " + randomInt.toByteArray().size) // Write a message to the database val myRef = database.getReference(randomInt) val json = toJson(myRand) myRef.setValue(json) .addOnSuccessListener { println("END : Success") } .addOnFailureListener { println("END : Fail " + it.toString()) } CustomSettings.setID(sharedPreferences, randomInt) CustomSettings.setIDS(sharedPreferences, myRand) } else{ val myRef = database.getReference(CustomSettings.id) println("DBREF" + myRef) val json = toJson(CustomSettings.id_s) println("JSON : "+ json) myRef.setValue(json) .addOnSuccessListener { println("END : Success") } .addOnFailureListener { println("END : Fail " + it.toString()) } } } }
1
null
1
1
49f51d7b9644cef313eb5b7f927251d191228b03
5,886
Time-to-Drive
MIT License
app/src/main/java/com/shuhart/testlook/api/model/AutoCompleteResponse.kt
shuhart
121,277,253
false
null
package com.shuhart.testlook.api.model import com.google.gson.annotations.SerializedName data class AutoCompleteResponse( @SerializedName("cities") val cities: List<City>)
0
Kotlin
0
1
236c081dfde4c24cdbf081f9d7b81cd8f5eeab61
189
TestLook
Apache License 2.0
Adapters/Vungle/ISVungleAdapter/src/main/java/com/ironsource/adapters/vungle/interstitial/VungleInterstitialAdListener.kt
ironsource-mobile
456,103,088
false
{"Text": 1, "Ignore List": 1, "Markdown": 1, "Gradle": 36, "Java Properties": 18, "Shell": 12, "Proguard": 12, "XML": 26, "Kotlin": 41, "INI": 10, "Java": 42, "Batchfile": 3}
package com.ironsource.adapters.vungle.interstitial import com.ironsource.mediationsdk.logger.IronLog import com.ironsource.mediationsdk.logger.IronSourceError import com.ironsource.mediationsdk.sdk.InterstitialSmashListener import com.ironsource.mediationsdk.utils.ErrorBuilder import com.ironsource.mediationsdk.utils.IronSourceConstants import com.vungle.ads.BaseAd import com.vungle.ads.InterstitialAdListener import com.vungle.ads.VungleError import java.lang.ref.WeakReference class VungleInterstitialAdListener( private val mAdapter: WeakReference<VungleInterstitialAdapter>, private val mListener: InterstitialSmashListener, private val mPlacementId: String ) : InterstitialAdListener { /** * Called to indicate that an ad was loaded and it can now be shown. * * @param baseAd - Interstitial instance */ override fun onAdLoaded(baseAd: BaseAd) { IronLog.ADAPTER_CALLBACK.verbose("placementId = $mPlacementId") mAdapter.get()?.setInterstitialAdAvailability(mPlacementId,true) mListener.onInterstitialAdReady() } /** * Called when Ad failed to load * * @param baseAd - Interstitial instance * @param adError - adError with additional info about error */ override fun onAdFailedToLoad(baseAd: BaseAd, adError: VungleError) { IronLog.ADAPTER_CALLBACK.verbose("onAdFailedToLoad placementId = $mPlacementId, errorCode= ${adError.code} error = ${adError.errorMessage}") mAdapter.get()?.setInterstitialAdAvailability(mPlacementId,false) val adapterError = "${adError.errorMessage}( ${adError.code} )" val error = if (adError.code == VungleError.NO_SERVE) { IronSourceError(IronSourceError.ERROR_IS_LOAD_NO_FILL, adapterError) } else { ErrorBuilder.buildLoadFailedError(adapterError) } mListener.onInterstitialAdLoadFailed(error) } /** * Called to indicate that an ad started. * * @param baseAd - Interstitial instance */ override fun onAdStart(baseAd: BaseAd) { IronLog.ADAPTER_CALLBACK.verbose("placementId = $mPlacementId") mListener.onInterstitialAdShowSucceeded() } /** * Called to indicate that the fullscreen overlay is now the topmost screen. * * @param baseAd - Interstitial instance */ override fun onAdImpression(baseAd: BaseAd) { IronLog.ADAPTER_CALLBACK.verbose("placementId = $mPlacementId") mListener.onInterstitialAdOpened() } /** * Called to indicate that a request to show an ad (by calling [VungleInterstitial.show] * failed. You should call [VungleInterstitial.load] to request for a fresh ad. * * @param baseAd - Interstitial instance * @param adError - adError with additional info about error */ override fun onAdFailedToPlay(baseAd: BaseAd, adError: VungleError) { IronLog.ADAPTER_CALLBACK.verbose("onAdFailedToPlay placementId = $mPlacementId, errorCode = ${adError.code}, errorMessage = ${adError.message}") val errorMessage = " reason = " + adError.errorMessage + " errorCode = " + adError.code val error: IronSourceError = ErrorBuilder.buildShowFailedError( IronSourceConstants.INTERSTITIAL_AD_UNIT, errorMessage ) mListener.onInterstitialAdShowFailed(error) } /** * Called to indicate that an ad interaction was observed. * * @param baseAd - Interstitial instance */ override fun onAdClicked(baseAd: BaseAd) { IronLog.ADAPTER_CALLBACK.verbose("placementId = $mPlacementId") mListener.onInterstitialAdClicked() } /** * Called to indicate that the ad was ended and closed. * * @param baseAd - Interstitial instance */ override fun onAdEnd(baseAd: BaseAd) { IronLog.ADAPTER_CALLBACK.verbose("placementId = $mPlacementId") mListener.onInterstitialAdClosed() } /** * Called to indicate that the user may leave the application on account of interacting with the ad. * * @param baseAd Represents the [VungleInterstitialAd] ad */ override fun onAdLeftApplication(baseAd: BaseAd) { IronLog.ADAPTER_CALLBACK.verbose("placementId = $mPlacementId") } }
3
Java
2
5
69d4cb5535077ff5e7b3a892c61d7b847cd51fab
4,302
levelplay-android-adapters
Apache License 2.0
app/src/main/java/plantscam/android/prada/lab/plantscamera/di/module/AppModule.kt
plant-tw
124,741,434
false
null
package plantscam.android.prada.lab.plantscamera.di.module import android.app.Application import android.content.Context import android.content.SharedPreferences import android.content.res.AssetManager import javax.inject.Singleton import dagger.Module import dagger.Provides /** * Created by prada on 24/02/2018. */ @Module class AppModule(private val mApp: Application) { @Provides @Singleton fun provideSharedPreferences(): SharedPreferences { // UserDefault return mApp.getSharedPreferences("a", Context.MODE_PRIVATE) } @Provides @Singleton fun provideAssetManager(): AssetManager { return mApp.assets } }
2
null
2
6
3da8498e02bb8d1a909d14ed61053bffa326058d
666
PlantsCam-Android
MIT License
baselibrary/src/main/java/com/ballastlane/android/baselibrary/app/modules/network/NetworkModule.kt
Ballastlane-LLC
123,138,312
false
{"Gradle": 8, "Java Properties": 2, "Shell": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 3, "Java": 54, "XML": 72, "Kotlin": 64}
package com.ballastlane.android.baselibrary.app.modules.network import android.content.Context import android.content.res.Resources import com.ballastlane.android.baselibrary.R import com.ballastlane.android.baselibrary.app.di.* import com.ballastlane.android.baselibrary.utils.Constant import dagger.Module import dagger.Provides import okhttp3.Cache import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import okhttp3.logging.HttpLoggingInterceptor.Level import java.io.File import java.util.concurrent.TimeUnit /** * Created by Mariangela Salcedo ([email protected]) on 3/8/18. * Copyright (c) 2018 Ballast Lane Applications LLC. All rights reserved. */ @Module(includes = [(AppModule::class)]) class NetworkModule(private val authenticationInterceptor: Interceptor) { @Provides @AppScope @CacheQualifier fun provideCacheFile(@AppQualifier context: Context): File = File(context.cacheDir, Constant.Preferences.CACHE) @Provides @AppScope @CacheQualifier fun provideCacheMaxSize(): Long = 10 * 1024 * 1024 @Provides @AppScope fun provideCache(@CacheQualifier file: File, @CacheQualifier maxSize: Long): Cache = Cache(file, maxSize) @Provides @AppScope fun provideHttpLoggingInterceptor(): HttpLoggingInterceptor { return HttpLoggingInterceptor().setLevel(Level.BODY) } @Provides @AppScope @AuthenticationQualifier fun provideAuthenticatedOkHttpClient( httpLoggingInterceptor: HttpLoggingInterceptor, cache: Cache, resources: Resources): OkHttpClient = OkHttpClient.Builder() .cache(cache) .addInterceptor(authenticationInterceptor) .addInterceptor(httpLoggingInterceptor) .readTimeout( resources.getInteger(R.integer.read_timeout_seconds).toLong(), TimeUnit.SECONDS) .writeTimeout( resources.getInteger(R.integer.write_timeout_seconds).toLong(), TimeUnit.SECONDS) .connectTimeout( resources.getInteger(R.integer.connect_timeout_seconds).toLong(), TimeUnit.SECONDS) .build() @Provides @AppScope fun provideOkHttpClient( httpLoggingInterceptor: HttpLoggingInterceptor, cache: Cache, resources: Resources): OkHttpClient = OkHttpClient.Builder() .cache(cache) .addInterceptor(httpLoggingInterceptor) .readTimeout( resources.getInteger(R.integer.read_timeout_seconds).toLong(), TimeUnit.SECONDS) .writeTimeout( resources.getInteger(R.integer.write_timeout_seconds).toLong(), TimeUnit.SECONDS) .connectTimeout( resources.getInteger(R.integer.connect_timeout_seconds).toLong(), TimeUnit.SECONDS) .build() }
1
null
1
1
7b45852160a7ef9c6ae04e7225cd14d5335b300a
3,288
AndroidBaseLibrary
Apache License 2.0
app/src/main/java/com/crinoid/utils/SharedPrefs.kt
CrinoidTechnologies
228,843,233
false
null
package com.crinoid.utils import android.content.Context import android.content.SharedPreferences import android.util.Log import com.google.gson.Gson class SharedPrefs(context: Context) { private val fileName: String = context.packageName + ".prefFile" private val preferences: SharedPreferences val localData: LocalData init { preferences = context.getSharedPreferences(this.fileName, 0) val data = readString(99) Log.d("TAG", "BaseCurrentSession: $data") if (data.length > 1) { this.localData = Gson().fromJson<LocalData>(data, LocalData::class.java) }else{ this.localData = LocalData() } } fun writeString(key: Int, value: String) { this.preferences.edit().putString(key.toString(), value).apply() } private fun readString(key: Int): String { return this.preferences.getString(key.toString(), "")!! } fun saveDataLocally() { writeString(99,Gson().toJson(localData)) } fun isLoggedIn(): Boolean { return localData?.instaUserBd!=null } }
1
Kotlin
1
2
1fbeed7498b8cdbe29683fcf8db76b7f7aa3f60f
1,102
android-social-login-helper
MIT License
MVP/app/src/main/java/com/ko/mvp/navigation/NavigationProvider.kt
terracotta-ko
91,710,928
false
{"Java": 198855, "Kotlin": 47354}
package com.ko.mvp.navigation import android.content.Context import com.ko.common.navigation.AddActivityNavigator interface NavigationProvider { fun getAddActivityNavigator(context: Context): AddActivityNavigator }
1
Java
1
2
098d5844fb68cac5ed22fa79370de91e93551227
222
Android_Treasure_House
MIT License
app/src/main/java/io/jpsison/androidship/cargo/Checkout.kt
jpsison-io
277,090,940
false
null
package io.jpsison.androidship.cargo import android.os.Parcelable import io.jpsison.androidship.enums.CardType import io.jpsison.androidship.models.Cart import kotlinx.android.parcel.Parcelize @Parcelize data class Checkout( val cardType: CardType? = CardType.MASTERCARD, val cart: Cart? = null ): Parcelable
1
null
1
1
54ce88c5f05f4c47aac9006374700432cd491936
318
android-ship
MIT License
app/src/main/java/pk/sufiishq/app/ui/components/OccasionCard.kt
sufiishq
427,931,739
false
{"Kotlin": 950135}
/* * Copyright 2022-2023 SufiIshq * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pk.sufiishq.app.ui.components import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import pk.sufiishq.app.feature.occasions.model.Occasion import pk.sufiishq.app.utils.ImageRes import pk.sufiishq.app.utils.extention.formatTime import pk.sufiishq.aurora.components.SIHeightSpace import pk.sufiishq.aurora.components.SIImage import pk.sufiishq.aurora.components.SIText import pk.sufiishq.aurora.components.SIWidthSpace import pk.sufiishq.aurora.components.TextSize import pk.sufiishq.aurora.layout.SICard import pk.sufiishq.aurora.layout.SIColumn import pk.sufiishq.aurora.layout.SIConstraintLayout import pk.sufiishq.aurora.layout.SIRow import pk.sufiishq.aurora.theme.AuroraColor @Composable fun OccasionCard( occasion: Occasion, onCardClick: ((occasion: Occasion) -> Unit)? = null, ) { var clickableModifier: Modifier = Modifier onCardClick?.let { clickableModifier = Modifier.clickable { it.invoke(occasion) } } SICard( modifier = Modifier .fillMaxWidth() .height(300.dp) .then(clickableModifier), ) { SIConstraintLayout( modifier = Modifier .fillMaxSize(), bgColor = AuroraColor.Background, ) { val (coverRef, titleRef, metaRef) = createRefs() NetworkImage( modifier = Modifier .fillMaxWidth() .height(200.dp) .constrainAs(coverRef) { start.linkTo(parent.start) top.linkTo(parent.top) end.linkTo(parent.end) }, url = occasion.cover, contentScale = ContentScale.Crop, ) SIRow( modifier = Modifier.constrainAs(titleRef) { start.linkTo(parent.start, 30.dp) bottom.linkTo(parent.bottom, 78.dp) }, bgColor = AuroraColor.SecondaryVariant, padding = 12, radius = 4, horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, ) { SIText( text = occasion.title, textColor = it, textSize = TextSize.Regular, fontWeight = FontWeight.Bold, ) } SIColumn( modifier = Modifier .constrainAs(metaRef) { start.linkTo(titleRef.start) top.linkTo(titleRef.bottom) bottom.linkTo(parent.bottom) }, ) { SIRow(verticalAlignment = Alignment.CenterVertically) { SIImage(resId = ImageRes.mini_clock, tintColor = it) SIWidthSpace(value = 6) SIText(text = getTime(occasion), textColor = it, textSize = TextSize.Small) } SIHeightSpace(value = 8) SIRow(verticalAlignment = Alignment.CenterVertically) { SIImage(resId = ImageRes.mini_location, tintColor = it) SIWidthSpace(value = 6) SIText(text = occasion.address, textColor = it, textSize = TextSize.Small) } } } } } @Composable private fun getTime(occasion: Occasion): String { return buildString { append(occasion.startTimestamp.formatTime("MMMM dd, yyyy")) if (occasion.endTimestamp > occasion.startTimestamp) { append(" - ") append(occasion.endTimestamp.formatTime("MMMM dd, yyyy")) } } }
3
Kotlin
0
2
254eeb6c2b1cad21d2f971d8b49ba3327d446bb5
4,858
sufiishq-mobile
Apache License 2.0
compiler/testData/diagnostics/tests/multiplatform/directJavaActualization/directJavaActualization_withTypeParameter.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// WITH_KOTLIN_JVM_ANNOTATIONS // LANGUAGE:+DirectJavaActualization // MODULE: m1-common // FILE: common.kt expect class <!IMPLICIT_JVM_ACTUALIZATION{JVM}!>Case1<!><T> { fun <T> foo(a: T) } expect class <!IMPLICIT_JVM_ACTUALIZATION{JVM}!>Case2<!><T: Number>{ fun foo(a: T) } expect class <!IMPLICIT_JVM_ACTUALIZATION{JVM}!>Case3<!><T> where T: Number , T: Comparable<T>{ fun foo(a: T) } expect class <!IMPLICIT_JVM_ACTUALIZATION{JVM}!>Case4<!><out T> expect class <!IMPLICIT_JVM_ACTUALIZATION{JVM}!>Case5<!><in T> expect class <!IMPLICIT_JVM_ACTUALIZATION{JVM}!>Case6<!> { fun <T> foo(): T fun <T : Any> bar(): List<T> fun <S : Comparable<S>> baz(): List<S> } // MODULE: m2-jvm()()(m1-common) // FILE: Case1.java @kotlin.annotations.jvm.KotlinActual public class Case1<T> { @kotlin.annotations.jvm.KotlinActual public <T> void foo(T a){} } // FILE: Case2.java @kotlin.annotations.jvm.KotlinActual public class Case2<T extends Number> { @kotlin.annotations.jvm.KotlinActual public void foo(T a){} } // FILE: Case3.java @kotlin.annotations.jvm.KotlinActual public class Case3 <T extends Number&Comparable<T>> { @kotlin.annotations.jvm.KotlinActual public void foo(T a){} } // FILE: Case4.java @kotlin.annotations.jvm.KotlinActual public class Case4<T> { } // FILE: Case5.java @kotlin.annotations.jvm.KotlinActual public class Case5<T> { } // FILE: Case6.java import java.util.List; @kotlin.annotations.jvm.KotlinActual public class Case6 { @kotlin.annotations.jvm.KotlinActual public <T> T foo() {} @kotlin.annotations.jvm.KotlinActual public <T> List<T> bar() { return null; } @kotlin.annotations.jvm.KotlinActual public <S extends Comparable<S>> List<S> baz() { return null; } }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,764
kotlin
Apache License 2.0
app/src/main/java/com/challenge/xkcd/dataLayer/remote/RemoteService.kt
AbdullahAimen
408,370,136
false
null
package com.challenge.xkcd.dataLayer.remote import com.challenge.xkcd.dataLayer.dataModel.Comic import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Url interface RemoteService { @GET fun loadComic(@Url url: String): Call<Comic> }
0
null
0
0
759c2faffad8059309beb7d3affa3fd569ff0245
257
xkcd-shortcut.io
Apache License 2.0
plugin/kermit-ir-plugin/src/main/kotlin/co/touchlab/kermit/irplugin/KermitChiselTransformer.kt
touchlab
254,470,560
false
{"JavaScript": 111161, "Kotlin": 101182, "CSS": 21764, "TypeScript": 821, "Shell": 151}
/* * Copyright (c) 2021 Touchlab * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package co.touchlab.kermit.irplugin import org.jetbrains.kotlin.backend.common.IrElementTransformerVoidWithContext import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext import org.jetbrains.kotlin.backend.common.lower.DeclarationIrBuilder import org.jetbrains.kotlin.ir.builders.* import org.jetbrains.kotlin.ir.expressions.IrCall import org.jetbrains.kotlin.ir.expressions.IrExpression import org.jetbrains.kotlin.ir.types.classFqName import org.jetbrains.kotlin.ir.types.isSubtypeOfClass import org.jetbrains.kotlin.name.FqName class KermitChiselTransformer( private val pluginContext: IrPluginContext, stripBelow: String ) : IrElementTransformerVoidWithContext() { private val classLogger = pluginContext.referenceClass(FqName("co.touchlab.kermit.Logger"))!! private val stripFunctionSet = makeStripFunctionNameSet(stripBelow) override fun visitCall(expression: IrCall): IrExpression { val recType = expression.dispatchReceiver?.type if (recType != null && recType.isSubtypeOfClass(classLogger)) { val functionName = expression.symbol.owner.name.identifier val stripCall = stripFunctionSet.contains(functionName) if (stripCall) { return DeclarationIrBuilder(pluginContext, expression.symbol).irUnit() } } return super.visitCall(expression) } private fun makeStripFunctionNameSet(severity: String): Set<String> = when (severity) { "None", "Verbose" -> emptySet() "Debug" -> setOf("v") "Info" -> setOf("v", "d") "Warn" -> setOf("v", "d", "i") "Error" -> setOf("v", "d", "i", "w") "Assert" -> setOf("v", "d", "i", "w", "e") "All" -> setOf("v", "d", "i", "w", "e", "a") else -> emptySet() } }
39
JavaScript
40
691
e87d7da197cac4c970d7309dd6b8486a401d886b
2,394
Kermit
Apache License 2.0
src/commonMain/kotlin/com/algolia/search/model/search/Point.kt
pallavirawat
205,637,107
true
{"Kotlin": 941656, "Ruby": 4462}
package com.algolia.search.model.search import com.algolia.search.model.Raw import kotlinx.serialization.* import kotlinx.serialization.internal.FloatSerializer /** * A set of geo-coordinates [latitude] and [longitude]. */ @Serializable(Point.Companion::class) public data class Point( val latitude: Float, val longitude: Float ) : Raw<List<Float>> { override val raw = listOf(latitude, longitude) companion object : KSerializer<Point> { private val serializer = FloatSerializer.list override val descriptor = serializer.descriptor override fun serialize(encoder: Encoder, obj: Point) { serializer.serialize(encoder, obj.raw) } override fun deserialize(decoder: Decoder): Point { val floats = serializer.deserialize(decoder) return Point(floats[0], floats[1]) } } }
0
Kotlin
0
0
a7127793476d4453873266222ea71b1fce5c8c32
881
algoliasearch-client-kotlin
MIT License
feature/user/profile/src/main/kotlin/com/ngapps/feature/profile/navigation/ProfileNavigation.kt
ngapp-dev
752,386,763
false
{"Kotlin": 1840445, "Shell": 10136}
/* * Copyright 2024 NGApps Dev (https://github.com/ngapp-dev). All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ngapps.feature.profile.navigation import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.NavOptions import androidx.navigation.compose.composable import androidx.navigation.navigation import com.ngapps.feature.profile.ProfileRoute private const val profileGraphRoutePattern = "profile_graph" const val profileRoute = "profile_route" fun NavController.navigateToProfileGraph(navOptions: NavOptions? = null) { this.navigate(profileGraphRoutePattern, navOptions) } fun NavGraphBuilder.profileGraph( onBackClick: () -> Unit, onMoreActionClick: () -> Unit, nestedGraphs: NavGraphBuilder.() -> Unit, ) { navigation( route = profileGraphRoutePattern, startDestination = profileRoute, ) { composable(route = profileRoute) { ProfileRoute( onBackClick = onBackClick, onMoreActionClick = onMoreActionClick, ) } nestedGraphs() } }
0
Kotlin
0
3
dc6556f93cedf210597f0397ad3553de0fbb7a47
1,659
phototime
Apache License 2.0
app/src/main/kotlin/jp/co/yumemi/android/code_check/util/VisibilityUtil.kt
yuchan2215
532,719,899
false
null
package jp.co.yumemi.android.code_check.util import android.view.View object VisibilityUtil { /** * BooleanをVisibilityな値にする。 * @param defaultInvisible 非表示の時の値 */ fun booleanToVisibility(boolean: Boolean, defaultInvisible: Int = View.GONE): Int { return if (boolean) View.VISIBLE else defaultInvisible } }
1
Kotlin
0
0
23820fe5a75abf4759e7973363a20ca64725be36
342
android-engineer-codecheck
Apache License 2.0
src/main/kotlin/br/anhembi/funmodechild/entity/Order.kt
svbgabriel
199,749,038
false
{"Kotlin": 43080, "JavaScript": 12575}
package br.anhembi.funmodechild.entity import br.anhembi.funmodechild.model.response.OrderDetailResponse import br.anhembi.funmodechild.model.response.OrderResponse import org.springframework.data.annotation.Id import org.springframework.data.mongodb.core.mapping.Document import org.springframework.data.mongodb.core.mapping.DocumentReference import java.time.LocalDateTime @Document("orders") data class Order( @Id val id: String? = null, val createdAt: LocalDateTime = LocalDateTime.now(), @DocumentReference(lazy = true) val customer: Customer, val details: List<OrderDetail> = emptyList(), val totalPrice: Double = 0.0, var active: Boolean = true ) { fun toApiResponse() = OrderResponse( this.id!!, this.createdAt, details .map { it.toApiResponse() } .toList(), this.totalPrice, this.active ) data class OrderDetail( @DocumentReference(lazy = true) val product: Product, val price: Double = 0.0, val quantity: Int = 0, ) { fun toApiResponse() = OrderDetailResponse( product = product.toApiResponse(), price = this.price, quantity = this.quantity ) } }
3
Kotlin
0
0
35c91197e3709f60073766048bf295c51dee6eae
1,260
fun-mode-child
MIT License
src/main/kotlin/org/kotlinbitcointools/ur/fountain/FountainDecoder.kt
kotlin-bitcoin-tools
662,277,344
false
{"Kotlin": 78108, "Java": 10358, "Just": 254}
/* * Copyright 2023-2024 thunderbiscuit and contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the ./LICENSE.txt file. */ package org.kotlinbitcointools.ur.fountain import org.kotlinbitcointools.ur.fountain.FountainEncoder.Companion.xor import org.kotlinbitcointools.ur.utilities.crc32Checksum import java.util.TreeMap // Refer to Decoder section of this document for in-depth explanation of the workflow: // https://github.com/BlockchainCommons/Research/blob/master/papers/bcr-2024-001-multipart-ur.md#6-the-decoder public class FountainDecoder { // NOTE: The Swift and Java implementations use a Map<Set<Int>, Part> to store simple parts but this feels like a // small mistake: simple parts can only have one fragment index, so a Map<Int, Part> feels more appropriate. // This is also how the Rust ur-rs implementation does it. private val simpleParts: MutableMap<Int, Part> = TreeMap() private var mixedParts: MutableMap<Set<Int>, Part> = mutableMapOf() private val queuedParts: MutableList<Part> = mutableListOf() private var expectedFragmentIndexes: Set<Int>? = null private val receivedFragmentIndexes: MutableSet<Int> = mutableSetOf() private var expectedFragmentLen = 0 private var expectedMessageLen = 0 private var expectedChecksum: Long = 0 // TODO: Write up what is this variable really used for private var lastFragmentIndexes: Set<Int>? = null public var result: Result<ByteArray>? = null // TODO: The Rust ur-rs implementation returns a Result instead, which I think is more elegant here // because the boolean returned by this function is true if the part was processed and false // if it was not _or_ if it was invalid _or_ if the decoder is already done. This is a bit // confusing. public fun receivePart(encoderPart: FountainEncoder.Part): Boolean { // Don't process the part if we are already done if (this.result != null) return false // Don't continue if this part is not valid if (!isPartValid(encoderPart)) return false // Add this part to the queue val fragmentIndexes: Set<Int> = chooseFragments(encoderPart.sequenceNumber, encoderPart.sequenceLength, encoderPart.checksum) val part = Part(encoderPart, fragmentIndexes) lastFragmentIndexes = fragmentIndexes enqueue(part) // Process the queue until the message is reconstructed in full or the queue is empty processQueue() // Keep track of how many parts we've processed // TODO: Look into where this is used and why we should expose it in the API // processedPartsCount += 1 return true } private fun enqueue(part: Part): Unit { queuedParts.add(part) } private fun processQueue(): Unit { // Process the queue until the message is reconstructed in full or the queue is empty while (queuedParts.isNotEmpty() && result == null) { val part: Part = queuedParts.removeAt(0) if (part.isSimple) { processSimplePart(part) } else { processMixedPart(part) } } } private fun processSimplePart(part: Part): Unit { require(part.isSimple) { "Part must be simple" } // Don't process duplicate parts val fragmentIndex: Int = part.fragmentIndexes.first() if (fragmentIndex in receivedFragmentIndexes) return // Record this part simpleParts.put(fragmentIndex, part) receivedFragmentIndexes.add(fragmentIndex) // If we've received all the parts, return a Result if (receivedFragmentIndexes == expectedFragmentIndexes) { // Reassemble the message from its fragments. Note that the simpleParts map is already sorted in ascending // order by fragment index because it's a TreeMap val fragments: List<ByteArray> = simpleParts.values.map { it.data } val message: ByteArray = joinFragments(fragments, expectedMessageLen) // If the checksum of the reassembled message matches the expected checksum, set result to success result = if (crc32Checksum(message) == expectedChecksum) { Result.success(message) } else { Result.failure(Exception("Checksum mismatch")) } } else { // If we haven't received all the parts, attempt to reduce all mixed parts by this part reduceMixed(part) } } private fun processMixedPart(part: Part): Unit { // Don't process duplicate parts if (part.fragmentIndexes in mixedParts.keys) return // Reduce this part by all the others val allParts: List<Part> = simpleParts.values + mixedParts.values val reducedPart: Part = allParts.fold(part) { acc, reduceBy -> reducePart(acc, reduceBy) } // If the reduced part is now simple, enqueue it if (reducedPart.isSimple) { enqueue(reducedPart) } else { // If the reduced part is still mixed, reduce all the mixed parts by it reduceMixed(reducedPart) // Record this new mixed part mixedParts.put(reducedPart.fragmentIndexes, reducedPart) } } // Join fragments into a single message, discarding any padding (by taking the first messageLength bytes) public fun joinFragments(fragments: List<ByteArray>, messageLength: Int): ByteArray { val combinedFragments: List<Byte> = fragments.flatMap { it.toList() }.take(messageLength) return combinedFragments.toByteArray() } private fun reduceMixed(by: Part): Unit { // Reduce all mixed parts by the given part val reducedParts: List<Part> = mixedParts.map { (_, part) -> reducePart(part, by) } val newMixed: MutableMap<Set<Int>, Part> = mutableMapOf() reducedParts.forEach { reducedPart -> if (reducedPart.isSimple) { enqueue(reducedPart) } else { newMixed.put(reducedPart.fragmentIndexes, reducedPart) } } this.mixedParts = newMixed } // Reduce part a by part b. For example, if part a is [1, 2, 3] and part b is [2, 3], the result is [1] private fun reducePart(partA: Part, partB: Part): Part { // If the fragments mixed into b are a strict subset of those in a, reduce a by b if (partA.fragmentIndexes.containsAll(partB.fragmentIndexes)) { // The new fragments in the revised part are Set(a) - Set(b) val newIndexes: Set<Int> = partA.fragmentIndexes - partB.fragmentIndexes // The new data in the revised part is a XOR b val reducedData = xor(partA.data, partB.data) return Part(reducedData, newIndexes) } else { // If a is not reducible by b, simply return a return partA } } private fun isPartValid(part: FountainEncoder.Part): Boolean { // If this is the first part we see, set the expected values if (expectedFragmentIndexes == null) { expectedFragmentIndexes = (0..<part.sequenceLength).toSet() expectedFragmentLen = part.data.size expectedMessageLen = part.messageLength expectedChecksum = part.checksum } else { // If this part doesn't match the expected values, do not process it (return false) if (part.sequenceLength != expectedFragmentIndexes!!.size) return false if (part.data.size != expectedFragmentLen) return false if (part.messageLength != expectedMessageLen) return false if (part.checksum != expectedChecksum) return false } // This part should be processed return true } public class Part(public val data: ByteArray, public val fragmentIndexes: Set<Int>) { public constructor( part: FountainEncoder.Part, fragmentIndexes: Set<Int> ) : this(part.data, fragmentIndexes) public val isSimple: Boolean get() = fragmentIndexes.size == 1 } }
0
Kotlin
0
0
90e0d5d3ccefd4c4fe0854a583f3bbf1f3b7145b
8,260
ur
Apache License 2.0
cosmos-sdk/src/jvmMain/kotlin/cosmos/crisis/v1beta1/tx.converter.jvm.kt
jdekim43
759,720,689
false
{"Kotlin": 8940168, "Java": 3242559}
// Transform from cosmos/crisis/v1beta1/tx.proto @file:GeneratorVersion(version = "0.3.1") package cosmos.crisis.v1beta1 import com.google.protobuf.Descriptors import com.google.protobuf.Parser import cosmos.base.v1beta1.CoinJvmConverter import kr.jadekim.protobuf.`annotation`.GeneratorVersion import kr.jadekim.protobuf.converter.mapper.ProtobufTypeMapper public object MsgVerifyInvariantJvmConverter : ProtobufTypeMapper<MsgVerifyInvariant, Tx.MsgVerifyInvariant> { public override val descriptor: Descriptors.Descriptor = Tx.MsgVerifyInvariant.getDescriptor() public override val parser: Parser<Tx.MsgVerifyInvariant> = Tx.MsgVerifyInvariant.parser() public override fun convert(obj: Tx.MsgVerifyInvariant): MsgVerifyInvariant = MsgVerifyInvariant( sender = obj.getSender(), invariantModuleName = obj.getInvariantModuleName(), invariantRoute = obj.getInvariantRoute(), ) public override fun convert(obj: MsgVerifyInvariant): Tx.MsgVerifyInvariant { val builder = Tx.MsgVerifyInvariant.newBuilder() builder.setSender(obj.sender) builder.setInvariantModuleName(obj.invariantModuleName) builder.setInvariantRoute(obj.invariantRoute) return builder.build() } } public object MsgVerifyInvariantResponseJvmConverter : ProtobufTypeMapper<MsgVerifyInvariantResponse, Tx.MsgVerifyInvariantResponse> { public override val descriptor: Descriptors.Descriptor = Tx.MsgVerifyInvariantResponse.getDescriptor() public override val parser: Parser<Tx.MsgVerifyInvariantResponse> = Tx.MsgVerifyInvariantResponse.parser() public override fun convert(obj: Tx.MsgVerifyInvariantResponse): MsgVerifyInvariantResponse = MsgVerifyInvariantResponse( ) public override fun convert(obj: MsgVerifyInvariantResponse): Tx.MsgVerifyInvariantResponse { val builder = Tx.MsgVerifyInvariantResponse.newBuilder() return builder.build() } } public object MsgUpdateParamsJvmConverter : ProtobufTypeMapper<MsgUpdateParams, Tx.MsgUpdateParams> { public override val descriptor: Descriptors.Descriptor = Tx.MsgUpdateParams.getDescriptor() public override val parser: Parser<Tx.MsgUpdateParams> = Tx.MsgUpdateParams.parser() public override fun convert(obj: Tx.MsgUpdateParams): MsgUpdateParams = MsgUpdateParams( authority = obj.getAuthority(), constantFee = CoinJvmConverter.convert(obj.getConstantFee()), ) public override fun convert(obj: MsgUpdateParams): Tx.MsgUpdateParams { val builder = Tx.MsgUpdateParams.newBuilder() builder.setAuthority(obj.authority) builder.setConstantFee(CoinJvmConverter.convert(obj.constantFee)) return builder.build() } } public object MsgUpdateParamsResponseJvmConverter : ProtobufTypeMapper<MsgUpdateParamsResponse, Tx.MsgUpdateParamsResponse> { public override val descriptor: Descriptors.Descriptor = Tx.MsgUpdateParamsResponse.getDescriptor() public override val parser: Parser<Tx.MsgUpdateParamsResponse> = Tx.MsgUpdateParamsResponse.parser() public override fun convert(obj: Tx.MsgUpdateParamsResponse): MsgUpdateParamsResponse = MsgUpdateParamsResponse( ) public override fun convert(obj: MsgUpdateParamsResponse): Tx.MsgUpdateParamsResponse { val builder = Tx.MsgUpdateParamsResponse.newBuilder() return builder.build() } }
0
Kotlin
0
0
eb9b3ba5ad6b798db1d8da208b5435fc5c1f6cdc
3,315
chameleon.proto
Apache License 2.0
cosmos-sdk/src/jvmMain/kotlin/cosmos/crisis/v1beta1/tx.converter.jvm.kt
jdekim43
759,720,689
false
{"Kotlin": 8940168, "Java": 3242559}
// Transform from cosmos/crisis/v1beta1/tx.proto @file:GeneratorVersion(version = "0.3.1") package cosmos.crisis.v1beta1 import com.google.protobuf.Descriptors import com.google.protobuf.Parser import cosmos.base.v1beta1.CoinJvmConverter import kr.jadekim.protobuf.`annotation`.GeneratorVersion import kr.jadekim.protobuf.converter.mapper.ProtobufTypeMapper public object MsgVerifyInvariantJvmConverter : ProtobufTypeMapper<MsgVerifyInvariant, Tx.MsgVerifyInvariant> { public override val descriptor: Descriptors.Descriptor = Tx.MsgVerifyInvariant.getDescriptor() public override val parser: Parser<Tx.MsgVerifyInvariant> = Tx.MsgVerifyInvariant.parser() public override fun convert(obj: Tx.MsgVerifyInvariant): MsgVerifyInvariant = MsgVerifyInvariant( sender = obj.getSender(), invariantModuleName = obj.getInvariantModuleName(), invariantRoute = obj.getInvariantRoute(), ) public override fun convert(obj: MsgVerifyInvariant): Tx.MsgVerifyInvariant { val builder = Tx.MsgVerifyInvariant.newBuilder() builder.setSender(obj.sender) builder.setInvariantModuleName(obj.invariantModuleName) builder.setInvariantRoute(obj.invariantRoute) return builder.build() } } public object MsgVerifyInvariantResponseJvmConverter : ProtobufTypeMapper<MsgVerifyInvariantResponse, Tx.MsgVerifyInvariantResponse> { public override val descriptor: Descriptors.Descriptor = Tx.MsgVerifyInvariantResponse.getDescriptor() public override val parser: Parser<Tx.MsgVerifyInvariantResponse> = Tx.MsgVerifyInvariantResponse.parser() public override fun convert(obj: Tx.MsgVerifyInvariantResponse): MsgVerifyInvariantResponse = MsgVerifyInvariantResponse( ) public override fun convert(obj: MsgVerifyInvariantResponse): Tx.MsgVerifyInvariantResponse { val builder = Tx.MsgVerifyInvariantResponse.newBuilder() return builder.build() } } public object MsgUpdateParamsJvmConverter : ProtobufTypeMapper<MsgUpdateParams, Tx.MsgUpdateParams> { public override val descriptor: Descriptors.Descriptor = Tx.MsgUpdateParams.getDescriptor() public override val parser: Parser<Tx.MsgUpdateParams> = Tx.MsgUpdateParams.parser() public override fun convert(obj: Tx.MsgUpdateParams): MsgUpdateParams = MsgUpdateParams( authority = obj.getAuthority(), constantFee = CoinJvmConverter.convert(obj.getConstantFee()), ) public override fun convert(obj: MsgUpdateParams): Tx.MsgUpdateParams { val builder = Tx.MsgUpdateParams.newBuilder() builder.setAuthority(obj.authority) builder.setConstantFee(CoinJvmConverter.convert(obj.constantFee)) return builder.build() } } public object MsgUpdateParamsResponseJvmConverter : ProtobufTypeMapper<MsgUpdateParamsResponse, Tx.MsgUpdateParamsResponse> { public override val descriptor: Descriptors.Descriptor = Tx.MsgUpdateParamsResponse.getDescriptor() public override val parser: Parser<Tx.MsgUpdateParamsResponse> = Tx.MsgUpdateParamsResponse.parser() public override fun convert(obj: Tx.MsgUpdateParamsResponse): MsgUpdateParamsResponse = MsgUpdateParamsResponse( ) public override fun convert(obj: MsgUpdateParamsResponse): Tx.MsgUpdateParamsResponse { val builder = Tx.MsgUpdateParamsResponse.newBuilder() return builder.build() } }
0
Kotlin
0
0
eb9b3ba5ad6b798db1d8da208b5435fc5c1f6cdc
3,315
chameleon.proto
Apache License 2.0
app/src/main/java/com/stfalcon/new_uaroads_android/repos/routes/UaroadsRoutesRepo.kt
stfalcon-studio
49,490,060
false
null
/* * Copyright (c) 2017 stfalcon.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.stfalcon.new_uaroads_android.repos.routes import com.stfalcon.new_uaroads_android.common.network.models.LatLng import com.stfalcon.new_uaroads_android.common.network.services.RoutesService import io.reactivex.Single import io.reactivex.schedulers.Schedulers /* * Created by <NAME> on 4/12/17. */ class UaroadsRoutesRepo(val service: RoutesService) : RoutesRepo { override fun getRouteInstruction(locationFrom: LatLng, locationTo: LatLng): Single<String> { return service.getRouteInstructions(listOf(locationFrom, locationTo)) .subscribeOn(Schedulers.io()) } }
1
null
6
24
1332f62043a91206f0c6fdbade6ac31e6864b8cc
1,236
uaroads_android
Apache License 2.0
src/main/kotlin/com/github/vhromada/catalog/domain/Game.kt
vhromada
795,933,875
false
{"Kotlin": 1771817, "Dockerfile": 376}
package com.github.vhromada.catalog.domain import jakarta.persistence.CascadeType import jakarta.persistence.Column import jakarta.persistence.Entity import jakarta.persistence.FetchType import jakarta.persistence.GeneratedValue import jakarta.persistence.GenerationType import jakarta.persistence.Id import jakarta.persistence.JoinColumn import jakarta.persistence.OneToOne import jakarta.persistence.SequenceGenerator import jakarta.persistence.Table /** * A class represents game. * * @author <NAME> */ @Entity @Table(name = "games") @Suppress("JpaDataSourceORMInspection") data class Game( /** * ID */ @Id @SequenceGenerator(name = "game_generator", sequenceName = "games_sq", allocationSize = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "game_generator") var id: Int?, /** * UUID */ val uuid: String, /** * Name */ @Column(name = "game_name") var name: String, /** * Normalized name */ @Column(name = "normalized_game_name") var normalizedName: String, /** * URL to english Wikipedia page about game */ @Column(name = "wiki_en") var wikiEn: String?, /** * URL to czech Wikipedia page about game */ @Column(name = "wiki_cz") var wikiCz: String?, /** * Count of media */ @Column(name = "media_count") var mediaCount: Int, /** * Format */ var format: String, /** * Cheat */ @OneToOne(cascade = [CascadeType.ALL], fetch = FetchType.EAGER, orphanRemoval = true) @JoinColumn(name = "cheat") var cheat: Cheat?, /** * True if there is crack */ var crack: Boolean, /** * True if there is serial key */ @Column(name = "serial_key") var serialKey: Boolean, /** * True if there is patch */ var patch: Boolean, /** * True if there is trainer */ var trainer: Boolean, /** * True if there is data for trainer */ @Column(name = "trainer_data") var trainerData: Boolean, /** * True if there is editor */ @Column(name = "editor") var editor: Boolean, /** * True if there are saves */ var saves: Boolean, /** * Other data */ @Column(name = "other_data") var otherData: String?, /** * Note */ var note: String? ) : Audit() { /** * Merges game. * * @param game game */ @Suppress("DuplicatedCode") fun merge(game: Game) { name = game.name normalizedName = game.normalizedName wikiEn = game.wikiEn wikiCz = game.wikiCz mediaCount = game.mediaCount format = game.format crack = game.crack serialKey = game.serialKey patch = game.patch trainer = game.trainer trainerData = game.trainerData editor = game.serialKey saves = game.saves otherData = game.otherData note = game.note } }
0
Kotlin
0
0
9feab9abeb8b1ae84ae9c5e1d3c81ef7df7d0f97
3,045
catalog-be
MIT License
composeApp/src/commonMain/kotlin/App.kt
Hieu-Luu
761,312,099
false
{"Kotlin": 21698, "Swift": 594, "HTML": 304}
import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.Button import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.SpaceXSDK import kotlinx.datetime.Clock import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone import kotlinx.datetime.toLocalDateTime import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.painterResource @Composable fun Home(sdk: SpaceXSDK) { MaterialTheme { LaunchesScreen(sdk) } } @OptIn(ExperimentalResourceApi::class) @Composable fun App() { MaterialTheme { var showContent by remember { mutableStateOf(false) } val greeting = remember { Greeting().greet() } Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { Text( text = "Today's date is ${todaysDate()}", modifier = Modifier.padding(20.dp), fontSize = 24.sp, textAlign = TextAlign.Center ) Button(onClick = { showContent = !showContent }) { Text("Click me!") } AnimatedVisibility(showContent) { Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { Image(painterResource("compose-multiplatform.xml"), null) Text("Compose: $greeting") } } } } } fun todaysDate(): String { fun LocalDateTime.format() = toString().substringBefore('T') val now = Clock.System.now() val zone = TimeZone.currentSystemDefault() return now.toLocalDateTime(zone).format() }
0
Kotlin
0
0
80b9335218ec4cbc3d35f6f6ae36b1caee16a94a
2,332
kmp-example
Apache License 2.0
composeApp/src/commonMain/kotlin/App.kt
Hieu-Luu
761,312,099
false
{"Kotlin": 21698, "Swift": 594, "HTML": 304}
import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.Button import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.SpaceXSDK import kotlinx.datetime.Clock import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone import kotlinx.datetime.toLocalDateTime import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.painterResource @Composable fun Home(sdk: SpaceXSDK) { MaterialTheme { LaunchesScreen(sdk) } } @OptIn(ExperimentalResourceApi::class) @Composable fun App() { MaterialTheme { var showContent by remember { mutableStateOf(false) } val greeting = remember { Greeting().greet() } Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { Text( text = "Today's date is ${todaysDate()}", modifier = Modifier.padding(20.dp), fontSize = 24.sp, textAlign = TextAlign.Center ) Button(onClick = { showContent = !showContent }) { Text("Click me!") } AnimatedVisibility(showContent) { Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { Image(painterResource("compose-multiplatform.xml"), null) Text("Compose: $greeting") } } } } } fun todaysDate(): String { fun LocalDateTime.format() = toString().substringBefore('T') val now = Clock.System.now() val zone = TimeZone.currentSystemDefault() return now.toLocalDateTime(zone).format() }
0
Kotlin
0
0
80b9335218ec4cbc3d35f6f6ae36b1caee16a94a
2,332
kmp-example
Apache License 2.0
src/main/java/com/mindboardapps/app/smallsketch/tosvg/svg/SvgRes.kt
mindboard
163,968,002
false
{"Gradle": 2, "Shell": 1, "Text": 1, "Markdown": 1, "INI": 1, "Groovy": 7, "Kotlin": 44, "Java": 2, "SVG": 1, "JSON": 4}
package com.mindboardapps.app.smallsketch.tosvg.svg import com.mindboardapps.app.smallsketch.tosvg.model.Color object SvgRes { fun createRgbColor(color: Color): String{ return "rgb(${color.r}, ${color.g}, ${color.b})" } }
1
null
1
1
9356e378cb589f23e559725b8ed97eb4794bade7
240
ssf2img
MIT License
connector/src/main/java/org/unifiedpush/android/connector/MessagingReceiver.kt
karmanyaahm
330,565,753
true
{"Kotlin": 9015}
package org.unifiedpush.android.connector import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.util.Log interface MessagingReceiverHandler { fun onNewEndpoint(context: Context?, endpoint: String) fun onRegistrationFailed(context: Context?) fun onRegistrationRefused(context: Context?) fun onUnregistered(context: Context?) fun onMessage(context: Context?, message: String) } open class MessagingReceiver(private val handler: MessagingReceiverHandler) : BroadcastReceiver() { private val up = Registration() override fun onReceive(context: Context?, intent: Intent?) { if (up.getToken(context!!) != intent!!.getStringExtra(EXTRA_TOKEN)) { return } when (intent!!.action) { ACTION_NEW_ENDPOINT -> { val endpoint = intent.getStringExtra(EXTRA_ENDPOINT)!! [email protected](context, endpoint) } ACTION_REGISTRATION_FAILED -> { val message = intent.getStringExtra(EXTRA_MESSAGE) ?: "No reason supplied" Log.i("UP-registration", "Failed: $message") [email protected](context) up.removeToken(context!!) } ACTION_REGISTRATION_REFUSED -> { val message = intent.getStringExtra(EXTRA_MESSAGE) ?: "No reason supplied" Log.i("UP-registration", "Refused: $message") [email protected](context) up.removeToken(context!!) } ACTION_UNREGISTERED -> { [email protected](context) up.removeToken(context!!) up.removeDistributor(context!!) } ACTION_MESSAGE -> { val message = intent.getStringExtra(EXTRA_MESSAGE)!! val id = intent.getStringExtra(EXTRA_MESSAGE_ID) ?: "" [email protected](context, message) acknowledgeMessage(context, id) } } } private fun acknowledgeMessage(context: Context, id: String) { val token = up.getToken(context)!! val broadcastIntent = Intent() broadcastIntent.`package` = up.getDistributor(context) broadcastIntent.action = ACTION_MESSAGE_ACK broadcastIntent.putExtra(EXTRA_TOKEN, token) broadcastIntent.putExtra(EXTRA_MESSAGE_ID, id) context.sendBroadcast(broadcastIntent) } }
0
null
0
0
8e35db811755d7d3136d5d3a0814ffe2527f13a2
2,631
android-connector
Apache License 2.0
app/src/main/java/com/hypertrack/android/ui/screens/background_permissions/BackgroundPermissionsFragment.kt
hypertrack
241,723,736
false
null
package com.hypertrack.android.ui.screens.background_permissions import android.graphics.Typeface import android.os.Build import android.os.Bundle import android.text.Spannable import android.text.SpannableStringBuilder import android.text.style.StyleSpan import android.view.View import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import com.hypertrack.android.di.Injector import com.hypertrack.android.interactors.app.RegisterScreenAction import com.hypertrack.android.interactors.app.state.BackgroundPermissionsScreen import com.hypertrack.android.ui.MainActivity import com.hypertrack.android.ui.base.BaseFragment import com.hypertrack.android.ui.base.navigate import com.hypertrack.android.ui.common.util.hide import com.hypertrack.android.ui.common.util.observeWithErrorHandling import com.hypertrack.android.utils.MyApplication import com.hypertrack.logistics.android.github.R import kotlinx.android.synthetic.main.fragment_background_permission.* import kotlinx.coroutines.FlowPreview @FlowPreview class BackgroundPermissionsFragment : BaseFragment<MainActivity>(R.layout.fragment_background_permission) { private val vm: BackgroundPermissionsViewModel by viewModels { Injector.provideViewModelFactory() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) Injector.provideAppInteractor() .handleAction(RegisterScreenAction(BackgroundPermissionsScreen)) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { val hint = getString(R.string.background_location_permission_option_hint) val sb = SpannableStringBuilder(hint + "\n" + MyApplication.context.packageManager.backgroundPermissionOptionLabel) sb.setSpan( StyleSpan(Typeface.BOLD), hint.length, sb.length, Spannable.SPAN_INCLUSIVE_INCLUSIVE ); // make first 4 characters Bold tvOptionHint.text = sb } else { tvOptionHint.hide() } vm.destination.observeWithErrorHandling(viewLifecycleOwner, vm::onError) { findNavController().navigate(it) } btnContinue.setOnClickListener { vm.handleAction(OnAllowClick(mainActivity())) } } //todo migrate to new approach @Deprecated("Deprecated in Java") override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) vm.handleAction(OnPermissionsResult(mainActivity())) } }
1
Kotlin
17
31
c5dd23621aed11ff188cf98ac037b67f435e9f5b
2,763
visits-android
MIT License
patterns/src/main/kotlin/io/nullables/api/playground/patterns/singleton/main.kt
AlexRogalskiy
331,076,596
false
null
/* * Copyright (C) 2021. <NAME>. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.nullables.api.playground.patterns.singleton /** * Lazy initialization Singleton Pattern * * Thread safety with SYNCHRONIZED mode to ensure only one instance * will be created in race condition. */ fun main(args: Array<String>) { DummySingleton.instance.print() } class Dummy { fun print() = println("Print Something!") } object DummySingleton { val instance: Dummy by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { Dummy() } }
13
Kotlin
1
2
d7173ec1d9ef227308d926e71335b530c43c92a8
1,082
gradle-kotlin-sample
Apache License 2.0
ksp-processor/src/jvmMain/kotlin/com/jamshedalamqaderi/tawraktorapi/visitors/websocket/ClientWebsocketFunParamVisitorImpl.kt
JamshedAlamQaderi
572,014,958
false
{"Kotlin": 89751}
package com.jamshedalamqaderi.tawraktorapi.visitors.websocket import com.google.devtools.ksp.processing.KSPLogger import com.google.devtools.ksp.symbol.KSValueParameter import com.jamshedalamqaderi.tawraktorapi.interfaces.ClientCodeAppender import com.jamshedalamqaderi.tawraktorapi.interfaces.TawraVisitor import com.jamshedalamqaderi.tawraktorapi.utils.ext.KSValueParameterExtensions.nullOperator import com.jamshedalamqaderi.tawraktorapi.utils.ext.KSValueParameterExtensions.qualifiedType class ClientWebsocketFunParamVisitorImpl( private val logger: KSPLogger ) : TawraVisitor<ClientCodeAppender, KSValueParameter, Unit> { override fun visit(appender: ClientCodeAppender, declaration: KSValueParameter) { appender.addCode("${declaration.name?.asString()} : ${declaration.qualifiedType()}${declaration.nullOperator()},") } }
0
Kotlin
0
3
1f92acdc3c3b8c0d1f133bce2c8daec0224d9365
851
tawra-ktor-api
Apache License 2.0
ksp-processor/src/jvmMain/kotlin/com/jamshedalamqaderi/tawraktorapi/visitors/websocket/ClientWebsocketFunParamVisitorImpl.kt
JamshedAlamQaderi
572,014,958
false
{"Kotlin": 89751}
package com.jamshedalamqaderi.tawraktorapi.visitors.websocket import com.google.devtools.ksp.processing.KSPLogger import com.google.devtools.ksp.symbol.KSValueParameter import com.jamshedalamqaderi.tawraktorapi.interfaces.ClientCodeAppender import com.jamshedalamqaderi.tawraktorapi.interfaces.TawraVisitor import com.jamshedalamqaderi.tawraktorapi.utils.ext.KSValueParameterExtensions.nullOperator import com.jamshedalamqaderi.tawraktorapi.utils.ext.KSValueParameterExtensions.qualifiedType class ClientWebsocketFunParamVisitorImpl( private val logger: KSPLogger ) : TawraVisitor<ClientCodeAppender, KSValueParameter, Unit> { override fun visit(appender: ClientCodeAppender, declaration: KSValueParameter) { appender.addCode("${declaration.name?.asString()} : ${declaration.qualifiedType()}${declaration.nullOperator()},") } }
0
Kotlin
0
3
1f92acdc3c3b8c0d1f133bce2c8daec0224d9365
851
tawra-ktor-api
Apache License 2.0
src/main/kotlin/gdscript/parser/stmt/GdWhileStmtParser.kt
penguinencounter
792,086,846
false
{"Kotlin": 671320, "Java": 128067, "Lex": 24468, "PHP": 15692, "GDScript": 6273, "HTML": 4726, "Python": 3568, "Makefile": 198}
package gdscript.parser.stmt import com.intellij.psi.tree.IElementType import gdscript.parser.GdPsiBuilder import gdscript.parser.expr.GdExprParser import gdscript.psi.GdTypes.* object GdWhileStmtParser : GdStmtBaseParser { override val STMT_TYPE: IElementType = WHILE_ST override val endWithEndStmt: Boolean = false override fun parse(b: GdPsiBuilder, l: Int, optional: Boolean): Boolean { if (!b.nextTokenIs(WHILE)) return false var ok = b.consumeToken(WHILE, pin = true) ok = ok && GdExprParser.parse(b, l + 1) b.errorPin(ok, "expression") ok = ok && b.consumeToken(COLON) ok = ok && GdStmtParser.parse(b, l + 1) b.errorPin(ok, "statement") return ok } }
0
Kotlin
0
0
662c945adb0ee2cca4e1342a5f684ea3b8d18b75
746
gdscript
MIT License
app/src/main/java/com/furkanaskin/app/podpocket/service/BaseRetrofitCallback.kt
furkanaskin
183,442,441
false
null
package com.furkanaskin.app.podpocket.service import com.furkanaskin.app.podpocket.core.BaseCallBack import retrofit2.Call import retrofit2.Callback import retrofit2.Response import timber.log.Timber /** * Created by Furkan on 18.04.2019 */ abstract class BaseRetrofitCallback<T>(private val callBack: BaseCallBack<T>?) : Callback<T> { private val API_ERROR = "Api Error" override fun onResponse(call: Call<T>?, response: Response<T>?) { callBack?.let { if (response?.isSuccessful != true) { callBack.onFail(API_ERROR) Timber.e(response?.message()) return } val apiResponse = response.body() if (apiResponse == null) { callBack.onFail(API_ERROR) return } callBack.onSuccess(response.body()!!) } } override fun onFailure(call: Call<T>?, t: Throwable?) { callBack?.let { t?.let { callBack.onFail(t.message ?: API_ERROR) } Timber.e(t) } } }
3
null
18
109
9af0d1052f83cfb79824e2eaa96ade938cdefdfe
1,076
podpocket
MIT License
src/main/kotlin/zielu/gittoolbox/cache/PerRepoInfoCache.kt
koalazub
341,766,854
true
{"Java": 355922, "Kotlin": 312085, "HTML": 7800}
package zielu.gittoolbox.cache import com.intellij.openapi.project.Project import com.intellij.util.messages.Topic import git4idea.repo.GitRepository import zielu.gittoolbox.util.AppUtil.getServiceInstance internal interface PerRepoInfoCache : DirMappingAware, RepoChangeAware { fun getInfo(repository: GitRepository): RepoInfo fun getAllInfos(): List<RepoInfo> fun refreshAll() fun refresh(repositories: Iterable<GitRepository>) companion object { @JvmField val CACHE_CHANGE_TOPIC = Topic.create("Status cache change", PerRepoStatusCacheListener::class.java) @JvmStatic fun getInstance(project: Project): PerRepoInfoCache { return getServiceInstance(project, PerRepoInfoCache::class.java) } } }
0
null
0
0
c9dc7d2f7d77d5130288ae4d6ba3a9a8867314ba
741
GitToolBox
Apache License 2.0
src/main/kotlin/edu/ort/tuguia/core/user/application/Login.kt
ort-tuguia
480,584,853
false
null
package edu.ort.tuguia.core.user.application import javax.validation.constraints.NotBlank class Login(username: String, password: String) { @NotBlank(message = "El username es obligatorio") val username: String @NotBlank(message = "El password es obligatorio") val password: String init { this.username = username.lowercase() this.password = <PASSWORD> } }
0
Kotlin
0
1
52cbddaf0946b7fcab0cec642415164621148881
400
tuguia-api
MIT License
js/js.translator/testData/reservedWords/cases/enumEntryYield.kt
javaljj
52,061,310
true
{"Markdown": 32, "XML": 692, "Ant Build System": 45, "Git Attributes": 1, "Ignore List": 7, "Maven POM": 51, "Kotlin": 23506, "Java": 4612, "JavaScript": 64, "JSON": 1, "Groovy": 23, "Shell": 11, "Batchfile": 10, "Java Properties": 14, "Gradle": 75, "HTML": 184, "INI": 18, "CSS": 2, "Text": 5151, "ANTLR": 1, "Protocol Buffer": 7, "JAR Manifest": 3, "Roff": 151, "Roff Manpage": 18, "Proguard": 1, "JFlex": 2}
package foo // NOTE THIS FILE IS AUTO-GENERATED by the generateTestDataForReservedWords.kt. DO NOT EDIT! enum class Foo { `yield` } fun box(): String { testNotRenamed("yield", { Foo.`yield` }) return "OK" }
0
Java
0
1
c9cc9c55cdcc706c1d382a1539998728a2e3ca50
222
kotlin
Apache License 2.0
src/main/kotlin/dev/syoritohatsuki/yacg/YetAnotherCobblestoneGenerator.kt
syorito-hatsuki
589,090,428
false
null
package dev.syoritohatsuki.yacg import com.mojang.logging.LogUtils import dev.syoritohatsuki.yacg.registry.BlocksEntityRegistry import dev.syoritohatsuki.yacg.registry.BlocksRegistry import net.fabricmc.api.ModInitializer import net.fabricmc.fabric.api.itemgroup.v1.FabricItemGroup import net.minecraft.item.ItemGroup import net.minecraft.item.ItemStack import net.minecraft.util.Identifier import org.slf4j.Logger object YetAnotherCobblestoneGenerator : ModInitializer { const val MOD_ID = "yacg" val logger: Logger = LogUtils.getLogger() val GENERATOR_ITEM_GROUP: ItemGroup = FabricItemGroup.builder(Identifier(MOD_ID, "generator")) .icon { ItemStack(BlocksRegistry.BLOCKS.keys.first()) }.build() override fun onInitialize() { BlocksRegistry BlocksEntityRegistry } }
0
Kotlin
1
0
26c958b132f5e888912507de96982ede0d4dbfe4
818
yet-another-cobble-gen
MIT License
src/main/kotlin/io/github/facilityapi/intellij/FsdLiveTemplateContext.kt
jzbrooks
417,683,092
true
null
package io.github.facilityapi.intellij import com.intellij.codeInsight.template.TemplateActionContext import com.intellij.codeInsight.template.TemplateContextType class FsdLiveTemplateContext : TemplateContextType(FsdLanguage.id, FsdLanguage.displayName) { override fun isInContext(templateActionContext: TemplateActionContext): Boolean { return templateActionContext.file is FsdFile } }
0
Kotlin
0
0
977a16f45eea6372b97d8a89ac8846728d76f893
406
FacilityIntellij
MIT License
app/src/main/java/com/example/rappiinterview/ui/activity/main/MainContract.kt
emilioq48
178,939,302
false
null
package com.example.rappiinterview.ui.activity.main import com.example.rappiinterview.domain.model.Item interface MainContract { interface View { fun showError(errorMessage: String) fun getDefaultErrorMessage(): String fun updateItems(items: List<Item>?) fun hideProgress() fun showProgress() fun showOnMovieClickedMessage(movie: Item) fun showMovieDetail(movie: Item) fun showNoItemsFound() fun hideNoItemsFound() fun hideKeyboard() } interface Presenter { fun refreshMovies() fun onStop() fun onMovieClicked(movie: Item) fun onTopRatedMoviesButtonClicked() fun onUpcomingMoviesButtonClicked() fun onPopularMoviesButtonClicked() fun onDestroy() fun onPopularFABClicked() fun onTopRatedFABClicked() fun onUpcomingFABClicked() fun onMovieLongClicked(movie: Item) fun onSearchIconClicked(query: String) } }
0
Kotlin
0
0
0c269bad01624c6c75c5835c5540f8967bd15402
999
rappiinterview
Apache License 2.0
composeApp/src/desktopMain/kotlin/Platform.jvm.kt
BinTianqi
784,265,677
false
{"Kotlin": 42605, "HTML": 304}
import androidx.compose.material3.ColorScheme import java.awt.Toolkit import java.awt.datatransfer.StringSelection actual fun getPlatform() = "desktop" actual fun writeClipBoard(content: String) { try{ val stringSelection = StringSelection(content) val clipboard = Toolkit.getDefaultToolkit().systemClipboard clipboard.setContents(stringSelection,null) }catch(e:Exception){ println(e) } } actual fun getDynamicTheme():Pair<ColorScheme, ColorScheme>? = null
0
Kotlin
1
5
4653fe29e68fe23530017ab26d1ef55169bd71f7
504
ZWLab
The Unlicense
app/src/main/java/com/pierbezuhoff/clonium/ui/game/OrderAdapter.kt
pier-bezuhoff
196,375,991
false
null
package com.pierbezuhoff.clonium.ui.game import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.* import androidx.recyclerview.widget.RecyclerView import com.pierbezuhoff.clonium.databinding.OrderItemBinding import com.pierbezuhoff.clonium.domain.* import com.pierbezuhoff.clonium.models.ChipSet import com.pierbezuhoff.clonium.models.ColorPrism import com.pierbezuhoff.clonium.models.GameBitmapLoader import com.pierbezuhoff.clonium.models.GameModel import com.pierbezuhoff.clonium.utils.Connection import kotlin.math.roundToInt private inline fun <reified S : Any, reified T> ObservableField<S>.map( crossinline project: (S) -> T ): ObservableField<T> = object : ObservableField<T>(this) { override fun get(): T? = [email protected]()?.let(project) } data class OrderItem(val player: Player) { internal val stat = ObservableField(Game.PlayerStat(0, 0, 0.0)) val sumLevel = stat.map { if (it.sumLevel == 0) "" else "${it.sumLevel}" } val chipCount = stat.map { if (it.chipCount == 0) "" else "${it.chipCount}" } val conqueredPercent = stat.map { if (it.conquered == 0.0) "" else "${(it.conquered * 100).roundToInt()}%" } val tactic: PlayerTactic = player.tactic val alive = ObservableBoolean(true) } internal fun orderItemsOf(gameModel: GameModel): List<OrderItem> = with(gameModel.game) { order.map { OrderItem(it) } } class OrderAdapter( private var orderItems: List<OrderItem>, private val bitmapLoader: GameBitmapLoader, private val chipSet: ChipSet, private val colorPrism: ColorPrism ) : RecyclerView.Adapter<OrderAdapter.ViewHolder>() , GameModel.StatHolder , GameModel.CurrentPlayerHolder { class ViewHolder(val binding: OrderItemBinding) : RecyclerView.ViewHolder(binding.root) private var nOfAlivePlayers = orderItems.size private val uiThreadUserConnection = Connection<UiThreadHolder>() internal val uiThreadSubscription = uiThreadUserConnection.subscription override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = OrderItemBinding.inflate( LayoutInflater.from(parent.context), parent, false ) return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = orderItems[position] holder.binding.orderItem = item val minLevel = Level(chipSet.levelRange.first) // NOTE: use chip without holes if available val chipBitmap = bitmapLoader.loadChip(chipSet, colorPrism, Chip(item.player.playerId, minLevel)) holder.binding.chipView.setImageBitmap(chipBitmap) } override fun getItemCount(): Int = orderItems.size override fun updateStat(gameStat: GameStat) { val dying = mutableSetOf<Int>() for ((ix, orderItem) in orderItems.withIndex()) { val stat = gameStat.getValue(orderItem.player) orderItem.stat.set(stat) val alive = stat.chipCount > 0 orderItem.alive.set(alive) if (ix < nOfAlivePlayers && !alive) { dying += ix } } for (ix in dying) { nOfAlivePlayers -- if (ix != nOfAlivePlayers) // may be already at the right place moveOrderItem(ix, nOfAlivePlayers) } } override fun updateCurrentPlayer(player: Player) { if (orderItems.first().player != player) { moveOrderItem(0, nOfAlivePlayers - 1) } } fun setOrderItems(newOrderItems: List<OrderItem>) { orderItems = newOrderItems nOfAlivePlayers = newOrderItems.size notifyDataSetChanged() } private fun moveOrderItem(from: Int, to: Int) { val size = orderItems.size require(from in 0 until size) require(to in 0 until size) require(from != to) orderItems = when { to == size -> { val before = orderItems.subList(0, from) val between = orderItems.subList(from + 1, size) before + between + orderItems[from] } // pushing item at `to` backward from < to -> { val before = orderItems.subList(0, from) val between = orderItems.subList(from + 1, to + 1) val after = orderItems.subList(to + 1, size) before + between + orderItems[from] + after } // pushing item at `to` forward else -> { val before = orderItems.subList(0, to) val between = orderItems.subList(to, from) val after = orderItems.subList(from + 1, size) before + orderItems[from] + between + after } } uiThreadUserConnection.send { doOnUiThread { notifyItemMoved(from, minOf(size - 1, to)) } } } }
7
null
2
6
aaa5dcef4f81c0d7630af2acace7d9daa633b7b6
5,067
Clonium4Android
Apache License 2.0
src/year2022/08/Day08.kt
Vladuken
573,128,337
false
null
package year2022.`08` import readInput fun main() { fun createGrid(input: List<String>): List<List<Int>> { return input.map { it.split("") .drop(1) .dropLast(1) .map { item -> item.toInt() } } } fun <E> transpose(xs: List<List<E>>): List<List<E>> { fun <E> List<E>.head(): E = this.first() fun <E> List<E>.tail(): List<E> = this.takeLast(this.size - 1) fun <E> E.append(xs: List<E>): List<E> = listOf(this).plus(xs) xs.filter { it.isNotEmpty() }.let { ys -> return when (ys.isNotEmpty()) { true -> ys.map { it.head() }.append(transpose(ys.map { it.tail() })) else -> emptyList() } } } fun <T> genericCombine( first: List<List<T>>, second: List<List<T>>, block: (left: T, right: T) -> T ): List<List<T>> { return first.mapIndexed { i, line -> List(line.size) { j -> block(first[i][j], second[i][j]) } } } fun <T> Iterable<T>.takeUntil(predicate: (T) -> Boolean): List<T> { val list = ArrayList<T>() for (item in this) { if (!predicate(item)) { list.add(item) return list } list.add(item) } return list } fun calculateHorizontalVisibilityGrid( grid: List<List<Int>>, ): List<List<Boolean>> { return grid.mapIndexed { i, line -> List(line.size) { j -> val currentTreeSize = grid[i][j] val leftSide = grid[i].take(j) val rightSide = grid[i].drop(j + 1) val isVisibleFromLeft = leftSide.all { it < currentTreeSize } val isVisibleFromRight = rightSide.all { it < currentTreeSize } isVisibleFromLeft || isVisibleFromRight } } } fun calculateHorizontalScoreGrid( grid: List<List<Int>>, ): List<List<Int>> { return grid.mapIndexed { i, line -> List(line.size) { j -> val currentTreeSize = grid[i][j] val fromLeft = grid[i].take(j).reversed() val fromLeftTaken = fromLeft.takeUntil { it < currentTreeSize } val fromRight = grid[i].drop(j + 1) val fromRightTaken = fromRight.takeUntil { it < currentTreeSize } val leftCount = fromLeftTaken.count().takeIf { it != 0 } ?: 1 val rightCount = fromRightTaken.count().takeIf { it != 0 } ?: 1 if (fromLeft.isEmpty() || fromRight.isEmpty()) { 0 } else { leftCount * rightCount } } } } fun part1(input: List<String>): Int { val grid = createGrid(input) val vertical = transpose(calculateHorizontalVisibilityGrid(transpose(grid))) val horizontal = calculateHorizontalVisibilityGrid(grid) return genericCombine(vertical, horizontal) { left, right -> left || right } .flatten() .count { it } } fun part2(input: List<String>): Int { val grid = createGrid(input) val horizontal = calculateHorizontalScoreGrid(grid) val vertical = transpose(calculateHorizontalScoreGrid(transpose(grid))) return genericCombine(vertical, horizontal) { left, right -> left * right } .flatten() .max() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") val part1Test = part2(testInput) println(part1Test) check(part1Test == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
5
1e51ed2e6c60966692370eb9b7c7971899d1357e
3,823
KotlinAdventOfCode
Apache License 2.0
core/src/main/java/com/mecheka/core/compose/CommonNewsItem.kt
Mecheka
628,698,363
false
null
@file:OptIn(ExperimentalFoundationApi::class) package com.mecheka.core.compose import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Text import androidx.compose.runtime.Composable 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.text.style.TextOverflow import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import coil.request.ImageRequest @Composable fun CommonNewsItem( image: String, title: String, author: String, onClick: () -> Unit = {}, onLockClick: () -> Unit = {}, ) { Row( modifier = Modifier .padding(8.dp) .fillMaxWidth() .combinedClickable( onClick = onClick, onLongClick = onLockClick ) ) { AsyncImage( model = ImageRequest.Builder(LocalContext.current) .data(image) .crossfade(true) .build(), contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier .size(100.dp) .clip(RoundedCornerShape(8.dp)) ) Column( modifier = Modifier .weight(1f) .padding(start = 8.dp) ) { Text(text = author) Text( text = title, maxLines = 3, overflow = TextOverflow.Ellipsis ) } } }
0
Kotlin
0
0
90d23c97e7970b4cbd7c0f4b9653ef1684b1d700
1,977
Compose-news
Apache License 2.0
moshi-adapters/src/test/kotlin/dev/zacsweers/moshix/adapters/TrackUnknownKeysTest.kt
ZacSweers
208,339,277
false
{"Kotlin": 578398, "Java": 22715, "Shell": 880}
/* * Copyright (C) 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.zacsweers.moshix.adapters import com.google.common.truth.Truth.assertThat import com.squareup.moshi.JsonClass import com.squareup.moshi.Moshi.Builder import com.squareup.moshi.adapter import org.junit.Test class TrackUnknownKeysTest { @Test fun simpleCase() { // language=JSON val json = "{\"a\":1,\"b\":2,\"c\":3}" val tracker = RecordingKeysTracker() val moshi = Builder().add(TrackUnknownKeys.Factory(tracker = tracker)).build() val example = moshi.adapter<Letters>().fromJson(json)!! assertThat(example).isEqualTo(Letters(1, 2)) tracker.assertUnknown<Letters>("c") } @TrackUnknownKeys @JsonClass(generateAdapter = true) data class Letters(val a: Int, val b: Int) class RecordingKeysTracker : TrackUnknownKeys.UnknownKeysTracker { val recorded = mutableMapOf<Class<*>, List<String>>() override fun track(clazz: Class<*>, unknownKeys: List<String>) { recorded[clazz] = unknownKeys } inline fun <reified T> assertUnknown(vararg expected: String) { val clazz = T::class.java val keys = recorded[clazz] ?: error("No keys found for $clazz") assertThat(keys).containsExactly(*expected).inOrder() } } }
9
Kotlin
37
516
591928671e6149a429490b441c2c25b4785d1922
1,799
MoshiX
Apache License 2.0
common/src/main/java/com/test/common/api/AuthInterceptor.kt
nexy791
702,228,674
false
{"Kotlin": 52056}
package com.test.common.api import okhttp3.Interceptor import okhttp3.Response class AuthInterceptor( private val apiKey: String, ) : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { var req = chain.request() val url = req.url.newBuilder().addQueryParameter(QUERY_KEY, apiKey).build() req = req.newBuilder().url(url).build() return chain.proceed(req) } companion object { private const val QUERY_KEY = "api_key" } }
0
Kotlin
0
0
5bc8fd683fe3b22344b87a99959313a0405f3301
504
DrumNCode
Apache License 2.0
app/src/main/java/com/example/mychimney/EditVPNActivity.kt
Evan2698
231,755,278
false
{"Kotlin": 30911}
package com.example.mychimney import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.example.mychimney.datacore.VPNOpDao import com.example.mychimney.datacore.VPNProfile import com.google.android.material.snackbar.Snackbar import kotlinx.android.synthetic.main.activity_edit_vpn.* import kotlinx.android.synthetic.main.content_edit_vpn.* import java.util.regex.Pattern class EditVPNActivity : AppCompatActivity() { var isNew : Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_edit_vpn) //setSupportActionBar(toolSaveBar) isNew = this.intent!!.getBooleanExtra("new", true) var vpn : VPNProfile? = null if (isNew) { remotedns.setText("1.1.1.1") this.passwd.setText("<PASSWORD>#@!#\$@!123") } else { var position = this.intent.getIntExtra("data", -1) var dao = VPNOpDao() var list = dao.query() if (position != -1 && list.count() > position) { vpn = list[position] this.vpnname.setText(vpn.name) this.servername.setText(vpn.server) this.remoteport.setText(vpn.remoteport.toString()) this.passwd.setText(vpn.password) this.remotedns.setText(vpn.remoteDNS) } } saveVPN.setOnClickListener { view -> if (!checkBlankValue()){ Snackbar.make(view, "please fill every item", Snackbar.LENGTH_LONG) .setAction(getString(R.string.app_name), null).show() return@setOnClickListener } if (!checkPortValue()){ Snackbar.make(view, "the port value is 1-65535.", Snackbar.LENGTH_LONG) .setAction(getString(R.string.app_name), null).show() return@setOnClickListener } if (!checkIPAddress()) { Snackbar.make(view, "please check ip address or URL", Snackbar.LENGTH_LONG) .setAction(getString(R.string.app_name), null).show() return@setOnClickListener } saveToDB(vpn) NotifyCenter.instance.nofityUI() Toast.makeText(this.applicationContext, "save success!", Toast.LENGTH_LONG).show() finish() } } fun saveToDB(v: VPNProfile?) { var vpn = VPNProfile() vpn.name = this.vpnname.text.toString().trim() vpn.server = this.servername.text.toString().trim() vpn.remoteport = this.remoteport.text.toString().toInt() vpn.remoteDNS = this.remotedns.text.toString().trim() vpn.password = this.passwd.text.toString().trim() var dao = VPNOpDao() if (this.isNew) { dao.addVPN(vpn) } else { vpn.id_ = v!!.id_ dao.updateVPN(vpn) } } fun checkIPAddress() :Boolean { var patten = Pattern.compile( "^((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}\$") var name = this.servername.text.toString() var dns = this.remotedns.text.toString() if ((name.startsWith("http") || patten.matcher(name).matches()) && (dns.startsWith("http") || patten.matcher(dns).matches() )){ return true } return false } fun checkPortValue() : Boolean { var port = this.remoteport.text.toString().toInt() if (port < 1) { return false } return true } fun checkBlankValue() : Boolean { var vpn = this.servername.text var port = this.remoteport.text var pass = this.passwd.text var dns = this.remotedns.text if (vpn.isBlank()|| this.vpnname.text.isBlank()|| port.isBlank()|| pass.isBlank() || dns.isBlank()){ return false } return true } }
0
Kotlin
0
0
82ff90faca2422730ed5b65dc78f4d9487791f04
4,113
MyChimney
MIT License
components/ledger/ledger-utxo-flow/src/test/kotlin/net/corda/ledger/utxo/flow/impl/transaction/serializer/amqp/UtxoFilteredTransactionSerializerTest.kt
corda
346,070,752
false
{"Kotlin": 20585393, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244}
package net.corda.ledger.utxo.flow.impl.transaction.serializer.amqp import net.corda.internal.serialization.amqp.helper.TestSerializationService import net.corda.ledger.common.flow.impl.transaction.filtered.serializer.amqp.FilteredTransactionSerializer import net.corda.ledger.utxo.flow.impl.transaction.filtered.UtxoFilteredTransactionImpl import net.corda.ledger.utxo.flow.impl.transaction.filtered.UtxoFilteredTransactionTestBase import net.corda.ledger.utxo.test.UtxoLedgerTest import net.corda.utilities.serialization.deserialize import net.corda.v5.ledger.utxo.transaction.filtered.UtxoFilteredTransaction import org.assertj.core.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test class UtxoFilteredTransactionSerializerTest : UtxoLedgerTest() { private val testBase = UtxoFilteredTransactionTestBase() private val serializationService = TestSerializationService.getTestSerializationService({ it.register(wireTransactionAMQPSerializer, it) it.register(FilteredTransactionSerializer(jsonMarshallingService, merkleTreeProvider), it) it.register(UtxoFilteredTransactionSerializer(serializationServiceNullCfg), it) }, cipherSchemeMetadata) @BeforeEach fun beforeEach() { testBase.beforeEach() } @Test fun `should serialize and then deserialize a utxo filtered transaction`() { val utxoFilteredTransaction: UtxoFilteredTransaction = UtxoFilteredTransactionImpl(testBase.serializationService, testBase.filteredTransaction) val bytes = serializationService.serialize(utxoFilteredTransaction) val deserialized = serializationService.deserialize(bytes) Assertions.assertThat(deserialized.id).isEqualTo(utxoFilteredTransaction.id) } }
96
Kotlin
7
69
0766222eb6284c01ba321633e12b70f1a93ca04e
1,786
corda-runtime-os
Apache License 2.0
presentation/src/main/java/me/androidbox/presentation/authentication/reset/ResetScreen.kt
steve1rm
804,664,997
false
{"Kotlin": 77121}
@file:OptIn(ExperimentalFoundationApi::class) package me.androidbox.presentation.authentication.reset import android.content.res.Configuration import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.vectorResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import me.androidbox.presentation.R import me.androidbox.presentation.components.ActionButton import me.androidbox.presentation.components.EmailTextField import me.androidbox.presentation.components.GradientBackground import me.androidbox.presentation.ui.theme.BusbyNimbleSurveyTheme @OptIn(ExperimentalMaterial3Api::class) @Composable fun ResetPasswordScreen( resetPasswordState: ResetPasswordState, modifier: Modifier = Modifier, onResetPasswordAction: (ResetPasswordAction) -> Unit, onBackPressed: () -> Unit, onResetPasswordSuccess: (message: String) -> Unit ) { LaunchedEffect(key1 = resetPasswordState.isResetPasswordSuccess) { if(resetPasswordState.isResetPasswordSuccess && resetPasswordState.message.isNotBlank()) { onResetPasswordSuccess(resetPasswordState.message) } } Scaffold( modifier = modifier, topBar = { TopAppBar( title = {}, navigationIcon = { Icon( modifier = Modifier.clickable { onBackPressed() }, imageVector = Icons.AutoMirrored.Default.ArrowBack, contentDescription = "Go Back" ) } ) } ) { paddingValues -> Column( modifier = Modifier .padding(paddingValues) .padding(horizontal = 16.dp), verticalArrangement = Arrangement.Center ) { Spacer(modifier = Modifier.height(32.dp)) Image( modifier = Modifier.fillMaxWidth(), imageVector = ImageVector.vectorResource(id = R.drawable.nimblelogo), contentDescription = null ) Spacer(modifier = Modifier.height(32.dp)) Text(text = "Enter your email for instructions for resetting your password") Spacer(modifier = Modifier.height(32.dp)) EmailTextField( state = resetPasswordState.email, hint = stringResource(R.string.email) ) Spacer(modifier = Modifier.height(16.dp)) ActionButton( label = stringResource(R.string.reset), onButtonClicked = { onResetPasswordAction(ResetPasswordAction.OnPasswordResetClicked) }) } } } @Composable @Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL) fun PreviewResetScreen() { BusbyNimbleSurveyTheme { GradientBackground { ResetPasswordScreen( resetPasswordState = ResetPasswordState(), onResetPasswordAction = {}, onBackPressed = {}, onResetPasswordSuccess = { } ) } } }
0
Kotlin
0
0
deb94aa1e9b96538ea5aeb321316edf54cb58ac0
4,243
BusbyNimbleSurvey
MIT License