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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sample/hilt-di/src/main/java/com/plusmobileapps/savedstateflowhilt/MyApplication.kt | plusmobileapps | 441,450,960 | false | null | package com.plusmobileapps.savedstateflowhilt
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class MyApplication : Application() | 0 | Kotlin | 0 | 13 | 5b9d4522d6f3aef6b2fb24042e05621a46b0edd9 | 172 | SavedStateFlow | MIT License |
client/app/src/main/java/com/hao/heji/data/db/BookUSerDao.kt | RUANHAOANDROID | 324,589,079 | false | null | package com.rh.heji.data.db
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
/**
*
* @date 2023/4/25
* @author 锅得铁
* @since v1.0
*/
@Dao
interface BookUSerDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(bookUser: BookUser)
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun upsert(category: Category)
@Query("select count(0) from book_user")
fun count(): Int
} | 0 | null | 11 | 36 | c5491871ebbe68bca3684d1a7db3f1f78c870d68 | 484 | heji | Apache License 2.0 |
libraries/stdlib/src/kotlin/coroutines/CoroutinesH.kt | JetBrains | 3,432,266 | false | null | /*
* 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
@PublishedApi
@SinceKotlin("1.3")
internal expect class SafeContinuation<in T> : Continuation<T> {
internal constructor(delegate: Continuation<T>, initialResult: Any?)
@PublishedApi
internal constructor(delegate: Continuation<T>)
@PublishedApi
internal fun getOrThrow(): Any?
override val context: CoroutineContext
override fun resumeWith(result: SuccessOrFailure<T>): Unit
}
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 598 | kotlin | Apache License 2.0 |
src/jsMain/kotlin/Head.kt | CodeWithDino | 514,549,450 | false | null | import androidx.compose.runtime.Composable
import kotlinx.browser.document
import org.jetbrains.compose.web.css.Style
import org.jetbrains.compose.web.dom.TagElement
import org.jetbrains.compose.web.dom.Text
import org.w3c.dom.HTMLLinkElement
import org.w3c.dom.HTMLScriptElement
@Composable
fun Head() {
Style(AppStyle)
Link(href = "https://fonts.googleapis.com/css2?family=Open+Sans:wght@100;300;400;500;700&display=swap", rel = "stylesheet")
Link(href = "https://dev-cats.github.io/code-snippets/JetBrainsMono.css", rel = "stylesheet")
Script(src = "https://kit.fontawesome.com/74fed0e2b5.js", crossOrigin = CrossOrigin.ANONYMOUS)
Script(src = "https://www.googletagmanager.com/gtag/js?id=GTM-TLKF992", mode = ScriptMode.ASYNC)
Script(
content = "function gtag(){dataLayer.push(arguments)}window.dataLayer=window.dataLayer||[],gtag('js',new Date),gtag('config','GTM-TLKF992')"
)
}
@Composable
fun Link(href: String, rel: String = "", type: String = "") {
TagElement<HTMLLinkElement>("link", {
attr("href", href)
if (rel.isNotEmpty()) attr("rel", rel)
if (type.isNotEmpty()) attr("type", type)
}) {}
}
enum class ScriptMode(val value: String) {
DEFAULT(""),
ASYNC("async"),
DEFER("defer")
}
enum class CrossOrigin(val value: String) {
NONE(""),
ANONYMOUS("anonymous"),
USE_CREDENTIALS("use-credentials")
}
@Composable
fun Script(src: String, crossOrigin: CrossOrigin = CrossOrigin.NONE, mode: ScriptMode = ScriptMode.DEFAULT) {
TagElement<HTMLScriptElement>("script", {
attr("src", src)
if (crossOrigin.value.isNotEmpty()) attr("crossorigin", crossOrigin.value)
if (mode.value.isNotEmpty())
when (mode) {
ScriptMode.ASYNC -> attr("async", "")
ScriptMode.DEFER -> attr("defer", "")
else -> Unit
}
}) {}
}
@Composable
fun Script(content: String) {
TagElement<HTMLScriptElement>("script", null) {
Text(content)
}
}
fun setTitle(title: String) {
document.querySelector("title")?.textContent = title
} | 3 | Kotlin | 0 | 2 | dd0099373bc2b1d44bef250654391dfdd6354948 | 1,959 | CodeWithDino | MIT License |
chaos/src/main/java/io/rhprincess/chaos/main/widgets/View.kt | rhprincess | 248,666,926 | false | null | @file:Suppress("unused")
package io.rhprincess.chaos.main.widgets
import android.view.View
import android.view.ViewManager
import android.webkit.WebView
import android.widget.*
import androidx.annotation.LayoutRes
import androidx.annotation.StyleRes
import io.rhprincess.chaos.annotations.LazyInject
import io.rhprincess.chaos.main.ChaosManager
import io.rhprincess.chaos.main.internalContext
/**
*
* TODO: For ViewManager
*
*/
// TODO: Button
/**
* Another simple usage for button
* button("Simple Button")
*/
@LazyInject("android.widget")
fun ViewManager.button(
text: CharSequence = "",
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: Button.() -> Unit = { this.text = text }
): Button {
return ChaosManager.link(internalContext, theme, styledLayout, init) {
Button(it)
}.into(this)
}
// TODO: CheckBox
@LazyInject("android.widget")
fun ViewManager.checkBox(
text: CharSequence = "",
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: CheckBox.() -> Unit = { this.text = text }
): CheckBox {
return ChaosManager.link(internalContext, theme, styledLayout, init) {
CheckBox(it)
}.into(this)
}
// TODO: EditText
@LazyInject("android.widget")
fun ViewManager.editText(
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: EditText.() -> Unit = {}
): EditText {
return ChaosManager.link(internalContext, theme, styledLayout, init) {
EditText(it)
}.into(this)
}
// TODO: TextView
@LazyInject("android.widget")
fun ViewManager.textView(
text: CharSequence = "",
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: TextView.() -> Unit = { this.text = text }
): TextView {
return ChaosManager.link(internalContext, theme, styledLayout, init) { TextView(it) }
.into(this)
}
// TODO: Switch
@LazyInject("android.widget")
fun ViewManager.switch(
text: CharSequence = "",
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: Switch.() -> Unit = { this.text = text }
): Switch {
return ChaosManager.link(internalContext, theme, styledLayout, init) { Switch(it) }.into(this)
}
// TODO: ImageButton
@LazyInject("android.widget")
fun ViewManager.imageButton(
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: ImageButton.() -> Unit = {}
): ImageButton {
return ChaosManager.link(internalContext, theme, styledLayout, init) {
ImageButton(it)
}.into(this)
}
// TODO: RadioGroup
@LazyInject("android.widget")
fun ViewManager.radioGroup(
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: RadioGroup.() -> Unit = {}
): RadioGroup {
return ChaosManager.link(internalContext, theme, styledLayout, init) {
RadioGroup(it)
}.into(this)
}
// TODO: RadioButton
@LazyInject("android.widget")
fun ViewManager.radioButton(
text: CharSequence = "",
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: RadioButton.() -> Unit = { this.text = text }
): RadioButton {
return ChaosManager.link(internalContext, theme, styledLayout, init) { RadioButton(it) }
.into(this)
}
// TODO: ToggleButton
@LazyInject("android.widget")
fun ViewManager.toggleButton(
text: CharSequence = "",
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: ToggleButton.() -> Unit = { this.text = text }
): ToggleButton {
return ChaosManager.link(internalContext, theme, styledLayout, init) { ToggleButton(it) }
.into(this)
}
// TODO: View
@LazyInject("android.view")
fun ViewManager.view(
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: View.() -> Unit = {}
): View {
return ChaosManager.link(internalContext, theme, styledLayout, init) { View(it) }.into(this)
}
// TODO: ImageView
@LazyInject("android.widget")
fun ViewManager.imageView(
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: ImageView.() -> Unit = {}
): ImageView {
return ChaosManager.link(internalContext, theme, styledLayout, init) { ImageView(it) }
.into(this)
}
// TODO: WebView
@LazyInject("android.webkit")
fun ViewManager.webView(
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: WebView.() -> Unit = {}
): WebView {
return ChaosManager.link(internalContext, theme, styledLayout, init) { WebView(it) }
.into(this)
}
// TODO: VideoView
@LazyInject("android.widget")
fun ViewManager.videoView(
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: VideoView.() -> Unit = {}
): VideoView {
return ChaosManager.link(internalContext, theme, styledLayout, init) { VideoView(it) }
.into(this)
}
// TODO: CalendarView
@LazyInject("android.widget")
fun ViewManager.calendarView(
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: CalendarView.() -> Unit = {}
): CalendarView {
return ChaosManager.link(internalContext, theme, styledLayout, init) { CalendarView(it) }
.into(this)
}
// TODO: ProgressBar
@LazyInject("android.widget")
fun ViewManager.progressBar(
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: ProgressBar.() -> Unit = {}
): ProgressBar {
return ChaosManager.link(internalContext, theme, styledLayout, init) { ProgressBar(it) }
.into(this)
}
// TODO: SeekBar
@LazyInject("android.widget")
fun ViewManager.seekBar(
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: SeekBar.() -> Unit = {}
): SeekBar {
return ChaosManager.link(internalContext, theme, styledLayout, init) { SeekBar(it) }
.into(this)
}
// TODO: RatingBar
@LazyInject("android.widget")
fun ViewManager.ratingBar(
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: RatingBar.() -> Unit = {}
): RatingBar {
return ChaosManager.link(internalContext, theme, styledLayout, init) { RatingBar(it) }
.into(this)
}
// TODO: SearchView
@LazyInject("android.widget")
fun ViewManager.searchView(
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: SearchView.() -> Unit = {}
): SearchView {
return ChaosManager.link(internalContext, theme, styledLayout, init) { SearchView(it) }
.into(this)
}
// TODO: Spinner
@LazyInject("android.widget")
fun ViewManager.spinner(
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: Spinner.() -> Unit = {}
): Spinner {
return ChaosManager.link(internalContext, theme, styledLayout, init) { Spinner(it) }
.into(this)
}
// TODO: ScrollView
@LazyInject("android.widget")
fun ViewManager.scrollView(
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: ScrollView.() -> Unit = {}
): ScrollView {
return ChaosManager.link(internalContext, theme, styledLayout, init) { ScrollView(it) }
.into(this)
}
// TODO: HorizontalScrollView
@LazyInject("android.widget")
fun ViewManager.horizontalScrollView(
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: HorizontalScrollView.() -> Unit = {}
): HorizontalScrollView {
return ChaosManager.link(
internalContext,
theme,
styledLayout,
init
) { HorizontalScrollView(it) }.into(this)
}
// TODO: Toolbar
@LazyInject("android.widget")
fun ViewManager.toolbar(
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: Toolbar.() -> Unit = {}
): Toolbar {
return ChaosManager.link(internalContext, theme, styledLayout, init) { Toolbar(it) }
.into(this)
}
// TODO: ListView
@LazyInject("android.widget")
fun ViewManager.listView(
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: ListView.() -> Unit = {}
): ListView {
return ChaosManager.link(internalContext, theme, styledLayout, init) { ListView(it) }
.into(this)
}
// TODO: GridView
@LazyInject("android.widget")
fun ViewManager.gridView(
@StyleRes theme: Int = 0,
@LayoutRes styledLayout: Int = 0,
init: GridView.() -> Unit = {}
): GridView {
return ChaosManager.link(internalContext, theme, styledLayout, init) { GridView(it) }
.into(this)
} | 0 | Kotlin | 0 | 1 | 55fc82e6587947c80186e3d08d2773d497a39260 | 8,254 | chaos | Apache License 2.0 |
livingdoc-results/src/test/kotlin/org/livingdoc/results/examples/decisiontables/DecisionTableResultBuilderTest.kt | LivingDoc | 85,412,044 | false | null | package org.livingdoc.results.examples.decisiontables
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.livingdoc.repositories.model.decisiontable.DecisionTable
import org.livingdoc.repositories.model.decisiontable.Field
import org.livingdoc.repositories.model.decisiontable.Header
import org.livingdoc.repositories.model.decisiontable.Row
import org.livingdoc.results.Status
import org.livingdoc.results.examples.scenarios.ScenarioResultBuilderTest
internal class DecisionTableResultBuilderTest {
private val fixtureClass: Class<*> = ScenarioResultBuilderTest.FixtureClass::class.java
private val h1 = Header("header1")
private val h2 = Header("header2")
private val row1: Row = Row(mapOf(h1 to Field("a"), h2 to Field("b")))
private val row2: Row = Row(mapOf(h1 to Field("c"), h2 to Field("d")))
private val emptyDecisionTable = DecisionTable(emptyList(), emptyList())
private val decisionTable = DecisionTable(listOf(h1, h2), listOf(row1, row2))
private val rowResult1 = RowResult.Builder()
.withRow(row1)
.withFieldResult(
h1, FieldResult.Builder()
.withValue("a")
.withStatus(Status.Executed)
.build()
)
.withFieldResult(
h2, FieldResult.Builder()
.withValue("b")
.withStatus(Status.Executed)
.build()
)
.withStatus(Status.Executed)
.build()
private val rowResult2 = RowResult.Builder()
.withRow(row2)
.withFieldResult(
h1, FieldResult.Builder()
.withValue("c")
.withStatus(Status.Executed)
.build()
)
.withFieldResult(
h2, FieldResult.Builder()
.withValue("d")
.withStatus(Status.Executed)
.build()
)
.withStatus(Status.Executed)
.build()
@Test
fun `test decision table with no rows`() {
val result = DecisionTableResult.Builder()
.withDecisionTable(emptyDecisionTable)
.withFixtureSource(fixtureClass)
.withStatus(Status.Executed)
.build()
assertThat(result.decisionTable).isEqualTo(emptyDecisionTable)
assertThat(result.fixtureSource).isEqualTo(fixtureClass)
assertThat(result.status).isEqualTo(Status.Executed)
assertThat(result.headers).hasSize(0)
assertThat(result.rows).hasSize(0)
}
@Test
fun `test decision table with rows`() {
val result = DecisionTableResult.Builder()
.withDecisionTable(decisionTable)
.withRow(rowResult1)
.withRow(rowResult2)
.withFixtureSource(fixtureClass)
.withStatus(Status.Executed)
.build()
assertThat(result.decisionTable).isEqualTo(decisionTable)
assertThat(result.headers).hasSize(2)
assertThat(result.rows).hasSize(2)
assertThat(result.rows[0]).isEqualTo(rowResult1)
assertThat(result.rows[1]).isEqualTo(rowResult2)
}
@Test
fun `test decision table result with missing row result`() {
val builder = DecisionTableResult.Builder()
.withDecisionTable(decisionTable)
.withRow(rowResult1)
.withFixtureSource(fixtureClass)
.withStatus(Status.Executed)
assertThrows<IllegalStateException> {
builder.build()
}
}
@Test
fun `test decision table result with too many row results`() {
val row3 = Row(mapOf(h1 to Field("e"), h2 to Field("f")))
val rowResult3 = RowResult.Builder()
.withRow(row3)
.withFieldResult(
h1, FieldResult.Builder()
.withValue("e")
.withStatus(Status.Executed)
.build()
)
.withFieldResult(
h2, FieldResult.Builder()
.withValue("f")
.withStatus(Status.Executed)
.build()
)
.withStatus(Status.Executed)
.build()
val builder = DecisionTableResult.Builder()
.withDecisionTable(decisionTable)
.withRow(rowResult1)
.withRow(rowResult2)
.withRow(rowResult3)
.withFixtureSource(fixtureClass)
.withStatus(Status.Executed)
assertThrows<IllegalStateException> {
builder.build()
}
}
@Test
fun `test decision table result with wrong row result`() {
val row3 = Row(mapOf(h1 to Field("e"), h2 to Field("f")))
val rowResult3 = RowResult.Builder()
.withRow(row3)
.withFieldResult(
h1, FieldResult.Builder()
.withValue("e")
.withStatus(Status.Executed)
.build()
)
.withFieldResult(
h2, FieldResult.Builder()
.withValue("f")
.withStatus(Status.Executed)
.build()
)
.withStatus(Status.Executed)
.build()
val builder = DecisionTableResult.Builder()
.withDecisionTable(decisionTable)
.withRow(rowResult1)
.withRow(rowResult3)
.withFixtureSource(fixtureClass)
.withStatus(Status.Executed)
assertThrows<IllegalStateException> {
builder.build()
}
}
@Test
fun `test decision table result with missing status`() {
val builder = DecisionTableResult.Builder()
.withDecisionTable(emptyDecisionTable)
.withFixtureSource(fixtureClass)
assertThrows<IllegalStateException> {
builder.build()
}
}
@Test
fun `test decision table result with missing decision table`() {
val builder = DecisionTableResult.Builder()
.withFixtureSource(fixtureClass)
.withStatus(Status.Executed)
assertThrows<IllegalStateException> {
builder.build()
}
}
@Test
fun `test decision table result with missing fixture`() {
val result = DecisionTableResult.Builder()
.withDecisionTable(emptyDecisionTable)
.withStatus(Status.Executed)
.build()
assertThat(result.fixtureSource).isNull()
}
@Test
fun `test finalized builder`() {
val builder = DecisionTableResult.Builder()
.withDecisionTable(decisionTable)
.withRow(rowResult1)
.withRow(rowResult2)
.withFixtureSource(fixtureClass)
.withStatus(Status.Executed)
builder.build()
assertThrows<IllegalStateException> {
builder.withStatus(Status.Manual)
}
assertThrows<IllegalStateException> {
builder.withRow(rowResult1)
}
assertThrows<IllegalStateException> {
builder.withDecisionTable(decisionTable)
}
assertThrows<IllegalStateException> {
builder.withFixtureSource(fixtureClass)
}
}
@Test
fun `test with unassigned skipped`() {
val result = DecisionTableResult.Builder()
.withDecisionTable(decisionTable)
.withRow(rowResult1)
.withUnassignedRowsSkipped()
.withFixtureSource(fixtureClass)
.withStatus(Status.Executed)
.build()
assertThat(result.rows).hasSize(2)
assertThat(result.rows[0]).isEqualTo(rowResult1)
assertThat(result.rows[1].status).isEqualTo(Status.Skipped)
}
@Test
fun `test auto generate row results for manual test`() {
val result = DecisionTableResult.Builder()
.withDecisionTable(decisionTable)
.withFixtureSource(fixtureClass)
.withStatus(Status.Manual)
.build()
assertThat(result.status).isEqualTo(Status.Manual)
assertThat(result.rows).hasSize(2)
assertThat(result.rows[0].status).isEqualTo(Status.Manual)
assertThat(result.rows[1].status).isEqualTo(Status.Manual)
}
class FixtureClass
}
| 34 | Kotlin | 16 | 14 | f3d52b8bacbdf81905e4b4a753d75f584329b297 | 8,353 | livingdoc | Apache License 2.0 |
src/test/kotlin/com/developerphil/adbidea/compatibility/BackwardCompatibleGetterTest.kt | longforus | 146,382,514 | true | {"Markdown": 4, "Gradle": 1, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 1, "INI": 1, "Kotlin": 97, "XML": 6, "Java": 4} | package com.darshan.ezylogin.compatibility
import com.google.common.truth.Truth.assertThat
import org.joor.ReflectException
import org.junit.Assert.fail
import org.junit.Test
class BackwardCompatibleGetterTest {
@Test
fun onlyCallCurrentImplementationWhenItIsValid() {
var value = false
object : BackwardCompatibleGetter<Boolean>() {
override fun getCurrentImplementation(): Boolean {
value = true
return true
}
override fun getPreviousImplementation(): Boolean {
fail("should not be called")
return true
}
}.get()
assertThat(value).isTrue()
}
@Test
fun callPreviousImplementationWhenCurrentThrowsErrors() {
expectPreviousImplementationIsCalledFor(ClassNotFoundException())
expectPreviousImplementationIsCalledFor(NoSuchMethodException())
expectPreviousImplementationIsCalledFor(NoSuchFieldException())
expectPreviousImplementationIsCalledFor(LinkageError())
expectPreviousImplementationIsCalledFor(ReflectException())
}
@Test(expected = RuntimeException::class)
fun throwExceptionsWhenTheyAreNotRelatedToBackwardCompatibility() {
object : BackwardCompatibleGetter<Boolean>() {
override fun getCurrentImplementation(): Boolean {
throw RuntimeException("exception!")
}
override fun getPreviousImplementation(): Boolean {
fail("should not be called")
return false
}
}.get()
}
private fun expectPreviousImplementationIsCalledFor(throwable: Throwable) {
var value = false
object : BackwardCompatibleGetter<Boolean>() {
override fun getCurrentImplementation(): Boolean {
throw throwable
}
override fun getPreviousImplementation(): Boolean {
value = true
return true
}
}.get()
assertThat(value).isTrue()
}
} | 2 | Kotlin | 3 | 31 | 8e3c405ca80b9d341b419d65693d4c4d4e0c546e | 2,078 | adb-idea-plus | Apache License 2.0 |
shared/src/test/kotlin/com/egm/stellio/shared/util/ApiUtilsTests.kt | stellio-hub | 257,818,724 | false | null | package com.egm.stellio.shared.util
import com.egm.stellio.shared.model.BadRequestDataException
import com.egm.stellio.shared.util.JsonLdUtils.NGSILD_CORE_CONTEXT
import com.egm.stellio.shared.util.OptionsParamValue.TEMPORAL_VALUES
import com.egm.stellio.shared.web.CustomWebFilter
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.fail
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.web.reactive.server.WebTestClient
import java.util.Optional
@OptIn(ExperimentalCoroutinesApi::class)
@ActiveProfiles("test")
class ApiUtilsTests {
private val webClient = WebTestClient.bindToController(MockkedHandler()).webFilter<WebTestClient.ControllerSpec>(
CustomWebFilter()
).build()
@Test
fun `it should not find a value if there is no options query param`() {
assertFalse(hasValueInOptionsParam(Optional.empty(), TEMPORAL_VALUES))
}
@Test
fun `it should not find a value if it is not in a single value options query param`() {
assertFalse(hasValueInOptionsParam(Optional.of("one"), TEMPORAL_VALUES))
}
@Test
fun `it should not find a value if it is not in a multi value options query param`() {
assertFalse(hasValueInOptionsParam(Optional.of("one,two"), TEMPORAL_VALUES))
}
@Test
fun `it should find a value if it is in a single value options query param`() {
assertTrue(hasValueInOptionsParam(Optional.of("temporalValues"), TEMPORAL_VALUES))
}
@Test
fun `it should find a value if it is in a multi value options query param`() {
assertTrue(hasValueInOptionsParam(Optional.of("one,temporalValues"), TEMPORAL_VALUES))
}
@Test
fun `it should return an empty list if no attrs param is provided`() {
assertTrue(parseAndExpandRequestParameter(null, "").isEmpty())
}
@Test
fun `it should return an singleton list if there is one provided attrs param`() {
assertEquals(1, parseAndExpandRequestParameter("attr1", NGSILD_CORE_CONTEXT).size)
}
@Test
fun `it should return a list with two elements if there are two provided attrs param`() {
assertEquals(2, parseAndExpandRequestParameter("attr1, attr2", NGSILD_CORE_CONTEXT).size)
}
@Test
fun `it should return 411 if Content-Length is null`() {
webClient.post()
.uri("/router/mockkedroute")
.header(HttpHeaders.CONTENT_TYPE, "application/json")
.exchange()
.expectStatus().isEqualTo(HttpStatus.LENGTH_REQUIRED)
.expectBody().isEmpty
}
@Test
fun `it should support Mime-type with parameters`() {
webClient.post()
.uri("/router/mockkedroute")
.header(HttpHeaders.CONTENT_TYPE, "application/ld+json;charset=UTF-8")
.bodyValue("Some body")
.exchange()
.expectStatus().isCreated
}
@Test
fun `it should extract a @context from a valid Link header`() = runTest {
getContextFromLinkHeader(listOf(buildContextLinkHeader(APIC_COMPOUND_CONTEXT))).shouldSucceedWith {
assertNotNull(it)
assertEquals(APIC_COMPOUND_CONTEXT, it)
}
}
@Test
fun `it should return a null @context if no Link header was provided`() = runTest {
getContextFromLinkHeader(emptyList()).shouldSucceedWith {
assertNull(it)
}
}
@Test
fun `it should return a BadRequestData error if @context provided in Link header is invalid`() = runTest {
getContextFromLinkHeader(listOf(APIC_COMPOUND_CONTEXT)).shouldFail {
assertInstanceOf(BadRequestDataException::class.java, it)
assertEquals(
"Badly formed Link header: $APIC_COMPOUND_CONTEXT",
it.message
)
}
}
@Test
fun `it should return the default @context if no Link header was provided and default is asked`() = runTest {
val httpHeaders = HttpHeaders()
getContextFromLinkHeaderOrDefault(httpHeaders).shouldSucceedWith {
assertEquals(NGSILD_CORE_CONTEXT, it)
}
}
@Test
fun `it should get a single @context from a JSON-LD input`() = runTest {
val httpHeaders = HttpHeaders().apply {
set("Content-Type", "application/ld+json")
}
val jsonLdInput = mapOf(
"id" to "urn:ngsi-ld:Building:farm001",
"type" to "Building",
"@context" to "https://fiware.github.io/data-models/context.jsonld"
)
checkAndGetContext(httpHeaders, jsonLdInput).shouldSucceedWith {
assertEquals(1, it.size)
assertEquals("https://fiware.github.io/data-models/context.jsonld", it[0])
}
}
@Test
fun `it should get a list of @context from a JSON-LD input`() = runTest {
val httpHeaders = HttpHeaders().apply {
set("Content-Type", "application/ld+json")
}
val jsonLdInput = mapOf(
"id" to "urn:ngsi-ld:Building:farm001",
"type" to "Building",
"@context" to listOf(
"https://fiware.github.io/data-models/context.jsonld",
"https://uri.etsi.org/ngsi-ld/v1/ngsi-ld-core-context-v1.7.jsonld"
)
)
checkAndGetContext(httpHeaders, jsonLdInput).shouldSucceedWith {
assertEquals(2, it.size)
assertTrue(
it.containsAll(
listOf(
"https://fiware.github.io/data-models/context.jsonld",
"https://uri.etsi.org/ngsi-ld/v1/ngsi-ld-core-context-v1.7.jsonld"
)
)
)
}
}
@Test
fun `it should throw an exception if a JSON-LD input has no @context`() = runTest {
val httpHeaders = HttpHeaders().apply {
set("Content-Type", "application/ld+json")
}
val jsonLdInput = mapOf(
"id" to "urn:ngsi-ld:Building:farm001",
"type" to "Building"
)
checkAndGetContext(httpHeaders, jsonLdInput).shouldFail {
assertInstanceOf(BadRequestDataException::class.java, it)
assertEquals(
"Request payload must contain @context term for a request having an application/ld+json content type",
it.message
)
}
}
@Test
fun `it should parse and expand entity type selection query`() {
val query = "(TypeA|TypeB);(TypeC,TypeD)"
val defaultExpand = "https://uri.etsi.org/ngsi-ld/default-context/"
val expandedQuery = parseAndExpandTypeSelection(query, NGSILD_CORE_CONTEXT)
val expectedExpandTypeSelection =
"(${defaultExpand}TypeA|${defaultExpand}TypeB);(${defaultExpand}TypeC,${defaultExpand}TypeD)"
assertEquals(expectedExpandTypeSelection, expandedQuery)
}
@Test
fun `it should parse a conform datetime parameter`() {
val parseResult = "2023-10-16T16:18:00Z".parseTimeParameter("Invalid date time")
parseResult.onLeft {
fail("it should have parsed the date time")
}
}
@Test
fun `it should return an error if datetime parameter is not conform`() {
val parseResult = "16/10/2023".parseTimeParameter("Invalid date time")
parseResult.fold(
{ assertEquals("Invalid date time", it) }
) {
fail("it should not have parsed the date time")
}
}
@Test
fun `it should validate a correct idPattern`() {
val validationResult = validateIdPattern("urn:ngsi-ld:Entity:*")
validationResult.onLeft {
fail("it should have parsed the date time")
}
}
@Test
fun `it should not validate an incorrect idPattern`() {
val validationResult = validateIdPattern("(?x)urn:ngsi-ld:Entity:{*}2")
validationResult.fold(
{ assertTrue(it.message.startsWith("Invalid value for idPattern: (?x)urn:ngsi-ld:Entity:{*}2")) },
{ fail("it should not have validated the idPattern") }
)
}
}
| 29 | null | 11 | 27 | 3faf0a44de75e182bdeabf55b74b73d2173540c8 | 8,353 | stellio-context-broker | Apache License 2.0 |
mvvm/src/main/java/ro/dobrescuandrei/mvvm/utils/Constants.kt | irfanirawansukirman | 171,591,919 | false | null | package ro.dobrescuandrei.mvvm.utils
const val NO_VALUE_INT = 0
const val NO_VALUE_FLOAT = 0.0f
const val NO_VALUE_DOUBLE = 0.0
const val NO_VALUE_LONG = 0L
const val ARG_MODEL = "MODEL"
const val ARG_CHOOSE_MODE = "CHOOSE_MODE"
const val RESULTS_PER_PAGE = 100
| 0 | Kotlin | 5 | 1 | f940702c98847e42dc0ce230485da8f35bc32e32 | 271 | DobDroidMVVM | Apache License 2.0 |
app/src/main/java/com/example/foodie/data/repository/FavoriteRepository.kt | DayanaOviedo2001 | 806,851,708 | false | {"Kotlin": 74414} | package com.example.foodie.data.repository
import com.example.foodie.data.datasource.FavoriteDataSource
import com.example.foodie.data.entity.FavoriteFood
class FavoriteRepository(var fds: FavoriteDataSource) {
suspend fun loadFavoriteFood(): List<FavoriteFood> =
fds.loadFavoriteFood()
suspend fun addFavoriteFood(foodId: Int, foodName: String, foodImageName: String, foodPrice: Int) =
fds.addFavoriteFood(foodId, foodName, foodImageName, foodPrice)
suspend fun deleteFavoriteFood(foodId: Int) =
fds.deleteFavoriteFood(foodId)
} | 0 | Kotlin | 0 | 0 | 91b28a7f2845316033845d31e653519be0be17e9 | 569 | Foodie | MIT License |
src/main/kotlin/uk/gov/justice/digital/hmpps/pecs/jpc/controller/constraints/DuplicateLocationConstraintsValidator.kt | ministryofjustice | 292,861,912 | false | null | package uk.gov.justice.digital.hmpps.pecs.jpc.constraint
import org.springframework.stereotype.Component
import uk.gov.justice.digital.hmpps.pecs.jpc.controller.MapFriendlyLocationController.MapLocationForm
import uk.gov.justice.digital.hmpps.pecs.jpc.service.LocationsService
import javax.validation.ConstraintValidator
import javax.validation.ConstraintValidatorContext
@Component
class DuplicateLocationConstraintsValidator(
val service: LocationsService
) : ConstraintValidator<ValidDuplicateLocation?, MapLocationForm?> {
override fun initialize(arg0: ValidDuplicateLocation?) {}
override fun isValid(form: MapLocationForm?, context: ConstraintValidatorContext): Boolean {
return form == null || form.locationName.isEmpty() || !service.locationAlreadyExists(
form.agencyId,
form.locationName
)
}
}
| 1 | Kotlin | 2 | 3 | fe19b13bbccc99d14ac70cfb1e3dfb017b62c87e | 835 | calculate-journey-variable-payments | MIT License |
module-square/src/main/java/com/bbgo/module_square/viewmodel/SquareViewModelFactory.kt | BlueSky15171 | 394,822,061 | true | {"Kotlin": 303361, "Java": 6868} | package com.bbgo.module_square.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.bbgo.module_square.repository.SquareRepository
/**
* author: wangyb
* date: 3/29/21 9:47 PM
* description: todo
*/
class SquareViewModelFactory(private val repository: SquareRepository) : ViewModelProvider.NewInstanceFactory() {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return SquareViewModel(repository) as T
}
} | 0 | null | 0 | 0 | 33680499e2a5d1fd95e5528dd525e2cd5f873a9d | 527 | WanAndroid | Apache License 2.0 |
plugins/github/src/org/jetbrains/plugins/github/util/CollectionDelta.kt | hieuprogrammer | 284,920,751 | false | null | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.template.util
class CollectionDelta<out T>(oldCollection: Collection<T>, val newCollection: Collection<T>) {
val newItems: Collection<T> = newCollection - oldCollection
val removedItems: Collection<T> = oldCollection - newCollection
val isEmpty = newItems.isEmpty() && removedItems.isEmpty()
} | 1 | null | 1 | 2 | dc846ecb926c9d9589c1ed8a40fdb20e47874db9 | 472 | intellij-community | Apache License 2.0 |
app/src/main/java/com/hello/curiosity/template/splash/SplashActivity.kt | HelloCuriosity | 190,705,036 | false | null | package com.hello.curiosity.template.splash
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.hello.curiosity.template.main.MainActivity
import com.hello.curiosity.R
import com.hello.curiosity.data.threading.SchedulerProvider
class SplashActivity : AppCompatActivity(), SplashView {
private lateinit var presenter: SplashPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
presenter = SplashPresenter(SchedulerProvider.default)
}
override fun onResume() {
super.onResume()
presenter.bind(this)
}
override fun onPause() {
presenter.unbind()
super.onPause()
}
override fun startMainActivity() {
startActivity(MainActivity.createIntent(this))
finish()
}
}
| 16 | Kotlin | 0 | 1 | 62f139839ec3d004e9404a26ca7b7b83597153db | 890 | android-app | MIT License |
play-services-safetynet-core/src/main/kotlin/org/microg/gms/safetynet/SafetyNetClientService.kt | microg | 19,082,715 | false | null | /*
* SPDX-FileCopyrightText: 2021 microG Project Team
* SPDX-License-Identifier: Apache-2.0
*/
package org.microg.gms.safetynet
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.os.Build.VERSION.SDK_INT
import android.os.Bundle
import android.os.Parcel
import android.os.ResultReceiver
import android.util.Base64
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.google.android.gms.common.api.Status
import com.google.android.gms.common.internal.GetServiceRequest
import com.google.android.gms.common.internal.IGmsCallbacks
import com.google.android.gms.safetynet.AttestationData
import com.google.android.gms.safetynet.RecaptchaResultData
import com.google.android.gms.safetynet.SafetyNetStatusCodes
import com.google.android.gms.safetynet.internal.ISafetyNetCallbacks
import com.google.android.gms.safetynet.internal.ISafetyNetService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.microg.gms.BaseService
import org.microg.gms.common.GmsService
import org.microg.gms.common.PackageUtils
import org.microg.gms.droidguard.core.DroidGuardPreferences
import org.microg.gms.droidguard.core.DroidGuardResultCreator
import org.microg.gms.settings.SettingsContract
import org.microg.gms.settings.SettingsContract.CheckIn.getContentUri
import org.microg.gms.settings.SettingsContract.getSettings
import java.io.IOException
import java.net.URLEncoder
import java.util.*
private const val TAG = "GmsSafetyNet"
private const val DEFAULT_API_KEY = "AIzaSyDqVnJBjE5ymo--oBJt3On7HQx9xNm1RHA"
class SafetyNetClientService : BaseService(TAG, GmsService.SAFETY_NET_CLIENT) {
override fun handleServiceRequest(callback: IGmsCallbacks, request: GetServiceRequest, service: GmsService) {
callback.onPostInitComplete(0, SafetyNetClientServiceImpl(this, request.packageName, lifecycle), null)
}
}
private fun StringBuilder.appendUrlEncodedParam(key: String, value: String?) = append("&")
.append(URLEncoder.encode(key, "UTF-8"))
.append("=")
.append(value?.let { URLEncoder.encode(it, "UTF-8") } ?: "")
class SafetyNetClientServiceImpl(private val context: Context, private val packageName: String, private val lifecycle: Lifecycle) : ISafetyNetService.Stub(), LifecycleOwner {
override fun getLifecycle(): Lifecycle = lifecycle
override fun attest(callbacks: ISafetyNetCallbacks, nonce: ByteArray) {
attestWithApiKey(callbacks, nonce, DEFAULT_API_KEY)
}
override fun attestWithApiKey(callbacks: ISafetyNetCallbacks, nonce: ByteArray?, apiKey: String) {
if (nonce == null) {
callbacks.onAttestationData(Status(SafetyNetStatusCodes.DEVELOPER_ERROR, "ApiKey missing"), null)
return
}
if (!SafetyNetPreferences.isEnabled(context)) {
Log.d(TAG, "ignoring SafetyNet request, SafetyNet is disabled")
callbacks.onAttestationData(Status(SafetyNetStatusCodes.ERROR, "Disabled"), null)
return
}
if (!DroidGuardPreferences.isEnabled(context)) {
Log.d(TAG, "ignoring SafetyNet request, DroidGuard is disabled")
callbacks.onAttestationData(Status(SafetyNetStatusCodes.ERROR, "Disabled"), null)
return
}
lifecycleScope.launchWhenStarted {
try {
val attestation = Attestation(context, packageName)
attestation.buildPayload(nonce)
val data = mapOf("contentBinding" to attestation.payloadHashBase64)
val dg = withContext(Dispatchers.IO) { DroidGuardResultCreator.getResult(context, "attest", data) }
attestation.setDroidGaurdResult(Base64.encodeToString(dg, Base64.NO_WRAP + Base64.NO_PADDING + Base64.URL_SAFE))
val jwsResult = withContext(Dispatchers.IO) { attestation.attest(apiKey) }
callbacks.onAttestationData(Status.SUCCESS, AttestationData(jwsResult))
} catch (e: Exception) {
Log.w(TAG, "Exception during attest: ${e.javaClass.name}", e)
val code = when(e) {
is IOException -> SafetyNetStatusCodes.NETWORK_ERROR
else -> SafetyNetStatusCodes.ERROR
}
callbacks.onAttestationData(Status(code, e.localizedMessage), null)
}
}
}
override fun getSharedUuid(callbacks: ISafetyNetCallbacks) {
PackageUtils.checkPackageUid(context, packageName, getCallingUid())
PackageUtils.assertExtendedAccess(context)
// TODO
Log.d(TAG, "dummy Method: getSharedUuid")
callbacks.onString("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")
}
override fun lookupUri(callbacks: ISafetyNetCallbacks, s1: String, threatTypes: IntArray, i: Int, s2: String) {
Log.d(TAG, "unimplemented Method: lookupUri")
}
override fun init(callbacks: ISafetyNetCallbacks) {
Log.d(TAG, "dummy Method: init")
callbacks.onBoolean(Status.SUCCESS, true)
}
override fun getHarmfulAppsList(callbacks: ISafetyNetCallbacks) {
Log.d(TAG, "dummy Method: unknown4")
callbacks.onHarmfulAppsData(Status.SUCCESS, ArrayList())
}
override fun verifyWithRecaptcha(callbacks: ISafetyNetCallbacks, siteKey: String?) {
if (siteKey == null) {
callbacks.onAttestationData(Status(SafetyNetStatusCodes.RECAPTCHA_INVALID_SITEKEY, "SiteKey missing"), null)
return
}
if (!SafetyNetPreferences.isEnabled(context)) {
Log.d(TAG, "ignoring SafetyNet request, SafetyNet is disabled")
callbacks.onRecaptchaResult(Status(SafetyNetStatusCodes.ERROR, "Disabled"), null)
return
}
if (!DroidGuardPreferences.isEnabled(context)) {
Log.d(TAG, "ignoring SafetyNet request, DroidGuard is disabled")
callbacks.onRecaptchaResult(Status(SafetyNetStatusCodes.ERROR, "Disabled"), null)
return
}
val intent = Intent("org.microg.gms.safetynet.RECAPTCHA_ACTIVITY")
intent.`package` = context.packageName
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
val androidId = getSettings(context, getContentUri(context), arrayOf(SettingsContract.CheckIn.ANDROID_ID)) { cursor: Cursor -> cursor.getLong(0) }
val params = StringBuilder()
val packageFileDigest = try {
Base64.encodeToString(Attestation.getPackageFileDigest(context, packageName), Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING)
} catch (e: Exception) {
if (packageName == "com.blogspot.android_er.recaptcha") {
"kXkOWm-DT-q__5MnrdyCRLowptdd2PjNA1RAnyQ1A-4"
} else {
callbacks.onRecaptchaResult(Status(SafetyNetStatusCodes.ERROR, e.localizedMessage), null)
return
}
}
val packageSignatures = try {
Attestation.getPackageSignatures(context, packageName).map { Base64.encodeToString(it, Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING) }
} catch (e: Exception) {
if (packageName == "com.blogspot.android_er.recaptcha") {
listOf("xgEpqm72luj7TLUt7kMxIyN-orV6v03_T_yCkR4A93Y")
} else {
callbacks.onRecaptchaResult(Status(SafetyNetStatusCodes.ERROR, e.localizedMessage), null)
return
}
}
params.appendUrlEncodedParam("k", siteKey)
.appendUrlEncodedParam("di", androidId.toString())
.appendUrlEncodedParam("pk", packageName)
.appendUrlEncodedParam("sv", SDK_INT.toString())
.appendUrlEncodedParam("gv", "20.47.14 (040306-{{cl}})")
.appendUrlEncodedParam("gm", "260")
.appendUrlEncodedParam("as", packageFileDigest)
for (signature in packageSignatures) {
Log.d(TAG, "Sig: $signature")
params.appendUrlEncodedParam("ac", signature)
}
params.appendUrlEncodedParam("ip", "com.android.vending")
.appendUrlEncodedParam("av", false.toString())
.appendUrlEncodedParam("si", null)
intent.putExtra("params", params.toString())
intent.putExtra("result", object : ResultReceiver(null) {
override fun onReceiveResult(resultCode: Int, resultData: Bundle) {
if (resultCode != 0) {
callbacks.onRecaptchaResult(Status(resultData.getInt("errorCode"), resultData.getString("error")), null)
} else {
callbacks.onRecaptchaResult(Status.SUCCESS, RecaptchaResultData().apply { token = resultData.getString("token") })
}
}
})
context.startActivity(intent)
}
override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean {
if (super.onTransact(code, data, reply, flags)) return true
Log.d(TAG, "onTransact [unknown]: $code, $data, $flags")
return false
}
}
| 746 | null | 539 | 4,529 | 17b8371b489f919d6ff87607c4a289b0af38d159 | 9,302 | GmsCore | Apache License 2.0 |
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/dms/CfnEndpointDynamoDbSettingsPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.dms
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.services.dms.CfnEndpoint
/**
* Provides information, including the Amazon Resource Name (ARN) of the IAM role used to define an
* Amazon DynamoDB target endpoint.
*
* This information also includes the output format of records applied to the endpoint and details
* of transaction and control table data information. For information about other available settings,
* see [Using object mapping to migrate data to
* DynamoDB](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.DynamoDB.html#CHAP_Target.DynamoDB.ObjectMapping)
* in the *AWS Database Migration Service User Guide* .
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.dms.*;
* DynamoDbSettingsProperty dynamoDbSettingsProperty = DynamoDbSettingsProperty.builder()
* .serviceAccessRoleArn("serviceAccessRoleArn")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-dynamodbsettings.html)
*/
@CdkDslMarker
public class CfnEndpointDynamoDbSettingsPropertyDsl {
private val cdkBuilder: CfnEndpoint.DynamoDbSettingsProperty.Builder =
CfnEndpoint.DynamoDbSettingsProperty.builder()
/**
* @param serviceAccessRoleArn The Amazon Resource Name (ARN) used by the service to access the
* IAM role.
* The role must allow the `iam:PassRole` action.
*/
public fun serviceAccessRoleArn(serviceAccessRoleArn: String) {
cdkBuilder.serviceAccessRoleArn(serviceAccessRoleArn)
}
public fun build(): CfnEndpoint.DynamoDbSettingsProperty = cdkBuilder.build()
}
| 1 | Kotlin | 0 | 0 | 17c41bdaffb2e10d31b32eb2282b73dd18be09fa | 1,994 | awscdk-dsl-kotlin | Apache License 2.0 |
src/main/kotlin/com/github/cetonek/bigbiznis/BigBiznisApplication.kt | cetonek | 393,110,614 | false | null | package com.github.cetonek.bigbiznis
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.properties.ConfigurationPropertiesScan
import org.springframework.boot.runApplication
import org.springframework.cache.annotation.EnableCaching
import org.springframework.scheduling.annotation.EnableScheduling
import java.util.*
import javax.annotation.PostConstruct
fun main(args: Array<String>) {
runApplication<BigBiznisApplication>(*args)
}
@ConfigurationPropertiesScan
@EnableScheduling
@EnableCaching
@SpringBootApplication
class BigBiznisApplication
| 0 | Kotlin | 0 | 0 | fa70fd5c1edfca1ba22b0cee54a02413184cce2b | 609 | big-biznis | MIT License |
platform/lang-impl/src/com/intellij/codeInsight/intention/impl/IntentionActionAsAction.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.intention.impl
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
/**
* Wrapper for IntentionAction to allow assigning keyboard shortcuts to it
*
* The wrapper actions are created and managed by [IntentionShortcutManager].
*/
class IntentionActionAsAction(intention: IntentionAction)
: AnAction({CodeInsightBundle.message("intention.action.wrapper.name", intention.familyName)}) {
private val actionId = intention.wrappedActionId
override fun actionPerformed(e: AnActionEvent) {
val intention = findIntention() ?: return
val dataContext = e.dataContext
val file = dataContext.getData(CommonDataKeys.PSI_FILE) ?: return
val editor = dataContext.getData(CommonDataKeys.EDITOR) ?: return
intention.invokeAsAction(editor, file)
}
override fun update(e: AnActionEvent) {
val editor = e.dataContext.getData(CommonDataKeys.EDITOR) ?: return
val file = e.dataContext.getData(CommonDataKeys.PSI_FILE) ?: return
val project = e.project ?: return
e.presentation.isEnabled = findIntention()?.isAvailable(project, editor, file) == true
}
private fun findIntention(): IntentionAction? = IntentionShortcutManager.getInstance().findIntention(actionId)
}
| 214 | null | 4829 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 1,611 | intellij-community | Apache License 2.0 |
server/src/test/kotlin/at/yawk/javabrowser/server/typesearch/FullIndexBenchmark.kt | yawkat | 135,326,421 | false | null | package at.yawk.javabrowser.server.typesearch
import at.yawk.javabrowser.DbConfig
import at.yawk.javabrowser.server.Config
import at.yawk.numaec.LargeByteBuffer
import at.yawk.numaec.LargeByteBufferAllocator
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import org.eclipse.collections.impl.list.mutable.primitive.LongArrayList
import org.skife.jdbi.v2.Handle
import java.io.File
import java.util.concurrent.Semaphore
private const val PAGE_SIZE = 4096
fun main(args: Array<String>) {
val config = ObjectMapper(YAMLFactory()).findAndRegisterModules().readValue(File(args[0]), Config::class.java)
var pageCounter: PageCounter? = null
val searchIndex = object : SearchIndex<String, String>(
chunkSize = config.typeIndexChunkSize * 4,
storageDir = config.typeIndexDirectory
) {
override fun transformAllocator(allocator: LargeByteBufferAllocator): LargeByteBufferAllocator? {
return LargeByteBufferAllocator { size ->
object : RecordingBuffer(allocator.allocate(size)) {
override fun recordAccess(position: Long, length: Long, write: Boolean) {
val pc = pageCounter
if (pc != null) {
var pos = position
while (pos < position + length) {
pc.recordAccess(position / PAGE_SIZE)
pos += PAGE_SIZE
}
}
}
}
}
}
}
println("Building index...")
val dbi = config.database.start(mode = DbConfig.Mode.FRONTEND)
val semaphore = Semaphore(1)
dbi.inTransaction { outerConn: Handle, _ ->
val artifacts = outerConn.createQuery("select id from artifacts").map { _, r, _ -> r.getString(1) }.list()
artifacts.stream().parallel().forEach { artifactId ->
semaphore.acquire()
dbi.inTransaction { conn: Handle, _ ->
println(" Building index for $artifactId")
val itr = conn.createQuery("select binding, sourceFile from bindings where realm = 0 and isType and artifactId = ?")
.bind(0, artifactId)
.map { _, r, _ ->
SearchIndex.Input(
string = r.getString(1),
value = r.getString(2))
}
.iterator()
searchIndex.replace(artifactId, itr, BindingTokenizer.Java)
}
semaphore.release()
}
}
println("Running test...")
for (word in listOf("url", "urle", "conchashma", "conchasma")) {
pageCounter = PageCounter()
searchIndex.find(word).take(100).toList()
println(" Search for query '$word' took ${pageCounter.missCount} cache misses")
}
}
private class PageCounter(private val lruSize: Int = 1024) {
private val queue = LongArrayList(lruSize)
var missCount = 0
private set
@Synchronized
fun recordAccess(page: Long) {
if (!queue.remove(page)) {
missCount++
}
if (queue.size() == lruSize) {
queue.removeAtIndex(0)
}
queue.add(page)
}
}
private abstract class RecordingBuffer(private val delegate: LargeByteBuffer) : LargeByteBuffer {
protected abstract fun recordAccess(position: Long, length: Long, write: Boolean)
override fun getInt(position: Long): Int {
recordAccess(position, 4, write = false)
return delegate.getInt(position)
}
override fun getLong(position: Long): Long {
recordAccess(position, 8, write = false)
return delegate.getLong(position)
}
override fun setShort(position: Long, value: Short) {
recordAccess(position, 2, write = true)
return delegate.setShort(position, value)
}
override fun setLong(position: Long, value: Long) {
recordAccess(position, 8, write = true)
return delegate.setLong(position, value)
}
override fun getShort(position: Long): Short {
recordAccess(position, 2, write = false)
return delegate.getShort(position)
}
override fun setInt(position: Long, value: Int) {
recordAccess(position, 4, write = true)
return delegate.setInt(position, value)
}
override fun getByte(position: Long): Byte {
recordAccess(position, 1, write = false)
return delegate.getByte(position)
}
override fun size(): Long {
return delegate.size()
}
override fun copyFrom(from: LargeByteBuffer, fromIndex: Long, toIndex: Long, length: Long) {
this.recordAccess(toIndex, length, write = true)
if (from is RecordingBuffer) {
from.recordAccess(fromIndex, length, write = false)
this.delegate.copyFrom(from.delegate, fromIndex, toIndex, length)
} else {
this.delegate.copyFrom(from, fromIndex, toIndex, length)
}
}
override fun setByte(position: Long, value: Byte) {
recordAccess(position, 1, write = true)
return delegate.setByte(position, value)
}
} | 17 | null | 3 | 35 | b9233824bf594bacffaee2efbf12ab9ea941763e | 5,333 | java-browser | Apache License 2.0 |
math-vector/math-vector-core/src/commonMain/kotlin/tz/co/asoft/Vec2.math.kt | aSoft-Ltd | 332,269,443 | false | null | package tz.co.asoft
operator fun Vec2<*>.plus(p: Vec2<*>) = Vec2(
x = x.toDouble() + p.x.toDouble(),
y = y.toDouble() + p.y.toDouble()
)
operator fun Vec2<*>.minus(p: Vec2<*>) = Vec2(
x = x.toDouble() - p.x.toDouble(),
y = y.toDouble() - p.y.toDouble()
)
operator fun Number.times(p: Vec2<*>) = Vec2(
x = toDouble() * p.x.toDouble(),
y = toDouble() * p.y.toDouble()
) | 0 | Kotlin | 1 | 1 | 1fe38daa72aff667ef14a43de2a4f6d7bd6f1cbd | 394 | math | MIT License |
blog/src/main/kotlin/com/liux/blog/markdown/node/MoreSuspend.kt | lx0758 | 334,699,858 | false | {"Kotlin": 200977, "Vue": 104221, "CSS": 94393, "JavaScript": 82498, "HTML": 63110, "TypeScript": 23981} | package com.liux.blog.markdown.node
import org.commonmark.node.CustomBlock
class MoreSuspend : CustomBlock() | 0 | Kotlin | 0 | 0 | 094a3d2d040ad610d3161d1b6d71f7343da6d67b | 110 | Blog | MIT License |
navigation-core/src/commonMain/kotlin/com.chrynan.navigation/NavigationContextStacks.kt | chRyNaN | 439,481,580 | false | null | package com.chrynan.navigation
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.MapSerializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.descriptors.buildClassSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
/**
* A component that wraps a [Map] of [NavigationContext] to [MutableStack] of [NavigationDestination]s and provides
* convenience functions for accessing and altering the values. Note that this component is mutable.
*/
@Serializable(with = NavigationContextStacksSerializer::class)
internal class NavigationContextStacks<Destination : NavigationDestination, Context : NavigationContext<Destination>> internal constructor(
internal val initialContext: Context,
contextStacks: Map<Context, Stack<Destination>> = emptyMap()
) {
private val destinationStacksByContext: MutableMap<Context, MutableStack<Destination>> =
mutableMapOf(initialContext to mutableStackOf(initialContext.initialDestination)).apply {
contextStacks.entries.forEach { entry ->
this[entry.key] = entry.value.toMutableStack()
}
}
/**
* Retrieves the [Stack] of [Destination]s for the provided [Context].
*/
operator fun get(context: Context): Stack<Destination> =
destinationStacksByContext[context]?.toStack() ?: stackOf(context.initialDestination)
/**
* Retrieves the current [Destination] on top of the [Stack] for the provided [Context] without removing it.
*/
fun peek(context: Context): Destination =
get(context = context).peekOrNull() ?: context.initialDestination
/**
* Removes and returns the [Destination] on top of the [Stack] for the provided [Context], or `null` if the item
* cannot be removed. There must always be at least one item within a [Destination] [Stack], attempting to remove
* that item will fail and return `null` instead.
*/
fun pop(context: Context): Destination? {
val stack = destinationStacksByContext[context] ?: return null
if (stack.size <= 1) return null
val removed = stack.pop()
destinationStacksByContext[context] = stack
return removed
}
/**
* Pushes the provided [destination] to the top of the [Stack] of [Destination]s for the provided [context].
*/
fun push(context: Context, destination: Destination) {
val stack = destinationStacksByContext[context] ?: mutableStackOf(context.initialDestination)
stack.push(destination)
destinationStacksByContext[context] = stack
}
/**
* Pushes the provided [destination] to the top of the [Stack] of [Destination]s for the provided [context], but
* if the provided [destination] already exists in the [Stack] of [Destination]s for the provided [context], all
* the items on top of it will be popped from the stack.
*/
fun pushDropping(context: Context, destination: Destination) {
val stack = destinationStacksByContext[context] ?: mutableStackOf(context.initialDestination)
val index = stack.indexOf(destination)
if (index == -1) {
stack.push(destination)
destinationStacksByContext[context] = stack
} else {
val dropCount = (stack.size - (stack.size - index)) + 1
val newStack = stack.toList().drop(dropCount).toMutableStack()
newStack.push(destination)
destinationStacksByContext[context] = newStack
}
}
/**
* Pushes all the provided [destinations] to the top of the [Stack] of [Destination]s for the provided [context].
*/
fun pushAll(context: Context, destinations: Stack<Destination>) {
val stack = destinationStacksByContext[context] ?: mutableStackOf(context.initialDestination)
destinations.forEach { destination -> stack.push(destination) }
destinationStacksByContext[context] = stack
}
/**
* Clears the stack for the provided [context] and resets it back to its initial state.
*/
fun clear(context: Context) {
destinationStacksByContext[context] = mutableStackOf(context.initialDestination)
}
/**
* Clears all the [Stack]s of [Destination]s for all the [Context]s. This resets the internal data structure back
* to its initial state.
*/
fun clearAll() {
destinationStacksByContext.clear()
destinationStacksByContext[initialContext] = mutableStackOf(initialContext.initialDestination)
}
/**
* Returns a [Map] of the [Context] to [Stack] of [Destination]s.
*/
fun toMap(): Map<Context, Stack<Destination>> = destinationStacksByContext
}
/**
* Pops the top destination off the provided [context] stack and returns the new top destination, or `null` if the
* provided [context] stack could not be popped (there must be at least one item in the stack at all times).
*/
internal fun <Destination : NavigationDestination, Context : NavigationContext<Destination>> NavigationContextStacks<Destination, Context>.popToPreviousDestinationForContext(
context: Context
): Destination? {
this.pop(context) ?: return null
return this.peek(context)
}
/**
* A [KSerializer] for [NavigationContextStacks].
*/
internal class NavigationContextStacksSerializer<Destination : NavigationDestination, Context : NavigationContext<Destination>> internal constructor(
destinationSerializer: KSerializer<Destination>,
private val contextSerializer: KSerializer<Context>
) : KSerializer<NavigationContextStacks<Destination, Context>> {
private val stackSerializer = StackSerializer(destinationSerializer)
private val mapSerializer = MapSerializer(contextSerializer, stackSerializer)
override val descriptor: SerialDescriptor = buildClassSerialDescriptor(serialName = "NavigationContextStacks") {
element(elementName = "initialContext", descriptor = contextSerializer.descriptor)
element(elementName = "context_stacks", descriptor = mapSerializer.descriptor)
}
override fun serialize(encoder: Encoder, value: NavigationContextStacks<Destination, Context>) {
encoder.encodeSerializableValue(serializer = contextSerializer, value = value.initialContext)
encoder.encodeSerializableValue(serializer = mapSerializer, value = value.toMap())
}
override fun deserialize(decoder: Decoder): NavigationContextStacks<Destination, Context> {
val initialContext = decoder.decodeSerializableValue(deserializer = contextSerializer)
val contextStacks = decoder.decodeSerializableValue(deserializer = mapSerializer)
return NavigationContextStacks(
initialContext = initialContext,
contextStacks = contextStacks
)
}
}
| 1 | null | 2 | 43 | f48e6dbf813e86fa2f11ea4f02c6351fbcadf4b9 | 6,916 | navigation | Apache License 2.0 |
app/src/main/java/com/codepunk/core/MainActivity.kt | codepunk | 405,428,738 | false | {"Gradle": 13, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 7, "Batchfile": 1, "Markdown": 1, "Proguard": 5, "Kotlin": 32, "XML": 43, "INI": 4, "Java": 2} | /*
* Copyright (C) 2021 Codepunk, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.codepunk.core
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import com.codepunk.core.databinding.MainActivityBinding
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
/**
* The main Activity for the Codepunk app.
*/
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
// region Properties
/**
* The application [SharedPreferences].
*/
@Inject
lateinit var sharedPreferences: SharedPreferences
/**
* The binding for this activity.
*/
private lateinit var binding: MainActivityBinding
// endregion Properties
// region Lifecycle methods
/**
* Sets the content view for the activity.
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.main_activity)
setSupportActionBar(binding.toolbar)
}
/**
* Examines shared preferences.
*/
override fun onResume() {
super.onResume()
sharedPreferences.all // TODO Examine sharedPreferences if needed
}
// endregion Lifecycle methods
}
| 1 | null | 1 | 1 | 207a10bc90c8d903cc5fea535b02ddcda09790c9 | 1,877 | codepunk-android-app-core-2021 | Apache License 2.0 |
src/commonMain/kotlin/requests/response/StockTradeAccumulate.kt | devngho | 565,833,597 | false | {"Kotlin": 268528} | package io.github.devngho.kisopenapi.requests.response
import com.ionspin.kotlin.bignum.integer.BigInteger
import kotlinx.serialization.Contextual
import kotlinx.serialization.SerialName
/**
* [KIS Developers 문서](https://apiportal.koreainvestment.com/apiservice/apiservice-domestic-stock-quotations)를 참조하세요.
* @see io.github.devngho.kisopenapi.requests.InquirePrice
*/
interface StockTradeAccumulate: StockTrade {
/** 누적 거래 대금 */
@SerialName("acml_tr_pbmn") @Contextual val accumulateTradePrice: BigInteger?
} | 0 | Kotlin | 1 | 2 | bba61df1301f0d75f9051e5f423773faadb0a333 | 522 | kt_kisopenapi | MIT License |
AdventOfCodeDay22/src/nativeMain/kotlin/RebootStep.kt | bdlepla | 451,510,571 | false | {"Kotlin": 165771} | data class RebootStep(val on:Boolean,
val xRange:IntRange,
val yRange:IntRange,
val zRange:IntRange) | 0 | Kotlin | 0 | 0 | 1d60a1b3d0d60e0b3565263ca8d3bd5c229e2871 | 166 | AdventOfCode2021 | The Unlicense |
app/src/main/java/io/nosyntax/foundation/domain/model/app_config/BottomBarConfig.kt | aelrahmanashraf | 683,553,348 | false | {"Kotlin": 192262, "Groovy": 3276, "Batchfile": 1149, "Shell": 744, "HTML": 97} | package io.nosyntax.foundation.domain.model.app_config
data class BottomBarConfig(
val display: Boolean,
val background: String,
val label: String
) | 0 | Kotlin | 0 | 0 | 3ba4fdf92d9c3e3ace37737c7bde19ca37b7b0ab | 161 | nosyntax-foundation-android | MIT License |
app/src/main/java/com/kcteam/app/domain/NewOrderSizeDao.kt | DebashisINT | 558,234,039 | false | null | package com.anayaenterprises.app.domain
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.anayaenterprises.app.AppConstant
@Dao
interface NewOrderSizeDao {
@Insert
fun insert(vararg newOrderSizeEntity: NewOrderSizeEntity)
@Insert(onConflict = OnConflictStrategy.REPLACE)
@JvmSuppressWildcards
abstract fun insertAll(kist: List<NewOrderSizeEntity>)
@Query("DELETE FROM " + AppConstant.NEW_ORDER_SIZE)
fun deleteAll()
@Query("SELECT * FROM " + AppConstant.NEW_ORDER_SIZE + " where product_id=:product_id ")
fun getSizeListProductWise(product_id:Int): List<NewOrderSizeEntity>
@Query("update " + AppConstant.NEW_ORDER_SIZE+" set size = UPPER(size) ")
fun updateSizeNametoUpperCase()
} | 0 | null | 1 | 1 | e6114824d91cba2e70623631db7cbd9b4d9690ed | 812 | NationalPlastic | Apache License 2.0 |
wasabi-core/src/main/kotlin/org/wasabifx/wasabi/encoding/EncodingDecoding.kt | wasabifx | 9,009,498 | false | null | package org.wasabifx.wasabi.encoding
import org.apache.commons.codec.binary.Base64
fun String.decodeBase64(encoding: String): String {
if (encoding == "base64") {
return String(Base64.decodeBase64(this)!!)
} else {
throw IllegalArgumentException()
}
}
fun String.encodeBase64(): String {
return Base64.encodeBase64(this.toByteArray()).toString()
} | 20 | null | 58 | 510 | 9148843ca0aa9c4f79ca1228df8f36d590d0a24b | 383 | wasabi | Apache License 2.0 |
PopitaApp/app/src/main/java/com/example/popitaapp/activities/MyProfileActivity.kt | gpiechnik2 | 304,087,999 | false | null | package com.example.popitaapp.activities
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import com.example.popitaapp.R
import kotlinx.android.synthetic.main.activity_my_profile.*
class MyProfileActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_my_profile)
//back button
back_btn.setOnClickListener {
// Handler code here.
val intent = Intent(this, RoomActivity::class.java)
startActivity(intent);
}
//set profile info
txtJob.text = getIntent().getStringExtra("job")
var txt_name = findViewById(R.id.txtName) as TextView
txt_name.text = getIntent().getStringExtra("first_name")
txtDescription.text = getIntent().getStringExtra("description")
txtAlcohol.text = getIntent().getStringExtra("preferred_drink")
//set dynamically image based on user info
val gender = getIntent().getStringExtra("gender")
if (gender == "Male") {
profileImage.setImageResource(R.drawable.ic_gender_male)
} else {
profileImage.setImageResource(R.drawable.ic_gender_female)
}
//change background color
val background = getIntent().getStringExtra("background_color")
if (background == "Orange") {
root.setBackgroundColor(getResources().getColor(R.color.orange))
} else if (background == "Blue") {
root.setBackgroundColor(getResources().getColor(R.color.blue))
} else if (background == "Green") {
root.setBackgroundColor(getResources().getColor(R.color.green))
} else if (background == "Yellow") {
root.setBackgroundColor(getResources().getColor(R.color.yellow))
} else if (background == "Pink") {
root.setBackgroundColor(getResources().getColor(R.color.pink))
}
//edit profile button
editButton.setOnClickListener {
// Handler code here.
val intent = Intent(this, SettingsChangeProfileActivity::class.java)
//needed info for EditProfileActivity
val user_id = getIntent().getStringExtra("user_id")
val job = getIntent().getStringExtra("job")
val first_name = getIntent().getStringExtra("first_name")
val description = getIntent().getStringExtra("description")
val preferred_drink = getIntent().getStringExtra("preferred_drink")
val background_color = getIntent().getStringExtra("background_color")
val gender = getIntent().getStringExtra("gender")
intent.putExtra("id", user_id)
intent.putExtra("job", job)
intent.putExtra("first_name", first_name)
intent.putExtra("description", description)
intent.putExtra("preferred_drink", preferred_drink)
intent.putExtra("background_color", background_color)
intent.putExtra("gender", gender)
startActivity(intent);
}
}
}
| 0 | Kotlin | 0 | 0 | ad044f0884d1dcac6943e036187d867d5209ffd1 | 3,199 | popita | Apache License 2.0 |
app/src/main/java/cc/sovellus/vrcaa/ui/screen/login/LoginScreenModel.kt | Nyabsi | 745,635,224 | false | {"Kotlin": 74992} | package cc.sovellus.vrcaa.ui.screen.login
import android.content.Context
import android.util.Log
import android.widget.Toast
import androidx.compose.runtime.mutableStateOf
import cafe.adriel.voyager.core.model.ScreenModel
import cafe.adriel.voyager.core.model.screenModelScope
import cafe.adriel.voyager.navigator.Navigator
import cc.sovellus.vrcaa.api.ApiContext
import kotlinx.coroutines.launch
import okhttp3.internal.wait
class LoginScreenModel(
private val api: ApiContext,
private val context: Context,
private val navigator: Navigator
) : ScreenModel {
var username = mutableStateOf<String>("")
var password = mutableStateOf<String>("")
fun doLogin() {
screenModelScope.launch {
val token = api.getToken(username.value, password.value)
if (token.isNotEmpty()) {
navigator.push(TwoAuthScreen(token))
} else {
Toast.makeText(
context,
"Wrong username or password.",
Toast.LENGTH_SHORT
).show()
}
}
}
} | 0 | Kotlin | 0 | 1 | 5d8dea3ac3a281dcffa02ce96a987c0e353f241a | 1,109 | vrcaa | MIT License |
kompiledb-core/src/test/kotlin/com/saveourtool/kompiledb/core/io/parsers/WindowsCommandLineParserTest.kt | saveourtool | 651,012,030 | false | {"Kotlin": 123056} | package com.saveourtool.kompiledb.core.io.parsers
import com.saveourtool.kompiledb.core.io.CommandLineParser
import io.kotest.matchers.collections.shouldContainExactly
import kotlin.test.Test
/**
* @see WindowsCommandLineParser
*/
class WindowsCommandLineParserTest {
private val parser: CommandLineParser = WindowsCommandLineParser
@Test
fun `command should be split on whitespace`() {
parser("clang -c file.c").shouldContainExactly("clang", "-c", "file.c")
}
@Test
fun `leading and trailing whitespace should be trimmed`() {
parser(" clang -c file.c").shouldContainExactly("clang", "-c", "file.c")
parser("clang -c file.c ").shouldContainExactly("clang", "-c", "file.c")
parser(" clang -c file.c ").shouldContainExactly("clang", "-c", "file.c")
parser(" clang").shouldContainExactly("clang")
parser("clang ").shouldContainExactly("clang")
parser(" clang ").shouldContainExactly("clang")
}
@Test
fun `double-quoted arguments should be handled correctly`() {
parser(""""clang" -c file.c""").shouldContainExactly("clang", "-c", "file.c")
parser("""clang "-c" file.c""").shouldContainExactly("clang", "-c", "file.c")
parser("""clang -c "file.c"""").shouldContainExactly("clang", "-c", "file.c")
parser(""""clang" "-c" "file.c"""").shouldContainExactly("clang", "-c", "file.c")
parser(""""/ path / to / clang" "-c" "f i l e.c"""").shouldContainExactly("/ path / to / clang", "-c", "f i l e.c")
}
@Test
fun `zero-length quoted arguments should be preserved`() {
parser("""clang -c """"").shouldContainExactly("clang", "-c", "")
parser(""""" "" """"").shouldContainExactly("", "", "")
}
@Test
fun `adjacent quoted fragments glued together (no whitespace)`() {
parser("""clang -c "fi""le.c"""").shouldContainExactly("clang", "-c", "file.c")
parser("clang -c \"\"\"file.c\"").shouldContainExactly("clang", "-c", "file.c")
parser("clang -c \"file.c\"\"\"").shouldContainExactly("clang", "-c", "file.c")
}
@Test
fun `adjacent quoted and non-quoted fragments glued together (no whitespace)`() {
parser("""clang -c "fi"le.c""").shouldContainExactly("clang", "-c", "file.c")
parser("""clang -c fi"le.c"""").shouldContainExactly("clang", "-c", "file.c")
parser("""clang -c ""file.c""").shouldContainExactly("clang", "-c", "file.c")
parser("""clang -c file.c""""").shouldContainExactly("clang", "-c", "file.c")
}
@Test
fun `single quotation marks inside double-quoted arguments`() {
parser("""clang -c "'file1.c'" "'file2.c'"""").shouldContainExactly("clang", "-c", "'file1.c'", "'file2.c'")
parser("""clang -c "'f i l e 1.c'" "'f i l e 2.c'"""").shouldContainExactly("clang", "-c", "'f i l e 1.c'", "'f i l e 2.c'")
}
}
| 2 | Kotlin | 0 | 8 | d1e304e61ef74cc979c7ea4405a0a741b82d087e | 2,890 | kompiledb | MIT License |
platform/platform-api/src/com/intellij/ui/tabs/newImpl/SameHeightTabs.kt | tresat | 189,062,407 | true | null | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.tabs.newImpl
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.tabs.TabInfo
import java.awt.Dimension
open class SameHeightTabs(project: Project?, actionManager: ActionManager, focusManager: IdeFocusManager, parent: Disposable) : JBEditorTabs(project, actionManager, focusManager, parent) {
override fun createTabLabel(info: TabInfo): TabLabel {
return SingleHeightLabel(this, info)
}
open inner class SingleHeightLabel(tabs: JBTabsImpl, info: TabInfo) : TabLabel(tabs, info) {
override fun getPreferredSize(): Dimension {
val size = super.getPreferredSize()
val insets = insets
val layoutInsets = layoutInsets
insets.top += layoutInsets.top
insets.bottom += layoutInsets.bottom
val height = TabsHeightController.toolWindowHeight - insets.top - insets.bottom
return if(size.height >= height) size else Dimension(size.width, height)
}
}
} | 0 | null | 0 | 0 | d169dcb59b79b133ef94c00f8037788baaf009be | 1,230 | intellij-community | Apache License 2.0 |
platform/platform-api/src/com/intellij/ui/tabs/newImpl/SameHeightTabs.kt | tresat | 189,062,407 | true | null | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.tabs.newImpl
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.tabs.TabInfo
import java.awt.Dimension
open class SameHeightTabs(project: Project?, actionManager: ActionManager, focusManager: IdeFocusManager, parent: Disposable) : JBEditorTabs(project, actionManager, focusManager, parent) {
override fun createTabLabel(info: TabInfo): TabLabel {
return SingleHeightLabel(this, info)
}
open inner class SingleHeightLabel(tabs: JBTabsImpl, info: TabInfo) : TabLabel(tabs, info) {
override fun getPreferredSize(): Dimension {
val size = super.getPreferredSize()
val insets = insets
val layoutInsets = layoutInsets
insets.top += layoutInsets.top
insets.bottom += layoutInsets.bottom
val height = TabsHeightController.toolWindowHeight - insets.top - insets.bottom
return if(size.height >= height) size else Dimension(size.width, height)
}
}
} | 0 | null | 0 | 0 | d169dcb59b79b133ef94c00f8037788baaf009be | 1,230 | intellij-community | Apache License 2.0 |
src/commonMain/kotlin/com/github/shaart/pstorage/multiplatform/ui/table/TextTableCell.kt | shaart | 643,580,361 | false | null | package com.github.shaart.pstorage.multiplatform.ui.table
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.padding
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.filled.Edit
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
@Composable
fun RowScope.TextTableCell(
text: String,
weight: Float,
alignment: TextAlign = TextAlign.Center,
title: Boolean = false,
editable: Boolean = false,
shouldBeEmptyOnEditStart: Boolean = false,
shouldBeMasked: Boolean = false,
onEdit: (newValue: String) -> Unit = {},
) {
var textValue by remember { mutableStateOf(text) }
var isInEditionMode by remember { mutableStateOf(false) }
val focusRequester = remember { FocusRequester() }
if (editable && isInEditionMode) {
TextField(
enabled = true,
modifier = Modifier.padding(10.dp).weight(weight).focusRequester(focusRequester)
.focusProperties { },
value = textValue,
onValueChange = { textValue = it },
colors = TextFieldDefaults.textFieldColors(
textColor = Color.Black,
backgroundColor = Color.White,
),
textStyle = TextStyle(
fontWeight = if (title) FontWeight.Bold else FontWeight.Normal,
textAlign = alignment,
),
visualTransformation = if (shouldBeMasked) PasswordVisualTransformation() else VisualTransformation.None,
)
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}
IconButton(onClick = {
isInEditionMode = false
onEdit(textValue)
}) {
Icon(imageVector = Icons.Filled.Check, contentDescription = "Confirm cell edit")
}
IconButton(onClick = {
isInEditionMode = false
textValue = text
}) {
Icon(imageVector = Icons.Filled.Clear, contentDescription = "Cancel cell edit")
}
} else {
Text(
text = text,
modifier = Modifier.padding(10.dp).weight(weight),
fontWeight = if (title) FontWeight.Bold else FontWeight.Normal,
textAlign = alignment,
)
IconButton(onClick = {
isInEditionMode = true
textValue = if (shouldBeEmptyOnEditStart) "" else text
}) {
Icon(imageVector = Icons.Filled.Edit, contentDescription = "Edit cell value")
}
}
} | 4 | Kotlin | 0 | 0 | a406663164f86cdf81d0e59e4a52257eb63257fd | 3,187 | pstorage-multiplatform | Apache License 2.0 |
ls2sdk-core/src/main/java/com/curiosityhealth/ls2sdk/core/rs/LS2ParticipantAccountGeneratorRequestingCredentialsStep.kt | CuriosityHealth | 125,130,072 | false | null | package com.curiosityhealth.ls2sdk.core.rs
import android.text.InputType
import org.researchsuite.rsuiteextensionscore.RSLoginStep
open class LS2ParticipantAccountGeneratorRequestingCredentialsStep @JvmOverloads constructor(
identifier: String,
title: String? = null,
text: String? = null,
buttonText: String? = null,
val generatorID: String? = null,
identityFieldName: String? = null,
passwordFieldName: String? = null
): RSLoginStep(
identifier = identifier,
title = title ?: "Log in",
text = text ?: "Please log in",
logInLayoutClass = LS2ParticipantAccountGeneratorRequestingCredentialsStepLayout::class.java,
loginButtonTitle = buttonText ?: "Create Account",
identityFieldName = identityFieldName ?: "Study ID",
showIdentityField = (generatorID == null),
passwordFieldName = passwordFieldName ?: "Study Passphrase",
passwordFieldInputType = InputType.TYPE_CLASS_TEXT
) {
} | 1 | null | 1 | 1 | ef4506be6ac8e9c76a958286ded2006944cf6b30 | 1,009 | LS2SDK-Android | Apache License 2.0 |
app/src/main/java/com/github/maravicentina/remotesecuritylockarduino/activities/LockControlActivity.kt | mara-vicentina | 779,477,358 | false | {"Kotlin": 14823} | package com.github.maravicentina.remotesecuritylockarduino.activities
import android.os.Bundle
import android.view.View
import android.widget.EditText
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.github.maravicentina.remotesecuritylockarduino.R
/**
* Atividade responsável pelo controle do bloqueio.
* Esta atividade permite ao usuário interagir com o bloqueio remoto através do aplicativo.
*/
class LockControlActivity : AppCompatActivity() {
private var passwordField: EditText? = null
/**
* Método chamado quando a atividade é criada.
* Inicializa a interface de usuário e configura o comportamento dos elementos visuais.
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_lock_control)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
passwordField = findViewById(R.id.passwordField)
}
/**
* Método chamado ao clicar no botão para desconectar o Bluetooth.
* Fecha a conexão Bluetooth e encerra a atividade.
*/
fun disconnectBluetooth(view: View) {
if (ConnectActivity.bluetoothConnection?.close() == true) {
finish()
}
}
/**
* Método chamado ao clicar no botão para desbloquear o dispositivo.
* Envia uma mensagem para o dispositivo de bloqueio com a senha inserida pelo usuário.
*/
fun unlock(view: View) {
if (passwordField?.text.toString() != "") {
ConnectActivity.bluetoothConnection?.sendMessage("a:" + passwordField?.text.toString())
}
}
/**
* Método chamado ao clicar no botão para bloquear o dispositivo.
* Envia uma mensagem para o dispositivo de bloqueio para ativar o bloqueio.
*/
fun lock(view: View) {
ConnectActivity.bluetoothConnection?.sendMessage("f:0")
}
} | 0 | Kotlin | 0 | 0 | 30c79b1643739531fb2b9f0bfa6cf8e6545c731b | 2,275 | remoteSecurityLock | MIT License |
src/test/kotlin/no/nav/medlemskap/sykepenger/lytter/service/RegelMotorResponsHandlerTest.kt | navikt | 392,288,955 | false | null | package no.nav.medlemskap.sykepenger.lytter.service
import no.nav.medlemskap.sykepenger.lytter.config.objectMapper
import no.nav.medlemskap.sykepenger.lytter.rest.Spørsmål
import org.junit.Ignore
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
class RegelMotorResponsHandlerTest {
@Test
fun eosborger(){
val fileContent = this::class.java.classLoader.getResource("UAVKLART_EOS_BORGER.json").readText(Charsets.UTF_8)
RegelMotorResponsHandler().interpretLovmeRespons(fileContent)
val jsonNode = objectMapper.readTree(fileContent)
Assertions.assertTrue(jsonNode.erEosBorger())
Assertions.assertFalse(jsonNode.erTredjelandsborger())
Assertions.assertFalse(jsonNode.erTredjelandsborgerMedEØSFamilie())
}
@Test
fun tredjelandsBorgerGiftMedEOSPerson(){
val fileContent = this::class.java.classLoader.getResource("UAVKLART_3LAND_GIFTEOS_BORGER.json").readText(Charsets.UTF_8)
RegelMotorResponsHandler().interpretLovmeRespons(fileContent)
val jsonNode = objectMapper.readTree(fileContent)
Assertions.assertFalse(jsonNode.erEosBorger())
Assertions.assertTrue(jsonNode.erTredjelandsborger())
Assertions.assertTrue(jsonNode.erTredjelandsborgerMedEØSFamilie())
Assertions.assertFalse(jsonNode.harOppholdsTilatelse())
}
@Test
fun tredjelandsBorgerGiftMedEOSPersonSomHarOppholdsTilatelse(){
val fileContent = this::class.java.classLoader.getResource("UAVKLART_3LAND_GIFTEOS_BORGER_MED_OPPHOLD.json").readText(Charsets.UTF_8)
RegelMotorResponsHandler().interpretLovmeRespons(fileContent)
val jsonNode = objectMapper.readTree(fileContent)
Assertions.assertFalse(jsonNode.erEosBorger())
Assertions.assertTrue(jsonNode.erTredjelandsborger())
Assertions.assertTrue(jsonNode.erTredjelandsborgerMedEØSFamilie())
Assertions.assertTrue(jsonNode.harOppholdsTilatelse())
}
@Test
fun tredjelandsBorgerIkkeGiftMedEOSPerson(){
val fileContent = this::class.java.classLoader.getResource("UAVKLART_3LAND_IKKE_GIFT_EOS_BORGER.json").readText(Charsets.UTF_8)
RegelMotorResponsHandler().interpretLovmeRespons(fileContent)
val jsonNode = objectMapper.readTree(fileContent)
Assertions.assertFalse(jsonNode.erEosBorger())
Assertions.assertTrue(jsonNode.erTredjelandsborger())
Assertions.assertFalse(jsonNode.erTredjelandsborgerMedEØSFamilie())
Assertions.assertFalse(jsonNode.harOppholdsTilatelse())
}
@Test
fun regel_19_1(){
val fileContent = this::class.java.classLoader.getResource("REGEL_19_1.json").readText(Charsets.UTF_8)
RegelMotorResponsHandler().interpretLovmeRespons(fileContent)
val jsonNode = objectMapper.readTree(fileContent)
Assertions.assertFalse(jsonNode.erEosBorger())
Assertions.assertTrue(jsonNode.erTredjelandsborger())
Assertions.assertFalse(jsonNode.erTredjelandsborgerMedEØSFamilie())
Assertions.assertFalse(jsonNode.harOppholdsTilatelse())
}
fun regel_19_3_1(){
val fileContent = this::class.java.classLoader.getResource("respons_regelmotor_kunn_19_3_1_brudd.json").readText(Charsets.UTF_8)
val anbefalt = RegelMotorResponsHandler().interpretLovmeRespons(fileContent)
val jsonNode = objectMapper.readTree(fileContent)
Assertions.assertFalse(jsonNode.erEosBorger())
Assertions.assertTrue(jsonNode.erTredjelandsborger())
Assertions.assertFalse(jsonNode.erTredjelandsborgerMedEØSFamilie())
Assertions.assertFalse(jsonNode.harOppholdsTilatelse())
Assertions.assertTrue(anbefalt.sporsmal.containsAll(setOf(Spørsmål.OPPHOLDSTILATELSE,Spørsmål.ARBEID_UTENFOR_NORGE,Spørsmål.OPPHOLD_UTENFOR_NORGE)),"oppholdstilatelse, arbeid utenfor norge og opphold utenfor norge skal finnes")
}
@Test
fun regel_19_8(){
val fileContent = this::class.java.classLoader.getResource("REGEL_19_8.json").readText(Charsets.UTF_8)
RegelMotorResponsHandler().interpretLovmeRespons(fileContent)
val jsonNode = objectMapper.readTree(fileContent)
Assertions.assertFalse(jsonNode.erEosBorger())
Assertions.assertTrue(jsonNode.erTredjelandsborger())
Assertions.assertFalse(jsonNode.erTredjelandsborgerMedEØSFamilie())
Assertions.assertFalse(jsonNode.harOppholdsTilatelse())
}
@Test
fun regel_19_7(){
val fileContent = this::class.java.classLoader.getResource("REGEL_19_7.json").readText(Charsets.UTF_8)
RegelMotorResponsHandler().interpretLovmeRespons(fileContent)
val jsonNode = objectMapper.readTree(fileContent)
Assertions.assertTrue(jsonNode.erBritiskBorger())
Assertions.assertFalse(jsonNode.harOppholdsTilatelse())
}
@Test
fun REGEL_0_1(){
val fileContent = this::class.java.classLoader.getResource("REGEL_0_1.json").readText(Charsets.UTF_8)
val respons = RegelMotorResponsHandler().interpretLovmeRespons(fileContent)
val jsonNode = objectMapper.readTree(fileContent)
Assertions.assertFalse(jsonNode.erBritiskBorger())
Assertions.assertFalse(jsonNode.harOppholdsTilatelse())
}
@Test
fun aarsakerInneholderEnEllerFlereRegler_test(){
val fileContent = this::class.java.classLoader.getResource("REGEL_0_1.json").readText(Charsets.UTF_8)
val respons = RegelMotorResponsHandler().interpretLovmeRespons(fileContent)
val jsonNode = objectMapper.readTree(fileContent)
Assertions.assertFalse(jsonNode.aarsakerInneholderEnEllerFlereRegler(listOf("REGEL_C")))
Assertions.assertTrue(jsonNode.aarsakerInneholderEnEllerFlereRegler(listOf("REGEL_0_1")))
Assertions.assertTrue(jsonNode.aarsakerInneholderEnEllerFlereRegler(listOf("REGEL_0_1","REGEL_C")))
Assertions.assertFalse(jsonNode.aarsakerInneholderEnEllerFlereRegler(listOf("REGEL_A","REGEL_C")))
Assertions.assertTrue(respons.sporsmal.isEmpty())
}
@Test
fun aarsakerInneholderKunEnRegle_test(){
val fileContent = this::class.java.classLoader.getResource("REGEL_0_1.json").readText(Charsets.UTF_8)
val respons = RegelMotorResponsHandler().interpretLovmeRespons(fileContent)
val jsonNode = objectMapper.readTree(fileContent)
Assertions.assertFalse(jsonNode.aarsakerInneholderKunEnReglel(listOf("REGEL_C")))
Assertions.assertTrue(jsonNode.aarsakerInneholderKunEnReglel(listOf("REGEL_0_1")))
Assertions.assertTrue(jsonNode.aarsakerInneholderKunEnReglel(listOf("REGEL_0_1","REGEL_C")))
Assertions.assertFalse(jsonNode.aarsakerInneholderKunEnReglel(listOf("REGEL_A","REGEL_C")))
Assertions.assertTrue(respons.sporsmal.isEmpty())
}
@Test
fun aarsakerInneholderKunEnReglerMedFlereaarsaker_test(){
val fileContent = this::class.java.classLoader.getResource("sampleVurdering_uavklart.json").readText(Charsets.UTF_8)
val respons = RegelMotorResponsHandler().interpretLovmeRespons(fileContent)
val jsonNode = objectMapper.readTree(fileContent)
Assertions.assertFalse(jsonNode.aarsakerInneholderKunEnReglel(listOf("REGEL_25")))
Assertions.assertTrue(respons.sporsmal.isEmpty())
}
@Test
fun aarsakerInneholderKunRegel_3_test(){
val fileContent = this::class.java.classLoader.getResource("sampleVurdering_uavklart_REGEL_3.json").readText(Charsets.UTF_8)
val respons = RegelMotorResponsHandler().interpretLovmeRespons(fileContent)
val jsonNode = objectMapper.readTree(fileContent)
Assertions.assertTrue(jsonNode.aarsakerInneholderKunEnReglel(listOf("REGEL_3")))
Assertions.assertFalse(respons.sporsmal.isEmpty())
}
} | 0 | Kotlin | 1 | 0 | bde89aefee0f50e1f611d697bfbfa4fd7f4a244f | 7,766 | medlemskap-sykepengerlytter | MIT License |
app/src/main/java/net/dcnnt/core/utils.kt | cyanomiko | 268,339,742 | false | null | package net.dcnnt.core
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.provider.OpenableColumns
import android.webkit.MimeTypeMap
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCaller
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import net.dcnnt.R
import java.io.ByteArrayOutputStream
import java.io.File
import java.lang.reflect.TypeVariable
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
import kotlin.reflect.KClass
enum class FileStatus { WAIT, RUN, CANCEL, DONE, FAIL }
enum class EntryType { FILE, LINK }
data class FileEntry(
val name: String,
var size: Long,
var status: FileStatus = FileStatus.WAIT,
var data: ByteArray? = null,
var localUri: Uri? = null,
val remoteIndex: Long? = null,
val remoteChildren: List<FileEntry>? = null,
val entryType: EntryType = EntryType.FILE
) {
val isDir: Boolean = ((remoteIndex == null) and (remoteChildren != null))
val isLocal: Boolean = ((remoteIndex == null) and (remoteChildren == null))
val isRemote: Boolean = !isLocal
val idStr: String = "$name+$size+$localUri+$remoteIndex"
}
fun getFileInfoFromUri(context: Context, uri: Uri): FileEntry? {
when {
"${uri.scheme}".lowercase() == "content" -> {
context.contentResolver.also { cr ->
val mimeType = cr.getType(uri).toString()
val fallbackExtension = if (mimeType.contains('/')) mimeType.split('/')[1] else "bin"
cr.query(uri, null, null, null, null)?.apply {
val nameIndex = getColumnIndex(OpenableColumns.DISPLAY_NAME)
val sizeIndex = getColumnIndex(OpenableColumns.SIZE)
moveToFirst()
var name = getString(nameIndex)
val size = getLong(sizeIndex)
if (!name.contains('.')) name = "$name.$fallbackExtension"
close()
return FileEntry(name, size, localUri = uri)
}
}
}
"${uri.scheme}".lowercase() == "file" -> {
File(uri.path ?: return null).let {
return FileEntry(it.name, it.length(), localUri = uri)
}
}
}
return null
}
fun drawableToBitmap(drawable: Drawable): Bitmap {
if (drawable is BitmapDrawable) {
if (drawable.bitmap != null) {
return drawable.bitmap
}
}
val bitmap: Bitmap = when((drawable.intrinsicWidth <= 0) || (drawable.intrinsicHeight <= 0)) {
true -> Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)
false -> Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
}
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
return bitmap
}
fun bitmapToPNG(bitmap: Bitmap): ByteArray = ByteArrayOutputStream().apply {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, this) }.toByteArray()
fun drawableToPNG(drawable: Drawable) = bitmapToPNG(drawableToBitmap(drawable))
fun mimeTypeByPath(path: String): String {
MimeTypeMap.getFileExtensionFromUrl(path)?.let {
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(it) ?: "*/*"
}
return "*/*"
}
fun fileIconByPath(path: String): Int {
val mime = mimeTypeByPath(path)
if (mime.startsWith("image")) return R.drawable.ic_image
if (mime.startsWith("audio")) return R.drawable.ic_audiotrack
if (mime.startsWith("video")) return R.drawable.ic_movie
if (path.endsWith("zip", false)) return R.drawable.ic_archive
if (path.endsWith("tar", false)) return R.drawable.ic_archive
if (path.endsWith("gz", false)) return R.drawable.ic_archive
if (path.endsWith("xz", false)) return R.drawable.ic_archive
if (path.endsWith("bz2", false)) return R.drawable.ic_archive
if (path.endsWith("7z", false)) return R.drawable.ic_archive
if (path.endsWith("apk", false)) return R.drawable.ic_android
return R.drawable.ic_file
}
fun fileIcon(name: String?, mime: String?): Int {
if (mime?.startsWith("image") == true) return R.drawable.ic_image
if (mime?.startsWith("audio") == true) return R.drawable.ic_audiotrack
if (mime?.startsWith("video") == true) return R.drawable.ic_movie
if (name?.endsWith("zip", false) == true) return R.drawable.ic_archive
if (name?.endsWith("tar", false) == true) return R.drawable.ic_archive
if (name?.endsWith("gz", false) == true) return R.drawable.ic_archive
if (name?.endsWith("xz", false) == true) return R.drawable.ic_archive
if (name?.endsWith("bz2", false) == true) return R.drawable.ic_archive
if (name?.endsWith("7z", false) == true) return R.drawable.ic_archive
if (name?.endsWith("apk", false) == true) return R.drawable.ic_android
return R.drawable.ic_file
}
fun nowString(): String {
return SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.getDefault()).format(Calendar.getInstance().time)
}
fun simplifyFilename(filename: String): String {
return filename.take(21).trim(' ', '-', '.').replace(' ', '_')
.filter { c -> c.isLetterOrDigit() or (c == '_') }
}
/* Type-safe Parcelable extraction with workaround for old SDK versions */
inline fun <reified T: Parcelable> getParcelable(bundle: Bundle?, key: String): T? {
if (bundle == null) return null
return if (Build.VERSION.SDK_INT >= 33) {
bundle.getParcelable(key, T::class.java)
} else {
@Suppress("DEPRECATION")
bundle.getParcelable<Parcelable>(key) as? T
}
}
inline fun <reified T: Parcelable> getParcelableExtra(intent: Intent, key: String): T? {
return if (Build.VERSION.SDK_INT >= 33) {
intent.getParcelableExtra(key, T::class.java)
} else {
@Suppress("DEPRECATION")
intent.getParcelableExtra<Parcelable>(key) as? T
}
}
inline fun <reified T: Parcelable> getParcelableArrayListExtra(intent: Intent, key: String): ArrayList<T>? {
return if (Build.VERSION.SDK_INT >= 33) {
intent.getParcelableArrayListExtra(key, T::class.java)
} else {
ArrayList<T>().apply {
@Suppress("DEPRECATION")
intent.getParcelableArrayListExtra<Parcelable>(key)?.forEach {
this.add((it as? T) ?: return null)
}
}
}
}
fun newActivityCaller(caller: ActivityResultCaller, okResultOnly: Boolean = true,
handler: (resultCode: Int, intent: Intent?) -> Unit):
ActivityResultLauncher<Intent> {
val launcher = caller.registerForActivityResult(
ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
if ((result.resultCode == Activity.RESULT_OK) or (!okResultOnly)) {
handler(result.resultCode, result.data)
}
}
return launcher
} | 6 | Kotlin | 6 | 99 | 1fa43a1d02a76985bcb90bd39dc32e58e9bb1b3f | 7,284 | dcnnt-android | MIT License |
app/src/main/java/net/dcnnt/core/utils.kt | cyanomiko | 268,339,742 | false | null | package net.dcnnt.core
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.provider.OpenableColumns
import android.webkit.MimeTypeMap
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCaller
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import net.dcnnt.R
import java.io.ByteArrayOutputStream
import java.io.File
import java.lang.reflect.TypeVariable
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
import kotlin.reflect.KClass
enum class FileStatus { WAIT, RUN, CANCEL, DONE, FAIL }
enum class EntryType { FILE, LINK }
data class FileEntry(
val name: String,
var size: Long,
var status: FileStatus = FileStatus.WAIT,
var data: ByteArray? = null,
var localUri: Uri? = null,
val remoteIndex: Long? = null,
val remoteChildren: List<FileEntry>? = null,
val entryType: EntryType = EntryType.FILE
) {
val isDir: Boolean = ((remoteIndex == null) and (remoteChildren != null))
val isLocal: Boolean = ((remoteIndex == null) and (remoteChildren == null))
val isRemote: Boolean = !isLocal
val idStr: String = "$name+$size+$localUri+$remoteIndex"
}
fun getFileInfoFromUri(context: Context, uri: Uri): FileEntry? {
when {
"${uri.scheme}".lowercase() == "content" -> {
context.contentResolver.also { cr ->
val mimeType = cr.getType(uri).toString()
val fallbackExtension = if (mimeType.contains('/')) mimeType.split('/')[1] else "bin"
cr.query(uri, null, null, null, null)?.apply {
val nameIndex = getColumnIndex(OpenableColumns.DISPLAY_NAME)
val sizeIndex = getColumnIndex(OpenableColumns.SIZE)
moveToFirst()
var name = getString(nameIndex)
val size = getLong(sizeIndex)
if (!name.contains('.')) name = "$name.$fallbackExtension"
close()
return FileEntry(name, size, localUri = uri)
}
}
}
"${uri.scheme}".lowercase() == "file" -> {
File(uri.path ?: return null).let {
return FileEntry(it.name, it.length(), localUri = uri)
}
}
}
return null
}
fun drawableToBitmap(drawable: Drawable): Bitmap {
if (drawable is BitmapDrawable) {
if (drawable.bitmap != null) {
return drawable.bitmap
}
}
val bitmap: Bitmap = when((drawable.intrinsicWidth <= 0) || (drawable.intrinsicHeight <= 0)) {
true -> Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)
false -> Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
}
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
return bitmap
}
fun bitmapToPNG(bitmap: Bitmap): ByteArray = ByteArrayOutputStream().apply {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, this) }.toByteArray()
fun drawableToPNG(drawable: Drawable) = bitmapToPNG(drawableToBitmap(drawable))
fun mimeTypeByPath(path: String): String {
MimeTypeMap.getFileExtensionFromUrl(path)?.let {
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(it) ?: "*/*"
}
return "*/*"
}
fun fileIconByPath(path: String): Int {
val mime = mimeTypeByPath(path)
if (mime.startsWith("image")) return R.drawable.ic_image
if (mime.startsWith("audio")) return R.drawable.ic_audiotrack
if (mime.startsWith("video")) return R.drawable.ic_movie
if (path.endsWith("zip", false)) return R.drawable.ic_archive
if (path.endsWith("tar", false)) return R.drawable.ic_archive
if (path.endsWith("gz", false)) return R.drawable.ic_archive
if (path.endsWith("xz", false)) return R.drawable.ic_archive
if (path.endsWith("bz2", false)) return R.drawable.ic_archive
if (path.endsWith("7z", false)) return R.drawable.ic_archive
if (path.endsWith("apk", false)) return R.drawable.ic_android
return R.drawable.ic_file
}
fun fileIcon(name: String?, mime: String?): Int {
if (mime?.startsWith("image") == true) return R.drawable.ic_image
if (mime?.startsWith("audio") == true) return R.drawable.ic_audiotrack
if (mime?.startsWith("video") == true) return R.drawable.ic_movie
if (name?.endsWith("zip", false) == true) return R.drawable.ic_archive
if (name?.endsWith("tar", false) == true) return R.drawable.ic_archive
if (name?.endsWith("gz", false) == true) return R.drawable.ic_archive
if (name?.endsWith("xz", false) == true) return R.drawable.ic_archive
if (name?.endsWith("bz2", false) == true) return R.drawable.ic_archive
if (name?.endsWith("7z", false) == true) return R.drawable.ic_archive
if (name?.endsWith("apk", false) == true) return R.drawable.ic_android
return R.drawable.ic_file
}
fun nowString(): String {
return SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.getDefault()).format(Calendar.getInstance().time)
}
fun simplifyFilename(filename: String): String {
return filename.take(21).trim(' ', '-', '.').replace(' ', '_')
.filter { c -> c.isLetterOrDigit() or (c == '_') }
}
/* Type-safe Parcelable extraction with workaround for old SDK versions */
inline fun <reified T: Parcelable> getParcelable(bundle: Bundle?, key: String): T? {
if (bundle == null) return null
return if (Build.VERSION.SDK_INT >= 33) {
bundle.getParcelable(key, T::class.java)
} else {
@Suppress("DEPRECATION")
bundle.getParcelable<Parcelable>(key) as? T
}
}
inline fun <reified T: Parcelable> getParcelableExtra(intent: Intent, key: String): T? {
return if (Build.VERSION.SDK_INT >= 33) {
intent.getParcelableExtra(key, T::class.java)
} else {
@Suppress("DEPRECATION")
intent.getParcelableExtra<Parcelable>(key) as? T
}
}
inline fun <reified T: Parcelable> getParcelableArrayListExtra(intent: Intent, key: String): ArrayList<T>? {
return if (Build.VERSION.SDK_INT >= 33) {
intent.getParcelableArrayListExtra(key, T::class.java)
} else {
ArrayList<T>().apply {
@Suppress("DEPRECATION")
intent.getParcelableArrayListExtra<Parcelable>(key)?.forEach {
this.add((it as? T) ?: return null)
}
}
}
}
fun newActivityCaller(caller: ActivityResultCaller, okResultOnly: Boolean = true,
handler: (resultCode: Int, intent: Intent?) -> Unit):
ActivityResultLauncher<Intent> {
val launcher = caller.registerForActivityResult(
ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
if ((result.resultCode == Activity.RESULT_OK) or (!okResultOnly)) {
handler(result.resultCode, result.data)
}
}
return launcher
} | 6 | Kotlin | 6 | 99 | 1fa43a1d02a76985bcb90bd39dc32e58e9bb1b3f | 7,284 | dcnnt-android | MIT License |
tezos-rpc/src/test/kotlin/TestMocks.kt | airgap-it | 460,351,851 | false | null | import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkClass
import it.airgap.tezos.contract.ContractModule
import it.airgap.tezos.contract.internal.TezosContractModule
import it.airgap.tezos.core.Tezos
import it.airgap.tezos.core.crypto.CryptoProvider
import it.airgap.tezos.core.internal.di.DependencyRegistry
import it.airgap.tezos.core.internal.module.ModuleRegistry
import it.airgap.tezos.michelson.MichelsonModule
import it.airgap.tezos.michelson.internal.TezosMichelsonModule
import it.airgap.tezos.rpc.RpcModule
import it.airgap.tezos.rpc.http.HttpClientProvider
import it.airgap.tezos.rpc.internal.TezosRpcModule
import java.security.MessageDigest
// -- Tezos --
internal fun mockTezos(cryptoProvider: CryptoProvider? = null, httpClientProvider: HttpClientProvider = mockk(relaxed = true)): Tezos =
mockkClass(Tezos::class).also {
val cryptoProvider = cryptoProvider ?: mockk<CryptoProvider>(relaxed = true).also {
every { it.sha256(any()) } answers {
val messageDigest = MessageDigest.getInstance("SHA-256")
messageDigest.digest(firstArg())
}
}
val dependencyRegistry = DependencyRegistry(cryptoProvider)
val moduleRegistry = ModuleRegistry(
builders = mapOf(
TezosMichelsonModule::class to MichelsonModule,
TezosRpcModule::class to RpcModule.apply { this.httpClientProvider = httpClientProvider },
TezosContractModule::class to ContractModule,
),
)
every { it.dependencyRegistry } returns dependencyRegistry
every { it.moduleRegistry } returns moduleRegistry
} | 0 | Kotlin | 2 | 1 | c5af5ffdd4940670bd66842580d82c2b9d682d84 | 1,677 | tezos-kotlin-sdk | MIT License |
data/src/main/java/com/iliaberlana/movies/data/MovieRepository.kt | siayerestaba | 196,740,845 | false | null | package com.iliaberlana.movies.data
import arrow.core.Either
import com.iliaberlana.movies.domain.entities.Movie
import com.iliaberlana.movies.domain.exception.DomainError
interface MovieRepository {
suspend fun listMovies(page: Int): Either<DomainError, List<Movie>>
} | 0 | Kotlin | 0 | 0 | 479bdabe4f2e4dea59872d8d71d5a57468fac988 | 275 | kotlin-movies-app | MIT License |
app/src/main/java/com/rgonslayer/tiktokyc/firstapp/network/WeatherAPI.kt | rgonslayer | 493,754,649 | false | {"Kotlin": 36135} | package com.rgonslayer.tiktokyc.firstapp.network
import com.google.gson.annotations.SerializedName
import retrofit2.Call
import retrofit2.http.GET
/**
* Data class where it holds information on how to serialize / deserialize our data
*
* Try deserializing other fields!
*
* Note: @field is important!
*/
data class Weather(
//@field:Json(name = "area_metadata") val areaMetadata: List<AreaMetadata>,
//@field:Json(name = "items") val forecastItems: List<ForecastItem>
@SerializedName("area_metadata")
var areaMetadata: List<AreaMetadata?>? = null,
@SerializedName("items")
val forecastItems: List<ForecastItem>? = null
)
data class AirTemperature(
@field:SerializedName("metadata") val tempMetadata: List<TempMetadata>,
@field:SerializedName("items") val tempItems: List<TempItem>
)
data class Rainfall(
@field:SerializedName("metadata") val rainMetadata: List<RainMetadata>,
@field:SerializedName("items") val tempItems: List<RainItem>
)
data class RelativeHumidity(
@field:SerializedName("metadata") val HumidMetadata: List<HumidMetadata>,
@field:SerializedName("items") val tempItems: List<HumidItem>
)
data class WindDirection(
@field:SerializedName("metadata") val WindMetadata: List<WindMetadata>,
@field:SerializedName("items") val tempItems: List<WindItem>
)
data class WindSpeed(
@field:SerializedName("metadata") val SpeedMetadata: List<SpeedMetadata>,
@field:SerializedName("items") val tempItems: List<SpeedItem>
)
data class UVIndex(
@field:SerializedName("items") val UVItems: List<UVItem>
)
interface WeatherAPI {
@GET("v1/environment/2-hour-weather-forecast")
fun getWeatherData(): Call<Weather>
@GET("v1/environment/air-temperature")
fun getAirTemperatureData(): Call<AirTemperature>
@GET("v1/environment/rainfall")
fun getRainfallData(): Call<Rainfall>
@GET("v1/environment/relative-humidity")
fun getRelativeHumidityData(): Call<RelativeHumidity>
@GET("v1/environment/wind-direction")
fun getWindDirectionData(): Call<WindDirection>
@GET("v1/environment/wind-speed")
fun getWindSpeedData(): Call<WindSpeed>
@GET("v1/environment/uv-index")
fun getUVIndexData(): Call<UVIndex>
}
// Nested class AreaMetadata
class AreaMetadata(name: String, latLong: LatLong) {
val name: String
@SerializedName("label_location")
val latLong: LatLong
// Nested class LatLong
inner class LatLong(val latitude: Double, val longitude: Double)
init {
this.name = name
this.latLong = latLong
}
}
//Nested class ForecastItem
class ForecastItem(
@field:SerializedName("update_timestamp") val updateTimestamp: String, @field:SerializedName(
"timestamp"
) val timestamp: String, val forecasts: List<AreaForecast>
) {
// Nested class AreaForecast
inner class AreaForecast(val name: String, val forecast: String)
}
//Nested class ForecastItem
class UVItem(
@field:SerializedName("update_timestamp") val updateTimestamp: String, @field:SerializedName(
"timestamp"
) val timestamp: String, @field:SerializedName("index")val forecasts: List<Index>
) {
// Nested class AreaForecast
inner class Index(val timeStamp: String, val index: Double)
}
// Nested class AreaMetadata
class TempMetadata(stations: tempValues) {
@field:SerializedName("stations")
val stations: tempValues
inner class tempValues(val id: String, val device_id: String, val name: String, @field:SerializedName("location") val latLong: LatLong) {
// Nested class LatLong
inner class LatLong(val latitude: Double, val longitude: Double)}
init {
this.stations = stations
}
}
//Nested class ForecastItem
class TempItem(@field:SerializedName(
"timestamp"
) val timestamp: String, val forecasts: List<Readings>
) {
// Nested class AreaForecast
inner class Readings(val name: String, val temperature: Double)
}
// Nested class AreaMetadata
class RainMetadata(stations: tempValues) {
@field:SerializedName("stations")
val stations: tempValues
inner class tempValues(val id: String, val device_id: String, val name: String, @field:SerializedName("location") val latLong: LatLong) {
// Nested class LatLong
inner class LatLong(val latitude: Double, val longitude: Double)}
init {
this.stations = stations
}
}
//Nested class ForecastItem
class RainItem(@field:SerializedName(
"timestamp"
) val timestamp: String, val forecasts: List<Readings>
) {
// Nested class AreaForecast
inner class Readings(val name: String, val temperature: Double)
}
// Nested class AreaMetadata
class WindMetadata(stations: tempValues) {
@field:SerializedName("stations")
val stations: tempValues
inner class tempValues(val id: String, val device_id: String, val name: String, @field:SerializedName("location") val latLong: LatLong) {
// Nested class LatLong
inner class LatLong(val latitude: Double, val longitude: Double)}
init {
this.stations = stations
}
}
//Nested class ForecastItem
class WindItem(@field:SerializedName(
"timestamp"
) val timestamp: String, val forecasts: List<Readings>
) {
// Nested class AreaForecast
inner class Readings(val name: String, val temperature: Double)
}
class HumidMetadata(stations: tempValues) {
@field:SerializedName("stations")
val stations: tempValues
inner class tempValues(val id: String, val device_id: String, val name: String, @field:SerializedName("location") val latLong: LatLong) {
// Nested class LatLong
inner class LatLong(val latitude: Double, val longitude: Double)}
init {
this.stations = stations
}
}
//Nested class ForecastItem
class HumidItem(@field:SerializedName(
"timestamp"
) val timestamp: String, val forecasts: List<Readings>
) {
// Nested class AreaForecast
inner class Readings(val name: String, val temperature: Double)
}
// Nested class AreaMetadata
class SpeedMetadata(stations: tempValues) {
@field:SerializedName("stations")
val stations: tempValues
inner class tempValues(val id: String, val device_id: String, val name: String, @field:SerializedName("location") val latLong: LatLong) {
// Nested class LatLong
inner class LatLong(val latitude: Double, val longitude: Double)}
init {
this.stations = stations
}
}
//Nested class ForecastItem
class SpeedItem(@field:SerializedName(
"timestamp"
) val timestamp: String, val forecasts: List<Readings>
) {
// Nested class AreaForecast
inner class Readings(val name: String, val temperature: Double)
}
| 0 | Kotlin | 0 | 0 | e8af1c78323fb9087c0360b3158820f3b704fbb2 | 6,684 | weathertiktok | The Unlicense |
src/webMain/kotlin/money/tegro/market/web/store/tonwallet/Wallet.kt | TegroTON | 491,519,429 | false | {"Kotlin": 198445, "HTML": 3914, "JavaScript": 2388, "Dockerfile": 242} | package money.tegro.market.web.store.tonwallet
@OptIn(ExperimentalJsExport::class)
@JsExport
external interface Wallet {
val address: String
val publicKey: String
val walletVersion: String
}
| 11 | Kotlin | 4 | 0 | bd82acf423a4d4e1a00c3eac6347aa7cf18eee5f | 204 | TON-Marketplace-NFT-All | MIT License |
demoapp/src/main/java/com/mercadolibre/android/andesui/demoapp/MainApplication.kt | maaguero | 252,283,086 | false | null | package com.mercadolibre.android.andesui.demoapp
import android.app.Application
import android.content.Context
import android.os.Build
import android.provider.Settings
import androidx.multidex.MultiDex
import com.facebook.common.logging.FLog
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.imagepipeline.core.ImagePipelineConfig
import com.facebook.imagepipeline.listener.RequestListener
import com.facebook.imagepipeline.listener.RequestLoggingListener
/**
* Main Application class that extends from Application to execute the start method only once.
*/
class MainApplication : Application() {
override fun attachBaseContext(base: Context) {
super.attachBaseContext(base)
// No need for productFlavors, as proguard will remove all multidex related code in non-debug builds.
if (BuildConfig.BUILD_TYPE.contentEquals("debug")) {
MultiDex.install(this)
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
Settings.System.putInt(base.contentResolver, "show_touches", 1)
}
}
override fun onCreate() {
super.onCreate()
val requestListeners = setOf<RequestListener>(RequestLoggingListener())
val config = ImagePipelineConfig.newBuilder(this)
// other setters
.setRequestListeners(requestListeners)
.build()
Fresco.initialize(this, config)
FLog.setMinimumLoggingLevel(FLog.VERBOSE)
}
}
| 1 | null | 44 | 1 | bc12913d8a91c4a71faed6ba7e5d6fdfa16de123 | 1,490 | fury_andesui-android | MIT License |
logLib/src/main/java/com/simon/log/report/ReportLog.kt | SimonRHW | 241,857,792 | false | {"Gradle": 19, "Java Properties": 3, "Shell": 1, "Text": 1, "Ignore List": 15, "Batchfile": 1, "Markdown": 1, "JSON": 1, "Proguard": 13, "Kotlin": 109, "XML": 81, "INI": 10, "Java": 53, "Checksums": 32, "Groovy": 2} | package com.simon.log.report
import com.simon.log.BaseLog
import timber.log.Timber
/**
* @author Simon
* @date 2020/5/1
* @desc
*/
class ReportLog private constructor(
consoleLog: Boolean,
logLevel: Int
) : BaseLog(consoleLog, logLevel) {
companion object {
@Volatile
private var instance: ReportLog? = null
fun getInstance(
consoleLog: Boolean,
logLevel: Int,
logService: LogService?
) =
instance ?: synchronized(this) {
instance ?: ReportLog(
consoleLog,
logLevel
).also {
instance = it
Timber.plant(ReportTree(logLevel,logService))
}
}
}
} | 0 | Java | 0 | 1 | 2bc1d25b89c08ca066392e4b37deabd1cffec4fd | 786 | ABKnowledge | Apache License 2.0 |
samples/playground-android/src/main/kotlin/br/com/arch/toolkit/sample/playground/recyclerAdapter/StickyHeadersActivity.kt | matheus-corregiari | 131,161,672 | false | null | package br.com.arch.toolkit.sample.recycler.adapter
import android.os.Bundle
import android.widget.LinearLayout
import android.widget.Toast
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView
import br.com.arch.toolkit.delegate.viewProvider
import br.com.arch.toolkit.recycler.adapter.SimpleStickyAdapter
import br.com.arch.toolkit.recycler.adapter.stickyheader.StickyHeaderModel
import br.com.arch.toolkit.recycler.adapter.stickyheader.StickyHeadersLinearLayoutManager
import br.com.arch.toolkit.sample.recycler.adapter.itemView.StickyItemView
class StickyHeadersActivity : BaseActivity() {
private val recycler by viewProvider<RecyclerView>(R.id.recycler_view)
private val adapter = SimpleStickyAdapter(StickyItemView::Item, StickyItemView::Header)
.withListener(::onItemClick)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_list)
recycler.layoutManager = StickyHeadersLinearLayoutManager<SimpleStickyAdapter<StickyHeaderModelExample, StickyItemView.Item, StickyItemView.Header>>(this)
recycler.addItemDecoration(DividerItemDecoration(this, LinearLayout.VERTICAL))
recycler.adapter = adapter
adapter.setList(generateList())
}
private fun onItemClick(item: StickyHeaderModelExample) {
Toast.makeText(this, "Default Listener: ${item.title}", Toast.LENGTH_SHORT).show()
}
private fun generateList() = (1 until 19).map {
if (it == 1 || it % 4 == 0) {
StickyHeaderModelExample("Header $it").apply { isSticky = true }
} else {
StickyHeaderModelExample("Item $it")
}
}
class StickyHeaderModelExample(
val title: String
) : StickyHeaderModel {
override var isSticky = false
}
}
| 3 | null | 4 | 26 | 74ff8d1a4b8f88f8e667518ee60bde35cf1466f1 | 1,881 | arch-toolkit | Apache License 2.0 |
app/src/main/java/com/scriptsquad/unitalk/Notes/activities/PdfDetailActivity.kt | ST10029788 | 841,892,426 | false | {"Kotlin": 601706, "JavaScript": 1259} | package com.scriptsquad.unitalk.Notes.activities
import android.Manifest
import android.app.AlertDialog
import android.app.ProgressDialog
import android.content.Intent
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.LayoutInflater
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import com.google.firebase.auth.FirebaseAuth
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.firebase.storage.FirebaseStorage
import com.scriptsquad.unitalk.R
import com.scriptsquad.unitalk.Utilities.Utils
import com.scriptsquad.unitalk.Notes.MyApplication
import com.scriptsquad.unitalk.Notes.adapter.AdapterComment
import com.scriptsquad.unitalk.Notes.model.ModelComments
import com.scriptsquad.unitalk.databinding.ActivityPdfDetailBinding
import com.scriptsquad.unitalk.databinding.DialogCommentAddBinding
import www.sanju.motiontoast.MotionToast
import www.sanju.motiontoast.MotionToastStyle
import java.io.FileOutputStream
class PdfDetailActivity : AppCompatActivity() {
private lateinit var binding: ActivityPdfDetailBinding
private companion object {
private const val TAG = "PDF_DETAIL_TAG"
}
private var bookId = ""
private var bookTitle = ""
private var bookUrl = ""
private var bookImageUrl = ""
private lateinit var progressDialog: ProgressDialog
private lateinit var firebaseAuth: FirebaseAuth
//arraylist to hold comments
private lateinit var commentArrayList: ArrayList<ModelComments>
//adapter set to recyclerView
private lateinit var adapterComment:AdapterComment
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityPdfDetailBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
firebaseAuth = FirebaseAuth.getInstance()
bookId = intent.getStringExtra("bookId")!!
//init progress Bar
progressDialog = ProgressDialog(this)
progressDialog.setTitle("Please Wait...")
progressDialog.setCanceledOnTouchOutside(false)
//increment Notes count,whenever this page starts
MyApplication.incrementBooksViewCount(bookId)
loadBookDetail()
showComments()
binding.backBtn.setOnClickListener {
onBackPressedDispatcher.onBackPressed()
}
//handle read button click
binding.readBookBtn.setOnClickListener {
val intent = Intent(this@PdfDetailActivity, PdfViewActivity::class.java)
intent.putExtra("bookId", bookId)
startActivity(intent)
}
binding.downloadBookBtn.setOnClickListener {
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.WRITE_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED
) {
Log.d(TAG, "onCreate: STORAGE PERMISSION is already granted")
downloadBook()
} else {
Log.d(TAG, "onCreate: STORAGE PERMISSION not granted, LETS request it")
requestStoragePermissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
}
//handle click show comment dialog
binding.addCommentBtn.setOnClickListener {
//user must be logged in to comment
if (firebaseAuth.currentUser == null){
//user not logged in,comment not allowed
Utils.toast(this,"Only Logged in Use can Comment")
}
else{
//user loggged in comment allowed
addCommentDialog()
}
}
}
private fun showComments() {
//init arrayList
commentArrayList = ArrayList()
//db path to loadComments
val ref =FirebaseDatabase.getInstance().getReference("Books")
ref.child(bookId).child("Comments")
.addValueEventListener(object:ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
//clear list
commentArrayList.clear()
for (ds in snapshot.children){
//get data
val model = ds.getValue(ModelComments::class.java)
//add to list
commentArrayList.add(model!!)
}
//setup adapter
adapterComment = AdapterComment(this@PdfDetailActivity,commentArrayList)
binding.commentsRv.adapter = adapterComment
}
override fun onCancelled(error: DatabaseError) {
}
})
}
private var comment = ""
private fun addCommentDialog(){
//inflate view for dialog_comment_add.xml
val commentAddBinding = DialogCommentAddBinding.inflate(LayoutInflater.from(this))
//setup alert dialog
val builder = AlertDialog.Builder(this,R.style.CustomDialog)
builder.setView(commentAddBinding.root)
//create and show alert dialog
val alertDialog = builder.create()
alertDialog.show()
//handle click , dismiss dialog
commentAddBinding.backBtn.setOnClickListener {alertDialog.dismiss()}
// handle click add comment
commentAddBinding.submitBtn.setOnClickListener {
//GET data
comment = commentAddBinding.commentEt.text.toString().trim()
// validate data
if (comment.isEmpty()){
Utils.toast(this,"Enter Comment....")
}else{
addComment()
}
}
}
private fun addComment(){
//show progress
progressDialog.setMessage("Adding Comment")
progressDialog.show()
// timestamp for current id comment timestamp e.t.c
val timestamp = Utils.getTimestamp()
//set data to HashMap
val hashMap = HashMap<String,Any>()
hashMap["id"] = "$timestamp"
hashMap["bookId"] = "$bookId"
hashMap["timestamp"] = "$timestamp"
hashMap["comment"] = "$comment"
hashMap["uid"] = "${firebaseAuth.uid}"
//Db path to add data into it
//Books >bookId >> Comments >> Comment Id >> Comment DATA
val ref = FirebaseDatabase.getInstance().getReference("Books")
ref.child(bookId).child("Comments").child("$timestamp")
.setValue(hashMap).addOnSuccessListener {
progressDialog.dismiss()
Utils.toast(this,"Comment Added Successfully")
}.addOnFailureListener{e ->
progressDialog.dismiss()
Utils.toast(this,"Failed to Comment due to ${e.message} ")
}
}
private val requestStoragePermissionLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
//lets check if granted or not
if (isGranted) {
Log.d(TAG, "onCreate: STORAGE PERMISSION not granted")
} else {
Log.d(TAG, "onCreate: STORAGE PERMISSION not granted")
MotionToast.createColorToast(
this,
"Failed",
"Permission Denied",
MotionToastStyle.WARNING,
MotionToast.GRAVITY_BOTTOM,
MotionToast.LONG_DURATION,
ResourcesCompat.getFont(this, www.sanju.motiontoast.R.font.helvetica_regular)
)
}
}
private fun downloadBook() {
Log.d(TAG, "downloadBook: Downloading Books")
//progress bar
progressDialog.setMessage("Download Book")
progressDialog.show()
//lets download book from firebase storage storage url
val storageReference = FirebaseStorage.getInstance().getReferenceFromUrl(bookUrl)
storageReference.getBytes(Utils.MAX_BYTES_PDF)
.addOnSuccessListener { bytes ->
Log.d(TAG, "downloadBook: Book downloaded...")
saveToDownloadsFolder(bytes)
}
.addOnFailureListener { e ->
progressDialog.dismiss()
Log.d(TAG, "downloadBook: Failed to download book due to ${e.message}")
MotionToast.createColorToast(
this,
"Failed",
"Failed to Download due to ${e.message}",
MotionToastStyle.ERROR,
MotionToast.GRAVITY_BOTTOM,
MotionToast.LONG_DURATION,
ResourcesCompat.getFont(this, www.sanju.motiontoast.R.font.helvetica_regular)
)
}
}
private fun saveToDownloadsFolder(bytes: ByteArray?) {
Log.d(TAG, "saveToDownloadsFolder: saving downloaded book")
val nameWithExtension = "${bookTitle + System.currentTimeMillis()}.pdf"
try {
val downloadsFolder =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
downloadsFolder.mkdirs() // create folder if not exist
val filepath = downloadsFolder.path + "/" + nameWithExtension
val out = FileOutputStream(filepath)
out.write(bytes)
out.close()
MotionToast.createColorToast(
this,
"Successfully",
"Download Successfully",
MotionToastStyle.SUCCESS,
MotionToast.GRAVITY_BOTTOM,
MotionToast.LONG_DURATION,
ResourcesCompat.getFont(this, www.sanju.motiontoast.R.font.helvetica_regular)
)
Log.d(TAG, "saveToDownloadsFolder: Save to Donwlaod Folder")
progressDialog.dismiss()
incrementDownloadCount()
} catch (e: Exception) {
progressDialog.dismiss()
Log.e(TAG, "saveToDownloadsFolder: failed to save due to ${e.message}")
MotionToast.createColorToast(
this,
"Failed",
"Failed to Download due to ${e.message}",
MotionToastStyle.ERROR,
MotionToast.GRAVITY_BOTTOM,
MotionToast.LONG_DURATION,
ResourcesCompat.getFont(this, www.sanju.motiontoast.R.font.helvetica_regular)
)
}
}
private fun loadBookDetail() {
Log.d(TAG, "loadBookDetail: ")
//Books >bookId >Details
val ref = FirebaseDatabase.getInstance().getReference("Books")
ref.child(bookId)
.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
//get data
val categoryId = "${snapshot.child("categoryId").value}"
val description = "${snapshot.child("description").value}"
val downloadsCount = "${snapshot.child("downloadsCount").value}"
val timestamp = snapshot.child("timestamp").value as Long
bookTitle = "${snapshot.child("title").value}"
val uid = "${snapshot.child("uid").value}"
bookUrl = "${snapshot.child("url").value}"
bookImageUrl = "${snapshot.child("imageUrl").value}"
val viewsCount = "${snapshot.child("viewsCount").value}"
val formattedDate = MyApplication.formatTimestampDate(timestamp)
// loadPdfCategory
MyApplication.loadCategory(categoryId, binding.categoryTv)
// load Pdf ThumbNail
// MyApplication.loadPdfFromUrlSinglePage(
// "$bookUrl",
// "$title",
// binding.pdfView,
// binding.progressBar,
// binding.pagesTv
// )
//load boo Image
MyApplication.loadBookImage(
bookImageUrl,
binding.progressBar,
baseContext,
binding.booksImageIv
)
//load pdf size
MyApplication.loadPdfSize(bookUrl, "$title", binding.sizeTv)
//set data
binding.titleTv.text = bookTitle
binding.descriptionTv.text = description
binding.viewsTv.text = viewsCount
binding.downloadsTv.text = downloadsCount
binding.dateTv.text = formattedDate
Log.d(TAG, "onDataChange: Successfully")
}
override fun onCancelled(error: DatabaseError) {
Log.e(TAG, "onCancelled: failed due to $error")
}
})
}
private fun incrementDownloadCount() {
//increment download count
Log.d(TAG, "incrementDownloadCount: ")
val ref = FirebaseDatabase.getInstance().getReference("Books")
ref.child(bookId)
.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
//get download count
var downloadsCount = "${snapshot.child("downloadsCount").value}"
Log.d(
TAG,
"onDataChange: onDataChange: Current Downloads Count $downloadsCount"
)
if (downloadsCount == "" || downloadsCount == "null") {
downloadsCount = "0"
}
//covert to Long and increment
val newDownloadCount: Long = downloadsCount.toLong() + 1
Log.d(TAG, "onDataChange: New Download Count $newDownloadCount")
val hashMap: HashMap<String, Any> = HashMap()
hashMap["downloadsCount"] = newDownloadCount
//Update Increment downloads Count
val dbRef = FirebaseDatabase.getInstance().getReference("Books")
dbRef.child(bookId)
.updateChildren(hashMap)
.addOnSuccessListener {
Log.d(TAG, "onDataChange: Download Count increment")
}.addOnFailureListener { e ->
Log.e(TAG, "onDataChange: Failed to increment due to ${e.message}")
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
} | 0 | Kotlin | 0 | 0 | 3081ccec3bd60dd0680fd620d916f376db073b44 | 15,222 | UniTalk | MIT License |
src/main/kotlin/com/tiquionophist/ui/ScheduleTable.kt | tiquionophist | 405,590,882 | false | null | package com.tiquionophist.ui
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.LocalContentColor
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.painter.BitmapPainter
import com.tiquionophist.core.Lesson
import com.tiquionophist.core.Schedule
import com.tiquionophist.core.ScheduleConfiguration
import com.tiquionophist.core.Subject
import com.tiquionophist.ui.common.ColumnWidth
import com.tiquionophist.ui.common.ColumnWithHeader
import com.tiquionophist.ui.common.Table
import com.tiquionophist.ui.common.TableDivider
import com.tiquionophist.util.prettyName
/**
* A column which displays the period number for each period index row.
*/
private object PeriodNamesColumn : ColumnWithHeader<Int> {
override fun horizontalAlignment(rowIndex: Int) = Alignment.End
@Composable
override fun itemContent(value: Int) {
Text(
text = "Period ${value + 1}",
modifier = Modifier.padding(Dimens.SPACING_2),
)
}
}
/**
* A column which displays the set of [lessons] on a certain day.
*/
private class ScheduleDayColumn(
private val dayName: String,
private val lessons: List<Lesson>
) : ColumnWithHeader<Int> {
override val itemHorizontalAlignment = Alignment.Start
override val itemVerticalAlignment = Alignment.Top
override val width = ColumnWidth.Fixed(width = Dimens.ScheduleTable.CELL_WIDTH)
override fun fillCell(value: Int?): Boolean {
return value != null && lessons[value].subject == Subject.EMPTY
}
@Composable
override fun header() {
Text(
text = dayName,
modifier = Modifier.padding(Dimens.SPACING_2),
)
}
@Composable
override fun itemContent(value: Int) {
val lesson = lessons[value]
val subject = lesson.subject
if (subject == Subject.EMPTY) {
Box(
modifier = Modifier
.fillMaxWidth()
.height(Dimens.ScheduleTable.CELL_HEIGHT)
.background(LocalContentColor.current.copy(alpha = 0.05f))
) {
Text(
text = subject.prettyName,
modifier = Modifier.align(Alignment.Center)
)
}
} else {
Row(
modifier = Modifier.height(Dimens.ScheduleTable.CELL_HEIGHT).padding(Dimens.SPACING_2),
horizontalArrangement = Arrangement.spacedBy(Dimens.SPACING_2)
) {
subject.imageBitmap?.let { imageBitmap ->
Image(
painter = BitmapPainter(imageBitmap),
contentDescription = subject.prettyName,
)
}
Column {
Text(text = subject.prettyName, fontSize = Dimens.FONT_LARGE)
lesson.teacher?.let { teacher ->
Text(text = "by ${teacher.fullName}", fontSize = Dimens.FONT_SMALL)
}
lesson.assignedClassroom?.let { classroom ->
Text(text = "in $classroom", fontSize = Dimens.FONT_SMALL)
}
}
}
}
}
}
/**
* A grid-based view of the lessons in a [schedule] for the class at [classIndex].
*/
@Composable
fun ScheduleTable(configuration: ScheduleConfiguration, schedule: Schedule, classIndex: Int) {
val dayNames = remember(configuration.daysPerWeek) {
@Suppress("MagicNumber")
if (configuration.daysPerWeek == 5) {
listOf("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
} else {
List(configuration.daysPerWeek) { "Day ${it + 1}" }
}
}
val columns = remember(configuration.periodsPerDay, configuration.daysPerWeek, classIndex) {
val periodNamesColumn = PeriodNamesColumn
val chunkedLessons = schedule.lessons[classIndex].chunked(configuration.periodsPerDay)
val scheduleDayColumns = List(configuration.daysPerWeek) { day ->
ScheduleDayColumn(dayName = dayNames[day], lessons = chunkedLessons[day])
}
listOf(periodNamesColumn).plus(scheduleDayColumns)
}
val rows = remember(configuration.periodsPerDay) {
listOf(null).plus(List(configuration.periodsPerDay) { it })
}
Table(
columns = columns,
rows = rows,
// strong divider after the header row, weak dividers between each period row
horizontalDividers = List(rows.size - 1) { rowIndex ->
rowIndex + 1 to TableDivider(
color = if (rowIndex == 0) ThemeColors.current.divider else ThemeColors.current.weakDivider
)
}.toMap(),
// strong divider after the period name column, weak dividers between each day column
verticalDividers = List(columns.size - 1) { colIndex ->
colIndex + 1 to TableDivider(
color = if (colIndex == 0) ThemeColors.current.divider else ThemeColors.current.weakDivider
)
}.toMap(),
)
}
| 1 | Kotlin | 0 | 5 | 157b827f4441b615500b1951da98fb57ecffda86 | 5,688 | hhs-scheduler | MIT License |
java/java-tests/testSrc/com/intellij/roots/LibraryRootsChangedTest.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.roots
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.DisposableRule
import com.intellij.testFramework.rules.ProjectModelRule
import com.intellij.util.io.createDirectories
import com.intellij.util.io.systemIndependentPath
import com.intellij.util.io.zipFile
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
/**
* Checks that proper [com.intellij.openapi.roots.ModuleRootListener.rootsChanged] are sent for changes in library roots.
*/
class LibraryRootsChangedTest {
companion object {
@JvmField
@ClassRule
val appRule = ApplicationRule()
}
@Rule
@JvmField
val projectModel = ProjectModelRule()
@Rule
@JvmField
val disposableRule = DisposableRule()
private lateinit var moduleRootListener: RootsChangedTest.MyModuleRootListener
private lateinit var module: Module
@Before
fun setUp() {
moduleRootListener = RootsChangedTest.MyModuleRootListener(projectModel.project)
projectModel.project.messageBus.connect(disposableRule.disposable).subscribe(ModuleRootListener.TOPIC, moduleRootListener)
module = projectModel.createModule("main")
}
@Test
fun `create library JAR`() {
createLibraryJar("a.jar")
}
@Test
fun `create library JAR in subdirectory`() {
createLibraryJar("lib/a.jar")
}
private fun createLibraryJar(relativePath: String) {
val jarPath = projectModel.baseProjectDir.rootPath.resolve(relativePath)
val jarFile = jarPath.toFile()
val url = VfsUtil.getUrlForLibraryRoot(jarFile)
projectModel.addModuleLevelLibrary(module, "lib") {
it.addRoot(url, OrderRootType.CLASSES)
}
moduleRootListener.reset()
zipFile {
file("a.txt")
}.generate(jarFile)
val manager = VirtualFileManager.getInstance()
manager.refreshAndFindFileByUrl(VfsUtilCore.pathToUrl(jarFile.path))
val file = manager.refreshAndFindFileByUrl(url)
assertThat(file).isNotNull
moduleRootListener.assertEventsCountAndIncrementModificationCount(1, true, false)
}
@Test
fun `create library directory with jar extension`() {
createLibraryDirectory("dir.jar")
}
@Test
fun `create library directory`() {
createLibraryDirectory("dir")
}
@Test
fun `create library directory in subdirectory`() {
createLibraryDirectory("lib/dir")
}
private fun createLibraryDirectory(relativePath: String) {
val path = projectModel.baseProjectDir.rootPath.resolve(relativePath)
val url = VfsUtil.pathToUrl(path.systemIndependentPath)
projectModel.addModuleLevelLibrary(module, "lib") {
it.addRoot(url, OrderRootType.CLASSES)
}
moduleRootListener.reset()
path.createDirectories()
val file = VirtualFileManager.getInstance().refreshAndFindFileByUrl(url)
assertThat(file).isNotNull
moduleRootListener.assertEventsCountAndIncrementModificationCount(1, true, false)
}
} | 284 | null | 5162 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 3,407 | intellij-community | Apache License 2.0 |
vok-framework-vokdb/src/main/kotlin/eu/vaadinonkotlin/vaadin/vokdb/Converters.kt | mvysny | 56,166,503 | false | null | package eu.vaadinonkotlin.vaadin10.vokdb
import com.github.vokorm.KEntity
import com.gitlab.mvysny.jdbiorm.Dao
import com.vaadin.flow.data.binder.Binder
import com.vaadin.flow.data.binder.Result
import com.vaadin.flow.data.binder.ValueContext
import com.vaadin.flow.data.converter.Converter
/**
* Converts an entity to its ID and back. Useful for combo boxes which shows a list of entities as their options while being bound to a
* field containing ID of that entity.
* @param T the type of the entity
* @param ID the type of the ID field of the entity
*/
class EntityToIdConverter<ID: Any, T: KEntity<ID>>(val dao: Dao<T, ID>) : Converter<T?, ID?> {
constructor(clazz: Class<T>) : this(Dao(clazz))
override fun convertToModel(value: T?, context: ValueContext?): Result<ID?> =
Result.ok(value?.id)
override fun convertToPresentation(value: ID?, context: ValueContext?): T? {
if (value == null) return null
return dao.findById(value)
}
}
/**
* Converts an entity to its ID and back. Useful for combo boxes which shows a list of entities as their options while being bound to a
* field containing ID of that entity:
* ```kotlin
* data class Category(override var id: Long? = null, var name: String = "") : Entity<Long>
* data class Review(override var id: Long? = null, var category: Long? = null) : Entity<Long>
*
* // editing the Review, we want the user to be able to choose the Review's category
* val binder = BeanValidationBinder(Review::class.java)
* categoryBox = comboBox("Choose a category") {
* setItemLabelGenerator { it.name }
* isAllowCustomValue = false
* dataProvider = Category.dataProvider
* bind(binder).toId().bind(Review::category)
* }
* ```
*/
inline fun <BEAN, ID: Any, reified ENTITY: KEntity<ID>> Binder.BindingBuilder<BEAN, ENTITY?>.toId(): Binder.BindingBuilder<BEAN, ID?> =
withConverter(EntityToIdConverter(ENTITY::class.java))
| 6 | null | 17 | 186 | aa7fab9c130d8f74e96a4712659e1d8d11ac0d5e | 1,941 | vaadin-on-kotlin | MIT License |
lib/src/main/kotlin/louis2/wear/wff/group/part/draw/shape/Rectangle.kt | LouisCAD | 704,439,760 | false | {"Kotlin": 103017} | package louis2.wear.wff.group.part.draw.shape
import kotlinx.html.TagConsumer
import kotlinx.html.attributesMapOf
import kotlinx.html.visit
import louis2.wear.wff.*
import louis2.wear.wff.group.part.draw.PARTDRAW
/**
* Draws a Rectangle shape.
*
* [AndroidX doc](https://developer.android.com/training/wearables/wff/group/part/draw/shape/rectangle)
*/
@WffTagMarker
inline fun PARTDRAW.rectangle(
x: Float,
y: Float,
width: Float,
height: Float,
crossinline block: RECTANGLE.() -> Unit
): Unit = RECTANGLE(
initialAttributes = attributesMapOf(
"x", x.toString(),
"y", y.toString(),
"width", width.toString(),
"height", height.toString(),
),
consumer = consumer
).visit(block)
class RECTANGLE(
initialAttributes: Map<String, String>,
override val consumer: TagConsumer<*>
) : XMLTag(
tagName = "Rectangle",
consumer = consumer,
initialAttributes = initialAttributes,
namespace = null,
inlineTag = false,
emptyTag = false
), StrokeAble, FillAble, Transformable
| 3 | Kotlin | 0 | 2 | 23b1f99768c43ccbef24078e837753d5ebb6cafc | 1,062 | WatchFaceDsl | Apache License 2.0 |
src/main/kotlin/com/ort/firewolf/application/service/MessageService.kt | h-orito | 282,923,189 | false | {"Kotlin": 964665, "Batchfile": 522, "Shell": 454} | package com.ort.firewolf.application.service
import com.ort.dbflute.allcommon.CDef
import com.ort.firewolf.domain.model.ability.AbilityType
import com.ort.firewolf.domain.model.charachip.Chara
import com.ort.firewolf.domain.model.charachip.Charas
import com.ort.firewolf.domain.model.message.Message
import com.ort.firewolf.domain.model.message.MessageContent
import com.ort.firewolf.domain.model.message.MessageQuery
import com.ort.firewolf.domain.model.message.Messages
import com.ort.firewolf.domain.model.skill.Skills
import com.ort.firewolf.domain.model.village.Village
import com.ort.firewolf.domain.model.village.participant.VillageParticipant
import com.ort.firewolf.domain.service.ability.AbilityDomainService
import com.ort.firewolf.domain.service.coming_out.ComingOutDomainService
import com.ort.firewolf.domain.service.commit.CommitDomainService
import com.ort.firewolf.domain.service.participate.ParticipateDomainService
import com.ort.firewolf.infrastructure.datasource.message.MessageDataSource
import org.springframework.stereotype.Service
@Service
class MessageService(
private val messageDataSource: MessageDataSource,
private val abilityDomainService: AbilityDomainService,
private val participateDomainService: ParticipateDomainService,
private val commitDomainService: CommitDomainService,
private val comingOutDomainService: ComingOutDomainService,
private val notificationService: NotificationService,
) {
/**
* 発言取得
*
* @param villageId villageId
* @param villageDayId 村日付ID
* @param query query
* @return 発言
*/
fun findMessages(
villageId: Int,
villageDayId: Int,
query: MessageQuery
): Messages {
return messageDataSource.findMessages(villageId, villageDayId, query)
}
/**
* 最新発言日時取得
*
* @param villageId villageId
* @param messageTypeList 発言種別
* @param participant 参加情報
* @return 発言
*/
fun findLatestMessagesUnixTimeMilli(
villageId: Int,
messageTypeList: List<CDef.MessageType>,
participant: VillageParticipant? = null
): Long {
return messageDataSource.findLatestMessagesUnixTimeMilli(villageId, messageTypeList, participant)
}
/**
* アンカー発言取得
*
* @param villageId villageId
* @param messageType 発言種別
* @param messageNumber 発言番号
* @return 発言
*/
fun findMessage(villageId: Int, messageType: CDef.MessageType, messageNumber: Int): Message? {
return messageDataSource.findMessage(villageId, messageType, messageNumber)
}
/**
* 参加者のその日の発言数を取得
*/
fun findParticipateDayMessageList(
villageId: Int,
villageDay: com.ort.firewolf.domain.model.village.VillageDay,
participant: VillageParticipant?
): Map<CDef.MessageType, Int> {
participant ?: return mapOf()
return messageDataSource.selectParticipateDayMessageList(villageId, villageDay.id, participant)
}
/**
* 発言登録
*/
fun registerMessage(village: Village, message: Message): Message {
val registered = messageDataSource.registerMessage(village, message)
notificationService.notifyToDeveloperIfNeeded(village.id, registered)
return registered
}
/**
* 村作成時のシステムメッセージ登録
* @param village village
*/
fun registerInitialMessage(village: Village) = registerMessage(village, village.createVillagePrologueMessage())
/**
* 村に参加する際の発言を登録
* @param village village
* @param participant 参加者
* @param chara chara
* @param message message text
* @param isSpectate 見学か
*/
fun registerParticipateMessage(
village: Village,
participant: VillageParticipant,
chara: Chara,
message: String,
isSpectate: Boolean
) {
// {N}人目、{キャラ名}。
messageDataSource.registerMessage(
village,
participateDomainService.createParticipateMessage(village, chara, isSpectate)
)
// 参加発言
val messageContent = MessageContent.invoke(
if (isSpectate) CDef.MessageType.見学発言.code() else CDef.MessageType.通常発言.code(),
message,
CDef.FaceType.通常.code()
)
registerMessage(
village,
Message.createSayMessage(participant, village.day.prologueDay().id, messageContent)
)
}
/**
* 名前変更する際のシステムメッセージを登録
*/
fun registerChangeNameMessage(
village: Village,
before: VillageParticipant,
after: VillageParticipant
) =
registerMessage(
village,
participateDomainService.createChangeNameMessage(village, before, after)
)
/**
* 退村する際のシステムメッセージを登録
*/
fun registerLeaveMessage(village: Village, participant: VillageParticipant) =
registerMessage(
village,
participateDomainService.createLeaveMessage(village, participant)
)
/**
* 能力セットする際のシステムメッセージを登録
* @param village village
* @param participant 村参加者
* @param targetId 対象の村参加者ID
* @param abilityType abilityType
* @param charas キャラ
*/
fun registerAbilitySetMessage(
village: Village,
participant: VillageParticipant,
targetId: Int?,
abilityType: AbilityType,
charas: Charas
) {
val target = targetId?.let { village.participant.member(it) }
val message: Message = abilityDomainService.createAbilitySetMessage(village, participant, target, abilityType)
registerMessage(village, message)
}
/**
* コミットする際のシステムメッセージを登録
*/
fun registerCommitMessage(village: Village, myself: VillageParticipant, doCommit: Boolean) {
registerMessage(
village,
commitDomainService.createCommitMessage(myself, doCommit, village.day.latestDay().id)
)
}
fun registerComingOutMessage(village: Village, myself: VillageParticipant, skills: Skills) {
registerMessage(
village,
comingOutDomainService.createComingOutMessage(myself, skills, village.day.latestDay().id)
)
}
/**
* 差分更新
*/
fun updateDifference(village: Village, before: Messages, after: Messages) {
messageDataSource.updateDifference(village, before, after)
}
} | 0 | Kotlin | 0 | 0 | ec5bc96cfd1ce227c9783dc934dd2d087a9ba38c | 6,376 | firewolf-api | MIT License |
app/src/main/java/com/finderbar/jovian/utilities/api/ApiServices.kt | finderbar | 705,707,975 | false | {"Kotlin": 665596, "Java": 45822} | package com.finderbar.jovian.utilities.api
import com.finderbar.jovian.models.MyFile
import com.finderbar.jovian.models.MyVideo
import okhttp3.MultipartBody
import retrofit2.http.Multipart
import retrofit2.http.POST
import retrofit2.http.Part
import retrofit2.Call
import retrofit2.http.HeaderMap
/**
* Created by finder on 27-Dec-17.
*/
interface ApiServices {
@Multipart
@POST("/avatarUpload")
fun fileUpload(@HeaderMap header: Map<String, String?>, @Part file: MultipartBody.Part) : Call<MyFile>
@Multipart
@POST("/movieUpload")
fun movieUpload(@HeaderMap header: Map<String, String?>, @Part file: MultipartBody.Part) : Call<MyVideo>
} | 0 | Kotlin | 0 | 0 | 63bf5531f367d1892d77151c1baa50789f814b07 | 671 | finderbar-app | MIT License |
css-gg/src/commonMain/kotlin/compose/icons/cssggicons/OpenCollective.kt | DevSrSouza | 311,134,756 | false | {"Kotlin": 36719092} | package compose.icons.cssggicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.CssGgIcons
public val CssGgIcons.OpenCollective: ImageVector
get() {
if (_openCollective != null) {
return _openCollective!!
}
_openCollective = Builder(name = "OpenCollective", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, fillAlpha = 0.5f,
strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(16.682f, 15.753f)
lineTo(18.812f, 17.883f)
curveTo(20.175f, 16.305f, 21.0f, 14.249f, 21.0f, 12.0f)
curveTo(21.0f, 9.787f, 20.202f, 7.761f, 18.877f, 6.194f)
lineTo(16.744f, 8.327f)
curveTo(17.531f, 9.342f, 18.0f, 10.616f, 18.0f, 12.0f)
curveTo(18.0f, 13.42f, 17.507f, 14.725f, 16.682f, 15.753f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(15.673f, 16.744f)
curveTo(14.658f, 17.531f, 13.384f, 18.0f, 12.0f, 18.0f)
curveTo(8.686f, 18.0f, 6.0f, 15.314f, 6.0f, 12.0f)
curveTo(6.0f, 8.686f, 8.686f, 6.0f, 12.0f, 6.0f)
curveTo(13.42f, 6.0f, 14.725f, 6.493f, 15.753f, 7.318f)
lineTo(17.883f, 5.188f)
curveTo(16.305f, 3.825f, 14.249f, 3.0f, 12.0f, 3.0f)
curveTo(7.029f, 3.0f, 3.0f, 7.029f, 3.0f, 12.0f)
curveTo(3.0f, 16.971f, 7.029f, 21.0f, 12.0f, 21.0f)
curveTo(14.213f, 21.0f, 16.239f, 20.202f, 17.806f, 18.877f)
lineTo(15.673f, 16.744f)
close()
}
}
.build()
return _openCollective!!
}
private var _openCollective: ImageVector? = null
| 17 | Kotlin | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 2,776 | compose-icons | MIT License |
app/src/main/java/com/breezefieldombooks/features/viewAllOrder/interf/ProductListNewOrderOnClick.kt | DebashisINT | 876,753,253 | false | {"Kotlin": 17808242, "Java": 1030448} | package com.breezefieldombooks.features.viewAllOrder.interf
import com.breezefieldombooks.app.domain.NewOrderGenderEntity
import com.breezefieldombooks.app.domain.NewOrderProductEntity
interface ProductListNewOrderOnClick {
fun productListOnClick(product: NewOrderProductEntity)
} | 0 | Kotlin | 0 | 0 | 15ee06fe737a9dba90549856cdf40fde8d88dfb3 | 286 | OmBooks | Apache License 2.0 |
komapper-r2dbc/src/main/kotlin/org/komapper/r2dbc/dsl/runner/R2dbcTemplateSelectRunner.kt | komapper | 349,909,214 | false | null | package org.komapper.r2dbc.dsl.runner
import kotlinx.coroutines.flow.Flow
import org.komapper.core.DatabaseConfig
import org.komapper.core.DryRunStatement
import org.komapper.core.dsl.context.TemplateSelectContext
import org.komapper.core.dsl.query.Row
import org.komapper.r2dbc.R2dbcDatabaseConfig
internal class R2dbcTemplateSelectRunner<T, R>(
context: TemplateSelectContext,
transform: (Row) -> T,
private val collect: suspend (Flow<T>) -> R,
) : R2dbcRunner<R> {
private val flowBuilder = R2dbcTemplateSelectFlowBuilder(context, transform)
override fun check(config: DatabaseConfig) {
flowBuilder.check(config)
}
override suspend fun run(config: R2dbcDatabaseConfig): R {
val flow = flowBuilder.build(config)
return collect(flow)
}
override fun dryRun(config: DatabaseConfig): DryRunStatement {
return flowBuilder.dryRun(config)
}
}
| 8 | null | 4 | 97 | 851b313c66645d60f2e86934a5036efbe435396a | 916 | komapper | Apache License 2.0 |
net.akehurst.language/agl-processor/src/commonTest/kotlin/agl/syntaxAnalyser/GrammarTypeModelTest.kt | dhakehurst | 197,245,665 | false | {"Kotlin": 3441810, "ANTLR": 64742, "Rascal": 17698, "Java": 14285, "PEG.js": 6866, "JavaScript": 5287, "BASIC": 22} | /*
* Copyright (C) 2023 Dr. <NAME> (http://dr.david.h.akehurst.net)
*
* 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 net.akehurst.language.agl.grammarTypeModel
import net.akehurst.language.api.grammarTypeModel.GrammarTypeModel
import net.akehurst.language.typemodel.api.asString
import net.akehurst.language.typemodel.test.TypeModelTest
import kotlin.test.fail
object GrammarTypeModelTest {
fun assertEquals(expected: GrammarTypeModel?, actual: GrammarTypeModel?) {
kotlin.test.assertEquals(expected?.asString(), actual?.asString())
when {
(expected == null && actual == null) -> Unit // pass
expected == null -> fail()
actual == null -> fail()
else -> {
kotlin.test.assertEquals(expected.allRuleNameToType.size, actual.allRuleNameToType.size, "number of types in model is different")
for (k in expected.allRuleNameToType.keys) {
val expEl = expected.allRuleNameToType[k]
val actEl = actual.allRuleNameToType[k]
TypeModelTest.tmAssertEquals(expEl, actEl, "TypeModel")
}
TypeModelTest.assertEquals(expected, actual)
}
}
}
} | 2 | Kotlin | 7 | 43 | b225becb87afb0577bebaeff31c256d3f8b85b63 | 1,774 | net.akehurst.language | Apache License 2.0 |
app/src/main/java/com/example/workout_app/Workout.kt | RasmusUK | 858,649,168 | false | {"Kotlin": 32059} | package com.example.workout_app
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
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.graphics.Color
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.UUID
data class Workout(
@SerializedName("name") var name: String,
@SerializedName("id") var id: UUID = UUID.randomUUID(),
@SerializedName("exercises") val exercises: MutableList<Exercise> = mutableStateListOf(),
@SerializedName("date") var date: Date = Date(),
@SerializedName("dateString") val dateString: String = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).format(date)
)
data class Exercise(
@SerializedName("name") val name: String,
@SerializedName("sets") val sets: MutableList<Set> = mutableStateListOf()
)
data class Set(
@SerializedName("reps") val reps: Int,
@SerializedName("weight") val weight: Double,
)
@Composable
fun ExerciseCard(exercise: Exercise, onSetDelete: (Int) -> Unit, onExerciseDelete: () -> Unit, save: () -> Unit) {
var newReps by remember { mutableStateOf("") }
var newWeight by remember { mutableStateOf("") }
var showDialog by remember { mutableStateOf(false) }
var showExerciseDeleteDialog by remember { mutableStateOf(false) } // Add state for exercise delete dialog
var showSetDeleteDialog by remember { mutableStateOf(false) } // Add state for set delete dialog
var setToDelete by remember { mutableStateOf<Int?>(null) }
Card(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Column(
modifier = Modifier
.padding(16.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = exercise.name,
style = MaterialTheme.typography.titleMedium
)
IconButton(onClick = { showExerciseDeleteDialog = true }) {
Icon(Icons.Filled.Delete, contentDescription = "Delete exercise")
}
}
Spacer(modifier = Modifier.height(8.dp))
exercise.sets.forEachIndexed { index, set ->
var editingSet by remember { mutableStateOf(false) }
var reps by remember { mutableStateOf(set.reps.toString()) }
var weight by remember { mutableStateOf(set.weight.toString()) }
if (editingSet) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Row(modifier = Modifier.weight(1f)) {
TextField(
value = reps,
onValueChange = { reps = it },
label = { Text("Reps") },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
modifier = Modifier.width(100.dp)
)
Spacer(modifier = Modifier.width(10.dp))
TextField(
value = weight,
onValueChange = { weight = it },
label = { Text("Weight (kg)") },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
modifier = Modifier.width(100.dp)
)
}
Row {
IconButton(onClick = {
val newReps = reps.toIntOrNull() ?: set.reps
val newWeight = weight.toDoubleOrNull() ?: set.weight
exercise.sets[index] = set.copy(reps = newReps, weight = newWeight)
editingSet = false
save()
}) {
Icon(
imageVector = Icons.Filled.Check,
contentDescription = "Save set",
tint = Color(0xFF006400)
)
}
IconButton(onClick = { editingSet = false }) {
Icon(
imageVector = Icons.Filled.Close,
contentDescription = "Cancel",
tint = Color.Red
)
}
}
}
} else {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(text = "${set.reps} reps x ${set.weight} kg")
Row {
IconButton(onClick = { editingSet = true }) {
Icon(Icons.Filled.Edit, contentDescription = "Edit set")
}
IconButton(onClick = {
setToDelete = index
showSetDeleteDialog = true
}) {
Icon(Icons.Filled.Delete, contentDescription = "Delete set")
}
}
}
}
}
Spacer(modifier = Modifier.height(8.dp))
Button(onClick = { showDialog = true }) {
Text("Add set")
}
if (showDialog) {
AlertDialog(
onDismissRequest = { showDialog = false },
title = { Text("Add set") },
text = {
Column {
TextField(
value = newReps,
onValueChange = { newReps = it },
label = { Text("Reps") },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
TextField(
value = newWeight,
onValueChange = { newWeight = it },
label = { Text("Weight (kg)") },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
}
},
confirmButton = {
Button(onClick = {
val reps = newReps.toIntOrNull() ?: 0
val weight = newWeight.toDoubleOrNull() ?: 0.0
exercise.sets.add(Set(reps, weight))
save()
newReps = ""
newWeight = ""
showDialog = false
}) {
Text("OK")
}
},
dismissButton = {
Button(onClick = { showDialog = false }) {
Text("Cancel")
}
}
)
}
}
}
ConfirmationDialog(
showDialog = showExerciseDeleteDialog,
onDismiss = { showExerciseDeleteDialog = false },
onConfirm = {
onExerciseDelete()
save()
showExerciseDeleteDialog = false
},
title = "Confirm Delete",
text = "Are you sure you want to delete this exercise?"
)
ConfirmationDialog(
showDialog = showSetDeleteDialog,
onDismiss = {
showSetDeleteDialog = false
setToDelete = null
},
onConfirm = {
setToDelete?.let {
onSetDelete(it)
save()
showSetDeleteDialog = false
setToDelete = null
}
},
title = "Confirm Delete",
text = "Are you sure you want to delete this set?"
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WorkoutScreen(workout: Workout, onWorkoutDelete: () -> Unit, navController: NavController, save: () -> Unit, exerciseOptions: List<String>, viewModel: WorkoutViewModel) {
var showDialog by remember { mutableStateOf(false) }
var selectedExercise by remember { mutableStateOf("") }
var showWorkoutDeleteDialog by remember { mutableStateOf(false) }
Scaffold(
topBar = {
TopAppBar(title = { Text("Workout details") },
navigationIcon = {
IconButton(onClick = { navController.popBackStack() }) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, "backIcon")
}
})
},
floatingActionButton = {
FloatingActionButton(onClick = { showDialog = true }) {
Icon(imageVector = Icons.Filled.Add, contentDescription = "Add exercise")
}
}
) { contentPadding ->
LazyColumn(modifier = Modifier
.padding(contentPadding)
.fillMaxSize()
) {
item {
Column(modifier = Modifier.padding(16.dp)) {
Text(text = "Name: ${workout.name}", style = MaterialTheme.typography.titleSmall)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(text = "Date: ${workout.dateString}", style = MaterialTheme.typography.titleSmall)
IconButton(onClick = {
showWorkoutDeleteDialog = true
}) {
Icon(Icons.Filled.Delete, contentDescription = "Delete Workout")
}
}
Spacer(modifier = Modifier.height(16.dp))
}
}
items(workout.exercises) { exercise ->
ExerciseCard(exercise, onSetDelete = { index ->
exercise.sets.removeAt(index)
},
onExerciseDelete = {
workout.exercises.remove(exercise)
}, save)
}
}
if (showDialog) {
AlertDialog(
onDismissRequest = { showDialog = false },
title = { Text("Add exercise") },
text = {
CustomDropdownMenu(
options = exerciseOptions,
selectedOption = selectedExercise,
onOptionSelected = { selectedExercise = it }
)
},
confirmButton = {
Button(onClick = {
if (selectedExercise.isNotBlank()) {
val name = selectedExercise.trim()
val existingExercise = viewModel.getExistingExercise(name)
if (existingExercise != null) {
val gson = Gson()
val exerciseCopy = gson.fromJson(gson.toJson(existingExercise), Exercise::class.java)
workout.exercises.add(exerciseCopy)
}
else{
workout.exercises.add(Exercise(name))
}
save()
selectedExercise = ""
showDialog = false
}
}) {
Text("OK")
}
},
dismissButton = {
Button(onClick = { showDialog = false }) {
Text("Cancel")
}
}
)
}
}
ConfirmationDialog(
showDialog = showWorkoutDeleteDialog,
onDismiss = { showWorkoutDeleteDialog = false },
onConfirm = {
onWorkoutDelete()
navController.popBackStack()
},
title = "Confirm Delete",
text = "Are you sure you want to delete this workout?"
)
} | 0 | Kotlin | 0 | 0 | d799ada23567514fd3b59989ae4ccfc393fbe07f | 15,238 | workout-tracking-app | MIT License |
app/src/main/kotlin/com/francescsoftware/mosaic/data/image/ImageRepositoryImpl.kt | fvilarino | 487,330,720 | false | {"Kotlin": 67941} | package com.francescsoftware.mosaic.data.image
import com.francescsoftware.mosaic.core.dispatcher.DispatcherProvider
import com.francescsoftware.mosaic.core.wrapper.ImageUrl
import com.francescsoftware.mosaic.core.wrapper.Result
import kotlinx.coroutines.withContext
import javax.inject.Inject
private const val IMAGE_DIMENSION_START = 300
private const val BASE_URL = "https://placekitten.com/"
class ImageRepositoryImpl @Inject constructor(
private val dispatcherProvider: DispatcherProvider,
) : ImageRepository {
override suspend fun getImages(size: Int): Result<List<ImageUrl>> =
withContext(dispatcherProvider.Default) {
Result.Success(
List(size) { index ->
val width = IMAGE_DIMENSION_START + (10 * (index / 10))
val height = IMAGE_DIMENSION_START + (10 * (index % 10))
ImageUrl(
url = "$BASE_URL$width/$height"
)
}
)
}
}
| 0 | Kotlin | 1 | 2 | 4b054516345ec19957ea798ba1449728c9ab5903 | 1,017 | Mosaic | Apache License 2.0 |
src/main/kotlin/io/github/pandier/intellijdiscordrp/settings/DiscordSettings.kt | pandier | 768,334,300 | false | null | package io.github.pandier.intellijdiscordrp.settings
import io.github.pandier.intellijdiscordrp.activity.ActivityDisplayMode
import io.github.pandier.intellijdiscordrp.activity.ActivityFactory
data class DiscordSettings(
var reconnectOnUpdate: Boolean = true,
var customApplicationIdEnabled: Boolean = false,
var customApplicationId: String = "",
var defaultDisplayMode: ActivityDisplayMode = ActivityDisplayMode.FILE,
var logoStyle: LogoStyleSetting = LogoStyleSetting.MODERN,
var applicationDetails: String = "",
var applicationState: String = "",
var applicationLargeImage: ImageSetting = ImageSetting.APPLICATION,
var applicationLargeImageEnabled: Boolean = true,
var applicationLargeImageText: String = "{app_name}",
var applicationSmallImage: ImageSetting = ImageSetting.APPLICATION,
var applicationSmallImageEnabled: Boolean = false,
var applicationSmallImageText: String = "",
var applicationTimestampEnabled: Boolean = true,
var projectDetails: String = "In {project_name}",
var projectState: String = "",
var projectLargeImage: ImageSetting = ImageSetting.APPLICATION,
var projectLargeImageEnabled: Boolean = true,
var projectLargeImageText: String = "{app_name}",
var projectSmallImage: ImageSetting = ImageSetting.APPLICATION,
var projectSmallImageEnabled: Boolean = false,
var projectSmallImageText: String = "",
var projectTimestampEnabled: Boolean = true,
var fileDetails: String = "In {project_name}",
var fileState: String = "Editing {file_name}",
var fileLargeImage: ImageSetting = ImageSetting.FILE,
var fileLargeImageEnabled: Boolean = true,
var fileLargeImageText: String = "{file_type}",
var fileSmallImage: ImageSetting = ImageSetting.APPLICATION,
var fileSmallImageEnabled: Boolean = true,
var fileSmallImageText: String = "{app_name}",
var fileTimestampEnabled: Boolean = true,
) {
val applicationActivityFactory: ActivityFactory
get() = ActivityFactory(
displayMode = ActivityDisplayMode.APPLICATION,
logoStyle = logoStyle,
details = applicationDetails,
state = applicationState,
largeImage = if (applicationLargeImageEnabled) applicationLargeImage else null,
largeImageText = applicationLargeImageText,
smallImage = if (applicationSmallImageEnabled) applicationSmallImage else null,
smallImageText = applicationSmallImageText,
timestampEnabled = applicationTimestampEnabled,
)
val projectActivityFactory: ActivityFactory
get() = ActivityFactory(
displayMode = ActivityDisplayMode.PROJECT,
logoStyle = logoStyle,
details = projectDetails,
state = projectState,
largeImage = if (projectLargeImageEnabled) projectLargeImage else null,
largeImageText = projectLargeImageText,
smallImage = if (projectSmallImageEnabled) projectSmallImage else null,
smallImageText = projectSmallImageText,
timestampEnabled = projectTimestampEnabled,
)
val fileActivityFactory: ActivityFactory
get() = ActivityFactory(
displayMode = ActivityDisplayMode.FILE,
logoStyle = logoStyle,
details = fileDetails,
state = fileState,
largeImage = if (fileLargeImageEnabled) fileLargeImage else null,
largeImageText = fileLargeImageText,
smallImage = if (fileSmallImageEnabled) fileSmallImage else null,
smallImageText = fileSmallImageText,
timestampEnabled = fileTimestampEnabled,
)
fun getActivityFactory(mode: ActivityDisplayMode) = when (mode) {
ActivityDisplayMode.APPLICATION -> applicationActivityFactory
ActivityDisplayMode.PROJECT -> projectActivityFactory
ActivityDisplayMode.FILE -> fileActivityFactory
}
}
| 6 | null | 3 | 8 | 384d8354c59e1ffdb4053852630d6862e71b7802 | 3,963 | intellij-discord-rp | MIT License |
plugins/hh-carnival/src/main/kotlin/ru/hh/android/plugin/services/jira/JiraLinkFactory.kt | hhru | 159,637,875 | false | null | package ru.hh.android.plugin.services.jira
import com.atlassian.jira.rest.client.api.domain.input.LinkIssuesInput
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import ru.hh.android.plugin.core.model.jira.JiraLinkType
@Service
class JiraLinkFactory {
companion object {
fun getInstance(project: Project): JiraLinkFactory = project.service()
}
fun issueConsistsInAnotherIssue(consistingIssueKey: String, includingIssueKey: String): LinkIssuesInput {
return LinkIssuesInput(
includingIssueKey,
consistingIssueKey,
JiraLinkType.INCLUSION.remoteName,
null
)
}
} | 17 | null | 18 | 97 | 2d6c02fc814eff3934c17de77ef7ade91d3116f5 | 741 | android-multimodule-plugin | MIT License |
platform/backend/core/src/main/kotlin/io/hamal/core/req/SubmitRequest.kt | hamal-io | 622,870,037 | false | {"Kotlin": 1678862, "C": 1398401, "TypeScript": 47224, "Lua": 41508, "C++": 40651, "Makefile": 11728, "Java": 7564, "CMake": 2881, "JavaScript": 1532, "HTML": 694, "Shell": 449, "CSS": 118} | package io.hamal.core.req
import io.hamal.core.component.EncodePassword
import io.hamal.core.component.GenerateSalt
import io.hamal.core.component.GenerateToken
import io.hamal.core.req.req.CreateRootAccountReq
import io.hamal.lib.domain.CorrelatedState
import io.hamal.lib.domain.Event
import io.hamal.lib.domain.GenerateDomainId
import io.hamal.lib.domain.ReqId
import io.hamal.lib.domain._enum.ReqStatus.Submitted
import io.hamal.lib.domain.vo.*
import io.hamal.lib.domain.vo.AccountType.Root
import io.hamal.repository.api.*
import io.hamal.repository.api.log.BrokerRepository
import io.hamal.repository.api.submitted_req.*
import io.hamal.request.*
import org.springframework.stereotype.Component
data class InvokeExecReq(
val execId: ExecId,
val funcId: FuncId,
val correlationId: CorrelationId?,
val inputs: InvocationInputs,
val code: CodeValue?,
val codeId: CodeId?,
val codeVersion: CodeVersion?,
val events: List<Event>
)
@Component
class SubmitRequest(
private val generateDomainId: GenerateDomainId,
private val reqCmdRepository: ReqCmdRepository,
private val funcQueryRepository: FuncQueryRepository,
private val namespaceQueryRepository: NamespaceQueryRepository,
private val generateSalt: GenerateSalt,
private val encodePassword: EncodePassword,
private val generateToken: GenerateToken,
private val execQueryRepository: ExecQueryRepository,
private val eventBrokerRepository: BrokerRepository
) {
operator fun invoke(req: CreateRootAccountReq): SubmittedCreateAccountWithPasswordReq {
val salt = generateSalt()
return SubmittedCreateAccountWithPasswordReq(
reqId = generateDomainId(::ReqId),
status = Submitted,
id = AccountId.root,
type = Root,
groupId = GroupId.root,
namespaceId = generateDomainId(::NamespaceId),
name = req.name,
email = req.email,
authenticationId = generateDomainId(::AuthId),
hash = encodePassword(
password = <PASSWORD>, salt = salt
),
salt = salt,
token = generateToken()
).also(reqCmdRepository::queue)
}
operator fun invoke(req: InvokeExecReq): SubmittedInvokeExecReq {
val func = funcQueryRepository.get(req.funcId)
return SubmittedInvokeExecReq(
reqId = generateDomainId(::ReqId),
status = Submitted,
id = generateDomainId(::ExecId),
groupId = func.groupId,
funcId = req.funcId,
correlationId = req.correlationId,
inputs = req.inputs,
code = req.code,
codeId = req.codeId,
codeVersion = req.codeVersion,
events = listOf()
).also(reqCmdRepository::queue)
}
operator fun invoke(account: Account, password: Password): SubmittedSignInWithPasswordReq {
val encodedPassword = encodePassword(password, account.salt)
return SubmittedSignInWithPasswordReq(
reqId = generateDomainId(::ReqId),
status = Submitted,
authId = generateDomainId(::AuthId),
accountId = account.id,
hash = encodedPassword,
token = generateToken()
).also(reqCmdRepository::queue)
}
operator fun invoke(req: CreateAccountReq): SubmittedCreateAccountWithPasswordReq {
val salt = generateSalt()
return SubmittedCreateAccountWithPasswordReq(
reqId = generateDomainId(::ReqId),
status = Submitted,
id = generateDomainId(::AccountId),
type = AccountType.Enjoyer,
groupId = generateDomainId(::GroupId),
namespaceId = generateDomainId(::NamespaceId),
name = req.name,
email = req.email,
authenticationId = generateDomainId(::AuthId),
hash = encodePassword(
password = req.password ?: throw NoSuchElementException("Account not found"), salt = salt
),
salt = salt,
token = generateToken()
).also(reqCmdRepository::queue)
}
operator fun invoke(groupId: GroupId, req: InvokeAdhocReq) = SubmittedInvokeExecReq(
reqId = generateDomainId(::ReqId),
status = Submitted,
id = generateDomainId(::ExecId),
groupId = groupId,
inputs = req.inputs,
code = req.code,
codeId = null,
codeVersion = null,
funcId = null,
correlationId = null,
events = listOf()
).also(reqCmdRepository::queue)
operator fun invoke(funcId: FuncId, req: InvokeFuncReq): SubmittedInvokeExecReq {
val func = funcQueryRepository.get(funcId)
return SubmittedInvokeExecReq(
reqId = generateDomainId(::ReqId),
status = Submitted,
id = generateDomainId(::ExecId),
groupId = func.groupId,
funcId = funcId,
correlationId = req.correlationId,
inputs = req.inputs ?: InvocationInputs(),
code = null,
codeId = func.codeId,
codeVersion = func.codeVersion,
events = listOf()
).also(reqCmdRepository::queue)
}
operator fun invoke(execId: ExecId, req: CompleteExecReq) = SubmittedCompleteExecReq(
reqId = generateDomainId(::ReqId),
status = Submitted,
groupId = execQueryRepository.get(execId).groupId,
id = execId,
state = req.state,
events = req.events
).also(reqCmdRepository::queue)
operator fun invoke(execId: ExecId, req: FailExecReq) = SubmittedFailExecReq(
reqId = generateDomainId(::ReqId),
status = Submitted,
groupId = execQueryRepository.get(execId).groupId,
id = execId,
cause = req.cause
).also(reqCmdRepository::queue)
operator fun invoke(groupId: GroupId, req: CreateFuncReq) = SubmittedCreateFuncReq(
reqId = generateDomainId(::ReqId),
status = Submitted,
id = generateDomainId(::FuncId),
groupId = groupId,
namespaceId = req.namespaceId ?: namespaceQueryRepository.find(NamespaceName("hamal"))!!.id,
name = req.name,
inputs = req.inputs,
code = req.code,
codeId = generateDomainId(::CodeId)
).also(reqCmdRepository::queue)
operator fun invoke(funcId: FuncId, req: UpdateFuncReq) = SubmittedUpdateFuncReq(
reqId = generateDomainId(::ReqId),
status = Submitted,
groupId = funcQueryRepository.get(funcId).groupId,
id = funcId,
namespaceId = req.namespaceId,
name = req.name,
inputs = req.inputs,
code = req.code,
).also(reqCmdRepository::queue)
operator fun invoke(groupId: GroupId, req: CreateNamespaceReq) = SubmittedCreateNamespaceReq(
reqId = generateDomainId(::ReqId),
status = Submitted,
id = generateDomainId(::NamespaceId),
groupId = groupId,
name = req.name,
inputs = req.inputs
).also(reqCmdRepository::queue)
operator fun invoke(namespaceId: NamespaceId, req: UpdateNamespaceReq) = SubmittedUpdateNamespaceReq(
reqId = generateDomainId(::ReqId),
status = Submitted,
groupId = namespaceQueryRepository.get(namespaceId).groupId,
id = namespaceId,
name = req.name,
inputs = req.inputs
).also(reqCmdRepository::queue)
operator fun invoke(req: CreateTriggerReq): SubmittedCreateTriggerReq {
val func = funcQueryRepository.get(req.funcId)
return SubmittedCreateTriggerReq(
type = req.type,
reqId = generateDomainId(::ReqId),
status = Submitted,
id = generateDomainId(::TriggerId),
groupId = func.groupId,
name = req.name,
funcId = func.id,
namespaceId = req.namespaceId,
inputs = req.inputs,
correlationId = req.correlationId,
duration = req.duration,
topicId = req.topicId
).also(reqCmdRepository::queue)
}
operator fun invoke(groupId: GroupId, req: CreateTopicReq) = SubmittedCreateTopicReq(
reqId = generateDomainId(::ReqId),
status = Submitted,
groupId = groupId,
id = generateDomainId(::TopicId),
name = req.name
).also(reqCmdRepository::queue)
operator fun invoke(req: AppendEntryReq): SubmittedAppendToTopicReq {
val topic = eventBrokerRepository.getTopic(req.topicId)
return SubmittedAppendToTopicReq(
reqId = generateDomainId(::ReqId),
status = Submitted,
groupId = topic.groupId,
id = req.topicId,
payload = req.payload
).also(reqCmdRepository::queue)
}
operator fun invoke(req: SetStateReq): SubmittedSetStateReq {
val func = funcQueryRepository.get(req.correlation.funcId)
return SubmittedSetStateReq(
reqId = generateDomainId(::ReqId), status = Submitted, groupId = func.groupId, state = CorrelatedState(
correlation = req.correlation, value = req.value
)
).also(reqCmdRepository::queue)
}
}
| 6 | Kotlin | 0 | 0 | fd06bf799f18db2d425b7084abf15b741fa9878e | 9,259 | hamal | Creative Commons Zero v1.0 Universal |
compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/IrValidator.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.backend.common
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.config.IrVerificationMode
import org.jetbrains.kotlin.ir.IrBuiltIns
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.declarations.IrDeclaration
import org.jetbrains.kotlin.ir.declarations.IrDeclarationParent
import org.jetbrains.kotlin.ir.declarations.IrFile
import org.jetbrains.kotlin.ir.util.DeclarationParentsVisitor
import org.jetbrains.kotlin.ir.util.dump
import org.jetbrains.kotlin.ir.util.render
import org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid
import org.jetbrains.kotlin.ir.visitors.acceptChildrenVoid
import org.jetbrains.kotlin.ir.visitors.acceptVoid
typealias ReportIrValidationError = (IrFile?, IrElement, String, List<IrElement>) -> Unit
internal data class IrValidatorConfig(
val checkTypes: Boolean = true,
val checkProperties: Boolean = false,
val checkScopes: Boolean = false, // TODO: Consider setting to true by default and deleting
)
private class IrValidator(
irBuiltIns: IrBuiltIns,
val config: IrValidatorConfig,
val reportError: ReportIrValidationError
) : IrElementVisitorVoid {
var currentFile: IrFile? = null
private val parentChain = mutableListOf<IrElement>()
override fun visitFile(declaration: IrFile) {
currentFile = declaration
super.visitFile(declaration)
if (config.checkScopes) {
ScopeValidator(this::error, parentChain).check(declaration)
}
}
private fun error(element: IrElement, message: String) {
reportError(currentFile, element, message, parentChain)
}
private val elementChecker = CheckIrElementVisitor(irBuiltIns, this::error, config)
override fun visitElement(element: IrElement) {
element.acceptVoid(elementChecker)
parentChain.push(element)
element.acceptChildrenVoid(this)
parentChain.pop()
}
}
private fun IrElement.checkDeclarationParents(reportError: ReportIrValidationError) {
val checker = CheckDeclarationParentsVisitor()
accept(checker, null)
if (checker.errors.isNotEmpty()) {
val expectedParents = LinkedHashSet<IrDeclarationParent>()
reportError(
null,
this,
buildString {
append("Declarations with wrong parent: ")
append(checker.errors.size)
append("\n")
checker.errors.forEach {
append("declaration: ")
append(it.declaration.render())
append("\nexpectedParent: ")
append(it.expectedParent.render())
append("\nactualParent: ")
append(it.actualParent?.render())
}
append("\nExpected parents:\n")
expectedParents.forEach {
append(it.dump())
}
},
emptyList(),
)
}
}
private class CheckDeclarationParentsVisitor : DeclarationParentsVisitor() {
class Error(val declaration: IrDeclaration, val expectedParent: IrDeclarationParent, val actualParent: IrDeclarationParent?)
val errors = ArrayList<Error>()
override fun handleParent(declaration: IrDeclaration, actualParent: IrDeclarationParent) {
try {
val assignedParent = declaration.parent
if (assignedParent != actualParent) {
errors.add(Error(declaration, assignedParent, actualParent))
}
} catch (e: Exception) {
errors.add(Error(declaration, actualParent, null))
}
}
}
open class IrValidationError(message: String? = null) : IllegalStateException(message)
class DuplicateIrNodeError(element: IrElement) : IrValidationError(element.render())
/**
* Verifies common IR invariants that should hold in all the backends.
*/
private fun performBasicIrValidation(
element: IrElement,
irBuiltIns: IrBuiltIns,
checkProperties: Boolean = false,
checkTypes: Boolean = false,
reportError: ReportIrValidationError,
) {
val validatorConfig = IrValidatorConfig(
checkTypes = checkTypes,
checkProperties = checkProperties,
)
val validator = IrValidator(irBuiltIns, validatorConfig, reportError)
try {
element.acceptVoid(validator)
} catch (e: DuplicateIrNodeError) {
// Performing other checks may cause e.g. infinite recursion.
return
}
element.checkDeclarationParents(reportError)
}
/**
* [IrValidationContext] is responsible for collecting validation errors, logging them and optionally throwing [IrValidationError]
* (if the verification mode passed to [validateIr] is [IrVerificationMode.ERROR])
*/
sealed interface IrValidationContext {
/**
* Logs the validation error into the underlying [MessageCollector].
*/
fun reportIrValidationError(
file: IrFile?,
element: IrElement,
message: String,
phaseName: String,
parentChain: List<IrElement> = emptyList(),
)
/**
* Allows to abort the compilation process if after or during validating the IR there were errors and the verification mode is
* [IrVerificationMode.ERROR].
*/
fun throwValidationErrorIfNeeded()
/**
* Verifies common IR invariants that should hold in all the backends.
*
* Reports errors to [CommonBackendContext.messageCollector].
*
* **Note:** this method does **not** throw [IrValidationError]. Use [throwValidationErrorIfNeeded] for checking for errors and throwing
* [IrValidationError]. This gives the caller the opportunity to perform additional (for example, backend-specific) validation before
* aborting. The caller decides when it's time to abort.
*/
fun performBasicIrValidation(
fragment: IrElement,
irBuiltIns: IrBuiltIns,
phaseName: String,
checkProperties: Boolean = false,
checkTypes: Boolean = false,
) {
performBasicIrValidation(
fragment,
irBuiltIns,
checkProperties,
checkTypes,
) { file, element, message, parentChain ->
reportIrValidationError(file, element, message, phaseName, parentChain)
}
}
}
private class IrValidationContextImpl(
private val messageCollector: MessageCollector,
private val mode: IrVerificationMode
) : IrValidationContext {
private var hasValidationErrors: Boolean = false
override fun reportIrValidationError(
file: IrFile?,
element: IrElement,
message: String,
phaseName: String,
parentChain: List<IrElement>,
) {
val severity = when (mode) {
IrVerificationMode.WARNING -> CompilerMessageSeverity.WARNING
IrVerificationMode.ERROR -> CompilerMessageSeverity.ERROR
IrVerificationMode.NONE -> return
}
hasValidationErrors = true
val phaseMessage = if (phaseName.isNotEmpty()) "$phaseName: " else ""
messageCollector.report(
severity,
buildString {
append("[IR VALIDATION] ")
append(phaseMessage)
appendLine(message)
append(element.render())
for ((i, parent) in parentChain.asReversed().withIndex()) {
appendLine()
append(" ".repeat(i + 1))
append("inside ")
append(parent.render())
}
},
file?.let(element::getCompilerMessageLocation),
)
}
override fun throwValidationErrorIfNeeded() {
if (hasValidationErrors && mode == IrVerificationMode.ERROR) {
throw IrValidationError()
}
}
}
/**
* Logs validation errors encountered during the execution of the [runValidationRoutines] closure into [messageCollector].
*
* If [mode] is [IrVerificationMode.ERROR], throws [IrValidationError] after [runValidationRoutines] has finished,
* thus allowing to collect as many errors as possible instead of aborting after the first one.
*/
fun validateIr(
messageCollector: MessageCollector,
mode: IrVerificationMode,
runValidationRoutines: IrValidationContext.() -> Unit,
) {
if (mode == IrVerificationMode.NONE) return
val validationContext = IrValidationContextImpl(messageCollector, mode)
validationContext.runValidationRoutines()
validationContext.throwValidationErrorIfNeeded()
}
| 182 | null | 5646 | 48,182 | bc1ddd8205f6107c7aec87a9fb3bd7713e68902d | 8,868 | kotlin | Apache License 2.0 |
snark-storage-driver/src/main/kotlin/space/kscience/snark/storage/s3/S3File.kt | SciProgCentre | 507,609,502 | false | {"Kotlin": 191863, "Java": 82765, "JavaScript": 829, "Shell": 722, "Python": 566, "Dockerfile": 542} | package space.kscience.snark.storage.s3
import aws.sdk.kotlin.services.s3.S3Client
import aws.sdk.kotlin.services.s3.model.GetObjectRequest
import aws.sdk.kotlin.services.s3.putObject
import aws.smithy.kotlin.runtime.content.ByteStream
import aws.smithy.kotlin.runtime.content.toByteArray
import space.kscience.snark.storage.FileReader
import space.kscience.snark.storage.FileWriter
import java.nio.file.Path
internal class S3FileReader(private val client: S3Client, private val bucketName: String, private val path: Path) :
FileReader {
override suspend fun readAll(): ByteArray {
val result = client.getObject(GetObjectRequest {
bucket = bucketName
key = path.toString()
}) {
it.body?.toByteArray() ?: ByteArray(0)
}
return result
}
override fun close() {
}
}
internal class S3FileWriter(private val client: S3Client, private val bucketName: String, private val path: Path) :
FileWriter {
override suspend fun write(bytes: ByteArray) {
client.putObject {
bucket = bucketName
key = path.toString()
body = ByteStream.fromBytes(bytes)
}
}
override fun close() {
}
} | 0 | Kotlin | 0 | 5 | fb115e1ecbbb63adf87f18e0b3209f0ff6da1303 | 1,230 | snark | Apache License 2.0 |
presentation/src/main/java/com/wasin/presentation/splash/SplashScreen.kt | wa-sin-sang-dam | 828,217,645 | false | {"Kotlin": 301042} | package com.wasin.presentation.splash
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.wasin.presentation.R
import com.wasin.presentation._util.WasinBackHandler
import kotlinx.coroutines.delay
@Composable
fun SplashScreen(
navController: NavController,
viewModel: SplashViewModel = hiltViewModel()
) {
WasinBackHandler()
LaunchedEffect(key1 = true){
delay(500)
navController.popBackStack()
navController.navigate(viewModel.getScreen())
}
Box (
modifier = Modifier.fillMaxSize()
) {
Image(
painter = painterResource(id = R.drawable.wasin_logo),
contentDescription = "wasin_logo",
modifier = Modifier
.height(200.dp)
.align(Alignment.Center)
)
}
}
| 2 | Kotlin | 0 | 0 | 28a58078ff866f6f9baa460714217884fdbea3ab | 1,288 | wasin-android | MIT License |
presentation/src/main/java/com/wasin/presentation/splash/SplashScreen.kt | wa-sin-sang-dam | 828,217,645 | false | {"Kotlin": 301042} | package com.wasin.presentation.splash
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.wasin.presentation.R
import com.wasin.presentation._util.WasinBackHandler
import kotlinx.coroutines.delay
@Composable
fun SplashScreen(
navController: NavController,
viewModel: SplashViewModel = hiltViewModel()
) {
WasinBackHandler()
LaunchedEffect(key1 = true){
delay(500)
navController.popBackStack()
navController.navigate(viewModel.getScreen())
}
Box (
modifier = Modifier.fillMaxSize()
) {
Image(
painter = painterResource(id = R.drawable.wasin_logo),
contentDescription = "wasin_logo",
modifier = Modifier
.height(200.dp)
.align(Alignment.Center)
)
}
}
| 2 | Kotlin | 0 | 0 | 28a58078ff866f6f9baa460714217884fdbea3ab | 1,288 | wasin-android | MIT License |
kodein-di/src/jvmTest/kotlin/org/kodein/di/GenericJvmTests_16_Multiton.kt | kosi-libs | 34,046,231 | false | null | package org.kodein.di.erased
import org.kodein.di.Kodein
import org.kodein.di.bindings.ScopeCloseable
import org.kodein.di.bindings.SingleItemScopeRegistry
import org.kodein.di.bindings.UnboundedScope
import org.kodein.di.test.CloseableData
import org.kodein.di.test.FixMethodOrder
import org.kodein.di.test.MethodSorters
import org.kodein.di.test.Person
import kotlin.test.*
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class ErasedTests_16_Multiton {
@Test
fun test_00_Multiton() {
val kodein = Kodein { bind() from multiton { name: String -> Person(name) } }
val p1: Person by kodein.instance(arg = "Salomon")
val p2: Person by kodein.instance(fArg = { "Salomon" })
val p3: Person by kodein.instance(arg = "Laila")
val p4: Person by kodein.instance(fArg = { "Laila" })
assertSame(p1, p2)
assertSame(p3, p4)
assertNotSame(p1, p3)
assertEquals("Salomon", p1.name)
assertEquals("Laila", p3.name)
}
@Test
fun test_01_MultitonWithSingleItemScope() {
val myScope = UnboundedScope(SingleItemScopeRegistry())
val kodein = Kodein {
bind<CloseableData>() with scoped(myScope).multiton { name: String -> CloseableData(name) }
}
val a: CloseableData by kodein.instance(arg = "one")
val b: CloseableData by kodein.instance(arg = "one")
assertSame(a, b)
val c: CloseableData by kodein.instance(arg = "two")
assertNotSame(a, c)
assertTrue(a.closed)
assertFalse(c.closed)
val d: CloseableData by kodein.instance(arg = "one")
assertNotSame(c, d)
assertNotSame(a, d)
assertTrue(c.closed)
assertFalse(d.closed)
}
@Test
fun test_02_NonSyncedMultiton() {
val kodein = Kodein { bind() from multiton(sync = false) { name: String -> Person(name) } }
val p1: Person by kodein.instance(arg = "Salomon")
val p2: Person by kodein.instance(fArg = { "Salomon" })
val p3: Person by kodein.instance(arg = "Laila")
val p4: Person by kodein.instance(fArg = { "Laila" })
assertSame(p1, p2)
assertSame(p3, p4)
assertNotSame(p1, p3)
assertEquals("Salomon", p1.name)
assertEquals("Laila", p3.name)
}
}
| 6 | null | 174 | 3,189 | 573b264a3f6f5f7145583081efc318c4303fc4d2 | 2,314 | Kodein | MIT License |
src/test/java/pl/edu/amu/wmi/erykandroidcommon/test/PowerMockTest.kt | dagi12 | 107,324,186 | false | {"Gradle": 1, "Proguard": 1, "Text": 1, "Ignore List": 1, "Markdown": 1, "Java": 2, "Kotlin": 88, "XML": 19} | package pl.edu.amu.wmi.erykandroidcommon.test
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.powermock.api.mockito.PowerMockito
import org.powermock.api.mockito.PowerMockito.`when`
import org.powermock.core.classloader.annotations.PowerMockIgnore
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.rule.PowerMockRule
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import pl.edu.amu.wmi.erykandroidcommon.BuildConfig
/**
* @author <NAME> <<EMAIL>> on 16.01.18.
*/
@RunWith(RobolectricTestRunner::class)
@Config(constants = BuildConfig::class, sdk = [26])
@PowerMockIgnore("org.mockito.*", "org.robolectric.*", "android.*")
@PrepareForTest(TestStatic::class, TestNonStatic::class, Thread::class)
class PowerMockTest {
@JvmField
@Rule
val rule = PowerMockRule()
@Test
fun testThreadMock() {
PowerMockito.mockStatic(Thread::class.java)
val handler = Thread.UncaughtExceptionHandler { _, _ -> }
PowerMockito.`when`(Thread.getDefaultUncaughtExceptionHandler()).thenReturn(handler)
assertEquals(handler, Thread.getDefaultUncaughtExceptionHandler())
}
@Test
fun testStaticMocking() {
PowerMockito.mockStatic(TestStatic::class.java)
`when`(TestStatic.testMsg()).thenReturn("hello mock")
assertTrue(TestStatic.testMsg() == "hello mock")
}
@Test
fun testMocking() {
val mock = PowerMockito.mock(TestNonStatic::class.java)
PowerMockito.`when`(mock.nonStaticMethod()).thenReturn("hello mock")
assertTrue(mock.nonStaticMethod() == "hello mock")
}
@Test
fun testSuppress() {
PowerMockito.suppress(PowerMockito.method(TestNonStatic::class.java, "throwMethod"))
TestNonStatic().throwMethod()
}
} | 1 | null | 1 | 1 | 0715d59c3c208df668dc116171ece78a6cf9dd2c | 1,945 | eryk-android-common | Apache License 2.0 |
columba-cli/src/main/kotlin/io/github/leofuso/columba/cli/parser/DependencyGraphAwareSchemaParser.kt | LeoFuso | 584,494,829 | false | null | package io.github.leofuso.columba.cli.parser
import io.github.leofuso.columba.cli.ConsoleLogger
import io.github.leofuso.columba.cli.command.CompileCommand
import org.apache.avro.Protocol
import org.apache.avro.Schema
import java.io.File
import java.util.function.Supplier
/**
* A [Supplier] for a [DependencyGraphAwareSchemaParser].
*/
class SchemaParserSupplier(private val command: CompileCommand) : Supplier<DependencyGraphAwareSchemaParser> {
override fun get(): DependencyGraphAwareSchemaParser = DefaultSchemaParser(command.logger)
}
/**
* A **DependencyGraphAwareSchemaParser** is a [Parser][org.apache.avro.Schema.Parser] capable of producing
* [Schemas][org.apache.avro.Schema] and interpreting [Protocols][org.apache.avro.Protocol] by resolving the dependency
* graph up to *N* degrees without the need of **pre-inlining** them. This parser achieves this by transversing the
* file structure in depth-first order, resolving Schemas with O(n²) iterations, where (n) is the number of Schema
* definition files.
*
* **Notes:**
*
* 1. Repeated declarations do not imply runtime errors. They are solved by whoever appears first.
* 2. It is not an ideal strategy in any way, it doesn't need to be. This parser should be used only
* in the context of this application.
* 3. The name is a mouthful.
*/
interface DependencyGraphAwareSchemaParser {
/**
* Parse all definition schemas from the provided sources, returning all successful resolutions.
*/
fun parse(sources: Collection<File>): Resolution {
logger().lifecycle("Commencing Source file parsing.")
val classifier = getClassifier()
val emptyResolution = Resolution(schemas = mapOf(), protocol = mapOf())
val classification = classifier.classify(sources)
return classification.map { entry ->
when (entry.key) {
SchemaFileClassifier.FileClassification.Schema -> {
logger().lifecycle("Found {} Schema's definition files to be resolved.", entry.value.size)
val schemas = Schemas(entry.value)
val resolution = doParse(schemas)
SchemaResolution(resolution)
}
SchemaFileClassifier.FileClassification.Protocol -> {
logger().lifecycle("Found {} Protocol's definition files to be resolved.", entry.value.size)
val protocols = Protocols(entry.value)
val resolution = doParse(protocols)
ProtocolResolution(resolution)
}
}
}.fold(emptyResolution) { res, some ->
when (some) {
is ProtocolResolution -> res.copy(protocol = some.protocol)
is SchemaResolution -> res.copy(schemas = some.schema)
}
}
}
fun doParse(schemas: Schemas): Map<String, Schema>
fun doParse(protocols: Protocols): Map<String, Protocol> = protocols.elements.associate {
val protocol = Protocol.parse(it)
protocol.name to protocol
}
/**
* @return A [SchemaFileClassifier].
*/
fun getClassifier(): SchemaFileClassifier
/**
* Accessor to underlying [logger] implementation.
*/
fun logger(): ConsoleLogger
/**
* A wrapper Schema(.avsc) files.
*/
data class Schemas(val elements: Collection<File>)
/**
* A wrapper Protocol(.avpr) files.
*/
data class Protocols(val elements: Collection<File>)
}
/**
* A Resolution containing all successfully parsed definitions.
*/
data class Resolution(val schemas: Map<String, Schema>, val protocol: Map<String, Protocol>)
/**
* A [SchemaFileClassifier] is used to visit each of the definition files in a [Collection].
*/
interface SchemaFileClassifier {
enum class FileClassification { Schema, Protocol }
/**
* Classify all found definition files.
*/
fun classify(files: Collection<File>): Map<FileClassification, Collection<File>>
}
private sealed class SomeResolution(val schema: Map<String, Schema>, val protocol: Map<String, Protocol>)
private class ProtocolResolution(value: Map<String, Protocol>) : SomeResolution(schema = mapOf(), value)
private class SchemaResolution(value: Map<String, Schema>) : SomeResolution(value, protocol = mapOf())
| 2 | Kotlin | 0 | 5 | ea1bcd05a60cd6d2be517488af47a9faac456849 | 4,339 | argo | Apache License 2.0 |
compiler/testData/codegen/box/functions/functionNtoStringGeneric.kt | JakeWharton | 99,388,807 | false | null | // LAMBDAS: CLASS
// IGNORE_BACKEND: WASM
// WASM_MUTE_REASON: IGNORED_IN_JS
// IGNORE_BACKEND: JS_IR
// IGNORE_BACKEND: JS_IR_ES6
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
import kotlin.test.assertEquals
fun <T> bar(): String {
return { t: T -> t }.toString()
}
class Baz<T, V> {
fun <V : T> baz(v: V): String {
return (fun(t: List<T>): V = v).toString()
}
}
open class Foo<T, U : List<T>>(val lambda: (T) -> U)
class Bar<T> : Foo<T, List<T>>({ listOf(it) })
fun box(): String {
assertEquals("(T) -> T", bar<String>())
assertEquals("(kotlin.collections.List<T>) -> V", Baz<String, Int>().baz<String>(""))
assertEquals("(T) -> kotlin.collections.List<T>", Bar<Int>().lambda.toString())
return "OK"
}
| 34 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 819 | kotlin | Apache License 2.0 |
android/app/src/main/java/com/algorand/android/modules/swap/assetswap/data/di/AssetSwapRepositoryModule.kt | perawallet | 364,359,642 | false | null | /*
* Copyright 2022 Pera Wallet, LDA
* 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.algorand.android.modules.swap.assetswap.data.di
import com.algorand.android.modules.swap.confirmswap.data.mapper.CreateSwapQuoteTransactionsRequestBodyMapper
import com.algorand.android.modules.swap.assetswap.data.mapper.PeraFeeDTOMapper
import com.algorand.android.modules.swap.assetswap.data.mapper.PeraFeeRequestBodyMapper
import com.algorand.android.modules.swap.assetswap.data.mapper.SwapQuoteDTOMapper
import com.algorand.android.modules.swap.assetswap.data.mapper.SwapQuoteRequestBodyMapper
import com.algorand.android.modules.swap.confirmswap.data.mapper.SwapQuoteTransactionDTOMapper
import com.algorand.android.modules.swap.assetswap.data.mapper.decider.SwapQuoteProviderResponseDecider
import com.algorand.android.modules.swap.assetswap.data.repository.AssetSwapRepositoryImpl
import com.algorand.android.modules.swap.assetswap.domain.repository.AssetSwapRepository
import com.algorand.android.network.MobileAlgorandApi
import com.hipo.hipoexceptionsandroid.RetrofitErrorHandler
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Named
@Module
@InstallIn(SingletonComponent::class)
object AssetSwapRepositoryModule {
@Named(AssetSwapRepository.INJECTION_NAME)
@Provides
fun provideAssetSwapRepository(
mobileAlgorandApi: MobileAlgorandApi,
hipoErrorHandler: RetrofitErrorHandler,
swapQuoteDTOMapper: SwapQuoteDTOMapper,
swapQuoteRequestBodyMapper: SwapQuoteRequestBodyMapper,
swapQuoteProviderResponseDecider: SwapQuoteProviderResponseDecider,
peraFeeRequestBodyMapper: PeraFeeRequestBodyMapper,
peraFeeDTOMapper: PeraFeeDTOMapper,
swapQuoteTransactionDTOMapper: SwapQuoteTransactionDTOMapper,
createSwapQuoteTransactionsRequestBodyMapper: CreateSwapQuoteTransactionsRequestBodyMapper
): AssetSwapRepository {
return AssetSwapRepositoryImpl(
mobileAlgorandApi = mobileAlgorandApi,
hipoErrorHandler = hipoErrorHandler,
swapQuoteDTOMapper = swapQuoteDTOMapper,
swapQuoteRequestBodyMapper = swapQuoteRequestBodyMapper,
swapQuoteProviderResponseDecider = swapQuoteProviderResponseDecider,
peraFeeRequestBodyMapper = peraFeeRequestBodyMapper,
peraFeeDTOMapper = peraFeeDTOMapper,
swapQuoteTransactionDTOMapper = swapQuoteTransactionDTOMapper,
createSwapQuoteTransactionsRequestBodyMapper = createSwapQuoteTransactionsRequestBodyMapper
)
}
}
| 22 | null | 62 | 181 | 92fc77f73fa4105de82d5e87b03c1e67600a57c0 | 3,153 | pera-wallet | Apache License 2.0 |
framework/src/main/kotlin/br/com/zup/beagle/widget/action/AddChildren.kt | ZupIT | 391,145,988 | false | null | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* 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 br.com.zup.beagle.widget.action
import br.com.zup.beagle.core.ServerDrivenComponent
/**
* Defines the placement of where the children will be inserted in the list or if the contents
* of the list will be replaced.
*
* @property APPEND
* @property PREPEND
* @property REPLACE
*/
enum class Mode {
/**
* Adds the view in the end of the children's list.
*/
APPEND,
/**
* Adds the view on the beginning of the children's list.
*/
PREPEND,
/**
* Replaces all children of the widget.
*/
REPLACE
}
/**
* The AddChildren class is responsible for adding - at the beginning or in the end - or changing
* all views that inherit from Widget and who accept children.
*
* @param componentId Required. Defines the widget's id, in which you want to add the views.
* @param value Required. Defines the list of children you want to add.
* @param mode Defines the placement of where the children will be inserted in the list or if the contents of
* the list will be replaced.
*/
data class AddChildren(
var componentId: String,
var value: List<ServerDrivenComponent>,
var mode: Mode? = Mode.APPEND
) : Action
| 5 | null | 11 | 5 | e3f33bae4e209b3852c9a24182a109676166c3d9 | 1,814 | beagle-backend-kotlin | Apache License 2.0 |
framework/src/main/kotlin/br/com/zup/beagle/widget/action/AddChildren.kt | ZupIT | 391,145,988 | false | null | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* 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 br.com.zup.beagle.widget.action
import br.com.zup.beagle.core.ServerDrivenComponent
/**
* Defines the placement of where the children will be inserted in the list or if the contents
* of the list will be replaced.
*
* @property APPEND
* @property PREPEND
* @property REPLACE
*/
enum class Mode {
/**
* Adds the view in the end of the children's list.
*/
APPEND,
/**
* Adds the view on the beginning of the children's list.
*/
PREPEND,
/**
* Replaces all children of the widget.
*/
REPLACE
}
/**
* The AddChildren class is responsible for adding - at the beginning or in the end - or changing
* all views that inherit from Widget and who accept children.
*
* @param componentId Required. Defines the widget's id, in which you want to add the views.
* @param value Required. Defines the list of children you want to add.
* @param mode Defines the placement of where the children will be inserted in the list or if the contents of
* the list will be replaced.
*/
data class AddChildren(
var componentId: String,
var value: List<ServerDrivenComponent>,
var mode: Mode? = Mode.APPEND
) : Action
| 5 | null | 11 | 5 | e3f33bae4e209b3852c9a24182a109676166c3d9 | 1,814 | beagle-backend-kotlin | Apache License 2.0 |
src/main/kotlin/io/aethibo/features/articles/domain/model/Article.kt | primepixel | 726,740,875 | false | {"Kotlin": 66411} | package io.aethibo.features.articles.domain.model
import io.aethibo.features.users.domain.model.User
import kotlinx.serialization.Serializable
@Serializable
data class ArticleDTO(val article: Article?) {
fun validArticle(): Article {
require(article != null) { "Article is invalid" }
require(article.title?.isNotBlank() ?: true) { "Title is null" }
require(article.description?.isNotBlank() ?: true) { "Description is null" }
require(article.body.isNotBlank()) { "Body is empty" }
return article
}
}
@Serializable
data class ArticlesDTO(val articles: List<Article>, val articlesCount: Int)
@Serializable
data class Article(
val slug: String? = null,
val title: String? = null,
val description: String? = null,
val body: String,
val tagList: List<String> = listOf(),
val createdAt: Long? = null,
val updatedAt: Long? = null,
val favorited: Boolean = false,
val favoritesCount: Long = 0,
val author: User? = null,
)
| 0 | Kotlin | 0 | 0 | 0d6a5d26de40aec4ef72f908b0e29a38dfbf3627 | 1,007 | Atlas | Apache License 2.0 |
src/main/kotlin/io/aethibo/features/articles/domain/model/Article.kt | primepixel | 726,740,875 | false | {"Kotlin": 66411} | package io.aethibo.features.articles.domain.model
import io.aethibo.features.users.domain.model.User
import kotlinx.serialization.Serializable
@Serializable
data class ArticleDTO(val article: Article?) {
fun validArticle(): Article {
require(article != null) { "Article is invalid" }
require(article.title?.isNotBlank() ?: true) { "Title is null" }
require(article.description?.isNotBlank() ?: true) { "Description is null" }
require(article.body.isNotBlank()) { "Body is empty" }
return article
}
}
@Serializable
data class ArticlesDTO(val articles: List<Article>, val articlesCount: Int)
@Serializable
data class Article(
val slug: String? = null,
val title: String? = null,
val description: String? = null,
val body: String,
val tagList: List<String> = listOf(),
val createdAt: Long? = null,
val updatedAt: Long? = null,
val favorited: Boolean = false,
val favoritesCount: Long = 0,
val author: User? = null,
)
| 0 | Kotlin | 0 | 0 | 0d6a5d26de40aec4ef72f908b0e29a38dfbf3627 | 1,007 | Atlas | Apache License 2.0 |
MSDKUIDemo/MSDKUIApp/src/androidTest/java/com/here/msdkuiapp/espresso/impl/core/CoreMatchers.kt | heremaps | 141,680,627 | false | null | /*
* Copyright (C) 2017-2021 HERE Europe B.V.
*
* 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.here.msdkuiapp.espresso.impl.core
import android.graphics.drawable.GradientDrawable
import androidx.test.InstrumentationRegistry
import androidx.test.espresso.PerformException
import androidx.test.espresso.UiController
import androidx.test.espresso.ViewAction
import androidx.test.espresso.ViewInteraction
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.BoundedMatcher
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.espresso.util.HumanReadables
import androidx.test.espresso.util.TreeIterables
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import android.widget.DatePicker
import android.widget.TextView
import android.widget.TimePicker
import com.here.msdkui.common.DateFormatterUtil
import com.here.msdkui.common.ThemeUtil
import com.here.msdkuiapp.espresso.impl.utils.CurrentActivityUtils
import org.hamcrest.CoreMatchers.allOf
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.TypeSafeMatcher
import java.lang.Double.parseDouble
import java.util.*
import java.util.concurrent.TimeUnit.SECONDS
import java.util.concurrent.TimeoutException
/**
* Core framework matchers
*/
object CoreMatchers {
private const val TIMEOUT_WAIT_SEC: Long = 60
private const val TIMEOUT_DELAY_MILLIS: Long = 1500
private val TIMEOUT_WAIT_MILLIS: Long = SECONDS.toMillis(TIMEOUT_WAIT_SEC)
const val TIMEOUT_WAIT_DOUBLE_MILLIS: Long = 120000
const val TIMEOUT_WAIT_TRIPLE_MILLIS: Long = 180000
/**
* Waits util given view is successfully matched OR timeout happens.
* TODO: MSDKUI-496, MSDKUI-561 - remove this method when idling resource implemented
*
* @param viewMatcher view will be tested by this matcher.
* @param timeout timeout of wait in milliseconds.
* @param checkInterval delay between consecutive checks in milliseconds.
* @param isVisible whether the checked view must be visible.
* @param isEnabled whether the checked view must be enabled.
* @param isSelected whether the checked view must be selected.
*/
fun waitForCondition(viewMatcher: Matcher<View>, timeout: Long = TIMEOUT_WAIT_MILLIS,
checkInterval: Long = TIMEOUT_DELAY_MILLIS,
isVisible: Boolean = true, isEnabled: Boolean = false, isSelected: Boolean = false): ViewAction {
return object : ViewAction {
override fun getConstraints(): Matcher<View> {
return isRoot()
}
override fun getDescription(): String {
return "wait for a specific view during $timeout timeout."
}
override fun perform(uiController: UiController, view: View) {
uiController.loopMainThreadUntilIdle()
val startTime = System.currentTimeMillis()
val endTime = startTime + timeout
do {
uiController.loopMainThreadForAtLeast(checkInterval)
for (child in TreeIterables.breadthFirstViewTraversal(view)) {
if (isEnabled && viewMatcher.matches(child) && child.isEnabled) return
if (isSelected && viewMatcher.matches(child) && child.isSelected) return
if (isVisible && viewMatcher.matches(child)) return
if (!isVisible && !viewMatcher.matches(isDisplayed())) return
}
} while (System.currentTimeMillis() < endTime)
// timeout happens
throw PerformException.Builder()
.withActionDescription(this.description)
.withViewDescription(HumanReadables.describe(view))
.withCause(TimeoutException())
.build()
}
}
}
/**
* Waits util text of the view under [viewMatcher] changes OR timeout happens.
*
* @param viewMatcher view will be tested by this matcher.
* @param currentText wait till view display other text than given current text.
* @param timeout timeout of wait in milliseconds.
* @param checkInterval delay between consecutive checks in milliseconds.
*/
fun waitForTextChange(viewMatcher: Matcher<View>,
currentText: String,
timeout: Long = TIMEOUT_WAIT_MILLIS,
checkInterval: Long = TIMEOUT_DELAY_MILLIS): ViewAction {
return object : ViewAction {
override fun getConstraints(): Matcher<View> {
return isRoot()
}
override fun getDescription(): String {
return "wait for text in a specific view to change during $timeout timeout."
}
override fun perform(uiController: UiController, view: View) {
uiController.loopMainThreadUntilIdle()
val startTime = System.currentTimeMillis()
val endTime = startTime + timeout
do {
uiController.loopMainThreadForAtLeast(checkInterval)
for (child in TreeIterables.breadthFirstViewTraversal(view)) {
if (viewMatcher.matches(child) && (child as TextView).text != currentText) {
return
}
}
} while (System.currentTimeMillis() < endTime)
// timeout happens
throw PerformException.Builder()
.withActionDescription(this.description)
.withViewDescription(HumanReadables.describe(view))
.withCause(TimeoutException())
.build()
}
}
}
/**
* Matches the view with index in case of espresso matches several views with withId or withText.
*/
fun withIndex(matcher: Matcher<View>, index: Int): Matcher<View> {
return object : TypeSafeMatcher<View>() {
var currentIndex = 0
override fun describeTo(description: Description) {
description.appendText("with index: ")
description.appendValue(index)
matcher.describeTo(description)
}
public override fun matchesSafely(view: View): Boolean {
return matcher.matches(view) && currentIndex++ == index
}
}
}
/**
* Matches the size of list with given input size.
*/
fun withListSize(size: Int): Matcher<in View>? {
return object : TypeSafeMatcher<View>(), Matcher<View> {
override fun matchesSafely(view: View): Boolean {
return (view as RecyclerView).adapter!!.itemCount == size
}
override fun describeTo(description: Description) {
description.appendText("RecyclerView should have $size items")
}
}
}
/**
* Matches [TextView] with [date] text
*/
fun withDateText(date: Date): Matcher<View>? {
return withText(DateFormatterUtil.format(date))
}
/**
* [Matcher] that matches [TextView] with numeric text
*/
fun isNumeric():Matcher<View> {
return object: TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("is numeric ")
}
override fun matchesSafely(item: View): Boolean {
with(item as TextView) {
try {
parseDouble(text.toString())
} catch (e: NumberFormatException) {
return false
}
}
return true
}
}
}
/**
* Matches [TextView] based on it's attribute color.
* @param colorAttrId Attribute color id (from R.attr)
*/
fun hasTextColor(colorAttrId: Int): Matcher<View> {
return object : BoundedMatcher<View, TextView>(TextView::class.java) {
override fun matchesSafely(textView: TextView): Boolean {
val expectedColor = ThemeUtil.getColor(textView.context, colorAttrId)
val textViewColor = textView.currentTextColor
return textViewColor == expectedColor
}
override fun describeTo(description: Description) {
description.appendText("has color with attr id $colorAttrId ")
}
}
}
/**
* Matches [View] based on it's attribute color.
* @param drawableId Attribute id (from R.attr)
*/
fun withColorFromDrawable(drawableId: Int): Matcher<View> {
return object : BoundedMatcher<View, View>(View::class.java) {
override fun matchesSafely(view: View): Boolean {
val currentColor = (view.background.current as GradientDrawable)
.color?.defaultColor
val expectedColor = (ContextCompat.getDrawable(view.context, drawableId) as GradientDrawable)
.color?.defaultColor
return currentColor!! == (expectedColor)
}
override fun describeTo(description: Description) {
description.appendText("is drawable with id $drawableId ")
}
}
}
/**
* Get text from [TextView]
* @return [String] text from [TextView], represented by [ViewInteraction]
*/
fun getText(viewInteraction: ViewInteraction): String {
var stringHolder = String()
viewInteraction.perform(object : ViewAction {
override fun getConstraints() = isAssignableFrom(TextView::class.java)
override fun getDescription() = "Get text from view: "
override fun perform(uiController: UiController, view: View) {
val tv = view as TextView
stringHolder = tv.text.toString()
}
})
return stringHolder
}
/**
* Get date from [DatePicker]
* @return [Calendar] date from [DatePicker], represented by [ViewInteraction]
*/
fun getDate(viewInteraction: ViewInteraction): Calendar {
val date = Calendar.getInstance()
viewInteraction.perform(object : ViewAction {
override fun getConstraints() = isAssignableFrom(DatePicker::class.java)
override fun getDescription() = "Get date from DatePicker: "
override fun perform(uiController: UiController, view: View) {
with (view as DatePicker) {
date.set(year, month, dayOfMonth)
}
}
})
return date
}
/**
* Get time from [TimePicker]
* @return [Calendar] time from [TimePicker], represented by [ViewInteraction]
*/
fun getTime(viewInteraction: ViewInteraction): Calendar {
val time = Calendar.getInstance()
viewInteraction.perform(object : ViewAction {
override fun getConstraints() = isAssignableFrom(TimePicker::class.java)
override fun getDescription() = "Get time from TimePicker: "
override fun perform(uiController: UiController, view: View) {
with (view as TimePicker) {
time.set(Calendar.HOUR_OF_DAY, hour)
time.set(Calendar.MINUTE, minute)
}
}
})
return time
}
/**
* Get [String] by given resource id
* @return The [String] text
*/
fun getTextById(resourceId: Int): String {
return InstrumentationRegistry.getTargetContext().resources.getString(resourceId)
}
/**
* Check visibility of the given [ViewInteraction] component
*/
fun viewIsDisplayed(viewInteraction: ViewInteraction): Boolean {
var isDisplayed = true
viewInteraction.withFailureHandler { error, viewMatcher ->
isDisplayed = false }
.check(matches(isDisplayed()))
return isDisplayed
}
/**
* Matches the id and the string text of the view.
*/
fun withIdAndText(id: Int, text: String): Matcher<View> {
return allOf(withId(id), withText(text))
}
/**
* Matches the id and the tag of the view.
*/
fun withIdAndTag(id: Int, tag: Int): Matcher<View> {
return allOf(withId(id), withTag(tag))
}
/**
* Matches the id and the color of the text view.
*/
fun withIdAndTextColor(id: Int, color: Int): Matcher<View> {
return allOf(withId(id), withTextColor(color))
}
/**
* Get [Int] color by resource id
* @return The [Int] color
*/
fun getColorById(resourceId: Int): Int {
return ThemeUtil.getColor(CurrentActivityUtils.currentActivity, resourceId)
}
/**
* Matches the tag of the view.
*/
private fun withTag(tag: Int): Matcher<in View>? {
return object : TypeSafeMatcher<View>(), Matcher<View> {
override fun matchesSafely(view: View): Boolean {
return if (view.tag != null && view.tag is Int) {
view.tag == tag
} else {
false
}
}
override fun describeTo(description: Description) {
description.appendText("with tag: $tag")
}
}
}
/**
* Matches the text color of the view.
*/
private fun withTextColor(color: Int): Matcher<in View>? {
return object : TypeSafeMatcher<View>(), Matcher<View> {
override fun matchesSafely(view: View): Boolean {
if (view is TextView && color == view.currentTextColor) {
return true
}
return false
}
override fun describeTo(description: Description) {
description.appendText("with text color $color")
}
}
}
} | 1 | Java | 19 | 49 | 3b54e002f92cb92edb5a71e55fb064e6112158d6 | 14,728 | msdkui-android | Apache License 2.0 |
data/src/main/java/com/yapp/gallery/data/repository/ExhibitRecordRepositoryImpl.kt | YAPP-Github | 561,171,842 | false | null | package com.yapp.gallery.data.repository
import com.yapp.gallery.data.source.local.record.ExhibitRecordLocalDataSource
import com.yapp.gallery.data.source.remote.record.ExhibitRecordRemoteDataSource
import com.yapp.gallery.domain.entity.home.CategoryItem
import com.yapp.gallery.domain.entity.home.TempPostInfo
import com.yapp.gallery.domain.repository.ExhibitRecordRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.flatMapConcat
import kotlinx.coroutines.flow.flatMapMerge
import kotlinx.coroutines.flow.map
import javax.inject.Inject
class ExhibitRecordRepositoryImpl @Inject constructor(
private val localDataSource: ExhibitRecordLocalDataSource,
private val remoteDataSource: ExhibitRecordRemoteDataSource
) : ExhibitRecordRepository{
override fun getCategoryList(): Flow<List<CategoryItem>> {
return remoteDataSource.getCategoryList()
}
override fun createCategory(category: String): Flow<Long> {
return remoteDataSource.createCategory(category)
}
override fun createRecord(
name: String, categoryId: Long, postDate: String, attachedLink: String?
): Flow<Long> {
return remoteDataSource.createRecord(name, categoryId, postDate, attachedLink).flatMapMerge {
localDataSource.insertTempPost(it, name, categoryId, postDate, attachedLink)
}
}
override fun updateBoth(
postId: Long,
name: String,
categoryId: Long,
postDate: String,
postLink: String?,
): Flow<Long> {
return remoteDataSource.updateRecord(postId, name, categoryId, postDate, postLink).flatMapMerge {
localDataSource.updateTempPost(postId, name, categoryId, postDate, postLink)
}
}
override fun getTempPost(): Flow<TempPostInfo> {
return localDataSource.getTempPost().map {
p -> TempPostInfo(p.postId, p.name, p.categoryId, p.postDate, p.postLink) }
}
override fun deleteTempPost(): Flow<Long> {
return localDataSource.deleteTempPost()
}
override fun deleteBoth(): Flow<Boolean> {
// 로컬에 있는지 먼저 판단하고 지우기
return localDataSource.deleteTempPost().flatMapConcat {
remoteDataSource.deleteRecord(it)
}
}
} | 1 | null | 0 | 2 | c7051e5338f30175b87f6a1c2374d97653527a40 | 2,305 | 21st-ALL-Rounder-Team-2-Android | Apache License 2.0 |
src/main/kotlin/dev/aaronhowser/mods/geneticsresequenced/blocks/AntiFieldBlock.kt | aaronhowser1 | 780,170,281 | false | null | package dev.aaronhowser.mods.geneticsresequenced.blocks
import dev.aaronhowser.mods.geneticsresequenced.configs.ServerConfig
import net.minecraft.core.BlockPos
import net.minecraft.world.item.context.BlockPlaceContext
import net.minecraft.world.level.Level
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.block.state.StateDefinition
import net.minecraft.world.level.block.state.properties.BlockStateProperties
import net.minecraft.world.level.block.state.properties.BooleanProperty
import net.minecraft.world.level.material.Material
import java.util.*
// Apparently blocks with special states need to be classes, not objects
class AntiFieldBlock : Block(Properties.of(Material.METAL)) {
init {
registerDefaultState(stateDefinition.any().setValue(DISABLED, false))
}
override fun getStateForPlacement(pContext: BlockPlaceContext): BlockState? {
return defaultBlockState().setValue(DISABLED, false)
}
override fun createBlockStateDefinition(pBuilder: StateDefinition.Builder<Block, BlockState>) {
super.createBlockStateDefinition(pBuilder)
pBuilder.add(DISABLED)
}
@Suppress("OVERRIDE_DEPRECATION")
override fun neighborChanged(
pState: BlockState,
pLevel: Level,
pPos: BlockPos,
pBlock: Block,
pFromPos: BlockPos,
pIsMoving: Boolean
) {
val isPowered = pLevel.hasNeighborSignal(pPos)
if (pState.getValue(DISABLED) != isPowered) {
pLevel.setBlock(pPos, pState.setValue(DISABLED, isPowered), 2)
}
}
companion object {
val DISABLED: BooleanProperty = BlockStateProperties.POWERED
fun getNearestAntifield(level: Level, location: BlockPos): Optional<BlockPos> {
val radius = ServerConfig.antifieldBlockRadius.get()
return BlockPos.findClosestMatch(location, radius, radius) { pos ->
val blockState = level.getBlockState(pos)
blockState.block == ModBlocks.ANTIFIELD_BLOCK && !blockState.getValue(DISABLED)
}
}
fun locationIsNearAntifield(level: Level, location: BlockPos): Boolean {
return getNearestAntifield(level, location).isPresent
}
}
} | 6 | null | 0 | 1 | 11d035ab2a3f002ac6f2ebb392c242ce3d16636c | 2,317 | Genetics-Resequenced | MIT License |
ui/src/main/java/io/snabble/sdk/ui/payment/creditcard/shared/country/ui/CountrySelectionMenu.kt | snabble | 124,525,499 | false | {"Kotlin": 1339811, "Java": 559116, "HTML": 68836, "Shell": 2232} | package io.snabble.sdk.ui.payment.creditcard.shared.country.ui
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.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.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.sp
import io.snabble.sdk.ui.R
import io.snabble.sdk.ui.payment.creditcard.shared.country.domain.models.CountryItem
import io.snabble.sdk.ui.payment.creditcard.shared.country.domain.models.StateItem
@Composable
internal fun CountrySelectionMenu(
modifier: Modifier = Modifier,
countryItems: List<CountryItem>,
selectedCountryCode: CountryItem,
selectedStateCode: String? = null,
onCountrySelected: (CountryItem, StateItem?) -> Unit,
) {
var showCountryList by remember { mutableStateOf(false) }
var dismissCountryList by remember { mutableStateOf(true) }
var showStateList by remember { mutableStateOf(false) }
var dismissStateList by remember { mutableStateOf(true) }
var currentCountryItem by remember { mutableStateOf(selectedCountryCode) }
var currentStateItem by remember {
mutableStateOf(
selectedStateCode?.let { stateCode ->
currentCountryItem.stateItems?.firstOrNull { it.code == stateCode }
}
)
}
fun validateStateItem() {
if (currentCountryItem.stateItems?.contains(currentStateItem) != true) {
currentStateItem = null
}
}
DropDownMenu(
modifier = modifier,
isExpanded = showCountryList && !dismissCountryList,
onExpand = {
showCountryList = !showCountryList
dismissCountryList = false
},
onDismiss = { dismissCountryList = true },
label = stringResource(id = R.string.Snabble_Payment_CustomerInfo_country),
value = currentCountryItem.displayName,
menuItems = countryItems
) { country ->
DropdownMenuItem(
text = {
Text(
text = country.displayName,
style = MaterialTheme.typography.bodyLarge,
fontSize = 17.sp
)
},
onClick = {
currentCountryItem = country
validateStateItem()
onCountrySelected(country, currentStateItem)
showCountryList = false
}
)
}
if (currentCountryItem.stateItems != null) {
DropDownMenu(
modifier = modifier,
isExpanded = showStateList && !dismissStateList,
onExpand = {
showStateList = !showStateList
dismissStateList = false
},
onDismiss = { dismissStateList = true },
label = stringResource(id = R.string.Snabble_Payment_CustomerInfo_state),
value = currentStateItem?.displayName
?: stringResource(id = R.string.Snabble_Payment_CustomerInfo_stateSelect),
menuItems = currentCountryItem.stateItems
) { state ->
DropdownMenuItem(
text = {
Text(
text = state.displayName,
style = MaterialTheme.typography.bodyLarge,
fontSize = 17.sp
)
},
onClick = {
currentStateItem = state
onCountrySelected(currentCountryItem, state)
showStateList = false
}
)
}
}
}
| 0 | Kotlin | 0 | 5 | f6f5fd69553e14f39bb59c55a3b5e23c5912b9b6 | 3,815 | Android-SDK | MIT License |
app/src/main/java/com/pernasa/mybirdsapp/viewModels/BirdsListViewModel.kt | PernasA | 825,166,352 | false | {"Kotlin": 108244} | package com.pernasa.mybirdsapp.viewModels
import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.pernasa.mybirdsapp.models.Bird
import com.pernasa.mybirdsapp.models.room.RoomBird
import com.pernasa.mybirdsapp.models.room.RoomBirdsDao
import com.pernasa.mybirdsapp.utils.DrawableResourcesList
import com.pernasa.mybirdsapp.utils.InterfaceJsonLoader
import com.pernasa.mybirdsapp.utils.JsonReader
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.jetbrains.annotations.TestOnly
class BirdsListViewModel(
context: Context,
private val roomBirdsDao: RoomBirdsDao,
private val jsonReader: InterfaceJsonLoader = JsonReader()
) : ViewModel() {
var dataBirdsList: List<Bird> = emptyList()
private val _listObservedBirds = MutableStateFlow<List<RoomBird>>(emptyList())
val listObservedBirds: StateFlow<List<RoomBird>> = _listObservedBirds
fun getBirdObservationState(birdId: Int): Flow<Boolean> {
return _listObservedBirds
.map { birds -> birds.firstOrNull { it.id == birdId }?.wasObserved ?: false }
}
fun editBirdWasObserved(bird: RoomBird) {
viewModelScope.launch {
roomBirdsDao.editWasObservedBird(bird)
}
_listObservedBirds.update { birds ->
birds.map {
if (it.id == bird.id) it.copy(wasObserved = bird.wasObserved) else it
}
}
}
init {
viewModelScope.launch(Dispatchers.IO) {
val birdJsonList = jsonReader.loadJsonBirdsFromAssets(context, "birds_list.json")
dataBirdsList = birdJsonList.map { birdJson ->
Bird(
name = birdJson.name,
id = birdJson.id,
heightLocation = birdJson.heightLocation,
height = birdJson.height,
frequency = birdJson.frequency,
scientificName = birdJson.scientificName,
englishName = birdJson.englishName,
description = birdJson.description,
imageResId = getDrawableIdByBirdIdPosition(birdJson.id)
)
}
viewModelScope.launch {
_listObservedBirds.value = roomBirdsDao.getAllBirds().first()
if (_listObservedBirds.value.isEmpty()){
createFileAllBirds(dataBirdsList.size)
GlobalCounterBirdsObserved.setCounter(0)
} else {
val quantityBirdsWereObserved = _listObservedBirds.value.count { it.wasObserved }
GlobalCounterBirdsObserved.setCounter(quantityBirdsWereObserved)
}
}
}
}
@TestOnly
fun getDrawableIdByBirdIdPosition(birdId: Int): Int {
return DrawableResourcesList.drawableListBirds[birdId-1]
}
fun getBirdById(birdId: Int): Bird? {
return dataBirdsList.find { it.id == birdId }
}
@TestOnly
fun createFileAllBirds(quantityOfBirds: Int) {
_listObservedBirds.value = List(quantityOfBirds) { index ->
RoomBird(id = index + 1, wasObserved = false)
}
viewModelScope.launch {
roomBirdsDao.insertAll(_listObservedBirds.value)
}
}
}
| 0 | Kotlin | 0 | 0 | d45ed45461c18cbb375c12a001047d435c2bd00a | 3,575 | MyBirdsApp | MIT License |
app/src/main/java/com/pernasa/mybirdsapp/viewModels/BirdsListViewModel.kt | PernasA | 825,166,352 | false | {"Kotlin": 108244} | package com.pernasa.mybirdsapp.viewModels
import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.pernasa.mybirdsapp.models.Bird
import com.pernasa.mybirdsapp.models.room.RoomBird
import com.pernasa.mybirdsapp.models.room.RoomBirdsDao
import com.pernasa.mybirdsapp.utils.DrawableResourcesList
import com.pernasa.mybirdsapp.utils.InterfaceJsonLoader
import com.pernasa.mybirdsapp.utils.JsonReader
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.jetbrains.annotations.TestOnly
class BirdsListViewModel(
context: Context,
private val roomBirdsDao: RoomBirdsDao,
private val jsonReader: InterfaceJsonLoader = JsonReader()
) : ViewModel() {
var dataBirdsList: List<Bird> = emptyList()
private val _listObservedBirds = MutableStateFlow<List<RoomBird>>(emptyList())
val listObservedBirds: StateFlow<List<RoomBird>> = _listObservedBirds
fun getBirdObservationState(birdId: Int): Flow<Boolean> {
return _listObservedBirds
.map { birds -> birds.firstOrNull { it.id == birdId }?.wasObserved ?: false }
}
fun editBirdWasObserved(bird: RoomBird) {
viewModelScope.launch {
roomBirdsDao.editWasObservedBird(bird)
}
_listObservedBirds.update { birds ->
birds.map {
if (it.id == bird.id) it.copy(wasObserved = bird.wasObserved) else it
}
}
}
init {
viewModelScope.launch(Dispatchers.IO) {
val birdJsonList = jsonReader.loadJsonBirdsFromAssets(context, "birds_list.json")
dataBirdsList = birdJsonList.map { birdJson ->
Bird(
name = birdJson.name,
id = birdJson.id,
heightLocation = birdJson.heightLocation,
height = birdJson.height,
frequency = birdJson.frequency,
scientificName = birdJson.scientificName,
englishName = birdJson.englishName,
description = birdJson.description,
imageResId = getDrawableIdByBirdIdPosition(birdJson.id)
)
}
viewModelScope.launch {
_listObservedBirds.value = roomBirdsDao.getAllBirds().first()
if (_listObservedBirds.value.isEmpty()){
createFileAllBirds(dataBirdsList.size)
GlobalCounterBirdsObserved.setCounter(0)
} else {
val quantityBirdsWereObserved = _listObservedBirds.value.count { it.wasObserved }
GlobalCounterBirdsObserved.setCounter(quantityBirdsWereObserved)
}
}
}
}
@TestOnly
fun getDrawableIdByBirdIdPosition(birdId: Int): Int {
return DrawableResourcesList.drawableListBirds[birdId-1]
}
fun getBirdById(birdId: Int): Bird? {
return dataBirdsList.find { it.id == birdId }
}
@TestOnly
fun createFileAllBirds(quantityOfBirds: Int) {
_listObservedBirds.value = List(quantityOfBirds) { index ->
RoomBird(id = index + 1, wasObserved = false)
}
viewModelScope.launch {
roomBirdsDao.insertAll(_listObservedBirds.value)
}
}
}
| 0 | Kotlin | 0 | 0 | d45ed45461c18cbb375c12a001047d435c2bd00a | 3,575 | MyBirdsApp | MIT License |
app/src/main/java/com/andor/navigate/notepad/auth/ITalkToUI.kt | andor201995 | 188,668,352 | false | {"Kotlin": 95557} | package com.andor.navigate.notepad.auth
import com.google.firebase.auth.FirebaseUser
interface ITalkToUI {
fun signingInSuccess(user: FirebaseUser)
fun signingInFailed()
fun alreadySignedIn(user: FirebaseUser)
}
| 6 | Kotlin | 0 | 2 | d3ee59258616a1a1333f45e1b1e4ddeccc4a2262 | 227 | NoteIt | Apache License 2.0 |
sample/src/main/java/com/thinkup/sample/utils/DotSpinnerRenderer.kt | nicolasCastro | 205,704,034 | false | {"Kotlin": 43001} | package com.thinkup.sample.utils
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.annotation.ArrayRes
import com.thinkup.easycore.ViewRenderer
import com.thinkup.sample.DotSpinnerCallback
import com.thinkup.sample.R
import kotlinx.android.synthetic.main.item_spinner.view.*
class DotSpinnerRenderer(val callback: DotSpinnerCallback) : ViewRenderer<DotSpinnerRenderer.Item, View>(Item::class) {
override fun create(parent: ViewGroup): View = inflate(R.layout.item_spinner, parent, false)
override fun bind(view: View, model: Item, position: Int) {
val items = view.resources.getStringArray(model.stepTypes.array)
view.spinnerTitle.text = model.stepTypes.title
val spinnerArrayAdapter = ArrayAdapter(view.context, android.R.layout.simple_spinner_item, items)
view.spinnerView.adapter = spinnerArrayAdapter
view.spinnerView.setSelection(model.position)
view.spinnerView.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
model.position = position
callback(model.stepTypes, items[position], position)
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
}
class Item(
val stepTypes: Types,
var position: Int = 0
)
enum class Types(val title: String, @ArrayRes val array: Int, val default: Int) {
WIDTH("Dot width", R.array.dimens_array, 2),
SELECTEDWIDTH("Dot selected width", R.array.dimens_array, 2),
HEIGHT("Dot height", R.array.dimens_array, 2),
MARGIN("Dot margins", R.array.thick_array, 2),
SELECTEDRESOURCE("Dot selected resource", R.array.colors_array, 2),
UNSELECTEDRESOURCE("Dot unselected resource", R.array.colors_array, 0),
GRADIENT("Dot gradient progress", R.array.boolean_array, 0),
GRADIENTSELECTEDPERCENTAGE("Selected dot gradient %", R.array.percentage_array, 5),
GRADIENTNEARNEXTPERCENTAGE("Next dot gradient %", R.array.percentage_array, 5),
GRADIENTNEARPREPERCENTAGE("Previous dot gradient %", R.array.percentage_array, 5),
GRADIENTFARPERCENTAGE("Others dots gradient %", R.array.percentage_array, 5),
BORDER("Dot with borders", R.array.boolean_array, 0),
ROUNDED("Use rounded dots", R.array.boolean_array, 1),
STEPS("Use like steps indicators", R.array.boolean_array, 0),
LOADER("Use like a loader indicator", R.array.boolean_array, 0),
REPEAT("If is loader, haw many time repeat that", R.array.steps_index_array, 2),
LOADERDELAY("Delay between dots", R.array.anim_array, 1),
DURATION("Animation duration", R.array.anim_array, 1),
STEPSCOUNT("Count of dots in view", R.array.steps_array, 2),
CURRENTINDEX("Current selected selected width", R.array.steps_index_array, 0)
}
} | 0 | Kotlin | 1 | 3 | f99981ebf6c467c07db915e97ffcbda15d594743 | 3,040 | IndicatorsSuite | Apache License 2.0 |
001-HelloWorld/src/main/kotlin/org/testkotlin/main.kt | franck-benault | 164,351,139 | false | null | package org.testkotlin
fun main(args: Array<String>) {
println("Hello world");
} | 0 | Kotlin | 0 | 0 | 75fe442ac45d612f7f98d11346f421ff78cdf7f5 | 85 | test-kotlin | Apache License 2.0 |
aurademo/src/main/java/com/silverhetch/aurademo/resultpipe/FragmentResultDemoFragment.kt | fossabot | 268,971,220 | false | null | package com.larryhsiao.aurademo.resultpipe
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.larryhsiao.aura.AuraFragment
/**
* Demo Fragment for sending result to Activity with [AuraFragment.sendResult]
*/
class FragmentResultDemoFragment : AuraFragment() {
companion object {
private const val ARG_CODE = "ARG_CODE"
fun newInstance(code: Int): Fragment {
return FragmentResultDemoFragment().apply {
arguments = Bundle().apply {
putInt(ARG_CODE, code)
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
sendResult(
arguments?.getInt(ARG_CODE, -1) ?: -1,
Activity.RESULT_OK,
Intent()
)
}
} | 9 | null | 2 | 1 | fb00fe41a2b32dbbd9fcc88d0fcd8d531c9b0638 | 899 | Aura | MIT License |
app/src/main/java/com/wuruoye/know/ui/edit/RecordTypeEditFragment.kt | ruoyewu | 183,387,390 | false | {"Gradle": 3, "Markdown": 1, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Kotlin": 128, "XML": 74, "Java": 16} | package com.wuruoye.know.ui.edit
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.wuruoye.know.R
import com.wuruoye.know.ui.base.LeakFragment
import com.wuruoye.know.ui.edit.adapter.RecordTypeSelectAdapter
import com.wuruoye.know.ui.edit.adapter.ReviewStrategyAdapter
import com.wuruoye.know.ui.edit.vm.IRecordTypeEditVM
import com.wuruoye.know.ui.edit.vm.RecordTypeEditViewModel
import com.wuruoye.know.util.InjectorUtil
import com.wuruoye.know.util.ViewFactory
import com.wuruoye.know.util.model.RequestCode.RECORD_TYPE_EDIT_FOR_ADD
import com.wuruoye.know.util.model.RequestCode.RECORD_TYPE_EDIT_FOR_STRATEGY
import com.wuruoye.know.util.model.RequestCode.RECORD_TYPE_EDIT_FOR_UPDATE
import com.wuruoye.know.util.model.beans.RealRecordLayoutView
import com.wuruoye.know.util.model.beans.RecordTypeSelect
import com.wuruoye.know.util.orm.table.*
/**
* Created at 2019-04-22 15:02 by wuruoye
* Description:
*/
class RecordTypeEditFragment :
LeakFragment(),
View.OnClickListener,
RecordTypeSelectAdapter.OnClickListener,
ViewFactory.OnLongClickListener, ReviewStrategyAdapter.OnClickListener {
private lateinit var dlgReviewStrategy: BottomSheetDialog
private lateinit var rvReviewStrategy: RecyclerView
private lateinit var dlgSelectItem: BottomSheetDialog
private lateinit var rvSelectItem: RecyclerView
private lateinit var mParent: ViewGroup
private lateinit var mParentViews: ArrayList<RecordView>
private lateinit var mUpdateView: RecordView
private lateinit var llReviewStrategy: LinearLayout
private lateinit var tvReviewStrategy: TextView
private lateinit var llContent: LinearLayout
private lateinit var fabAdd: FloatingActionButton
private lateinit var vm: IRecordTypeEditVM
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_record_type_edit, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
vm = ViewModelProviders.of(activity!!,
InjectorUtil.recordTypeEditViewModelFactory(context!!))
.get(RecordTypeEditViewModel::class.java)
bindView(view)
bindListener()
initDlg()
subscribeUI()
}
private fun bindView(view: View) {
with(view) {
llReviewStrategy = findViewById(R.id.ll_review_strategy_record_type_edit)
tvReviewStrategy = findViewById(R.id.tv_review_strategy_record_type_edit)
llContent = findViewById(R.id.ll_record_type_edit)
fabAdd = findViewById(R.id.fab_record_type_edit)
}
}
private fun bindListener() {
fabAdd.setOnClickListener(this)
llReviewStrategy.setOnClickListener(this)
}
@SuppressLint("InflateParams")
private fun initDlg() {
val reviewStrategyAdapter = ReviewStrategyAdapter()
reviewStrategyAdapter.setOnClickListener(this)
rvReviewStrategy = LayoutInflater.from(context!!)
.inflate(R.layout.dlg_record_type, null) as RecyclerView
rvReviewStrategy.layoutManager = LinearLayoutManager(context!!)
rvReviewStrategy.adapter = reviewStrategyAdapter
dlgReviewStrategy = BottomSheetDialog(context!!)
dlgReviewStrategy.setContentView(rvReviewStrategy)
val selectAdapter = RecordTypeSelectAdapter()
selectAdapter.setOnClickListener(this)
rvSelectItem = LayoutInflater.from(context!!)
.inflate(R.layout.dlg_record_type, null) as RecyclerView
rvSelectItem.layoutManager = LinearLayoutManager(context!!)
rvSelectItem.adapter = selectAdapter
dlgSelectItem = BottomSheetDialog(context!!)
dlgSelectItem.setContentView(rvSelectItem)
}
private fun subscribeUI() {
vm.selectItems.observe(this, Observer {
(rvSelectItem.adapter as RecordTypeSelectAdapter).submitList(it)
})
vm.reviewStrategyList.observe(this, Observer {
(rvReviewStrategy.adapter as ReviewStrategyAdapter).submitList(it)
})
vm.recordType.observe(this, Observer {
llContent.removeAllViews()
for (v in it.items) {
ViewFactory.generateEditView(context!!,
v, llContent, it.items, true, this)
}
})
vm.reviewStrategyTitle.observe(this, Observer {
tvReviewStrategy.text = it
})
}
override fun onClick(recordView: RecordView, view: View,
parentView: ArrayList<RecordView>, parent: ViewGroup) {
AlertDialog.Builder(context!!)
.setItems(if (recordView is RealRecordLayoutView)
RecordTypeEditActivity.ITEM_LAYOUT else RecordTypeEditActivity.ITEM_VIEW) {
_, which ->
when (which) {
0 -> { // update
mParent = parent
mParentViews = parentView
mUpdateView = recordView
val intent = Intent(context, TypeItemEditActivity::class.java)
intent.putExtra(TypeItemEditActivity.RECORD_VIEW,
if (recordView is RealRecordLayoutView) {
RecordLayoutView(recordView, "")
} else {
recordView
})
startActivityForResult(intent, RECORD_TYPE_EDIT_FOR_UPDATE)
}
1 -> { // remove
parentView.remove(recordView)
parent.removeView(view)
vm.removeView(recordView)
}
2 -> { // add
mParent = view as ViewGroup
mParentViews = (recordView as RealRecordLayoutView).items
dlgSelectItem.show()
}
}
}
.show()
}
override fun onClick(item: RecordTypeSelect) {
dlgSelectItem.dismiss()
val intent = Intent(context, TypeItemEditActivity::class.java)
intent.putExtra(TypeItemEditActivity.RECORD_TYPE, item.id)
startActivityForResult(intent, RECORD_TYPE_EDIT_FOR_ADD)
}
override fun onClick(item: ReviewStrategy) {
dlgReviewStrategy.dismiss()
if (item.id != null) {
vm.setReviewStrategy(item.id!!)
} else {
startActivityForResult(Intent(context, ReviewStrategyEditActivity::class.java),
RECORD_TYPE_EDIT_FOR_STRATEGY)
}
}
override fun onClick(v: View?) {
when(v?.id) {
R.id.fab_record_type_edit -> {
mParentViews = vm.recordType.value!!.items
mParent = llContent
dlgSelectItem.show()
}
R.id.ll_review_strategy_record_type_edit -> {
dlgReviewStrategy.show()
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
RECORD_TYPE_EDIT_FOR_ADD -> {
val view = data!!.getParcelableExtra<RecordView>(
TypeItemEditActivity.RECORD_VIEW)
mParentViews.add(if (view is RecordLayoutView) {
RealRecordLayoutView(view, arrayListOf())
} else view)
}
RECORD_TYPE_EDIT_FOR_UPDATE -> {
val view = data!!.getParcelableExtra<RecordView>(
TypeItemEditActivity.RECORD_VIEW)
when (view) {
is RecordLayoutView -> {
(mUpdateView as RealRecordLayoutView).setInfo(view)
}
is RecordTextView -> {
(mUpdateView as RecordTextView).setInfo(view)
}
is RecordImageView -> {
(mUpdateView as RecordImageView).setInfo(view)
}
}
}
RECORD_TYPE_EDIT_FOR_STRATEGY -> {
val strategy = data!!.getParcelableExtra<ReviewStrategy>(
ReviewStrategyEditActivity.REVIEW_STRATEGY)
vm.updateReviewStrategy()
vm.setReviewStrategy(strategy.id!!)
}
}
vm.updateView()
}
}
} | 1 | null | 1 | 1 | 2de5a7fdecc8c135463c99c47cde417de0cbe2ec | 9,487 | know2 | Apache License 2.0 |
src/main/kotlin/com/github/wtfjoke/dgsDirectivesExamples/graphql/mutations/RatingMutation.kt | WtfJoke | 395,566,883 | false | null | package com.github.wtfjoke.dgsDirectivesExamples.graphql.mutations
import com.github.wtfjoke.generated.types.Rating
import com.github.wtfjoke.generated.types.RatingInput
import com.netflix.graphql.dgs.DgsComponent
import com.netflix.graphql.dgs.DgsMutation
import com.netflix.graphql.dgs.InputArgument
@DgsComponent
class RatingMutation {
@DgsMutation
fun addRating(@InputArgument rating: RatingInput): Rating? {
val stars = rating.stars
println("Rated ${rating.title} with $stars stars")
return Rating(stars)
}
} | 1 | Kotlin | 0 | 1 | 76db8e9d0b7741c0abf4ffb8c40ea7734809bc7d | 553 | graphql-dgs-directives-demo | MIT License |
projects/Kotlin/src/com/chronoxor/test/FlagsTypedEnum.kt | chronoxor | 145,696,528 | false | null | // Automatically generated by the Fast Binary Encoding compiler, do not modify!
// https://github.com/chronoxor/FastBinaryEncoding
// Source: test.fbe
// Version: 1.8.0.0
@file:Suppress("UnusedImport", "unused")
package com.chronoxor.test
@Suppress("EnumEntryName", "MemberVisibilityCanBePrivate", "RemoveRedundantCallsOfConversionMethods")
enum class FlagsTypedEnum
{
FLAG_VALUE_0(0x00uL)
, FLAG_VALUE_1(0x01uL)
, FLAG_VALUE_2(0x02uL)
, FLAG_VALUE_3(0x04uL)
, FLAG_VALUE_4(0x08uL)
, FLAG_VALUE_5(0x10uL)
, FLAG_VALUE_6(0x20uL)
, FLAG_VALUE_7(0x40uL)
, FLAG_VALUE_8(FLAG_VALUE_7.raw.toULong())
, FLAG_VALUE_9(FLAG_VALUE_2.raw.toULong() or FLAG_VALUE_4.raw.toULong() or FLAG_VALUE_6.raw.toULong())
;
var raw: ULong = 0uL
private set
constructor(value: UByte) { this.raw = value.toULong() }
constructor(value: UShort) { this.raw = value.toULong() }
constructor(value: UInt) { this.raw = value.toULong() }
constructor(value: ULong) { this.raw = value.toULong() }
constructor(value: FlagsTypedEnum) { this.raw = value.raw }
fun hasFlags(flags: ULong): Boolean = ((raw.toULong() and flags.toULong()) != 0uL) && ((raw.toULong() and flags.toULong()) == flags.toULong())
fun hasFlags(flags: FlagsTypedEnum): Boolean = hasFlags(flags.raw)
val allSet: java.util.EnumSet<FlagsTypedEnum> get() = java.util.EnumSet.allOf(FlagsTypedEnum::class.java)
val noneSet: java.util.EnumSet<FlagsTypedEnum> get() = java.util.EnumSet.noneOf(FlagsTypedEnum::class.java)
val currentSet: java.util.EnumSet<FlagsTypedEnum> get()
{
val result = java.util.EnumSet.noneOf(FlagsTypedEnum::class.java)
if ((raw.toULong() and FLAG_VALUE_0.raw.toULong()) != 0uL)
{
result.add(FLAG_VALUE_0)
}
if ((raw.toULong() and FLAG_VALUE_1.raw.toULong()) != 0uL)
{
result.add(FLAG_VALUE_1)
}
if ((raw.toULong() and FLAG_VALUE_2.raw.toULong()) != 0uL)
{
result.add(FLAG_VALUE_2)
}
if ((raw.toULong() and FLAG_VALUE_3.raw.toULong()) != 0uL)
{
result.add(FLAG_VALUE_3)
}
if ((raw.toULong() and FLAG_VALUE_4.raw.toULong()) != 0uL)
{
result.add(FLAG_VALUE_4)
}
if ((raw.toULong() and FLAG_VALUE_5.raw.toULong()) != 0uL)
{
result.add(FLAG_VALUE_5)
}
if ((raw.toULong() and FLAG_VALUE_6.raw.toULong()) != 0uL)
{
result.add(FLAG_VALUE_6)
}
if ((raw.toULong() and FLAG_VALUE_7.raw.toULong()) != 0uL)
{
result.add(FLAG_VALUE_7)
}
if ((raw.toULong() and FLAG_VALUE_8.raw.toULong()) != 0uL)
{
result.add(FLAG_VALUE_8)
}
if ((raw.toULong() and FLAG_VALUE_9.raw.toULong()) != 0uL)
{
result.add(FLAG_VALUE_9)
}
return result
}
override fun toString(): String
{
val sb = StringBuilder()
var first = true
if (hasFlags(FLAG_VALUE_0))
{
sb.append(if (first) "" else "|").append("FLAG_VALUE_0")
@Suppress("UNUSED_VALUE")
first = false
}
if (hasFlags(FLAG_VALUE_1))
{
sb.append(if (first) "" else "|").append("FLAG_VALUE_1")
@Suppress("UNUSED_VALUE")
first = false
}
if (hasFlags(FLAG_VALUE_2))
{
sb.append(if (first) "" else "|").append("FLAG_VALUE_2")
@Suppress("UNUSED_VALUE")
first = false
}
if (hasFlags(FLAG_VALUE_3))
{
sb.append(if (first) "" else "|").append("FLAG_VALUE_3")
@Suppress("UNUSED_VALUE")
first = false
}
if (hasFlags(FLAG_VALUE_4))
{
sb.append(if (first) "" else "|").append("FLAG_VALUE_4")
@Suppress("UNUSED_VALUE")
first = false
}
if (hasFlags(FLAG_VALUE_5))
{
sb.append(if (first) "" else "|").append("FLAG_VALUE_5")
@Suppress("UNUSED_VALUE")
first = false
}
if (hasFlags(FLAG_VALUE_6))
{
sb.append(if (first) "" else "|").append("FLAG_VALUE_6")
@Suppress("UNUSED_VALUE")
first = false
}
if (hasFlags(FLAG_VALUE_7))
{
sb.append(if (first) "" else "|").append("FLAG_VALUE_7")
@Suppress("UNUSED_VALUE")
first = false
}
if (hasFlags(FLAG_VALUE_8))
{
sb.append(if (first) "" else "|").append("FLAG_VALUE_8")
@Suppress("UNUSED_VALUE")
first = false
}
if (hasFlags(FLAG_VALUE_9))
{
sb.append(if (first) "" else "|").append("FLAG_VALUE_9")
@Suppress("UNUSED_VALUE")
first = false
}
return sb.toString()
}
companion object
{
private val mapping = java.util.HashMap<ULong, FlagsTypedEnum>()
init
{
for (value in FlagsTypedEnum.values())
mapping[value.raw] = value
}
fun mapValue(value: ULong): FlagsTypedEnum? { return mapping[value] }
}
}
| 35 | null | 81 | 764 | 67625fcfbd89ab6adf63982b1330deb84382aa0e | 5,293 | FastBinaryEncoding | MIT License |
composeApp/src/commonMain/kotlin/com/malliaridis/tui/domain/transmissions/MediaComponent.kt | malliaridis | 781,833,057 | false | {"Kotlin": 218283, "Swift": 1167} | package com.malliaridis.tui.domain.transmissions
/**
* The media component manages the state of any playable media, like video or audio files.
*/
interface MediaComponent
| 0 | Kotlin | 0 | 3 | 740442033e99b21bb7ed2dd8796cc6460a49ea2d | 174 | tactical-user-interface | MIT License |
composeApp/src/commonMain/kotlin/com/malliaridis/tui/domain/transmissions/MediaComponent.kt | malliaridis | 781,833,057 | false | {"Kotlin": 218283, "Swift": 1167} | package com.malliaridis.tui.domain.transmissions
/**
* The media component manages the state of any playable media, like video or audio files.
*/
interface MediaComponent
| 0 | Kotlin | 0 | 3 | 740442033e99b21bb7ed2dd8796cc6460a49ea2d | 174 | tactical-user-interface | MIT License |
android/integration/testData/architecture-samples/shared-test/src/main/java/com/example/android/architecture/blueprints/todoapp/data/FakeTaskRepository.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright 2019 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.xd.mvvm.boilerplate.data
import androidx.annotation.VisibleForTesting
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import java.util.UUID
/**
* Implementation of a tasks repository with static access to the data for easy testing.
*/
class FakeTaskRepository : TaskRepository {
private var shouldThrowError = false
private val _savedTasks = MutableStateFlow(LinkedHashMap<String, Task>())
val savedTasks: StateFlow<LinkedHashMap<String, Task>> = _savedTasks.asStateFlow()
private val observableTasks: Flow<List<Task>> = savedTasks.map {
if (shouldThrowError) {
throw Exception("Test exception")
} else {
it.values.toList()
}
}
fun setShouldThrowError(value: Boolean) {
shouldThrowError = value
}
override suspend fun refresh() {
// Tasks already refreshed
}
override suspend fun refreshTask(taskId: String) {
refresh()
}
override suspend fun createTask(title: String, description: String): String {
val taskId = generateTaskId()
Task(title = title, description = description, id = taskId).also {
saveTask(it)
}
return taskId
}
override fun getTasksStream(): Flow<List<Task>> = observableTasks
override fun getTaskStream(taskId: String): Flow<Task?> {
return observableTasks.map { tasks ->
return@map tasks.firstOrNull { it.id == taskId }
}
}
override suspend fun getTask(taskId: String, forceUpdate: Boolean): Task? {
if (shouldThrowError) {
throw Exception("Test exception")
}
return savedTasks.value[taskId]
}
override suspend fun getTasks(forceUpdate: Boolean): List<Task> {
if (shouldThrowError) {
throw Exception("Test exception")
}
return observableTasks.first()
}
override suspend fun updateTask(taskId: String, title: String, description: String) {
val updatedTask = _savedTasks.value[taskId]?.copy(
title = title,
description = description
) ?: throw Exception("Task (id $taskId) not found")
saveTask(updatedTask)
}
private fun saveTask(task: Task) {
_savedTasks.update { tasks ->
val newTasks = LinkedHashMap<String, Task>(tasks)
newTasks[task.id] = task
newTasks
}
}
override suspend fun completeTask(taskId: String) {
_savedTasks.value[taskId]?.let {
saveTask(it.copy(isCompleted = true))
}
}
override suspend fun activateTask(taskId: String) {
_savedTasks.value[taskId]?.let {
saveTask(it.copy(isCompleted = false))
}
}
override suspend fun clearCompletedTasks() {
_savedTasks.update { tasks ->
tasks.filterValues {
!it.isCompleted
} as LinkedHashMap<String, Task>
}
}
override suspend fun deleteTask(taskId: String) {
_savedTasks.update { tasks ->
val newTasks = LinkedHashMap<String, Task>(tasks)
newTasks.remove(taskId)
newTasks
}
}
override suspend fun deleteAllTasks() {
_savedTasks.update {
LinkedHashMap()
}
}
private fun generateTaskId() = UUID.randomUUID().toString()
@VisibleForTesting
fun addTasks(vararg tasks: Task) {
_savedTasks.update { oldTasks ->
val newTasks = LinkedHashMap<String, Task>(oldTasks)
for (task in tasks) {
newTasks[task.id] = task
}
newTasks
}
}
}
| 5 | null | 227 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 4,519 | android | Apache License 2.0 |
app/src/main/java/com/carin/data/local/daos/UserDao.kt | MEI-Grupo-4-CarIn | 773,390,235 | false | {"Kotlin": 348045} | package com.carin.data.local.daos
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.RawQuery
import androidx.room.Upsert
import androidx.sqlite.db.SimpleSQLiteQuery
import androidx.sqlite.db.SupportSQLiteQuery
import com.carin.data.local.entities.UserEntity
import com.carin.domain.enums.Role
@Dao
interface UserDao {
@Query("SELECT * FROM users WHERE id = :id LIMIT 1")
suspend fun getUserById(id: Int): UserEntity?
@Insert
suspend fun insertUser(user: UserEntity)
@Upsert
suspend fun upsertUser(user: UserEntity)
@Upsert
suspend fun upsertUsers(users: List<UserEntity>)
@Query("""
UPDATE users SET
firstName = CASE WHEN :firstName IS NOT NULL THEN :firstName ELSE firstName END,
lastName = CASE WHEN :lastName IS NOT NULL THEN :lastName ELSE lastName END,
email = CASE WHEN :email IS NOT NULL THEN :email ELSE email END
WHERE id = :id
""")
suspend fun updatePartialUser(
id: Int,
firstName: String?,
lastName: String?,
email: String?
)
@RawQuery
suspend fun getUsers(query: SupportSQLiteQuery): List<UserEntity>
suspend fun getListOfUsers(search: String?, role: Role?, page: Int = 1, perPage: Int = 10): List<UserEntity> {
val queryBuilder = StringBuilder("SELECT * FROM users WHERE status = 1")
val args = mutableListOf<Any?>()
if (!search.isNullOrEmpty()) {
queryBuilder.append(" AND (firstName LIKE ? OR lastName LIKE ? OR email LIKE ?)")
val searchPattern = "%${search}%"
args.add(searchPattern)
args.add(searchPattern)
args.add(searchPattern)
}
if (role != null) {
queryBuilder.append(" AND roleId = ?")
args.add(role.roleId)
}
queryBuilder.append(" ORDER BY id DESC")
val offset = (page - 1) * perPage
queryBuilder.append(" LIMIT ? OFFSET ?")
args.add(perPage)
args.add(offset)
val query = SimpleSQLiteQuery(queryBuilder.toString(), args.toTypedArray())
return getUsers(query)
}
}
| 2 | Kotlin | 0 | 0 | 70ea4c4ce707f3a7a1dd1e4daaf0d31302ef26c1 | 2,177 | CarIn.AndroidApp | MIT License |
app/src/main/java/com/beettechnologies/newsapp/common/data/ApiInterceptor.kt | beetsolutions | 162,338,193 | false | null | package com.beettechnologies.newsapp.common.data
import okhttp3.Interceptor
import okhttp3.Response
private const val PARAM_API_ID: String = "apiKey"
private const val PARAM_CACHE: String = "Cache-Control"
class ApiInterceptor(private val apiKey: String, private val cacheDuration: Int) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val url = request.url().newBuilder()
.addQueryParameter(PARAM_API_ID, apiKey)
.build()
val newRequest = request.newBuilder()
.url(url)
.addHeader(PARAM_CACHE, "public, max-age=$cacheDuration")
.build()
return chain.proceed(newRequest)
}
} | 0 | Kotlin | 0 | 0 | eb9b43f28e3c23385710e6b10199a38bad70efed | 739 | newsapp | MIT License |
apps/etterlatte-tidshendelser/src/main/kotlin/no/nav/etterlatte/tidshendelser/AldersovergangerService.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.tidshendelser
import kotlinx.coroutines.runBlocking
import no.nav.etterlatte.libs.common.retryOgPakkUt
import no.nav.etterlatte.libs.common.sak.SakId
import no.nav.etterlatte.libs.tidshendelser.JobbType
import no.nav.etterlatte.tidshendelser.klient.BehandlingKlient
import no.nav.etterlatte.tidshendelser.klient.GrunnlagKlient
import org.slf4j.LoggerFactory
class AldersovergangerService(
private val hendelseDao: HendelseDao,
private val grunnlagKlient: GrunnlagKlient,
private val behandlingKlient: BehandlingKlient,
) {
private val logger = LoggerFactory.getLogger(this::class.java)
fun execute(jobb: HendelserJobb): List<SakId> {
logger.info("Handling jobb ${jobb.id}, type=${jobb.type} (${jobb.type.beskrivelse})")
val yearsToSubtract =
when (jobb.type) {
JobbType.AO_BP20 -> 20L
JobbType.AO_BP21 -> 21L
JobbType.AO_OMS67 -> 67L
else -> throw IllegalArgumentException("Ikke-støttet jobbtype: ${jobb.type}")
}
val foedselsmaaned = jobb.behandlingsmaaned.minusYears(yearsToSubtract)
val saker =
runBlocking {
retryOgPakkUt {
grunnlagKlient.hentSaker(foedselsmaaned = foedselsmaaned)
}
}
// filtrerer bort saker som ikke er aktuelle
val sakerMap =
runBlocking {
retryOgPakkUt {
behandlingKlient.hentSaker(saker)
}
}
val aktuelleSaker =
saker.filter {
sakerMap[it]?.sakType == jobb.type.sakType
}
logger.info(
"Hentet ${saker.size} saker for brukere født i $foedselsmaaned, med ${aktuelleSaker.size} saker " +
"med riktig saktype",
)
if (aktuelleSaker.isNotEmpty()) {
hendelseDao.opprettHendelserForSaker(jobb.id, aktuelleSaker, Steg.IDENTIFISERT_SAK)
}
return aktuelleSaker
}
}
| 9 | Kotlin | 0 | 6 | e715675c319d4a0a826855615749573e45ae7a75 | 2,055 | pensjon-etterlatte-saksbehandling | MIT License |
thirdparty/ktfx-jfoenix-layouts/src/test/kotlin/ktfx/jfoenix/layouts/JfxSpinnerTest.kt | hanggrian | 102,934,147 | false | {"Kotlin": 1146536, "CSS": 1653} | package ktfx.jfoenix.layouts
import com.hanggrian.ktfx.test.LayoutsStyledTest
import com.jfoenix.controls.JFXSpinner
import ktfx.layouts.KtfxPane
import kotlin.test.assertEquals
class JfxSpinnerTest : LayoutsStyledTest<KtfxPane, JFXSpinner>() {
override fun manager() = KtfxPane()
override fun KtfxPane.childCount() = children.size
override fun child1() = jfxSpinner {}
override fun KtfxPane.child2() = jfxSpinner()
override fun child3() = styledJfxSpinner(styleClass = arrayOf("style"))
override fun KtfxPane.child4() = styledJfxSpinner(styleClass = arrayOf("style"))
override fun JFXSpinner.testDefaultValues() {
assertEquals(JFXSpinner.INDETERMINATE_PROGRESS, progress)
}
}
| 1 | Kotlin | 2 | 19 | 6e5ec9fedf8359423c31a2ba64cd175bc9864cd2 | 725 | ktfx | Apache License 2.0 |
src/test/kotlin/no/nav/pensjon/simulator/tech/security/egress/oauth2/OAuth2ParameterBuilderTest.kt | navikt | 753,551,695 | false | {"Kotlin": 1507098, "Java": 133600, "Dockerfile": 144} | package no.nav.pensjon.kalkulator.tech.security.egress.oauth2
import no.nav.pensjon.kalkulator.tech.security.egress.token.TokenAccessParameter
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import org.springframework.util.MultiValueMap
class OAuth2ParameterBuilderTest {
@Test
fun `buildClientCredentialsTokenRequestMap builds map with client credentials parameters`() {
val map = OAuth2ParameterBuilder()
.clientId("id1")
.clientSecret("secret1")
.tokenAccessParameter(TokenAccessParameter.clientCredentials("scope1"))
.buildClientCredentialsTokenRequestMap()
assertMapValue("client_credentials", map, "grant_type")
assertMapValue("scope1", map, "scope")
assertMapValue("id1", map, "client_id")
assertMapValue("secret1", map, "client_secret")
}
companion object {
private fun assertMapValue(expectedValue: String, map: MultiValueMap<String, String>, key: String) {
assertEquals(expectedValue, map[key]!![0])
}
}
}
| 0 | Kotlin | 0 | 0 | c36141a4a420f2a8837ba8bf235a437dc96a79e5 | 1,085 | pensjonssimulator | MIT License |
sykepenger-utbetaling/src/main/kotlin/no/nav/helse/hendelser/utbetaling/UtbetalingHendelse.kt | navikt | 193,907,367 | false | null | package no.nav.helse.hendelser.utbetaling
import java.time.LocalDateTime
import java.util.UUID
import no.nav.helse.hendelser.ArbeidstakerHendelse
import no.nav.helse.person.aktivitetslogg.Varselkode.RV_UT_2
import no.nav.helse.utbetalingslinjer.Oppdragstatus
import no.nav.helse.utbetalingslinjer.Oppdragstatus.AKSEPTERT_MED_FEIL
import no.nav.helse.utbetalingslinjer.Oppdragstatus.AVVIST
import no.nav.helse.utbetalingslinjer.Oppdragstatus.FEIL
class UtbetalingHendelse(
meldingsreferanseId: UUID,
aktørId: String,
fødselsnummer: String,
orgnummer: String,
private val fagsystemId: String,
private val utbetalingId: String,
val status: Oppdragstatus,
private val melding: String,
val avstemmingsnøkkel: Long,
val overføringstidspunkt: LocalDateTime
) : ArbeidstakerHendelse(meldingsreferanseId, fødselsnummer, aktørId, orgnummer) {
fun valider() = this.apply {
if (status == AVVIST || status == FEIL) info("Utbetaling feilet med status $status. Feilmelding fra Oppdragsystemet: $melding")
else if (status == AKSEPTERT_MED_FEIL) varsel(RV_UT_2)
}
fun skalForsøkesIgjen() = status in setOf(AVVIST, FEIL)
fun erRelevant(fagsystemId: String) = this.fagsystemId == fagsystemId
fun erRelevant(arbeidsgiverFagsystemId: String, personFagsystemId: String, utbetalingId: UUID) =
(erRelevant(arbeidsgiverFagsystemId) || erRelevant(personFagsystemId)) && this.utbetalingId == utbetalingId.toString()
}
| 2 | Kotlin | 6 | 5 | 314d8a6e32b3dda391bcac31e0b4aeeee68f9f9b | 1,481 | helse-spleis | MIT License |
core/src/main/java/com/gerosprime/gylog/models/data/DefaultDataImporter.kt | gerosprime | 213,372,637 | false | null | package com.gerosprime.gylog.models.data
import android.content.Context
import com.gerosprime.gylog.models.database.dao.*
import com.google.gson.Gson
import io.reactivex.Single
import java.io.*
class DefaultDataImporter(private val exerciseEntityDao : ExerciseEntityDao,
private val exercisePerformedDao : ExercisePerformedEntityDao,
private val exerciseTemplateEntityDao : ExerciseTemplateEntityDao,
private val performedSetEntityDao : PerformedSetEntityDao,
private val programEntityDao : ProgramEntityDao,
private val templateSetEntityDao : TemplateSetEntityDao,
private val workoutEntityDao : WorkoutEntityDao,
private val workoutSessionEntityDao : WorkoutSessionEntityDao,
private val bodyWeightEntityDao : BodyWeightEntityDao,
private val bodyFatEntityDao : BodyFatEntityDao) : DataImporter {
private val gson = Gson()
override fun importFromAsset(fileName : String, context: Context): Single<DataImportResult> {
return Single.fromCallable {
BufferedReader(InputStreamReader(context.assets.open(fileName)))
}.flatMap {
importFromReader(it)
}
}
override fun importFromFile(file: File): Single<DataImportResult> {
return Single.fromCallable {
BufferedReader(FileReader(file))
}.flatMap {
importFromReader(it)
}
}
private fun importFromReader(reader : Reader): Single<DataImportResult> {
return Single.fromCallable {
val importedData : ImportedJSONData
= gson.fromJson(reader, ImportedJSONData::class.java)
exerciseEntityDao.saveExercises(importedData.exercises)
exercisePerformedDao.saveExercises(importedData.performedExercises)
exerciseTemplateEntityDao.saveExercises(importedData.templateExercises)
performedSetEntityDao.saveSets(importedData.performedSets)
programEntityDao.savePrograms(importedData.programs)
templateSetEntityDao.saveTemplateSets(importedData.templateSets)
workoutEntityDao.saveWorkouts(importedData.workouts)
workoutSessionEntityDao.insertSessions(importedData.workoutsSessions)
bodyWeightEntityDao.saveBodyWeights(importedData.workoutBodyWeightEntities)
bodyFatEntityDao.saveMultiple(importedData.bodyFatEntities)
DataImportResult()
}
}
}
| 0 | Kotlin | 0 | 1 | a775377e6a8bdb81e405eb1b04ca5fd14f5dd9c6 | 2,617 | gylog-android-app | Apache License 2.0 |
intellij-plugin/educational-core/src/com/jetbrains/edu/coursecreator/actions/checkAllTasks/checkAllTasksUtil.kt | JetBrains | 43,696,115 | false | null | package com.jetbrains.edu.coursecreator.actions.checkAllTasks
import com.intellij.notification.Notification
import com.intellij.notification.NotificationListener
import com.intellij.notification.NotificationType.WARNING
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.jetbrains.edu.learning.checker.EduTaskCheckerBase
import com.jetbrains.edu.learning.courseFormat.*
import com.jetbrains.edu.learning.courseFormat.ext.configurator
import com.jetbrains.edu.learning.courseFormat.tasks.Task
import com.jetbrains.edu.learning.courseFormat.tasks.TheoryTask
import com.jetbrains.edu.learning.courseFormat.tasks.choice.ChoiceTask
import com.jetbrains.edu.learning.messages.EduCoreBundle
import com.jetbrains.edu.learning.navigation.NavigationUtils
import com.jetbrains.edu.learning.notification.EduNotificationManager
import com.jetbrains.edu.learning.statistics.EduCounterUsageCollector
import javax.swing.event.HyperlinkEvent
/**
* Checks all tasks that are in [studyItems] and returns a list of failed tasks
*/
/*
* Important note: we deliberately start with checking sections, then check lessons, and then individual tasks.
* Why? Because a person can choose out a separate task as a task located in the selected lesson / section.
* We don't want to check such tasks twice, and that’s why we have such order of checking.
*/
fun checkAllStudyItems(
project: Project,
course: Course,
studyItems: List<StudyItem>,
indicator: ProgressIndicator
): List<Task>? {
val failedTasks = mutableListOf<Task>()
val (tasks, lessons, sections) = splitStudyItems(studyItems)
val selectedCourse = studyItems.find { it is Course }
if (selectedCourse != null) {
return checkAllTasksInItemContainer(project, course, selectedCourse as Course, indicator)
}
for (section in sections) {
failedTasks += checkAllTasksInItemContainer(project, course, section, indicator) ?: return null
}
for (lesson in lessons) {
if (lesson.section in sections) continue
failedTasks += checkAllTasksInItemContainer(project, course, lesson, indicator) ?: return null
}
for (task in tasks) {
if (task.lesson in lessons || task.lesson.section in sections) continue
indicator.isIndeterminate = true
indicator.text = EduCoreBundle.message("progress.text.checking.task", task.name)
if (!checkTask(project, course, task, indicator)) {
failedTasks.add(task)
}
indicator.isIndeterminate = false
if (indicator.isCanceled) {
return null
}
}
return failedTasks
}
/**
* Split studyItems into (Tasks, Lessons, Sections)
*/
fun splitStudyItems(studyItems: List<StudyItem>): Triple<Set<Task>, Set<Lesson>, Set<Section>> {
val tasks = mutableSetOf<Task>()
val lessons = mutableSetOf<Lesson>()
val sections = mutableSetOf<Section>()
for (item in studyItems) {
when (item) {
is Task -> tasks += item
is Lesson -> lessons += item
is Section -> sections += item
}
}
return Triple(tasks, lessons, sections)
}
/**
* Checks all tasks in lesson container and returns list of failed tasks
*
* @return List of failed tasks, null if the indicator was cancelled
*/
fun checkAllTasksInItemContainer(
project: Project,
course: Course,
itemContainer: ItemContainer,
indicator: ProgressIndicator
): List<Task>? {
val failedTasks = mutableListOf<Task>()
var curTask = 0
val tasksNum = getNumberOfTasks(itemContainer)
val itemContainerVisitFunc = getVisitItemContainerFunc(itemContainer)
indicator.text = EduCoreBundle.message("progress.text.checking.tasks.in.container", itemContainer.name)
itemContainerVisitFunc.invoke {
if (indicator.isCanceled) {
return@invoke
}
curTask++
indicator.fraction = curTask * 1.0 / tasksNum
if (!checkTask(project, course, it, indicator)) {
failedTasks.add(it)
}
}
if (indicator.isCanceled) {
return null
}
return failedTasks
}
fun checkTask(
project: Project,
course: Course,
task: Task,
indicator: ProgressIndicator
): Boolean {
if (task is TheoryTask || (task is ChoiceTask && task.selectedVariants.isEmpty())) {
return true
}
val checker = course.configurator?.taskCheckerProvider?.getTaskChecker(task, project)!!
if (checker is EduTaskCheckerBase) {
checker.activateRunToolWindow = false
}
val checkResult = checker.check(indicator)
checker.clearState()
return checkResult.status == CheckStatus.Solved
}
/**
* @Returns Number of tasks in [itemContainer]
*/
fun getNumberOfTasks(itemContainer: ItemContainer): Int {
var ans = 0
getVisitItemContainerFunc(itemContainer).invoke { ans++ }
return ans
}
/**
* @Returns summary number of tasks in study items
*/
fun getNumberOfTasks(studyItems: List<StudyItem>): Int {
var sum = 0
val selectedCourse = studyItems.find { it is Course }
if (selectedCourse != null) {
return getNumberOfTasks(selectedCourse as Course)
}
val (tasks, lessons, sections) = splitStudyItems(studyItems)
sum += sections.sumOf { getNumberOfTasks(it) }
sum += lessons.sumOf {
if (it.section !in sections) getNumberOfTasks(it)
else 0
}
sum += tasks.filter { it.lesson !in lessons && it.lesson.section !in sections }.size
return sum
}
fun getVisitItemContainerFunc(itemContainer: ItemContainer): (((Task) -> Unit) -> Unit) {
return when (itemContainer) {
is LessonContainer -> itemContainer::visitTasks
is Lesson -> itemContainer::visitTasks
else -> error("Unable to get the number of tasks of ItemContainer that are not a Lesson or LessonContainer")
}
}
fun showFailedTasksNotification(project: Project, failedTasks: List<Task>, tasksNum: Int) {
EduNotificationManager
.create(WARNING, EduCoreBundle.message("notification.title.check"), notificationContent(failedTasks))
.apply {
subtitle = EduCoreBundle.message("notification.subtitle.some.tasks.failed", failedTasks.size, tasksNum)
setListener(object : NotificationListener.Adapter() {
override fun hyperlinkActivated(notification: Notification, e: HyperlinkEvent) {
notification.hideBalloon()
NavigationUtils.navigateToTask(project, failedTasks[Integer.valueOf(e.description)])
EduCounterUsageCollector.taskNavigation(EduCounterUsageCollector.TaskNavigationPlace.CHECK_ALL_NOTIFICATION)
}
})
if (failedTasks.size > 1) {
addAction(object : AnAction(EduCoreBundle.lazyMessage("action.open.first.failed.task.text")) {
override fun actionPerformed(e: AnActionEvent) {
[email protected]()
NavigationUtils.navigateToTask(project, failedTasks.first())
EduCounterUsageCollector.taskNavigation(EduCounterUsageCollector.TaskNavigationPlace.CHECK_ALL_NOTIFICATION)
}
})
}
}.notify(project)
}
@Suppress("UnstableApiUsage")
@NlsSafe
private fun notificationContent(failedTasks: List<Task>): String =
failedTasks.withIndex().joinToString("<br>") {
"<a href=\"${it.index}\">${it.value.fullName}</a>"
}
private val Task.fullName: String
get() = listOfNotNull(lesson.section, lesson, this).joinToString("/") { it.presentableName } | 7 | null | 49 | 150 | 9cec6c97d896f4485e76cf9a2a95f8a8dd21c982 | 7,345 | educational-plugin | Apache License 2.0 |
internal/src/main/kotlin/com/code42/jenkins/pipelinekt/internal/option/Retry.kt | code42 | 227,466,617 | false | {"Kotlin": 313768} | package com.code42.jenkins.pipelinekt.internal.option
import com.code42.jenkins.pipelinekt.core.StageOption
import com.code42.jenkins.pipelinekt.core.vars.Var
import com.code42.jenkins.pipelinekt.core.writer.GroovyWriter
data class Retry(val times: Var.Literal.Int) : StageOption {
override fun toGroovy(writer: GroovyWriter) {
writer.writeln("retry(${times.toGroovy()})")
}
}
| 4 | Kotlin | 9 | 55 | 7c37bb9c807ae97eecba1f90eac0c669f3da90da | 395 | pipelinekt | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.