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
lithic-kotlin-core/src/main/kotlin/com/lithic/api/models/FinancialAccountCreditConfigurationUpdateParams.kt
lithic-com
658,974,440
false
null
// File generated from our OpenAPI spec by Stainless. package com.lithic.api.models import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.lithic.api.core.ExcludeMissing import com.lithic.api.core.JsonValue import com.lithic.api.core.NoAutoDetect import com.lithic.api.core.toUnmodifiable import com.lithic.api.models.* import java.util.Objects import java.util.Optional class FinancialAccountCreditConfigurationUpdateParams constructor( private val financialAccountToken: String, private val creditLimit: Long?, private val creditProductToken: String?, private val externalBankAccountToken: String?, private val tier: String?, private val additionalQueryParams: Map<String, List<String>>, private val additionalHeaders: Map<String, List<String>>, private val additionalBodyProperties: Map<String, JsonValue>, ) { fun financialAccountToken(): String = financialAccountToken fun creditLimit(): Optional<Long> = Optional.ofNullable(creditLimit) fun creditProductToken(): Optional<String> = Optional.ofNullable(creditProductToken) fun externalBankAccountToken(): Optional<String> = Optional.ofNullable(externalBankAccountToken) fun tier(): Optional<String> = Optional.ofNullable(tier) @JvmSynthetic internal fun getBody(): FinancialAccountCreditConfigurationUpdateBody { return FinancialAccountCreditConfigurationUpdateBody( creditLimit, creditProductToken, externalBankAccountToken, tier, additionalBodyProperties, ) } @JvmSynthetic internal fun getQueryParams(): Map<String, List<String>> = additionalQueryParams @JvmSynthetic internal fun getHeaders(): Map<String, List<String>> = additionalHeaders fun getPathParam(index: Int): String { return when (index) { 0 -> financialAccountToken else -> "" } } @JsonDeserialize(builder = FinancialAccountCreditConfigurationUpdateBody.Builder::class) @NoAutoDetect class FinancialAccountCreditConfigurationUpdateBody internal constructor( private val creditLimit: Long?, private val creditProductToken: String?, private val externalBankAccountToken: String?, private val tier: String?, private val additionalProperties: Map<String, JsonValue>, ) { private var hashCode: Int = 0 @JsonProperty("credit_limit") fun creditLimit(): Long? = creditLimit /** Globally unique identifier for the credit product */ @JsonProperty("credit_product_token") fun creditProductToken(): String? = creditProductToken @JsonProperty("external_bank_account_token") fun externalBankAccountToken(): String? = externalBankAccountToken /** Tier to assign to a financial account */ @JsonProperty("tier") fun tier(): String? = tier @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is FinancialAccountCreditConfigurationUpdateBody && this.creditLimit == other.creditLimit && this.creditProductToken == other.creditProductToken && this.externalBankAccountToken == other.externalBankAccountToken && this.tier == other.tier && this.additionalProperties == other.additionalProperties } override fun hashCode(): Int { if (hashCode == 0) { hashCode = Objects.hash( creditLimit, creditProductToken, externalBankAccountToken, tier, additionalProperties, ) } return hashCode } override fun toString() = "FinancialAccountCreditConfigurationUpdateBody{creditLimit=$creditLimit, creditProductToken=$creditProductToken, externalBankAccountToken=$externalBankAccountToken, tier=$tier, additionalProperties=$additionalProperties}" companion object { @JvmStatic fun builder() = Builder() } class Builder { private var creditLimit: Long? = null private var creditProductToken: String? = null private var externalBankAccountToken: String? = null private var tier: String? = null private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() @JvmSynthetic internal fun from( financialAccountCreditConfigurationUpdateBody: FinancialAccountCreditConfigurationUpdateBody ) = apply { this.creditLimit = financialAccountCreditConfigurationUpdateBody.creditLimit this.creditProductToken = financialAccountCreditConfigurationUpdateBody.creditProductToken this.externalBankAccountToken = financialAccountCreditConfigurationUpdateBody.externalBankAccountToken this.tier = financialAccountCreditConfigurationUpdateBody.tier additionalProperties( financialAccountCreditConfigurationUpdateBody.additionalProperties ) } @JsonProperty("credit_limit") fun creditLimit(creditLimit: Long) = apply { this.creditLimit = creditLimit } /** Globally unique identifier for the credit product */ @JsonProperty("credit_product_token") fun creditProductToken(creditProductToken: String) = apply { this.creditProductToken = creditProductToken } @JsonProperty("external_bank_account_token") fun externalBankAccountToken(externalBankAccountToken: String) = apply { this.externalBankAccountToken = externalBankAccountToken } /** Tier to assign to a financial account */ @JsonProperty("tier") fun tier(tier: String) = apply { this.tier = tier } fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.putAll(additionalProperties) } fun build(): FinancialAccountCreditConfigurationUpdateBody = FinancialAccountCreditConfigurationUpdateBody( creditLimit, creditProductToken, externalBankAccountToken, tier, additionalProperties.toUnmodifiable(), ) } } fun _additionalQueryParams(): Map<String, List<String>> = additionalQueryParams fun _additionalHeaders(): Map<String, List<String>> = additionalHeaders fun _additionalBodyProperties(): Map<String, JsonValue> = additionalBodyProperties override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is FinancialAccountCreditConfigurationUpdateParams && this.financialAccountToken == other.financialAccountToken && this.creditLimit == other.creditLimit && this.creditProductToken == other.creditProductToken && this.externalBankAccountToken == other.externalBankAccountToken && this.tier == other.tier && this.additionalQueryParams == other.additionalQueryParams && this.additionalHeaders == other.additionalHeaders && this.additionalBodyProperties == other.additionalBodyProperties } override fun hashCode(): Int { return Objects.hash( financialAccountToken, creditLimit, creditProductToken, externalBankAccountToken, tier, additionalQueryParams, additionalHeaders, additionalBodyProperties, ) } override fun toString() = "FinancialAccountCreditConfigurationUpdateParams{financialAccountToken=$financialAccountToken, creditLimit=$creditLimit, creditProductToken=$creditProductToken, externalBankAccountToken=$externalBankAccountToken, tier=$tier, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" fun toBuilder() = Builder().from(this) companion object { @JvmStatic fun builder() = Builder() } @NoAutoDetect class Builder { private var financialAccountToken: String? = null private var creditLimit: Long? = null private var creditProductToken: String? = null private var externalBankAccountToken: String? = null private var tier: String? = null private var additionalQueryParams: MutableMap<String, MutableList<String>> = mutableMapOf() private var additionalHeaders: MutableMap<String, MutableList<String>> = mutableMapOf() private var additionalBodyProperties: MutableMap<String, JsonValue> = mutableMapOf() @JvmSynthetic internal fun from( financialAccountCreditConfigurationUpdateParams: FinancialAccountCreditConfigurationUpdateParams ) = apply { this.financialAccountToken = financialAccountCreditConfigurationUpdateParams.financialAccountToken this.creditLimit = financialAccountCreditConfigurationUpdateParams.creditLimit this.creditProductToken = financialAccountCreditConfigurationUpdateParams.creditProductToken this.externalBankAccountToken = financialAccountCreditConfigurationUpdateParams.externalBankAccountToken this.tier = financialAccountCreditConfigurationUpdateParams.tier additionalQueryParams( financialAccountCreditConfigurationUpdateParams.additionalQueryParams ) additionalHeaders(financialAccountCreditConfigurationUpdateParams.additionalHeaders) additionalBodyProperties( financialAccountCreditConfigurationUpdateParams.additionalBodyProperties ) } fun financialAccountToken(financialAccountToken: String) = apply { this.financialAccountToken = financialAccountToken } fun creditLimit(creditLimit: Long) = apply { this.creditLimit = creditLimit } /** Globally unique identifier for the credit product */ fun creditProductToken(creditProductToken: String) = apply { this.creditProductToken = creditProductToken } fun externalBankAccountToken(externalBankAccountToken: String) = apply { this.externalBankAccountToken = externalBankAccountToken } /** Tier to assign to a financial account */ fun tier(tier: String) = apply { this.tier = tier } fun additionalQueryParams(additionalQueryParams: Map<String, List<String>>) = apply { this.additionalQueryParams.clear() putAllQueryParams(additionalQueryParams) } fun putQueryParam(name: String, value: String) = apply { this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) } fun putQueryParams(name: String, values: Iterable<String>) = apply { this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) } fun putAllQueryParams(additionalQueryParams: Map<String, Iterable<String>>) = apply { additionalQueryParams.forEach(this::putQueryParams) } fun removeQueryParam(name: String) = apply { this.additionalQueryParams.put(name, mutableListOf()) } fun additionalHeaders(additionalHeaders: Map<String, Iterable<String>>) = apply { this.additionalHeaders.clear() putAllHeaders(additionalHeaders) } fun putHeader(name: String, value: String) = apply { this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) } fun putHeaders(name: String, values: Iterable<String>) = apply { this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) } fun putAllHeaders(additionalHeaders: Map<String, Iterable<String>>) = apply { additionalHeaders.forEach(this::putHeaders) } fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } fun additionalBodyProperties(additionalBodyProperties: Map<String, JsonValue>) = apply { this.additionalBodyProperties.clear() this.additionalBodyProperties.putAll(additionalBodyProperties) } fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { this.additionalBodyProperties.put(key, value) } fun putAllAdditionalBodyProperties(additionalBodyProperties: Map<String, JsonValue>) = apply { this.additionalBodyProperties.putAll(additionalBodyProperties) } fun build(): FinancialAccountCreditConfigurationUpdateParams = FinancialAccountCreditConfigurationUpdateParams( checkNotNull(financialAccountToken) { "`financialAccountToken` is required but was not set" }, creditLimit, creditProductToken, externalBankAccountToken, tier, additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), additionalBodyProperties.toUnmodifiable(), ) } }
1
null
0
2
e26aa7f2ea0ecea64858e969d444d60291946a69
14,574
lithic-kotlin
Apache License 2.0
text/text/src/androidTest/java/androidx/compose/ui/text/android/selection/WordIteratorTest.kt
RikkaW
389,105,112
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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text.android.selection import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import com.google.common.truth.Truth.assertThat import java.text.BreakIterator import java.util.Locale import org.junit.Test import org.junit.runner.RunWith @SmallTest @RunWith(AndroidJUnit4::class) class WordIteratorTest { @Test(expected = IllegalArgumentException::class) fun testConstructor_IndexOutOfBounds_too_big() { WordIterator("text", 100, 100, Locale.ENGLISH) } @Test(expected = IllegalArgumentException::class) fun testConstructor_IndexOutOfBounds_too_small() { WordIterator("text", -100, -100, Locale.ENGLISH) } @Test fun testConstructor_valid_full_text() { val text = "text" WordIterator(text, 0, text.length, Locale.ENGLISH) } @Test fun testConstructor_valid_beginning() { val text = "text" WordIterator(text, 0, 0, Locale.ENGLISH) } @Test fun testConstructor_valid_end() { val text = "text" WordIterator(text, 0, text.length, Locale.ENGLISH) } @Test(expected = IllegalArgumentException::class) fun testNextBoundary_out_of_boundary_too_small() { val text = "abc def-ghi. jkl" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) wordIterator.nextBoundary(-1) } @Test(expected = IllegalArgumentException::class) fun testNextBoundary_out_of_boundary_too_big() { val text = "abc def-ghi. jkl" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) wordIterator.nextBoundary(text.length + 1) } @Test fun testNextBoundary_iterate_through() { val text = "abc def-ghi. jkl" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) // Start from the beginning. var currentOffset = 0 // The word is "abc". currentOffset = wordIterator.nextBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('c') + 1) // The word is space. currentOffset = wordIterator.nextBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('d')) // The word is "def". currentOffset = wordIterator.nextBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('f') + 1) // The word is "-". currentOffset = wordIterator.nextBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('g')) // The word is "ghi". currentOffset = wordIterator.nextBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('i') + 1) // The word is ".". currentOffset = wordIterator.nextBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('.') + 1) // The word is space. currentOffset = wordIterator.nextBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('j')) // The word is "jkl". currentOffset = wordIterator.nextBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.length) // WordIterator reaches the end. currentOffset = wordIterator.nextBoundary(currentOffset) assertThat(currentOffset).isEqualTo(BreakIterator.DONE) } @Test fun testNextBoundary_iterate_through_RTL() { // Hebrew -- "אבג דה-וז. חט" val text = "\u05d0\u05d1\u05d2 \u05d3\u05d4-\u05d5\u05d6. \u05d7\u05d8" val wordIterator = WordIterator( text, 0, text.length, Locale("he", "IL") ) // Start from the beginning. var currentOffset = 0 // The word is "\u05d0\u05d1\u05d2"("אבג") currentOffset = wordIterator.nextBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('\u05d2') + 1) // The word is space. currentOffset = wordIterator.nextBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('\u05d3')) // The word is "\u05d3\u05d4"("דה") currentOffset = wordIterator.nextBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('-')) // The word is "-". currentOffset = wordIterator.nextBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('\u05d5')) // The word is "\u05d5\u05d6("וז") currentOffset = wordIterator.nextBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('.')) // The word is ".". currentOffset = wordIterator.nextBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('.') + 1) // The word is space. currentOffset = wordIterator.nextBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('\u05d7')) // The word is "\u05d7\u05d8"("חט") currentOffset = wordIterator.nextBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.length) // WordIterator reaches the end. currentOffset = wordIterator.nextBoundary(currentOffset) assertThat(currentOffset).isEqualTo(BreakIterator.DONE) } @Test(expected = IllegalArgumentException::class) fun testPrevBoundary_out_of_boundary_too_small() { val text = "abc def-ghi. jkl" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) wordIterator.prevBoundary(-1) } @Test(expected = IllegalArgumentException::class) fun testPrevBoundary_out_of_boundary_too_big() { val text = "abc def-ghi. jkl" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) wordIterator.prevBoundary(text.length + 1) } @Test fun testPrevBoundary_iterate_through() { val text = "abc def-ghi. jkl" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) // Start from the end. var currentOffset = text.length // The word is "jkl". currentOffset = wordIterator.prevBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('j')) // The word is space. currentOffset = wordIterator.prevBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('.') + 1) // The word is ".". currentOffset = wordIterator.prevBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('i') + 1) // The word is "ghi". currentOffset = wordIterator.prevBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('g')) // The word is "-". currentOffset = wordIterator.prevBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('f') + 1) // The word is "def". currentOffset = wordIterator.prevBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('d')) // The word is space. currentOffset = wordIterator.prevBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('c') + 1) // The word is "abc". currentOffset = wordIterator.prevBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('a')) // WordIterator reaches the beginning. currentOffset = wordIterator.prevBoundary(currentOffset) assertThat(currentOffset).isEqualTo(BreakIterator.DONE) } @Test fun testPrevBoundary_iterate_through_RTL() { // Hebrew -- "אבג דה-וז. חט" val text = "\u05d0\u05d1\u05d2 \u05d3\u05d4-\u05d5\u05d6. \u05d7\u05d8" val wordIterator = WordIterator( text, 0, text.length, Locale("he", "IL") ) // Start from the end. var currentOffset = text.length // The word is "\u05d7\u05d8"("חט") currentOffset = wordIterator.prevBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('\u05d7')) // The word is space. currentOffset = wordIterator.prevBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('.') + 1) // The word is '.'. currentOffset = wordIterator.prevBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('.')) // The word is "\u05d5\u05d6("וז") currentOffset = wordIterator.prevBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('\u05d5')) // The word is "-". currentOffset = wordIterator.prevBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('-')) // The word is "\u05d3\u05d4"("דה") currentOffset = wordIterator.prevBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('\u05d3')) // The word is space. currentOffset = wordIterator.prevBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf(' ')) // The word is "\u05d0\u05d1\u05d2"("אבג") currentOffset = wordIterator.prevBoundary(currentOffset) assertThat(currentOffset).isEqualTo(text.indexOf('\u05d0')) // WordIterator reaches the beginning. currentOffset = wordIterator.prevBoundary(currentOffset) assertThat(currentOffset).isEqualTo(BreakIterator.DONE) } @Test(expected = IllegalArgumentException::class) fun testGetPrevWordBeginningOnTwoWordsBoundary_out_of_boundary_too_small() { val text = "abc def-ghi. jkl" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) wordIterator.getPrevWordBeginningOnTwoWordsBoundary(-1) } @Test(expected = IllegalArgumentException::class) fun testGetPrevWordBeginningOnTwoWordsBoundary_out_of_boundary_too_big() { val text = "abc def-ghi. jkl" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) wordIterator.getPrevWordBeginningOnTwoWordsBoundary(text.length + 1) } @Test fun testGetPrevWordBeginningOnTwoWordsBoundary_Empty_String() { val text = "" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) assertThat(wordIterator.getPrevWordBeginningOnTwoWordsBoundary(0)) .isEqualTo(BreakIterator.DONE) } @Test fun testGetPrevWordBeginningOnTwoWordsBoundary() { val text = "abc def-ghi. jkl" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) assertThat(wordIterator.getPrevWordBeginningOnTwoWordsBoundary(text.indexOf('a'))) .isEqualTo(text.indexOf('a')) assertThat(wordIterator.getPrevWordBeginningOnTwoWordsBoundary(text.indexOf('c'))) .isEqualTo(text.indexOf('a')) assertThat(wordIterator.getPrevWordBeginningOnTwoWordsBoundary(text.indexOf('d'))) .isEqualTo(text.indexOf('d')) assertThat(wordIterator.getPrevWordBeginningOnTwoWordsBoundary(text.indexOf('f'))) .isEqualTo(text.indexOf('d')) assertThat(wordIterator.getPrevWordBeginningOnTwoWordsBoundary(text.indexOf('-'))) .isEqualTo(text.indexOf('d')) assertThat(wordIterator.getPrevWordBeginningOnTwoWordsBoundary(text.indexOf('g'))) .isEqualTo(text.indexOf('g')) assertThat(wordIterator.getPrevWordBeginningOnTwoWordsBoundary(text.indexOf('.'))) .isEqualTo(text.indexOf('g')) } @Test fun testGetPrevWordBeginningOnTwoWordsBoundary_CJK() { // Japanese HIRAGANA letter + KATAKANA letters -- "あアィイ" val text = "\u3042\u30A2\u30A3\u30A4" val wordIterator = WordIterator(text, 0, text.length, Locale.JAPANESE) assertThat(wordIterator.getPrevWordBeginningOnTwoWordsBoundary(text.indexOf('\u3042'))) .isEqualTo(text.indexOf('\u3042')) assertThat(wordIterator.getPrevWordBeginningOnTwoWordsBoundary(text.indexOf('\u30A2'))) .isEqualTo(text.indexOf('\u3042')) assertThat(wordIterator.getPrevWordBeginningOnTwoWordsBoundary(text.indexOf('\u30A4'))) .isEqualTo(text.indexOf('\u30A2')) assertThat(wordIterator.getPrevWordBeginningOnTwoWordsBoundary(text.length)) .isEqualTo(text.indexOf('\u30A2')) } @Test fun testGetPrevWordBeginningOnTwoWordsBoundary_apostropheMiddleOfWord() { // These tests confirm that the word "isn't" is treated like one word. val text = "isn't he" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) assertThat(wordIterator.getPrevWordBeginningOnTwoWordsBoundary(text.indexOf('i'))) .isEqualTo(text.indexOf('i')) assertThat(wordIterator.getPrevWordBeginningOnTwoWordsBoundary(text.indexOf('n'))) .isEqualTo(text.indexOf('i')) assertThat(wordIterator.getPrevWordBeginningOnTwoWordsBoundary(text.indexOf('\''))) .isEqualTo(text.indexOf('i')) assertThat(wordIterator.getPrevWordBeginningOnTwoWordsBoundary(text.indexOf('t'))) .isEqualTo(text.indexOf('i')) assertThat(wordIterator.getPrevWordBeginningOnTwoWordsBoundary(text.indexOf('t') + 1)) .isEqualTo(text.indexOf('i')) assertThat(wordIterator.getPrevWordBeginningOnTwoWordsBoundary(text.indexOf('h'))) .isEqualTo(text.indexOf('h')) } @Test(expected = IllegalArgumentException::class) fun testGetNextWordEndOnTwoWordBoundary_out_of_boundary_too_small() { val text = "abc def-ghi. jkl" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) wordIterator.getNextWordEndOnTwoWordBoundary(-1) } @Test(expected = IllegalArgumentException::class) fun testGetNextWordEndOnTwoWordBoundary_out_of_boundary_too_big() { val text = "abc def-ghi. jkl" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) wordIterator.getNextWordEndOnTwoWordBoundary(text.length + 1) } @Test fun testGetNextWordEndOnTwoWordBoundary_Empty_String() { val text = "" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) assertThat(wordIterator.getNextWordEndOnTwoWordBoundary(0)) .isEqualTo(BreakIterator.DONE) } @Test fun testGetNextWordEndOnTwoWordBoundary() { val text = "abc def-ghi. jkl" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) assertThat(wordIterator.getNextWordEndOnTwoWordBoundary(text.indexOf('a'))) .isEqualTo(text.indexOf(' ')) assertThat(wordIterator.getNextWordEndOnTwoWordBoundary(text.indexOf('c'))) .isEqualTo(text.indexOf(' ')) assertThat(wordIterator.getNextWordEndOnTwoWordBoundary(text.indexOf('d'))) .isEqualTo(text.indexOf('-')) assertThat(wordIterator.getNextWordEndOnTwoWordBoundary(text.indexOf('f'))) .isEqualTo(text.indexOf('-')) assertThat(wordIterator.getNextWordEndOnTwoWordBoundary(text.indexOf('-'))) .isEqualTo(text.indexOf('-')) } @Test fun testGetNextWordEndOnTwoWordBoundary_CJK() { // Japanese HIRAGANA letter + KATAKANA letters -- "あアィイ" val text = "\u3042\u30A2\u30A3\u30A4" val wordIterator = WordIterator(text, 0, text.length, Locale.JAPANESE) assertThat(wordIterator.getNextWordEndOnTwoWordBoundary(text.indexOf('\u3042'))) .isEqualTo(text.indexOf('\u3042') + 1) assertThat(wordIterator.getNextWordEndOnTwoWordBoundary(text.indexOf('\u30A2'))) .isEqualTo(text.indexOf('\u30A4') + 1) assertThat(wordIterator.getNextWordEndOnTwoWordBoundary(text.indexOf('\u30A4'))) .isEqualTo(text.indexOf('\u30A4') + 1) assertThat(wordIterator.getNextWordEndOnTwoWordBoundary(text.indexOf('\u30A4') + 1)) .isEqualTo(text.indexOf('\u30A4') + 1) } @Test fun testGetNextWordEndOnTwoWordBoundary_apostropheMiddleOfWord() { // These tests confirm that the word "isn't" is treated like one word. val text = "isn't he" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) assertThat(wordIterator.getNextWordEndOnTwoWordBoundary(text.indexOf('i'))) .isEqualTo(text.indexOf('t') + 1) assertThat(wordIterator.getNextWordEndOnTwoWordBoundary(text.indexOf('n'))) .isEqualTo(text.indexOf('t') + 1) assertThat(wordIterator.getNextWordEndOnTwoWordBoundary(text.indexOf('\''))) .isEqualTo(text.indexOf('t') + 1) assertThat(wordIterator.getNextWordEndOnTwoWordBoundary(text.indexOf('t'))) .isEqualTo(text.indexOf('t') + 1) assertThat(wordIterator.getNextWordEndOnTwoWordBoundary(text.indexOf('h'))) .isEqualTo(text.indexOf('e') + 1) } @Test(expected = IllegalArgumentException::class) fun testGetPunctuationBeginning_out_of_boundary_too_small() { val text = "abc!? (^^;) def" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) wordIterator.getPunctuationBeginning(-2) } @Test(expected = IllegalArgumentException::class) fun testGetPunctuationBeginning_out_of_boundary_too_big() { val text = "abc!? (^^;) def" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) wordIterator.getPunctuationBeginning(text.length + 1) } @Test(expected = IllegalArgumentException::class) fun testGetPunctuationBeginning_DONE() { val text = "abc!? (^^;) def" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) wordIterator.getPunctuationBeginning(BreakIterator.DONE) } @Test fun testGetPunctuationBeginning() { val text = "abc!? (^^;) def" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) assertThat(wordIterator.getPunctuationBeginning(text.indexOf('a'))) .isEqualTo(BreakIterator.DONE) assertThat(wordIterator.getPunctuationBeginning(text.indexOf('c'))) .isEqualTo(BreakIterator.DONE) assertThat(wordIterator.getPunctuationBeginning(text.indexOf('!'))) .isEqualTo(text.indexOf('!')) assertThat(wordIterator.getPunctuationBeginning(text.indexOf('?') + 1)) .isEqualTo(text.indexOf('!')) assertThat(wordIterator.getPunctuationBeginning(text.indexOf(';'))) .isEqualTo(text.indexOf(';')) assertThat(wordIterator.getPunctuationBeginning(text.indexOf(')'))) .isEqualTo(text.indexOf(';')) assertThat(wordIterator.getPunctuationBeginning(text.length)) .isEqualTo(text.indexOf(';')) } @Test(expected = IllegalArgumentException::class) fun testGetPunctuationEnd_out_of_boundary_too_small() { val text = "abc!? (^^;) def" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) wordIterator.getPunctuationEnd(-2) } @Test(expected = IllegalArgumentException::class) fun testGetPunctuationEnd_out_of_boundary_too_big() { val text = "abc!? (^^;) def" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) wordIterator.getPunctuationEnd(text.length + 1) } @Test(expected = IllegalArgumentException::class) fun testGetPunctuationEnd_DONE() { val text = "abc!? (^^;) def" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) wordIterator.getPunctuationEnd(BreakIterator.DONE) } @Test fun testGetPunctuationEnd() { val text = "abc!? (^^;) def" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) assertThat(wordIterator.getPunctuationEnd(text.indexOf('a'))) .isEqualTo(text.indexOf('?') + 1) assertThat(wordIterator.getPunctuationEnd(text.indexOf('?') + 1)) .isEqualTo(text.indexOf('?') + 1) assertThat(wordIterator.getPunctuationEnd(text.indexOf('('))) .isEqualTo(text.indexOf('(') + 1) assertThat(wordIterator.getPunctuationEnd(text.indexOf('(') + 2)) .isEqualTo(text.indexOf(')') + 1) assertThat(wordIterator.getPunctuationEnd(text.indexOf(')') + 1)) .isEqualTo(text.indexOf(')') + 1) assertThat(wordIterator.getPunctuationEnd(text.indexOf('d'))) .isEqualTo(BreakIterator.DONE) assertThat(wordIterator.getPunctuationEnd(text.length)) .isEqualTo(BreakIterator.DONE) } @Test fun testIsAfterPunctuation() { val text = "abc!? (^^;) def" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) assertThat(wordIterator.isAfterPunctuation(text.indexOf('a'))).isFalse() assertThat(wordIterator.isAfterPunctuation(text.indexOf('!'))).isFalse() assertThat(wordIterator.isAfterPunctuation(text.indexOf('?'))).isTrue() assertThat(wordIterator.isAfterPunctuation(text.indexOf('?') + 1)).isTrue() assertThat(wordIterator.isAfterPunctuation(text.indexOf('d'))).isFalse() assertThat(wordIterator.isAfterPunctuation(BreakIterator.DONE)).isFalse() assertThat(wordIterator.isAfterPunctuation(text.length + 1)).isFalse() } @Test fun testIsOnPunctuation() { val text = "abc!? (^^;) def" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) assertThat(wordIterator.isOnPunctuation(text.indexOf('a'))).isFalse() assertThat(wordIterator.isOnPunctuation(text.indexOf('!'))).isTrue() assertThat(wordIterator.isOnPunctuation(text.indexOf('?'))).isTrue() assertThat(wordIterator.isOnPunctuation(text.indexOf('?') + 1)).isFalse() assertThat(wordIterator.isOnPunctuation(text.indexOf(')'))).isTrue() assertThat(wordIterator.isOnPunctuation(text.indexOf(')') + 1)).isFalse() assertThat(wordIterator.isOnPunctuation(text.indexOf('d'))).isFalse() assertThat(wordIterator.isOnPunctuation(BreakIterator.DONE)).isFalse() assertThat(wordIterator.isOnPunctuation(text.length)).isFalse() assertThat(wordIterator.isOnPunctuation(text.length + 1)).isFalse() } @Test fun testOneWord() { val text = "zen" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) verifyIsWord(wordIterator, 0, 3) } @Test fun testSpacesOnly() { val text = " " val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) verifyIsNotWord(wordIterator, 0, 1) } @Test fun testCommaWithSpace() { val text = ", " val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) verifyIsNotWord(wordIterator, 0, 2) } @Test fun testSymbols() { val text = ":-)" val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) verifyIsNotWord(wordIterator, 0, 3) } @Test fun testBeginningEnd1() { val text = "Well hello, there! " // 0123456789012345678901 val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) verifyIsWord(wordIterator, 0, 4) verifyIsWord(wordIterator, 5, 10) verifyIsNotWord(wordIterator, 11, 13) verifyIsWord(wordIterator, 14, 19) verifyIsNotWord(wordIterator, 20, 21) } @Test fun testBeginningEnd2() { val text = " Another - sentence" // 012345678901234567890 val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) verifyIsNotWord(wordIterator, 0, 1) verifyIsWord(wordIterator, 2, 9) verifyIsNotWord(wordIterator, 10, 11) verifyIsWord(wordIterator, 12, 20) } @Test fun testBeginningEnd3() { val text = "This is \u0644\u0627 tested" // Lama-aleph // 012345678 9 01234567 val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) verifyIsWord(wordIterator, 0, 4) verifyIsWord(wordIterator, 5, 7) verifyIsWord(wordIterator, 8, 10) verifyIsWord(wordIterator, 11, 17) } @Test fun testSurrogate() { val gothicBairkan = "\uD800\uDF31" val text = "one " + gothicBairkan + "xxx word" // 0123 45 678901234 val wordIterator = WordIterator(text, 0, text.length, Locale.ENGLISH) verifyIsWord(wordIterator, 0, 3) verifyIsWordWithSurrogate(wordIterator, 4, 9, 5) verifyIsWord(wordIterator, 10, 14) } private fun verifyIsWordWithSurrogate( wordIterator: WordIterator, beginning: Int, end: Int, surrogateIndex: Int ) { for (i in beginning..end) { if (i == surrogateIndex) continue assertThat(wordIterator.getPrevWordBeginningOnTwoWordsBoundary(i)) .isEqualTo(beginning) assertThat(wordIterator.getNextWordEndOnTwoWordBoundary(i)).isEqualTo(end) } } private fun verifyIsWord(wordIterator: WordIterator, beginning: Int, end: Int) { verifyIsWordWithSurrogate(wordIterator, beginning, end, -1) } private fun verifyIsNotWord(wordIterator: WordIterator, beginning: Int, end: Int) { for (i in beginning..end) { assertThat(wordIterator.getPrevWordBeginningOnTwoWordsBoundary(i)) .isEqualTo(BreakIterator.DONE) assertThat(wordIterator.getNextWordEndOnTwoWordBoundary(i)) .isEqualTo(BreakIterator.DONE) } } }
30
null
950
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
26,217
androidx
Apache License 2.0
plot-base-portable/src/commonMain/kotlin/jetbrains/datalore/plot/base/geom/AreaRidgesGeom.kt
JetBrains
176,771,727
false
null
/* * Copyright (c) 2022. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package jetbrains.datalore.plot.base.geom import jetbrains.datalore.base.geometry.DoubleVector import jetbrains.datalore.base.interval.DoubleSpan import jetbrains.datalore.plot.base.* import jetbrains.datalore.plot.base.geom.util.* import jetbrains.datalore.plot.base.interact.GeomTargetCollector import jetbrains.datalore.plot.base.interact.TipLayoutHint import jetbrains.datalore.plot.base.render.SvgRoot import jetbrains.datalore.plot.common.data.SeriesUtil class AreaRidgesGeom : GeomBase(), WithHeight { var scale: Double = DEF_SCALE var minHeight: Double = DEF_MIN_HEIGHT var quantileLines: Boolean = DEF_QUANTILE_LINES override fun buildIntern( root: SvgRoot, aesthetics: Aesthetics, pos: PositionAdjustment, coord: CoordinateSystem, ctx: GeomContext ) { buildLines(root, aesthetics, pos, coord, ctx) } private fun buildLines( root: SvgRoot, aesthetics: Aesthetics, pos: PositionAdjustment, coord: CoordinateSystem, ctx: GeomContext ) { val definedDataPoints = GeomUtil.withDefined(aesthetics.dataPoints(), Aes.X, Aes.Y, Aes.HEIGHT) if (!definedDataPoints.any()) return definedDataPoints .sortedByDescending(DataPointAesthetics::y) .groupBy(DataPointAesthetics::y) .map { (y, nonOrderedPoints) -> y to GeomUtil.ordered_X(nonOrderedPoints) } .forEach { (_, dataPoints) -> splitDataPointsByMinHeight(dataPoints).forEach { buildRidge(root, it, pos, coord, ctx) } } } private fun splitDataPointsByMinHeight(dataPoints: Iterable<DataPointAesthetics>): List<Iterable<DataPointAesthetics>> { val result = mutableListOf<Iterable<DataPointAesthetics>>() var dataPointsBunch: MutableList<DataPointAesthetics> = mutableListOf() for (p in dataPoints) if (p.height()!! >= minHeight) dataPointsBunch.add(p) else { if (dataPointsBunch.any()) result.add(dataPointsBunch) dataPointsBunch = mutableListOf() } if (dataPointsBunch.any()) result.add(dataPointsBunch) return result } private fun buildRidge( root: SvgRoot, dataPoints: Iterable<DataPointAesthetics>, pos: PositionAdjustment, coord: CoordinateSystem, ctx: GeomContext ) { val helper = LinesHelper(pos, coord, ctx) val boundTransform = toLocationBound(ctx) dataPoints.groupBy(DataPointAesthetics::fill).forEach { (_, points) -> val paths = helper.createBands( points, boundTransform, { p -> DoubleVector(p.x()!!, p.y()!!) }, simplifyBorders = true ) appendNodes(paths, root) } helper.setAlphaEnabled(false) dataPoints.groupBy(DataPointAesthetics::color).forEach { (_, points) -> appendNodes(helper.createLines(points, boundTransform), root) } if (quantileLines) drawQuantileLines(root, dataPoints, pos, coord, ctx) buildHints(dataPoints, ctx, helper, boundTransform) } private fun drawQuantileLines( root: SvgRoot, dataPoints: Iterable<DataPointAesthetics>, pos: PositionAdjustment, coord: CoordinateSystem, ctx: GeomContext ) { val pIt = dataPoints.sortedWith( compareBy( DataPointAesthetics::group, DataPointAesthetics::quantile, DataPointAesthetics::x ) ).iterator() if (!pIt.hasNext()) return var pPrev = pIt.next() while (pIt.hasNext()) { val pCurr = pIt.next() val quantilesAreSame = pPrev.quantile() == pCurr.quantile() || (pPrev.quantile()?.isFinite() != true && pCurr.quantile()?.isFinite() != true) if (!quantilesAreSame) drawQuantileLine(root, pCurr, pos, coord, ctx) pPrev = pCurr } } private fun drawQuantileLine( root: SvgRoot, dataPoint: DataPointAesthetics, pos: PositionAdjustment, coord: CoordinateSystem, ctx: GeomContext ) { val svgElementHelper = GeomHelper(pos, coord, ctx).createSvgElementHelper() val start = toLocationBound(ctx)(dataPoint) val end = DoubleVector(dataPoint.x()!!, dataPoint.y()!!) val line = svgElementHelper.createLine(start, end, dataPoint)!! root.add(line) } private fun toLocationBound(ctx: GeomContext): (p: DataPointAesthetics) -> DoubleVector { return fun(p: DataPointAesthetics): DoubleVector { val x = p.x()!! val y = p.y()!! + ctx.getResolution(Aes.Y) * scale * p.height()!! return DoubleVector(x, y) } } private fun buildHints( dataPoints: Iterable<DataPointAesthetics>, ctx: GeomContext, helper: GeomHelper, boundTransform: (p: DataPointAesthetics) -> DoubleVector ) { val multiPointDataList = MultiPointDataConstructor.createMultiPointDataByGroup( dataPoints, MultiPointDataConstructor.singlePointAppender { p -> boundTransform(p).let { helper.toClient(it, p) } }, MultiPointDataConstructor.reducer(0.999, false) ) val targetCollector = getGeomTargetCollector(ctx) val colorMarkerMapper = HintColorUtil.createColorMarkerMapper(GeomKind.AREA_RIDGES, ctx) for (multiPointData in multiPointDataList) { targetCollector.addPath( multiPointData.points, multiPointData.localToGlobalIndex, GeomTargetCollector.TooltipParams( markerColors = colorMarkerMapper(multiPointData.aes) ), if (ctx.flipped) { TipLayoutHint.Kind.VERTICAL_TOOLTIP } else { TipLayoutHint.Kind.HORIZONTAL_TOOLTIP } ) } } override fun heightSpan(p: DataPointAesthetics, coordAes: Aes<Double>, resolution: Double, isDiscrete: Boolean): DoubleSpan? { val sizeAes = Aes.HEIGHT val scaledResolution = resolution * this.scale val loc = p[coordAes] val size = p[sizeAes] return if (SeriesUtil.allFinite(loc, size)) { loc!! val expand = scaledResolution * size!! if (size >= this.minHeight) { DoubleSpan(loc, loc + expand) } else { null } } else { null } } companion object { const val DEF_SCALE = 1.0 const val DEF_MIN_HEIGHT = 0.0 const val DEF_QUANTILE_LINES = false const val HANDLES_GROUPS = true } }
72
Kotlin
43
830
06984a3321984037169c446c56544e3e0c4a1f2c
7,071
lets-plot
MIT License
app/src/main/java/eu/kanade/tachiyomi/ui/manga/external/ExternalItem.kt
CarlosEsco
182,704,531
false
null
package eu.kanade.tachiyomi.ui.manga.external import android.view.View import android.widget.ImageView import android.widget.TextView import com.mikepenz.fastadapter.FastAdapter import com.mikepenz.fastadapter.items.AbstractItem import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.external.ExternalLink open class ExternalItem(val externalLink: ExternalLink) : AbstractItem<ExternalItem.ViewHolder>() { /** defines the type defining this item. must be unique. preferably an id */ override val type: Int get() = R.id.external_items_id /** defines the layout which will be used for this item in the list */ override val layoutRes: Int get() = R.layout.external_item override fun getViewHolder(v: View): ViewHolder { return ViewHolder(v) } class ViewHolder(view: View) : FastAdapter.ViewHolder<ExternalItem>(view) { var logo = view.findViewById<ImageView>(R.id.external_logo)!! var container = view.findViewById<View>(R.id.external_logo_container)!! var title = view.findViewById<TextView>(R.id.external_title)!! override fun bindView(item: ExternalItem, payloads: List<Any>) { container.setBackgroundColor(item.externalLink.getLogoColor()) logo.setImageResource(item.externalLink.getLogo()) logo.contentDescription = item.externalLink.name title.setText(item.externalLink.name) } override fun unbindView(item: ExternalItem) { } } }
77
null
70
934
317243499e4131d3c3ee3604d81f8b69067414a4
1,506
Neko
Apache License 2.0
Android/java/doraemonkit/src/main/java/com/didichuxing/doraemonkit/DoKitReal.kt
yoyiyi
369,498,121
true
{"Ruby": 4, "Markdown": 26, "Text": 4, "Ignore List": 26, "OpenStep Property List": 16, "XML": 435, "Objective-C": 706, "JSON": 146, "Objective-C++": 1, "C": 7, "HTML": 7, "Swift": 23, "JavaScript": 94, "Vue": 34, "Less": 3, "Gradle": 38, "Java Properties": 14, "Shell": 17, "Batchfile": 3, "INI": 17, "Proguard": 15, "Kotlin": 510, "Java": 892, "AIDL": 2, "YAML": 4, "Dart": 41, "Makefile": 2, "JSON with Comments": 1}
package com.didichuxing.doraemonkit import android.app.Activity import android.app.Application import android.text.TextUtils import android.util.Log import com.didichuxing.doraemonkit.config.GlobalConfig import com.didichuxing.doraemonkit.config.GpsMockConfig import com.didichuxing.doraemonkit.config.PerformanceSpInfoConfig import com.didichuxing.doraemonkit.constant.DoKitConstant import com.didichuxing.doraemonkit.constant.SharedPrefsKey import com.didichuxing.doraemonkit.datapick.DataPickManager import com.didichuxing.doraemonkit.kit.AbstractKit import com.didichuxing.doraemonkit.kit.core.* import com.didichuxing.doraemonkit.kit.gpsmock.GpsMockManager import com.didichuxing.doraemonkit.kit.gpsmock.ServiceHookManager import com.didichuxing.doraemonkit.kit.health.AppHealthInfoUtil import com.didichuxing.doraemonkit.kit.health.model.AppHealthInfo.DataBean.BigFileBean import com.didichuxing.doraemonkit.kit.network.NetworkManager import com.didichuxing.doraemonkit.kit.network.okhttp.interceptor.DokitExtInterceptor import com.didichuxing.doraemonkit.kit.timecounter.instrumentation.HandlerHooker import com.didichuxing.doraemonkit.kit.toolpanel.KitWrapItem import com.didichuxing.doraemonkit.kit.toolpanel.ToolPanelUtil import com.didichuxing.doraemonkit.kit.webdoor.WebDoorManager import com.didichuxing.doraemonkit.kit.webdoor.WebDoorManager.WebDoorCallback import com.didichuxing.doraemonkit.util.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.MainScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File import java.util.* /** * Created by jintai on 2019/12/18. * DoKit 真正执行的类 不建议外部app调用 */ object DoKitReal { private const val TAG = "Doraemon" private lateinit var APPLICATION: Application fun setDebug(debug: Boolean) { LogHelper.setDebug(debug) } /** * @param app * @param mapKits 自定义kits 根据用户传进来的分组 建议优选选择mapKits 两者都传的话会选择mapKits * @param listKits 自定义kits * @param productId Dokit平台端申请的productId */ fun install( app: Application, mapKits: LinkedHashMap<String, List<AbstractKit>>, listKits: List<AbstractKit>, productId: String ) { registerModuleListener() pluginConfig() initThirdLibraryInfo() DoKitConstant.PRODUCT_ID = productId DoKitConstant.APP_HEALTH_RUNNING = GlobalConfig.getAppHealth() //赋值 APPLICATION = app //初始化工具类 initAndroidUtil(app) //判断进程名 if (!ProcessUtils.isMainProcess()) { return } //解锁系统隐藏api限制权限以及hook Instrumentation HandlerHooker.doHook(app) val strDokitMode = DoKitSPUtil.getString(SharedPrefsKey.FLOAT_START_MODE, "normal") DoKitConstant.IS_NORMAL_FLOAT_MODE = strDokitMode == "normal" //初始化第三方工具 installLeakCanary(app) checkLargeImgIsOpen() registerNetworkStatusChangedListener() startAppHealth() checkGPSMock() //hook WIFI GPS Telephony系统服务 ServiceHookManager.getInstance().install(app) //全局运行时hook globalRunTimeHook() //注册全局的activity生命周期回调 app.registerActivityLifecycleCallbacks(DokitActivityLifecycleCallbacks()) //DokitConstant.KIT_MAPS.clear() DoKitConstant.GLOBAL_KITS.clear() //添加用户的自定义kit when { mapKits.isNotEmpty() -> { mapKits.forEach { map -> val kitWraps: MutableList<KitWrapItem> = map.value.map { KitWrapItem( KitWrapItem.TYPE_KIT, DoKitCommUtil.getString(it.name), true, map.key, it ) } as MutableList<KitWrapItem> DoKitConstant.GLOBAL_KITS[map.key] = kitWraps } } mapKits.isEmpty() && listKits.isNotEmpty() -> { val kitWraps: MutableList<KitWrapItem> = listKits.map { KitWrapItem( KitWrapItem.TYPE_KIT, DoKitCommUtil.getString(it.name), true, DoKitCommUtil.getString(R.string.dk_category_biz), it ) } as MutableList<KitWrapItem> DoKitConstant.GLOBAL_KITS[DoKitCommUtil.getString(R.string.dk_category_biz)] = kitWraps } } //添加自定义的kit 需要读取配置文件 val job = MainScope().launch { addInnerKit(app) } job.invokeOnCompletion { job.cancel() } //添加自定义的kit 需要读取配置文件 // ThreadUtils.executeByIo(object : ThreadUtils.SimpleTask<Any>() { // override fun doInBackground(): Any { // addInnerKit(app) // return Any() // } // // override fun onSuccess(result: Any?) { // } // }) //addSystemKitForTest(app) //初始化悬浮窗管理类 DokitViewManager.getInstance().init(app) //上传app基本信息便于统计 if (DoKitConstant.ENABLE_UPLOAD) { try { DoraemonStatisticsUtil.uploadUserInfo(app) } catch (e: Exception) { e.printStackTrace() } } //上传埋点 DataPickManager.getInstance().postData() } /** * 注册模块之间通信 */ private fun registerModuleListener() { //前后台监听 AppUtils.registerAppStatusChangedListener(object : Utils.OnAppStatusChangedListener { //进入前台 override fun onForeground(activity: Activity?) { DokitServiceManager.dispatch( DokitServiceEnum.onForeground, activity!! ) } //进入后台 override fun onBackground(activity: Activity?) { DokitServiceManager.dispatch( DokitServiceEnum.onBackground, activity!! ) } }) //跨模块通信监听 try { val dokitServices = ServiceLoader.load(DokitServiceInterface::class.java, javaClass.classLoader) .toList() DokitServiceManager.register(dokitServices) } catch (e: Exception) { } } /** * 添加内置kit */ private suspend fun addInnerKit(application: Application) = withContext(Dispatchers.IO) { var json: String? if (FileUtils.isFileExists(DoKitConstant.SYSTEM_KITS_BAK_PATH)) { json = FileIOUtils.readFile2String(DoKitConstant.SYSTEM_KITS_BAK_PATH) if (TextUtils.isEmpty(json) || json == "[]") { val open = application.assets.open("dokit_system_kits.json") json = ConvertUtils.inputStream2String(open, "UTF-8") } } else { val open = application.assets.open("dokit_system_kits.json") json = ConvertUtils.inputStream2String(open, "UTF-8") } ToolPanelUtil.jsonConfig2InnerKits(json) //悬浮窗模式 DoKitConstant.GLOBAL_KITS[DoKitCommUtil.getString(R.string.dk_category_mode)] = mutableListOf() //添加退出项 DoKitConstant.GLOBAL_KITS[DoKitCommUtil.getString(R.string.dk_category_exit)] = mutableListOf() //版本号 DoKitConstant.GLOBAL_KITS[DoKitCommUtil.getString(R.string.dk_category_version)] = mutableListOf() //遍历初始化 DoKitConstant.GLOBAL_KITS.forEach { map -> map.value.forEach { kitWrap -> kitWrap.kit?.onAppInit(application) } } } /** * 插件会在当前方法中插入插件配置代码 */ private fun pluginConfig() {} /** * 插件会在当前方法中插入三方库的基本信息 */ private fun initThirdLibraryInfo() { } /** * 全局方法hook */ private fun globalRunTimeHook() { } private fun checkGPSMock() { if (GpsMockConfig.isGPSMockOpen()) { GpsMockManager.getInstance().startMock() } val latLng = GpsMockConfig.getMockLocation() ?: return GpsMockManager.getInstance().mockLocationWithNotify(latLng.latitude, latLng.longitude) } /** * 单个文件的阈值为1M */ private const val FILE_LENGTH_THRESHOLD = 1 * 1024 * 1024.toLong() //todo 测试时为1k 对外时需要修改回来 //private static long FILE_LENGTH_THRESHOLD = 1024; private fun traverseFile(rootFileDir: File?) { if (rootFileDir == null) { return } val files = rootFileDir.listFiles() files?.forEach { file -> if (file.isDirectory) { //若是目录,则递归打印该目录下的文件 //LogHelper.i(TAG, "文件夹==>" + file.getAbsolutePath()); traverseFile(file) } if (file.isFile) { //若是文件,直接打印 byte val fileLength = FileUtils.getLength(file) if (fileLength > FILE_LENGTH_THRESHOLD) { val fileBean = BigFileBean() fileBean.fileName = FileUtils.getFileName(file) fileBean.filePath = file.absolutePath fileBean.fileSize = "" + fileLength AppHealthInfoUtil.getInstance().addBigFilrInfo(fileBean) } //LogHelper.i(TAG, "文件==>" + file.getAbsolutePath() + " fileName===>" + FileUtils.getFileName(file) + " fileLength===>" + fileLength); } } } /** * 开启大文件检测 * https://blog.csdn.net/csdn_aiyang/article/details/80665185 内部存储和外部存储的概念 */ private fun startBigFileInspect() { ThreadUtils.executeByIo(object : ThreadUtils.SimpleTask<Any?>() { @Throws(Throwable::class) override fun doInBackground(): Any? { val externalCacheDir = APPLICATION.externalCacheDir if (externalCacheDir != null) { val externalRootDir = externalCacheDir.parentFile traverseFile(externalRootDir) } val innerCacheDir = APPLICATION.cacheDir if (innerCacheDir != null) { val innerRootDir = innerCacheDir.parentFile traverseFile(innerRootDir) } return null } override fun onSuccess(result: Any?) {} }) } /** * 开启健康体检 */ private fun startAppHealth() { if (!DoKitConstant.APP_HEALTH_RUNNING) { return } if (TextUtils.isEmpty(DoKitConstant.PRODUCT_ID)) { ToastUtils.showShort("要使用健康体检功能必须先去平台端注册") return } AppHealthInfoUtil.getInstance().start() //开启大文件检测 startBigFileInspect() } fun setWebDoorCallback(callback: WebDoorCallback?) { WebDoorManager.getInstance().webDoorCallback = callback } /** * 注册全局的网络状态监听 */ private fun registerNetworkStatusChangedListener() { NetworkUtils.registerNetworkStatusChangedListener(object : NetworkUtils.OnNetworkStatusChangedListener { override fun onDisconnected() { //ToastUtils.showShort("当前网络已断开"); Log.i("Doraemon", "当前网络已断开") } override fun onConnected(networkType: NetworkUtils.NetworkType) { //重启DebugDB //ToastUtils.showShort("当前网络类型:" + networkType.name()); Log.i("Doraemon", "当前网络类型" + networkType.name) } }) } /** * 确认大图检测功能时候被打开 */ private fun checkLargeImgIsOpen() { if (PerformanceSpInfoConfig.isLargeImgOpen()) { NetworkManager.get().startMonitor() } } /** * 安装leackCanary * * @param app */ private fun installLeakCanary(app: Application) { //反射调用 try { val leakCanaryManager = Class.forName("com.didichuxing.doraemonkit.LeakCanaryManager") val install = leakCanaryManager.getMethod("install", Application::class.java) //调用静态的install方法 install.invoke(null, app) val initAidlBridge = leakCanaryManager.getMethod("initAidlBridge", Application::class.java) //调用静态initAidlBridge方法 initAidlBridge.invoke(null, app) } catch (e: Exception) { } } private fun initAndroidUtil(app: Application) { Utils.init(app) LogUtils.getConfig() // 设置 log 总开关,包括输出到控制台和文件,默认开 .setLogSwitch(true) // 设置是否输出到控制台开关,默认开 .setConsoleSwitch(true) // 设置 log 全局标签,默认为空,当全局标签不为空时,我们输出的 log 全部为该 tag, 为空时,如果传入的 tag 为空那就显示类名,否则显示 tag .setGlobalTag("Doraemon") // 设置 log 头信息开关,默认为开 .setLogHeadSwitch(true) // 打印 log 时是否存到文件的开关,默认关 .setLog2FileSwitch(true) // 当自定义路径为空时,写入应用的/cache/log/目录中 .setDir("") // 当文件前缀为空时,默认为"util",即写入文件为"util-MM-dd.txt" .setFilePrefix("djx-table-log") // 输出日志是否带边框开关,默认开 .setBorderSwitch(true) // 一条日志仅输出一条,默认开,为美化 AS 3.1 的 Logcat .setSingleTagSwitch(true) // log 的控制台过滤器,和 logcat 过滤器同理,默认 Verbose .setConsoleFilter(LogUtils.V) // log 文件过滤器,和 logcat 过滤器同理,默认 Verbose .setFileFilter(LogUtils.E) // log 栈深度,默认为 1 .setStackDeep(2) .stackOffset = 0 } /** * 显示系统悬浮窗icon */ private fun showMainIcon() { if (ActivityUtils.getTopActivity() is UniversalActivity) { return } if (!DoKitConstant.AWAYS_SHOW_MAIN_ICON) { return } DokitViewManager.getInstance().attachMainIcon() DoKitConstant.MAIN_ICON_HAS_SHOW = true } fun show() { DoKitConstant.AWAYS_SHOW_MAIN_ICON = true if (!isShow) { showMainIcon() } } /** * 直接显示工具面板页面 */ fun showToolPanel() { DokitViewManager.getInstance().attachToolPanel() } fun hideToolPanel() { DokitViewManager.getInstance().detachToolPanel() } fun hide() { DoKitConstant.MAIN_ICON_HAS_SHOW = false DoKitConstant.AWAYS_SHOW_MAIN_ICON = false DokitViewManager.getInstance().detachMainIcon() } /** * 禁用app信息上传开关,该上传信息只为做DoKit接入量的统计,如果用户需要保护app隐私,可调用该方法进行禁用 */ fun disableUpload() { DoKitConstant.ENABLE_UPLOAD = false } val isShow: Boolean get() = DoKitConstant.MAIN_ICON_HAS_SHOW /** * 设置加密数据库的密码 */ fun setDatabasePass(map: Map<String, String>) { DoKitConstant.DATABASE_PASS = map } /** * 设置平台端文件管理端口号 */ fun setFileManagerHttpPort(port: Int) { DoKitConstant.FILE_MANAGER_HTTP_PORT = port } /** * 设置一机多控长连接端口号 */ fun setMCWSPort(port: Int) { DoKitConstant.MC_WS_PORT = port } /** * 是否显示主入口icon */ fun setAwaysShowMainIcon(awaysShow: Boolean) { DoKitConstant.AWAYS_SHOW_MAIN_ICON = awaysShow } /** * 设置一机多控自定义拦截器 */ fun setMCIntercept(interceptor: MCInterceptor) { DoKitConstant.MC_INTERCEPT = interceptor } /** * 设置扩展网络拦截器的代理对象 */ fun setNetExtInterceptor(extInterceptorProxy: DokitExtInterceptor.DokitExtInterceptorProxy) { DokitExtInterceptor.dokitExtInterceptorProxy = extInterceptorProxy } /** * 设置一机多控自定义拦截器 */ fun setCallBack(callback: DoKitCallBack) { DoKitConstant.CALLBACK = callback } }
0
Java
0
1
c461eaff8b9ed0d2e867d62d051acd9ce590bb8b
15,853
DoraemonKit
Apache License 2.0
app/src/main/java/com/jmdev/marvelheroes/data/network/HeroService.kt
juacosoft
431,293,126
false
{"Kotlin": 36911}
package com.jmdev.marvelheroes.data.network import android.util.Log import com.jmdev.marvelheroes.data.PageControler import com.jmdev.marvelheroes.data.models.characters.CharacterModel import com.jmdev.marvelheroes.data.models.comics.ComicsModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import javax.inject.Inject class HeroService @Inject constructor( private val api: HeroesMarveApi, private val pageControler: PageControler ) { suspend fun getNextAllcharacters():List<CharacterModel>{ if(pageControler.query.isEmpty()){ Log.d("callApi","NextAllCharacter with page: ${pageControler.offset}") return withContext(Dispatchers.IO){ val response=api.getAllCharacters( pageControler.limit,pageControler.offset ) response.body()?.dataModel?.characters ?: emptyList() } }else{ Log.d("callApi","NextAllCharacter with query ${pageControler.query}") return withContext(Dispatchers.IO){ val response=api.seacrhWithName( pageControler.query, pageControler.limit, pageControler.offset ) response.body()?.dataModel?.characters ?: emptyList() } } } suspend fun getAllComics():List<ComicsModel>{ return withContext(Dispatchers.IO){ val response=api.getAllComics( pageControler.limit,pageControler.offset ) response.body()?.comicData?.comics ?: emptyList() } } suspend fun getAllCharacters():List<CharacterModel>{ return withContext(Dispatchers.IO){ val response=api.getAllCharacters( 20,0 ) response.body()?.dataModel?.characters ?: emptyList() } } }
0
Kotlin
0
0
227c320bc7f6ffa591e1bbf21f418f506fa8b8ef
1,939
MarvelHeroesMVVM
Apache License 2.0
app/src/main/java/com/andrewgiang/homecontrol/ui/container/Container.kt
zularizal
164,204,405
false
null
/* * Copyright 2018 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.andrewgiang.homecontrol.ui.container import kotlinx.android.extensions.LayoutContainer interface Container : LayoutContainer { fun onBindView() }
0
Kotlin
0
0
58859ca2f76f8127735fad3c05d839b834af74ce
750
home-control
Apache License 2.0
plugins/fir/fir-plugin-prototype/src/org/jetbrains/kotlin/fir/plugin/FirAllOpenComponentRegistrar.kt
nskvortsov
367,097,840
true
null
/* * Copyright 2010-2020 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.fir.plugin import org.jetbrains.kotlin.fir.extensions.FirExtensionRegistrar import org.jetbrains.kotlin.fir.plugin.generators.* class FirAllOpenComponentRegistrar : FirExtensionRegistrar() { override fun ExtensionRegistrarContext.configurePlugin() { +::AllOpenStatusTransformer +::AllOpenVisibilityTransformer +::AllOpenSupertypeGenerator // Declaration generators +::AllOpenMemberGenerator +::AllOpenNestedClassGenerator +::AllOpenAdditionalCheckers +::AllOpenTopLevelDeclarationsGenerator +::AllOpenRecursiveNestedClassGenerator } }
1
null
1
3
58c7aa9937334b7f3a70acca84a9ce59c35ab9d1
856
kotlin
Apache License 2.0
app/src/main/java/io/aethibo/kart/features/product/presentation/components/ProductThumbnail.kt
primepixel
626,035,115
false
null
package io.aethibo.kart.features.product.presentation.components import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import io.aethibo.kart.R import io.aethibo.kart.core.ui.KartTheme import io.aethibo.kart.features.shared.presentation.components.DotsIndicator @OptIn(ExperimentalFoundationApi::class) @Composable fun ProductThumbnail(images: List<String>, modifier: Modifier = Modifier) { val pagerState = rememberPagerState() Column(horizontalAlignment = Alignment.CenterHorizontally) { HorizontalPager(pageCount = images.size, state = pagerState) { pagePosition -> AsyncImage( model = images[pagePosition], contentDescription = stringResource(id = R.string.product_image_description), contentScale = ContentScale.Fit, modifier = modifier .fillMaxWidth() .height(410.dp) ) } DotsIndicator( totalDots = images.size, selectedIndex = pagerState.currentPage, selectedColor = MaterialTheme.colorScheme.error, unSelectedColor = MaterialTheme.colorScheme.secondary, modifier = Modifier.padding(top = 16.dp) ) } } @Preview @Composable fun ProductImageSliderPreview() { KartTheme { ProductThumbnail(images = listOf("https://images.unsplash.com/photo-1681066471028-dec0c78b729c?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1976&q=80")) } }
0
Kotlin
0
0
e4a6bc4c1c00d8e681c1172dbd864a2984ac1547
2,165
Kart
Apache License 2.0
common/kotlinx-coroutines-core-common/src/Annotations.common.kt
DarkLab
142,666,798
true
{"Kotlin": 1920618, "CSS": 8215, "JavaScript": 2505, "Ruby": 1927, "HTML": 1675, "Shell": 1308, "Java": 356}
/* * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ // NOTE: We are defining them in a special internalAnnotations package because they would break // user code that uses kotlinx.coroutines library otherwise, see https://youtrack.jetbrains.com/issue/KT-23727 package kotlinx.coroutines.experimental.internalAnnotations @Target(AnnotationTarget.FILE, AnnotationTarget.FUNCTION) internal expect annotation class JvmName(val name: String) @Target(AnnotationTarget.FILE) internal expect annotation class JvmMultifileClass() internal expect annotation class JvmField() internal expect annotation class Volatile() internal expect annotation class JsName(val name: String)
0
Kotlin
0
0
9964b3d97377963e353f10d7dcca7e18770997a3
730
kotlinx.coroutines
Apache License 2.0
src/test/kotlin/com/korrit/kotlin/ktor/features/errorresponses/TestHelpers.kt
Koriit
217,291,432
false
null
package com.korrit.kotlin.ktor.features.errorresponses import com.jayway.jsonpath.matchers.JsonPathMatchers.hasJsonPath import com.jayway.jsonpath.matchers.JsonPathMatchers.isJson import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode import io.ktor.http.withCharset import io.ktor.server.testing.TestApplicationCall import io.ktor.server.testing.contentType import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.isA import org.hamcrest.core.IsEqual class Fixture(val field: String) class SomeDomainException : RuntimeException("Domain message") internal val asInt = isA<Int>(Int::class.java) internal val asLong = isA<Long>(Long::class.java) internal val asString = isA<String>(String::class.java) internal val asBoolean = isA<Boolean>(Boolean::class.java) internal fun TestApplicationCall.assertApiError(status: HttpStatusCode) { assertThat(response.status(), IsEqual(status)) assertThat(response.contentType(), IsEqual(ContentType.Application.Json.withCharset(Charsets.UTF_8))) assertThat(response.content, isJson()) assertThat(response.content, hasJsonPath("$.status", asInt)) assertThat(response.content, hasJsonPath("$.type", asString)) assertThat(response.content, hasJsonPath("$.title", asString)) assertThat(response.content, hasJsonPath("$.detail", asString)) assertThat(response.content, hasJsonPath("$.path", asString)) assertThat(response.content, hasJsonPath("$.instance", asString)) assertThat(response.content, hasJsonPath("$.timestamp", asString)) }
1
null
0
1
1b6ae82b2397c408c1ded777fd445063bc0365c1
1,543
ktor-error-responses
MIT License
src/commonMain/kotlin/com/lehaine/kiwi/component/LevelDynamicComponent.kt
LeHaine
354,414,117
false
null
package com.lehaine.kiwi.component import com.soywiz.korge.debug.uiCollapsibleSection import com.soywiz.korge.debug.uiEditableValue import com.soywiz.korui.UiContainer import kotlin.math.floor interface LevelDynamicComponent : DynamicComponent { var rightCollisionRatio: Double var leftCollisionRatio: Double var bottomCollisionRatio: Double var topCollisionRatio: Double var useTopCollisionRatio: Boolean var onLevelCollision: ((xDir: Int, yDir: Int) -> Unit)? override fun buildDebugInfo(container: UiContainer) { super.buildDebugInfo(container) container.uiCollapsibleSection("Level Dynamic Component") { uiEditableValue( this@LevelDynamicComponent::leftCollisionRatio, name = "Left Collision Ratio", min = 0.0, max = 1.0 ) uiEditableValue( this@LevelDynamicComponent::rightCollisionRatio, name = "Right Collision Ratio", min = 0.0, max = 1.0 ) uiEditableValue( this@LevelDynamicComponent::useTopCollisionRatio, name = "Use Top Collision Ratio" ) uiEditableValue( this@LevelDynamicComponent::topCollisionRatio, name = "Top Collision Ratio", min = 0.0, max = 1.0 ) uiEditableValue( this@LevelDynamicComponent::bottomCollisionRatio, name = "Bottom Collision Ratio", min = 0.0, max = 1.0 ) } } } open class LevelDynamicComponentDefault( private val levelComponent: LevelComponent<*>, override var cx: Int = 0, override var cy: Int = 0, override var xr: Double = 0.5, override var yr: Double = 0.5, override var anchorX: Double = 0.5, override var anchorY: Double = 0.5, override var gridCellSize: Int = 16, override var rightCollisionRatio: Double = 0.7, override var leftCollisionRatio: Double = 0.3, override var bottomCollisionRatio: Double = 1.0, override var topCollisionRatio: Double = 1.0, override var useTopCollisionRatio: Boolean = false, override var onLevelCollision: ((xDir: Int, yDir: Int) -> Unit)? = null ) : LevelDynamicComponent { override var preXCheck: (() -> Unit)? = null override var preYCheck: (() -> Unit)? = null override var gravityX: Double = 0.0 override var gravityY: Double = 0.0 override var gravityMultiplier: Double = 1.0 override var velocityX: Double = 0.0 override var velocityY: Double = 0.0 override var frictionX: Double = 0.82 override var frictionY: Double = 0.82 override var maxGridMovementPercent: Double = 0.33 override var interpolatePixelPosition: Boolean = true override var lastPx: Double = 0.0 override var lastPy: Double = 0.0 override var fixedProgressionRatio: Double = 1.0 override var width: Double = 16.0 override var height: Double = 16.0 override fun checkXCollision() { if (levelComponent.hasCollision(cx + 1, cy) && xr >= rightCollisionRatio) { xr = rightCollisionRatio velocityX *= 0.5 onLevelCollision?.invoke(1, 0) } if (levelComponent.hasCollision(cx - 1, cy) && xr <= leftCollisionRatio) { xr = leftCollisionRatio velocityX *= 0.5 onLevelCollision?.invoke(-1, 0) } } override fun checkYCollision() { val heightCoordDiff = if (useTopCollisionRatio) topCollisionRatio else floor(height / gridCellSize.toDouble()) if (levelComponent.hasCollision(cx, cy - 1) && yr <= heightCoordDiff) { yr = heightCoordDiff velocityY = 0.0 onLevelCollision?.invoke(0, -1) } if (levelComponent.hasCollision(cx, cy + 1) && yr >= bottomCollisionRatio) { velocityY = 0.0 yr = bottomCollisionRatio onLevelCollision?.invoke(0, 1) } } }
0
Kotlin
0
4
02f3e73f6776a6a378903153bdea4e49c37862d4
4,100
kiwi
MIT License
core/data/src/main/java/com/wap/wapp/core/data/repository/event/EventRepositoryImpl.kt
pknu-wap
689,890,586
false
{"Kotlin": 485245, "Shell": 233}
package com.wap.wapp.core.data.repository.event import com.wap.wapp.core.data.utils.toISOLocalDateTimeString import com.wap.wapp.core.model.event.Event import com.wap.wapp.core.network.source.event.EventDataSource import java.time.LocalDate import java.time.LocalDateTime import javax.inject.Inject class EventRepositoryImpl @Inject constructor( private val eventDataSource: EventDataSource, ) : EventRepository { override suspend fun getMonthEventList(date: LocalDate): Result<List<Event>> = eventDataSource.getMonthEventList(date).mapCatching { eventResponses -> eventResponses.map { eventResponse -> eventResponse.toDomain() }.sortedBy { it.startDateTime } } override suspend fun getEventList(): Result<List<Event>> = eventDataSource.getEventList().mapCatching { eventResponses -> eventResponses.map { eventResponse -> eventResponse.toDomain() }.sortedBy { it.startDateTime } } override suspend fun getDateEventList(date: LocalDate): Result<List<Event>> = eventDataSource.getDateEventList(date).mapCatching { eventResponses -> eventResponses.map { eventResponse -> eventResponse.toDomain() }.sortedBy { it.startDateTime } } override suspend fun getEventListFromDate(date: LocalDate): Result<List<Event>> = eventDataSource.getEventListFromDate(date).mapCatching { eventResponses -> eventResponses.map { eventResponse -> eventResponse.toDomain() }.sortedBy { it.startDateTime } } override suspend fun getEvent(eventId: String): Result<Event> = eventDataSource.getEvent(eventId).mapCatching { eventResponse -> eventResponse.toDomain() } override suspend fun postEvent( title: String, content: String, location: String, startDateTime: LocalDateTime, endDateTime: LocalDateTime, ): Result<Unit> = eventDataSource.postEvent( title = title, content = content, location = location, startDateTime = startDateTime.toISOLocalDateTimeString(), endDateTime = endDateTime.toISOLocalDateTimeString(), ) override suspend fun updateEvent( eventId: String, title: String, content: String, location: String, startDateTime: LocalDateTime, endDateTime: LocalDateTime, ): Result<Unit> = eventDataSource.updateEvent( eventId = eventId, title = title, content = content, location = location, startDateTime = startDateTime.toISOLocalDateTimeString(), endDateTime = endDateTime.toISOLocalDateTimeString(), ) }
6
Kotlin
0
8
c113f9748956e4fd0400f632eaed93ccf3e2ef78
2,819
WAPP
MIT License
src/main/kotlin/com/theapache64/gilfoyle/feature/device/SelectDeviceViewModel.kt
theapache64
332,862,297
false
null
package com.theapache64.gilfoyle.feature.device import com.theapache64.cyclone.core.livedata.LiveData import com.theapache64.cyclone.core.livedata.MutableLiveData import com.theapache64.gilfoyle.data.repos.AdbRepo import com.theapache64.gilfoyle.data.repos.ConfigRepo import javax.inject.Inject class SelectDeviceViewModel @Inject constructor( private val configRepo: ConfigRepo, private val adbRepo: AdbRepo ) { private val _devices = MutableLiveData<List<String>>() val devices: LiveData<List<String>> = _devices private val _shouldShowNoDeviceConnected = MutableLiveData<Boolean>() val shouldShowNoDeviceConnected: LiveData<Boolean> = _shouldShowNoDeviceConnected private val _launchUninstallActivity = MutableLiveData<String>() val launchUninstallActivity: LiveData<String> = _launchUninstallActivity init { val config = configRepo.config val devices = adbRepo.getConnectedDevices(config) if (devices.isEmpty()) { // show no device error _shouldShowNoDeviceConnected.value = true } else { // devices available _devices.value = devices } } /** * Invoked when device selected */ fun onDeviceSelected(device: String) { _launchUninstallActivity.value = device } }
0
Kotlin
1
23
f6da94f22cb99205c0a5eec6d2488b3f3e5bfb0e
1,330
gilfoyle
Apache License 2.0
idea/tests/testData/structuralsearch/callExpression/funArgCallVarRef.kt
JetBrains
278,369,660
false
null
fun a(): List<Int> { val x = <warning descr="SSR">listOf(1)</warning> val y = listOf(1, 2) return if(x.size == 1) x else y }
0
Kotlin
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
136
intellij-kotlin
Apache License 2.0
shared/src/main/kotlin/dev/fastmc/graphics/shared/instancing/entity/EntityInstancingBuilder.kt
FastMinecraft
447,964,530
false
{"Kotlin": 812223, "Java": 295977, "GLSL": 19607}
package dev.fastmc.graphics.shared.instancing.entity import dev.fastmc.graphics.shared.instancing.AbstractInstancingBuilder import dev.fastmc.graphics.shared.instancing.entity.info.IEntityInfo import dev.fastmc.graphics.shared.model.Model import dev.fastmc.graphics.shared.resource.ResourceEntry import dev.fastmc.graphics.shared.texture.ITexture import java.nio.ByteBuffer abstract class EntityInstancingBuilder<T : IEntityInfo<*>>(vertexSize: Int) : AbstractInstancingBuilder<T>(vertexSize) { protected fun ByteBuffer.putPos(info: T) { putFloat((info.prevX - builtPosX).toFloat()) putFloat((info.prevY - builtPosY).toFloat()) putFloat((info.prevZ - builtPosZ).toFloat()) putFloat((info.x - builtPosX).toFloat()) putFloat((info.y - builtPosY).toFloat()) putFloat((info.z - builtPosZ).toFloat()) } protected fun ByteBuffer.putRotations(info: T) { putFloat(info.rotationYaw) putFloat(info.rotationPitch) putFloat(info.prevRotationYaw) putFloat(info.prevRotationPitch) } protected fun ByteBuffer.putLightMapUV(info: T) { val lightMapUV = info.lightMapUV put((lightMapUV and 0xFF).toByte()) put((lightMapUV shr 16 and 0xFF).toByte()) } protected companion object { fun model(name: String): ResourceEntry<Model> { return ResourceEntry("entity/$name") { it.model } } fun shader(name: String): ResourceEntry<InstancingShaderProgram> { return ResourceEntry("entity/$name") { it.entityShader } } fun texture(name: String): ResourceEntry<ITexture> { return ResourceEntry("entity/$name") { it.texture } } } }
1
Kotlin
1
61
74eb9d6af0d4829caa8a6069f39bb3e0fa168538
1,809
fastmc-graphics
MIT License
technocracy.foundation/src/main/kotlin/net/cydhra/technocracy/foundation/network/componentsync/GuiUpdateListener.kt
notphinix
229,493,759
true
{"Kotlin": 1063752, "GLSL": 8977}
package net.cydhra.technocracy.foundation.network.componentsync import net.cydhra.technocracy.foundation.model.components.IComponent import net.cydhra.technocracy.foundation.model.multiblock.api.BaseMultiBlock import net.cydhra.technocracy.foundation.model.tileentities.machines.MachineTileEntity import net.cydhra.technocracy.foundation.model.tileentities.multiblock.TileEntityMultiBlockPart import net.cydhra.technocracy.foundation.network.PacketHandler import net.minecraft.entity.player.EntityPlayerMP import net.minecraft.nbt.NBTTagCompound import net.minecraft.util.math.BlockPos import net.minecraftforge.common.DimensionManager import net.minecraftforge.event.entity.player.PlayerContainerEvent import net.minecraftforge.fml.common.eventhandler.SubscribeEvent import net.minecraftforge.fml.common.gameevent.TickEvent import net.minecraftforge.fml.relauncher.Side import net.minecraftforge.fml.relauncher.SideOnly val guiInfoPacketSubscribers = mutableMapOf<EntityPlayerMP, Pair<BlockPos, Int>>() val lastGuiStates = mutableMapOf<EntityPlayerMP, MutableMap<Pair<BlockPos, Int>, NBTTagCompound>>() // uff class GuiUpdateListener { @SideOnly(Side.SERVER) @SubscribeEvent fun onInventoryClose(event: PlayerContainerEvent.Close) { guiInfoPacketSubscribers.remove(event.entityPlayer) } @SubscribeEvent fun onTick(event: TickEvent) { if (event.side == Side.SERVER) { guiInfoPacketSubscribers.forEach { (player, tePos) -> val world = DimensionManager.getWorld(tePos.second) if (world.isBlockLoaded(tePos.first)) { val te = world.getTileEntity(tePos.first) var tag: NBTTagCompound? = null if (te is MachineTileEntity) { tag = getTagForMachine(te.getComponents()) } else if (te is TileEntityMultiBlockPart<*>) { if(te.multiblockController != null) tag = getTagForMachine((te.multiblockController as BaseMultiBlock).getComponents()) } if (tag != null) { tag.setLong("pos", tePos.first.toLong()) lastGuiStates.putIfAbsent(player, mutableMapOf()) if (lastGuiStates[player]!![tePos] != tag) { lastGuiStates[player]!![tePos] = tag PacketHandler.sendToClient(MachineInfoPacket(tag), player) } } } } } } fun getTagForMachine(components: MutableList<Pair<String, IComponent>>): NBTTagCompound { val tag = NBTTagCompound() components.forEach { (name, component) -> tag.setTag(name, component.serializeNBT()) } return tag } }
0
Kotlin
0
0
71a044f54f813b0213b6ae1f0394f49324ac9c1c
2,865
Technocracy
MIT License
multisrc/overrides/madara/mangakio/src/MangaKio.kt
lmk1988
253,204,269
false
null
package eu.kanade.tachiyomi.extension.en.mangakio import eu.kanade.tachiyomi.multisrc.madara.Madara import java.text.SimpleDateFormat import java.util.Locale class MangaKio : Madara( "Manga Kio", "https://mangakio.com", "en", dateFormat = SimpleDateFormat("MMM d, yyyy", Locale.US), ) { override val useNewChapterEndpoint = true }
546
null
1130
5
3e1df100b87358d8b50ce8dd998e04552db9c91d
353
tachiyomi-extensions
Apache License 2.0
src/main/kotlin/dev/paulshields/aoc/day14/DockingData.kt
Pkshields
318,658,287
false
null
package dev.paulshields.aoc.day14 import dev.paulshields.aoc.common.readFileAsStringList val valueSetCaptureRegex = Regex("mem\\[(\\d+)] = (\\d+)") fun main() { val program = readFileAsStringList("/day14/InitializationProgram.txt") var memory = runInitializationProgramThroughDecoderChipV1(program) println("The sum of all data in memory is ${memory.values.sum()}!") memory = runInitializationProgramThroughDecoderChipV2(program) println("The sum of all data in memory is ${memory.values.sum()}!") } fun runInitializationProgramThroughDecoderChipV1(program: List<String>): MutableMap<Long, Long> { val memory = mutableMapOf<Long, Long>() var bitmask = Bitmask.zero for (line in program) { if (lineIsBitmaskString(line)) { bitmask = Bitmask.fromString(line.drop(7)) } else { valueSetCaptureRegex .find(line) ?.groupValues ?.let { memory[it.component2().toLong()] = bitmask.mask(it.component3().toLong()) } } } return memory } fun runInitializationProgramThroughDecoderChipV2(program: List<String>): MutableMap<Long, Long> { val memory = mutableMapOf<Long, Long>() var bitmask = AddressBitmask.empty for (line in program) { if (lineIsBitmaskString(line)) { bitmask = AddressBitmask.fromString(line.drop(7)) } else { valueSetCaptureRegex .find(line) ?.groupValues ?.let { loc -> bitmask .mask(loc.component2().toLong()) .forEach { memory[it] = loc.component3().toLong() } } } } return memory } private fun lineIsBitmaskString(input: String) = input.startsWith("mask")
0
Kotlin
0
0
a7bd42ee17fed44766cfdeb04d41459becd95803
1,849
AdventOfCode2020
MIT License
app/src/main/java/com/marcouberti/ninegame/ui/board/CardSwipeListener.kt
marcouberti
178,014,894
false
null
package com.marcouberti.ninegame.ui.board import com.marcouberti.ninegame.utils.OnSwipeListener interface CardSwipeListener { fun onSwipe(position: Pair<Int, Int>?, direction: OnSwipeListener.Direction) fun onTap(position: Pair<Int, Int>?) }
0
Kotlin
0
1
3dde0fc62c2d1c1edfa6e0afa5dc957467fb2aac
251
nine-game
Apache License 2.0
aws-ecs-agent/src/main/kotlin/jetbrains/buildServer/clouds/ecs/EcsAgentConfigurationProvider.kt
Julia-Alexandrova
107,976,053
true
{"Kotlin": 49257, "JavaScript": 17258, "Java": 11798, "CSS": 298}
package jetbrains.buildServer.clouds.ecs import jetbrains.buildServer.agent.AgentLifeCycleAdapter import jetbrains.buildServer.agent.AgentLifeCycleListener import jetbrains.buildServer.agent.BuildAgent import jetbrains.buildServer.agent.BuildAgentConfigurationEx import jetbrains.buildServer.util.EventDispatcher import jetbrains.buildServer.util.StringUtil /** * Created by <NAME> (<EMAIL>) on 20.09.17. */ class EcsAgentConfigurationProvider(agentEvents: EventDispatcher<AgentLifeCycleListener>, private val agentConfigurationEx: BuildAgentConfigurationEx) { init { agentEvents.addListener(object : AgentLifeCycleAdapter() { override fun afterAgentConfigurationLoaded(agent: BuildAgent) { super.afterAgentConfigurationLoaded(agent) appendEcsSpecificConfiguration() } }) } private fun appendEcsSpecificConfiguration() { val env = System.getenv() val providedAgentName = env[AGENT_NAME_ECS_ENV] if (!StringUtil.isEmpty(providedAgentName)) agentConfigurationEx.name = providedAgentName val providedServerUrl = env[SERVER_URL_ECS_ENV] if (!StringUtil.isEmpty(providedServerUrl)) agentConfigurationEx.serverUrl = providedServerUrl } }
0
Kotlin
0
0
e9b5d51a82f6eaad33baf0967825c2094ba440af
1,300
teamcity-amazon-ecs-plugin
Apache License 2.0
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/bedrock/CfnFlowProps.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 149148378}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.bedrock import io.cloudshiftdev.awscdk.IResolvable import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import kotlin.Any import kotlin.String import kotlin.Unit import kotlin.collections.Map import kotlin.jvm.JvmName /** * Properties for defining a `CfnFlow`. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.bedrock.*; * Object collector; * Object input; * Object iterator; * Object output; * CfnFlowProps cfnFlowProps = CfnFlowProps.builder() * .executionRoleArn("executionRoleArn") * .name("name") * // the properties below are optional * .customerEncryptionKeyArn("customerEncryptionKeyArn") * .definition(FlowDefinitionProperty.builder() * .connections(List.of(FlowConnectionProperty.builder() * .name("name") * .source("source") * .target("target") * .type("type") * // the properties below are optional * .configuration(FlowConnectionConfigurationProperty.builder() * .conditional(FlowConditionalConnectionConfigurationProperty.builder() * .condition("condition") * .build()) * .data(FlowDataConnectionConfigurationProperty.builder() * .sourceOutput("sourceOutput") * .targetInput("targetInput") * .build()) * .build()) * .build())) * .nodes(List.of(FlowNodeProperty.builder() * .name("name") * .type("type") * // the properties below are optional * .configuration(FlowNodeConfigurationProperty.builder() * .agent(AgentFlowNodeConfigurationProperty.builder() * .agentAliasArn("agentAliasArn") * .build()) * .collector(collector) * .condition(ConditionFlowNodeConfigurationProperty.builder() * .conditions(List.of(FlowConditionProperty.builder() * .name("name") * // the properties below are optional * .expression("expression") * .build())) * .build()) * .input(input) * .iterator(iterator) * .knowledgeBase(KnowledgeBaseFlowNodeConfigurationProperty.builder() * .knowledgeBaseId("knowledgeBaseId") * // the properties below are optional * .modelId("modelId") * .build()) * .lambdaFunction(LambdaFunctionFlowNodeConfigurationProperty.builder() * .lambdaArn("lambdaArn") * .build()) * .lex(LexFlowNodeConfigurationProperty.builder() * .botAliasArn("botAliasArn") * .localeId("localeId") * .build()) * .output(output) * .prompt(PromptFlowNodeConfigurationProperty.builder() * .sourceConfiguration(PromptFlowNodeSourceConfigurationProperty.builder() * .inline(PromptFlowNodeInlineConfigurationProperty.builder() * .modelId("modelId") * .templateConfiguration(PromptTemplateConfigurationProperty.builder() * .text(TextPromptTemplateConfigurationProperty.builder() * .text("text") * // the properties below are optional * .inputVariables(List.of(PromptInputVariableProperty.builder() * .name("name") * .build())) * .build()) * .build()) * .templateType("templateType") * // the properties below are optional * .inferenceConfiguration(PromptInferenceConfigurationProperty.builder() * .text(PromptModelInferenceConfigurationProperty.builder() * .maxTokens(123) * .stopSequences(List.of("stopSequences")) * .temperature(123) * .topK(123) * .topP(123) * .build()) * .build()) * .build()) * .resource(PromptFlowNodeResourceConfigurationProperty.builder() * .promptArn("promptArn") * .build()) * .build()) * .build()) * .retrieval(RetrievalFlowNodeConfigurationProperty.builder() * .serviceConfiguration(RetrievalFlowNodeServiceConfigurationProperty.builder() * .s3(RetrievalFlowNodeS3ConfigurationProperty.builder() * .bucketName("bucketName") * .build()) * .build()) * .build()) * .storage(StorageFlowNodeConfigurationProperty.builder() * .serviceConfiguration(StorageFlowNodeServiceConfigurationProperty.builder() * .s3(StorageFlowNodeS3ConfigurationProperty.builder() * .bucketName("bucketName") * .build()) * .build()) * .build()) * .build()) * .inputs(List.of(FlowNodeInputProperty.builder() * .expression("expression") * .name("name") * .type("type") * .build())) * .outputs(List.of(FlowNodeOutputProperty.builder() * .name("name") * .type("type") * .build())) * .build())) * .build()) * .definitionS3Location(S3LocationProperty.builder() * .bucket("bucket") * .key("key") * // the properties below are optional * .version("version") * .build()) * .definitionString("definitionString") * .definitionSubstitutions(Map.of( * "definitionSubstitutionsKey", "definitionSubstitutions")) * .description("description") * .tags(Map.of( * "tagsKey", "tags")) * .testAliasTags(Map.of( * "testAliasTagsKey", "testAliasTags")) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-bedrock-flow.html) */ public interface CfnFlowProps { /** * The Amazon Resource Name (ARN) of the KMS key that the flow is encrypted with. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-bedrock-flow.html#cfn-bedrock-flow-customerencryptionkeyarn) */ public fun customerEncryptionKeyArn(): String? = unwrap(this).getCustomerEncryptionKeyArn() /** * The definition of the nodes and connections between the nodes in the flow. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-bedrock-flow.html#cfn-bedrock-flow-definition) */ public fun definition(): Any? = unwrap(this).getDefinition() /** * The Amazon S3 location of the flow definition. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-bedrock-flow.html#cfn-bedrock-flow-definitions3location) */ public fun definitionS3Location(): Any? = unwrap(this).getDefinitionS3Location() /** * The definition of the flow as a JSON-formatted string. * * The string must match the format in * [FlowDefinition](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-bedrock-flow-flowdefinition.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-bedrock-flow.html#cfn-bedrock-flow-definitionstring) */ public fun definitionString(): String? = unwrap(this).getDefinitionString() /** * A map that specifies the mappings for placeholder variables in the prompt flow definition. * * This enables the customer to inject values obtained at runtime. Variables can be template * parameter names, resource logical IDs, resource attributes, or a variable in a key-value map. Only * supported with the `DefinitionString` and `DefinitionS3Location` fields. * * Substitutions must follow the syntax: `${key_name}` or `${variable_1,variable_2,...}` . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-bedrock-flow.html#cfn-bedrock-flow-definitionsubstitutions) */ public fun definitionSubstitutions(): Any? = unwrap(this).getDefinitionSubstitutions() /** * A description of the flow. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-bedrock-flow.html#cfn-bedrock-flow-description) */ public fun description(): String? = unwrap(this).getDescription() /** * The Amazon Resource Name (ARN) of the service role with permissions to create a flow. * * For more information, see [Create a service row for * flows](https://docs.aws.amazon.com/bedrock/latest/userguide/flows-permissions.html) in the Amazon * Bedrock User Guide. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-bedrock-flow.html#cfn-bedrock-flow-executionrolearn) */ public fun executionRoleArn(): String /** * The name of the flow. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-bedrock-flow.html#cfn-bedrock-flow-name) */ public fun name(): String /** * Metadata that you can assign to a resource as key-value pairs. For more information, see the * following resources:. * * * [Tag naming limits and * requirements](https://docs.aws.amazon.com/tag-editor/latest/userguide/tagging.html#tag-conventions) * * [Tagging best * practices](https://docs.aws.amazon.com/tag-editor/latest/userguide/tagging.html#tag-best-practices) * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-bedrock-flow.html#cfn-bedrock-flow-tags) */ public fun tags(): Map<String, String> = unwrap(this).getTags() ?: emptyMap() /** * A map of tag keys and values. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-bedrock-flow.html#cfn-bedrock-flow-testaliastags) */ public fun testAliasTags(): Any? = unwrap(this).getTestAliasTags() /** * A builder for [CfnFlowProps] */ @CdkDslMarker public interface Builder { /** * @param customerEncryptionKeyArn The Amazon Resource Name (ARN) of the KMS key that the flow * is encrypted with. */ public fun customerEncryptionKeyArn(customerEncryptionKeyArn: String) /** * @param definition The definition of the nodes and connections between the nodes in the flow. */ public fun definition(definition: IResolvable) /** * @param definition The definition of the nodes and connections between the nodes in the flow. */ public fun definition(definition: CfnFlow.FlowDefinitionProperty) /** * @param definition The definition of the nodes and connections between the nodes in the flow. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("b44461e6f081662d0b758fc27725257844f027e3911b9bd262d00e8397a4d026") public fun definition(definition: CfnFlow.FlowDefinitionProperty.Builder.() -> Unit) /** * @param definitionS3Location The Amazon S3 location of the flow definition. */ public fun definitionS3Location(definitionS3Location: IResolvable) /** * @param definitionS3Location The Amazon S3 location of the flow definition. */ public fun definitionS3Location(definitionS3Location: CfnFlow.S3LocationProperty) /** * @param definitionS3Location The Amazon S3 location of the flow definition. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("534bdb112aa12d670ceb2aa30506d4c9d7c21e5e24d7eaaef8cc4e19a371b18a") public fun definitionS3Location(definitionS3Location: CfnFlow.S3LocationProperty.Builder.() -> Unit) /** * @param definitionString The definition of the flow as a JSON-formatted string. * The string must match the format in * [FlowDefinition](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-bedrock-flow-flowdefinition.html) * . */ public fun definitionString(definitionString: String) /** * @param definitionSubstitutions A map that specifies the mappings for placeholder variables in * the prompt flow definition. * This enables the customer to inject values obtained at runtime. Variables can be template * parameter names, resource logical IDs, resource attributes, or a variable in a key-value map. * Only supported with the `DefinitionString` and `DefinitionS3Location` fields. * * Substitutions must follow the syntax: `${key_name}` or `${variable_1,variable_2,...}` . */ public fun definitionSubstitutions(definitionSubstitutions: IResolvable) /** * @param definitionSubstitutions A map that specifies the mappings for placeholder variables in * the prompt flow definition. * This enables the customer to inject values obtained at runtime. Variables can be template * parameter names, resource logical IDs, resource attributes, or a variable in a key-value map. * Only supported with the `DefinitionString` and `DefinitionS3Location` fields. * * Substitutions must follow the syntax: `${key_name}` or `${variable_1,variable_2,...}` . */ public fun definitionSubstitutions(definitionSubstitutions: Map<String, Any>) /** * @param description A description of the flow. */ public fun description(description: String) /** * @param executionRoleArn The Amazon Resource Name (ARN) of the service role with permissions * to create a flow. * For more information, see [Create a service row for * flows](https://docs.aws.amazon.com/bedrock/latest/userguide/flows-permissions.html) in the * Amazon Bedrock User Guide. */ public fun executionRoleArn(executionRoleArn: String) /** * @param name The name of the flow. */ public fun name(name: String) /** * @param tags Metadata that you can assign to a resource as key-value pairs. For more * information, see the following resources:. * * [Tag naming limits and * requirements](https://docs.aws.amazon.com/tag-editor/latest/userguide/tagging.html#tag-conventions) * * [Tagging best * practices](https://docs.aws.amazon.com/tag-editor/latest/userguide/tagging.html#tag-best-practices) */ public fun tags(tags: Map<String, String>) /** * @param testAliasTags A map of tag keys and values. */ public fun testAliasTags(testAliasTags: IResolvable) /** * @param testAliasTags A map of tag keys and values. */ public fun testAliasTags(testAliasTags: Map<String, String>) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.bedrock.CfnFlowProps.Builder = software.amazon.awscdk.services.bedrock.CfnFlowProps.builder() /** * @param customerEncryptionKeyArn The Amazon Resource Name (ARN) of the KMS key that the flow * is encrypted with. */ override fun customerEncryptionKeyArn(customerEncryptionKeyArn: String) { cdkBuilder.customerEncryptionKeyArn(customerEncryptionKeyArn) } /** * @param definition The definition of the nodes and connections between the nodes in the flow. */ override fun definition(definition: IResolvable) { cdkBuilder.definition(definition.let(IResolvable.Companion::unwrap)) } /** * @param definition The definition of the nodes and connections between the nodes in the flow. */ override fun definition(definition: CfnFlow.FlowDefinitionProperty) { cdkBuilder.definition(definition.let(CfnFlow.FlowDefinitionProperty.Companion::unwrap)) } /** * @param definition The definition of the nodes and connections between the nodes in the flow. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("b44461e6f081662d0b758fc27725257844f027e3911b9bd262d00e8397a4d026") override fun definition(definition: CfnFlow.FlowDefinitionProperty.Builder.() -> Unit): Unit = definition(CfnFlow.FlowDefinitionProperty(definition)) /** * @param definitionS3Location The Amazon S3 location of the flow definition. */ override fun definitionS3Location(definitionS3Location: IResolvable) { cdkBuilder.definitionS3Location(definitionS3Location.let(IResolvable.Companion::unwrap)) } /** * @param definitionS3Location The Amazon S3 location of the flow definition. */ override fun definitionS3Location(definitionS3Location: CfnFlow.S3LocationProperty) { cdkBuilder.definitionS3Location(definitionS3Location.let(CfnFlow.S3LocationProperty.Companion::unwrap)) } /** * @param definitionS3Location The Amazon S3 location of the flow definition. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("534bdb112aa12d670ceb2aa30506d4c9d7c21e5e24d7eaaef8cc4e19a371b18a") override fun definitionS3Location(definitionS3Location: CfnFlow.S3LocationProperty.Builder.() -> Unit): Unit = definitionS3Location(CfnFlow.S3LocationProperty(definitionS3Location)) /** * @param definitionString The definition of the flow as a JSON-formatted string. * The string must match the format in * [FlowDefinition](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-bedrock-flow-flowdefinition.html) * . */ override fun definitionString(definitionString: String) { cdkBuilder.definitionString(definitionString) } /** * @param definitionSubstitutions A map that specifies the mappings for placeholder variables in * the prompt flow definition. * This enables the customer to inject values obtained at runtime. Variables can be template * parameter names, resource logical IDs, resource attributes, or a variable in a key-value map. * Only supported with the `DefinitionString` and `DefinitionS3Location` fields. * * Substitutions must follow the syntax: `${key_name}` or `${variable_1,variable_2,...}` . */ override fun definitionSubstitutions(definitionSubstitutions: IResolvable) { cdkBuilder.definitionSubstitutions(definitionSubstitutions.let(IResolvable.Companion::unwrap)) } /** * @param definitionSubstitutions A map that specifies the mappings for placeholder variables in * the prompt flow definition. * This enables the customer to inject values obtained at runtime. Variables can be template * parameter names, resource logical IDs, resource attributes, or a variable in a key-value map. * Only supported with the `DefinitionString` and `DefinitionS3Location` fields. * * Substitutions must follow the syntax: `${key_name}` or `${variable_1,variable_2,...}` . */ override fun definitionSubstitutions(definitionSubstitutions: Map<String, Any>) { cdkBuilder.definitionSubstitutions(definitionSubstitutions.mapValues{CdkObjectWrappers.unwrap(it.value)}) } /** * @param description A description of the flow. */ override fun description(description: String) { cdkBuilder.description(description) } /** * @param executionRoleArn The Amazon Resource Name (ARN) of the service role with permissions * to create a flow. * For more information, see [Create a service row for * flows](https://docs.aws.amazon.com/bedrock/latest/userguide/flows-permissions.html) in the * Amazon Bedrock User Guide. */ override fun executionRoleArn(executionRoleArn: String) { cdkBuilder.executionRoleArn(executionRoleArn) } /** * @param name The name of the flow. */ override fun name(name: String) { cdkBuilder.name(name) } /** * @param tags Metadata that you can assign to a resource as key-value pairs. For more * information, see the following resources:. * * [Tag naming limits and * requirements](https://docs.aws.amazon.com/tag-editor/latest/userguide/tagging.html#tag-conventions) * * [Tagging best * practices](https://docs.aws.amazon.com/tag-editor/latest/userguide/tagging.html#tag-best-practices) */ override fun tags(tags: Map<String, String>) { cdkBuilder.tags(tags) } /** * @param testAliasTags A map of tag keys and values. */ override fun testAliasTags(testAliasTags: IResolvable) { cdkBuilder.testAliasTags(testAliasTags.let(IResolvable.Companion::unwrap)) } /** * @param testAliasTags A map of tag keys and values. */ override fun testAliasTags(testAliasTags: Map<String, String>) { cdkBuilder.testAliasTags(testAliasTags) } public fun build(): software.amazon.awscdk.services.bedrock.CfnFlowProps = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.bedrock.CfnFlowProps, ) : CdkObject(cdkObject), CfnFlowProps { /** * The Amazon Resource Name (ARN) of the KMS key that the flow is encrypted with. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-bedrock-flow.html#cfn-bedrock-flow-customerencryptionkeyarn) */ override fun customerEncryptionKeyArn(): String? = unwrap(this).getCustomerEncryptionKeyArn() /** * The definition of the nodes and connections between the nodes in the flow. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-bedrock-flow.html#cfn-bedrock-flow-definition) */ override fun definition(): Any? = unwrap(this).getDefinition() /** * The Amazon S3 location of the flow definition. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-bedrock-flow.html#cfn-bedrock-flow-definitions3location) */ override fun definitionS3Location(): Any? = unwrap(this).getDefinitionS3Location() /** * The definition of the flow as a JSON-formatted string. * * The string must match the format in * [FlowDefinition](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-bedrock-flow-flowdefinition.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-bedrock-flow.html#cfn-bedrock-flow-definitionstring) */ override fun definitionString(): String? = unwrap(this).getDefinitionString() /** * A map that specifies the mappings for placeholder variables in the prompt flow definition. * * This enables the customer to inject values obtained at runtime. Variables can be template * parameter names, resource logical IDs, resource attributes, or a variable in a key-value map. * Only supported with the `DefinitionString` and `DefinitionS3Location` fields. * * Substitutions must follow the syntax: `${key_name}` or `${variable_1,variable_2,...}` . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-bedrock-flow.html#cfn-bedrock-flow-definitionsubstitutions) */ override fun definitionSubstitutions(): Any? = unwrap(this).getDefinitionSubstitutions() /** * A description of the flow. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-bedrock-flow.html#cfn-bedrock-flow-description) */ override fun description(): String? = unwrap(this).getDescription() /** * The Amazon Resource Name (ARN) of the service role with permissions to create a flow. * * For more information, see [Create a service row for * flows](https://docs.aws.amazon.com/bedrock/latest/userguide/flows-permissions.html) in the * Amazon Bedrock User Guide. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-bedrock-flow.html#cfn-bedrock-flow-executionrolearn) */ override fun executionRoleArn(): String = unwrap(this).getExecutionRoleArn() /** * The name of the flow. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-bedrock-flow.html#cfn-bedrock-flow-name) */ override fun name(): String = unwrap(this).getName() /** * Metadata that you can assign to a resource as key-value pairs. For more information, see the * following resources:. * * * [Tag naming limits and * requirements](https://docs.aws.amazon.com/tag-editor/latest/userguide/tagging.html#tag-conventions) * * [Tagging best * practices](https://docs.aws.amazon.com/tag-editor/latest/userguide/tagging.html#tag-best-practices) * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-bedrock-flow.html#cfn-bedrock-flow-tags) */ override fun tags(): Map<String, String> = unwrap(this).getTags() ?: emptyMap() /** * A map of tag keys and values. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-bedrock-flow.html#cfn-bedrock-flow-testaliastags) */ override fun testAliasTags(): Any? = unwrap(this).getTestAliasTags() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): CfnFlowProps { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.bedrock.CfnFlowProps): CfnFlowProps = CdkObjectWrappers.wrap(cdkObject) as? CfnFlowProps ?: Wrapper(cdkObject) internal fun unwrap(wrapped: CfnFlowProps): software.amazon.awscdk.services.bedrock.CfnFlowProps = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.bedrock.CfnFlowProps } }
0
Kotlin
0
4
ddf2bfd2275b50bb86a667c4298dd92f59d7e342
24,913
kotlin-cdk-wrapper
Apache License 2.0
core/src/jvmTest/kotlin/entity/MessageTest.kt
kordlib
202,856,399
false
{"Kotlin": 2728142, "Java": 87103}
package dev.kord.core.entity import dev.kord.core.behavior.MessageBehavior import dev.kord.core.cache.data.MessageData import dev.kord.core.equality.BehaviorEqualityTest import dev.kord.core.equality.EntityEqualityTest import dev.kord.core.mockKord import io.mockk.every import io.mockk.mockk internal class MessageTest : EntityEqualityTest<Message> by EntityEqualityTest({ val kord = mockKord() val data = mockk<MessageData>() every { data.id } returns it every { data.channelId } returns it Message(data, kord) }), BehaviorEqualityTest<Message> { override fun Message.behavior(): KordEntity = MessageBehavior(messageId = id, channelId = id, kord = kord) }
52
Kotlin
82
922
e99c5c583229d20e69632aae39cee47da637abef
684
kord
MIT License
frontend/app/src/main/java/com/tec/frontend/DashboardPadres.kt
pedroalonsoms
701,575,731
false
{"Kotlin": 300410, "TypeScript": 18271}
package com.tec.frontend import android.content.ContentValues import android.content.Intent import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.background import androidx.compose.foundation.border 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.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.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope 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.graphics.RectangleShape import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Devices import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.tec.frontend.Api.Alumno import com.tec.frontend.Api.RetrofitInstance import com.tec.frontend.ui.theme.FrontendTheme import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class DashboardPadres : ComponentActivity() { private var ParentId: Int = -1 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { FrontendTheme { ParentId = intent.getIntExtra("ParentID", -1) Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { dashboardPadres(ParentId) BackButtonDashboardProfe(activityContext = this) } } } } } @Composable fun dashboardPadres(ParentID: Int) { val scrollState = rememberScrollState() var alumnos by remember { mutableStateOf<List<Alumno>>(emptyList()) } val coroutineScope = rememberCoroutineScope() LaunchedEffect(Unit) { coroutineScope.launch { try { // Make Retrofit API call on the background thread val response = withContext(Dispatchers.IO) { RetrofitInstance.apiService.getHijos(ParentId = ParentID) } // Assuming response contains an "id" and "type" field alumnos = response } catch (e: Exception) { // Handle error // You can display an error message or perform other actions Log.d(ContentValues.TAG, e.toString()) } } } Surface( modifier = Modifier.fillMaxSize(), color = Color(0xFF4169CF) ) { Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( modifier = Modifier.padding(bottom = 20.dp), text = "Hola de nuevo, papá/mamá!", style = TextStyle(fontSize = 35.sp), color = Color.White, textAlign = TextAlign.Center ) Box( modifier = Modifier .width(850.dp) .background(Color.White) .padding(30.dp) ) { Column( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = "Mi Hij@", style = TextStyle(fontSize = 40.sp, fontWeight = FontWeight.Bold), color = Color.Black, textAlign = TextAlign.Center, modifier = Modifier.padding(bottom = 30.dp) ) alumnos.forEach { alumno -> Row( modifier = Modifier .fillMaxWidth() ) { alumno.name?.let { Text( modifier = Modifier .border( 2.dp, Color.Gray, RoundedCornerShape(0.dp) ).padding(8.dp).width(600.dp), text = it, style = TextStyle( fontSize = 35.sp, fontWeight = FontWeight.Normal ) ) } val context = LocalContext.current Button( modifier = Modifier.padding(start=8.dp), onClick = { val intent = Intent(context, PerfilAlumnoPadre::class.java) intent.putExtra("alumnoId", alumno.id) context.startActivity(intent) }, shape = RoundedCornerShape(0.dp), colors = ButtonDefaults.buttonColors(Orange1) ) { Text("Info", color = Color.White, fontSize = 35.sp) } } Spacer(modifier = Modifier.height(15.dp)) } } } } } } @Composable fun BackButtonDashboardProfe(activityContext: ComponentActivity) { Row(modifier = Modifier .fillMaxWidth() .padding(16.dp), verticalAlignment = Alignment.Top) { Button( shape = RectangleShape, onClick = { activityContext.finish() }, colors = ButtonDefaults.buttonColors(Orange) ){ Text( "Atrás", style = TextStyle(fontSize = 35.sp) ) } } }
1
Kotlin
4
0
663ed05f18d349d5f94373d5e771730f7adc3697
7,454
mypictograms
MIT License
android_sdk/src/main/java/com/swirepay/android_sdk/ui/invoice/model/Invoice.kt
swirepay
344,241,532
false
null
package com.swirepay.android_sdk.ui.invoice.model import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class Invoice(val gid: String) : Parcelable
0
Kotlin
3
1
6d959e4feec3525ae38adfba27f8dc0535655683
175
swirepay-android
MIT License
app/src/main/java/com/maku/pombe/data/repo/DataStoreRepository.kt
ma-za-kpe
373,888,998
false
null
package com.maku.pombe.data.repo import android.content.Context import androidx.datastore.DataStore import androidx.datastore.preferences.* import com.maku.pombe.utils.Constants.Companion.PREFERENCES_BACK_ONLINE import com.maku.pombe.utils.Constants.Companion.PREFERENCES_NAME import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.scopes.ActivityRetainedScoped import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.map import java.io.IOException import javax.inject.Inject @ActivityRetainedScoped class DataStoreRepository @Inject constructor(@ApplicationContext private val context: Context) { private object PreferenceKeys { val backOnline = preferencesKey<Boolean>(PREFERENCES_BACK_ONLINE) } private val dataStore: DataStore<Preferences> = context.createDataStore( name = PREFERENCES_NAME ) suspend fun saveBackOnline(backOnline: Boolean) { dataStore.edit { preferences -> preferences[PreferenceKeys.backOnline] = backOnline } } val readBackOnline: Flow<Boolean> = dataStore.data .catch { exception -> if (exception is IOException) { emit(emptyPreferences()) } else { throw exception } } .map {preferences -> val backOnline = preferences[PreferenceKeys.backOnline] ?: false backOnline } }
0
Kotlin
0
0
cfdb0a2b0ad3399174b3cb33602854a8779df06e
1,476
Pombe
The Unlicense
library/src/main/java/com/cleveroad/droidart/TranslationSettings.kt
Cleveroad
140,836,589
false
null
package com.cleveroad.droidart import android.graphics.PointF import android.os.Parcel import android.os.Parcelable /** * Additional class with settings for translation */ internal class TranslationSettings : Settings { companion object { private const val DEFAULT_TRANSLATION = 0F @Suppress("unused") @JvmField val CREATOR: Parcelable.Creator<TranslationSettings> = object : Parcelable.Creator<TranslationSettings> { override fun createFromParcel(source: Parcel): TranslationSettings = TranslationSettings(source) override fun newArray(size: Int): Array<TranslationSettings?> = arrayOfNulls(size) } } private var storedTranslationX = DEFAULT_TRANSLATION private var storedTranslationY = DEFAULT_TRANSLATION /** * Get translation for x coordinate */ internal val translationX: Float get() = storedTranslationX + xEnd - xStart /** * Get translation for y coordinate */ internal val translationY: Float get() = storedTranslationY + yEnd - yStart /** * Sets the default value for translation */ internal fun resetTranslation(translationX: Float, translationY: Float){ storedTranslationX += translationX storedTranslationY += translationY startPoint = PointF() endPoint = PointF() } constructor() : super() constructor(source: Parcel?) : super(source) { source?.apply { storedTranslationX = readFloat() storedTranslationY = readFloat() } } /** * Store current values of x and y translations */ internal fun storeTranslations() { storedTranslationX = translationX storedTranslationY = translationY } override fun describeContents() = 0 override fun writeToParcel(dest: Parcel?, flags: Int) { super.writeToParcel(dest, flags) dest?.apply { writeFloat(storedTranslationX) writeFloat(storedTranslationY) } } }
3
Kotlin
27
211
29aee46602a0422dfbfe57eedd5673e054f0dda7
2,054
DroidArt
MIT License
core/src/main/java/com/staygrateful/core/network/remote/repository/INetworkRepository.kt
rikyahmad
804,148,308
false
{"Kotlin": 178776}
package com.staygrateful.core.network.remote.repository import com.staygrateful.core.network.remote.mapper.Resource import com.staygrateful.core.network.remote.model.DetailGameResponse import com.staygrateful.core.network.remote.model.GameResponse import com.staygrateful.core.network.remote.model.SearchGameResponse import kotlinx.coroutines.flow.Flow interface INetworkRepository { suspend fun getGameList(page: Int, pageSize: Int): Flow<Resource<GameResponse?>> suspend fun getDetailGame(gameId: Int): Flow<Resource<DetailGameResponse?>> suspend fun searchGames(query: String): Flow<Resource<SearchGameResponse?>> }
0
Kotlin
0
0
91a03109624d69530a69523cb1f934f8022ac9b2
633
GameListApp
MIT License
godot-kotlin/godot-library/src/nativeGen/kotlin/godot/AudioEffectHighShelfFilter.kt
utopia-rise
238,721,773
false
{"Kotlin": 655494, "Shell": 171}
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! ALL CHANGES TO IT WILL BE OVERWRITTEN ON EACH BUILD package godot import godot.internal.utils.invokeConstructor import kotlinx.cinterop.COpaquePointer open class AudioEffectBandPassFilter : AudioEffectFilter() { override fun __new(): COpaquePointer = invokeConstructor("AudioEffectBandPassFilter", "AudioEffectBandPassFilter") }
17
Kotlin
17
286
8d51f614df62a97f16e800e6635ea39e7eb1fd62
391
godot-kotlin-native
MIT License
src/client/kotlin/slabmagic/item/color/NodeBlockItemColor.kt
Jempasam
717,593,852
false
{"Kotlin": 356942, "Java": 1036}
package assets.`slab-magic`.block.color import net.minecraft.client.color.item.ItemColorProvider import net.minecraft.item.ItemStack import net.minecraft.util.DyeColor import slabmagic.components.SlabMagicComponents import slabmagic.helper.ColorTools object NodeBlockItemColor: ItemColorProvider { override fun getColor(stack: ItemStack, tintIndex: Int): Int { return stack.get(SlabMagicComponents.PART) ?.value() ?.color ?.let{ColorTools.int(it)} ?: DyeColor.GRAY.fireworkColor } }
0
Kotlin
0
0
5293f67ccc2484961d3c588c2d0824743be4066f
524
SlateMagic
Creative Commons Zero v1.0 Universal
src/commonMain/kotlin/nl/jacobras/humanreadable/i18n/locales/ItalianLocale.kt
jacobras
696,961,730
false
{"Kotlin": 23915}
package nl.jacobras.humanreadable.i18n.locales import nl.jacobras.humanreadable.i18n.HumanLocale import nl.jacobras.humanreadable.i18n.HumanTimeUnit internal object ItalianLocale : HumanLocale { override val code = "it" override val timeAgo: String get() = "%time% fa" override val timeInFuture: String get() = "tra %time%" override val now: String get() = "adesso" override fun format(unit: HumanTimeUnit, quantity: Long): String { return when (unit) { HumanTimeUnit.Second -> if (quantity == 1L) "secondo" else "secondi" HumanTimeUnit.Minute -> if (quantity == 1L) "minuto" else "minuti" HumanTimeUnit.Hour -> if (quantity == 1L) "ora" else "ore" HumanTimeUnit.Day -> if (quantity == 1L) "giorno" else "giorni" HumanTimeUnit.Week -> if (quantity == 1L) "settimana" else "settimane" HumanTimeUnit.Month -> if (quantity == 1L) "mese" else "mesi" HumanTimeUnit.Year -> if (quantity == 1L) "anno" else "anni" } } }
0
Kotlin
0
1
716e71e0d1e15c4fd2ea82fdb2357f86f2b238e5
1,064
Human-Readable
MIT License
app/src/main/java/io/github/binishmanandhar23/differentscreensize/notification/PlayerNotificationCreation.kt
binishmanandhar23
507,541,156
false
{"Kotlin": 60485}
package io.github.binishmanandhar23.differentscreensize.notification import android.app.Notification import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.BitmapFactory import android.media.MediaMetadata import android.media.session.MediaSession import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import io.github.binishmanandhar23.differentscreensize.R import io.github.binishmanandhar23.differentscreensize.data.BookDetailData import io.github.binishmanandhar23.differentscreensize.enums.PlayState import io.github.binishmanandhar23.differentscreensize.receivers.NotificationActionReceiver import okhttp3.internal.notify import java.io.IOException import java.net.URL class PlayerNotificationCreation { companion object { const val AudioBookChannelId = "AudioBookChannelId" const val ActionPrevious = "ActionPrevious" const val ActionPlay = "ActionPlay" const val ActionNext = "ActionNext" } fun createNotification( context: Context, bookDetailData: BookDetailData, playState: PlayState, position: Int, size: Int ) { val notificationManagerCompat = NotificationManagerCompat.from(context) val mediaSession = MediaSession(context, "AudioBookSession") mediaSession.setMetadata( MediaMetadata.Builder() .putString( MediaMetadata.METADATA_KEY_TITLE, bookDetailData.bookListPreviewData.bookTitle ) .putString( MediaMetadata.METADATA_KEY_ARTIST, bookDetailData.bookListPreviewData.bookAuthor ).build() ) val mediaStyle = Notification.MediaStyle().setMediaSession(mediaSession.sessionToken) val icon = try { URL(bookDetailData.bookListPreviewData.bookImageURL).let { BitmapFactory.decodeStream(it.openConnection().getInputStream()) } } catch (ex: IOException) { ex.printStackTrace() null } val intentPrevious = Intent(context, NotificationActionReceiver::class.java).setAction( ActionPrevious ) val pendingIntentPrevious = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.getBroadcast( context, 0, intentPrevious, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT ) else PendingIntent.getBroadcast( context, 0, intentPrevious, PendingIntent.FLAG_UPDATE_CURRENT ) val intentPlay = Intent(context, NotificationActionReceiver::class.java).setAction( ActionPlay ) val pendingIntentPlay = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.getBroadcast( context, 0, intentPlay, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT ) else PendingIntent.getBroadcast(context, 0, intentPlay, PendingIntent.FLAG_UPDATE_CURRENT) val intentNext = Intent(context, NotificationActionReceiver::class.java).setAction( ActionNext ) val pendingIntentNext = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.getBroadcast( context, 0, intentNext, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT ) else PendingIntent.getBroadcast(context, 0, intentNext, PendingIntent.FLAG_UPDATE_CURRENT) val notification = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { Notification.Builder(context, AudioBookChannelId).let { notificationCompat -> notificationCompat.setSmallIcon(R.drawable.ic_music_note) if (icon != null) notificationCompat.setLargeIcon(icon) notificationCompat.setOnlyAlertOnce(true) notificationCompat.setShowWhen(false) notificationCompat.addAction( Notification.Action.Builder( if (position == 0) 0 else R.drawable.ic_previous, "Previous", if (position == 0) null else pendingIntentPrevious ).build() ) notificationCompat.addAction( Notification.Action.Builder( R.drawable.ic_play, "Play", pendingIntentPlay ).build() ) notificationCompat.addAction( Notification.Action.Builder( if (position == size - 1) 0 else R.drawable.ic_next, "Previous", if (position == size - 1) null else pendingIntentNext ).build() ) notificationCompat.style = mediaStyle notificationCompat.build() } } else { NotificationCompat.Builder(context, AudioBookChannelId).let { notificationCompat -> notificationCompat.setSmallIcon(R.drawable.ic_music_note) notificationCompat.setContentTitle(bookDetailData.bookListPreviewData.bookTitle) notificationCompat.setContentText(bookDetailData.bookListPreviewData.bookAuthor) if (icon != null) notificationCompat.setLargeIcon(icon) notificationCompat.setOnlyAlertOnce(true) notificationCompat.setShowWhen(false) notificationCompat.addAction( if (position == 0) 0 else R.drawable.ic_previous, "Previous", if (position == 0) null else pendingIntentPrevious ) notificationCompat.addAction(R.drawable.ic_play, "Play", pendingIntentPlay) notificationCompat.addAction( if (position == size - 1) 0 else R.drawable.ic_next, "Previous", if (position == size - 1) null else pendingIntentNext ) notificationCompat.priority = NotificationCompat.PRIORITY_LOW notificationCompat.build() } } notificationManagerCompat.notify(1, notification) } }
0
Kotlin
0
0
1e2282e161750e11592cdbf5ca92367c71a45c5a
6,959
DifferentScreenSize
Apache License 2.0
sdk/src/main/java/com/microsoft/did/sdk/crypto/keys/KeyTypeFactory.kt
TaffyWrinkle
337,989,562
true
{"Kotlin": 572132}
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ package com.microsoft.did.sdk.crypto.keys import com.microsoft.did.sdk.crypto.models.webCryptoApi.algorithms.Algorithm import com.microsoft.did.sdk.util.controlflow.UnSupportedAlgorithmException import java.util.Locale /** * Factory class to create @enum KeyType objects */ object KeyTypeFactory { /** * Create the key type according to the selected algorithm. * @param algorithm Web crypto compliant algorithm object */ fun createViaWebCrypto(algorithm: Algorithm): KeyType { return when (algorithm.name.toLowerCase(Locale.ENGLISH)) { "hmac" -> KeyType.Octets "ecdsa", "ecdh" -> KeyType.EllipticCurve "rsassa-pkcs1-v1_5", "rsa-oaep", "rsa-oaep-256" -> KeyType.RSA else -> throw UnSupportedAlgorithmException("The algorithm '${algorithm.name}' is not supported") } } }
0
null
0
0
e29bf44879f3177c7ae07018e5d97a61053b1978
1,215
VerifiableCredential-SDK-Android
MIT License
src/main/kotlin/no/nav/syfo/minesykmeldte/MineSykmeldteMapper.kt
navikt
399,790,648
false
{"Kotlin": 245024, "Dockerfile": 277}
package no.nav.syfo.minesykmeldte import no.nav.syfo.minesykmeldte.model.Hendelse import no.nav.syfo.minesykmeldte.model.HendelseType import no.nav.syfo.minesykmeldte.model.PeriodeEnum import no.nav.syfo.minesykmeldte.model.PreviewFremtidigSoknad import no.nav.syfo.minesykmeldte.model.PreviewNySoknad import no.nav.syfo.minesykmeldte.model.PreviewSendtSoknad import no.nav.syfo.minesykmeldte.model.PreviewSoknad import no.nav.syfo.minesykmeldte.model.Soknadsperiode import no.nav.syfo.minesykmeldte.model.Sporsmal import no.nav.syfo.minesykmeldte.model.Svar import no.nav.syfo.minesykmeldte.model.Undersporsmal import no.nav.syfo.soknad.model.Soknad import no.nav.syfo.soknad.model.SoknadStatus class MineSykmeldteMapper private constructor() { companion object { fun toPreviewSoknad( soknad: Soknad, lest: Boolean, hendelser: List<Hendelse>, ): PreviewSoknad = when (soknad.status) { SoknadStatus.NY -> getNySoknad(soknad, lest, hendelser) SoknadStatus.SENDT -> getSendtSoknad(soknad, lest) SoknadStatus.FREMTIDIG -> getFremtidigSoknad(soknad) else -> throw IllegalArgumentException("Incorrect soknad status ${soknad.status}") } private fun getSendtSoknad(soknad: Soknad, lest: Boolean): PreviewSendtSoknad = PreviewSendtSoknad( id = soknad.id, sykmeldingId = soknad.sykmeldingId, fom = soknad.fom, tom = soknad.tom, lest = lest, korrigererSoknadId = soknad.korrigerer, sendtDato = soknad.sendtArbeidsgiver ?: throw IllegalStateException( "sendtArbeidsgiver is null for soknad: ${soknad.id}" ), perioder = soknad.soknadsperioder.map { it.toSoknadsperiode() } ) private fun getFremtidigSoknad(soknad: Soknad): PreviewFremtidigSoknad = PreviewFremtidigSoknad( id = soknad.id, sykmeldingId = soknad.sykmeldingId, fom = soknad.fom, tom = soknad.tom, perioder = soknad.soknadsperioder.map { it.toSoknadsperiode() } ) private fun getNySoknad( soknad: Soknad, lest: Boolean, hendelser: List<Hendelse> ): PreviewNySoknad = PreviewNySoknad( lest = lest, id = soknad.id, sykmeldingId = soknad.sykmeldingId, fom = soknad.fom, tom = soknad.tom, perioder = soknad.soknadsperioder.map { it.toSoknadsperiode() }, ikkeSendtSoknadVarsel = hendelser.any { it.id == soknad.id && it.oppgavetype == HendelseType.IKKE_SENDT_SOKNAD }, ikkeSendtSoknadVarsletDato = hendelser .find { it.id == soknad.id && it.oppgavetype == HendelseType.IKKE_SENDT_SOKNAD } ?.mottatt, ) fun no.nav.syfo.soknad.model.Soknadsperiode.toSoknadsperiode(): Soknadsperiode = Soknadsperiode( fom = fom, tom = tom, sykmeldingsgrad = sykmeldingsgrad, sykmeldingstype = PeriodeEnum.valueOf(sykmeldingstype.toString()), ) private fun no.nav.syfo.soknad.model.Sporsmal.toUndersporsmal(): Undersporsmal = Undersporsmal( id = id, tag = tag, min = min, max = max, sporsmalstekst = sporsmalstekst, undertekst = undertekst, svartype = svartype, kriterieForVisningAvUndersporsmal = kriterieForVisningAvUndersporsmal, svar = svar.map { Svar( verdi = requireNotNull(it.verdi), ) }, undersporsmal = undersporsmal.map { it.toUndersporsmal() }, ) fun no.nav.syfo.soknad.model.Sporsmal.toSporsmal(): Sporsmal = Sporsmal( id = id, tag = tag, min = min, max = max, sporsmalstekst = requireNotNull(sporsmalstekst), undertekst = undertekst, svartype = svartype, kriterieForVisningAvUndersporsmal = kriterieForVisningAvUndersporsmal, svar = svar.map { Svar( verdi = requireNotNull(it.verdi), ) }, undersporsmal = undersporsmal.map { it.toUndersporsmal() }, ) } }
1
Kotlin
1
1
492ff1d5a3ee4b703bbe338cb362f6eaaff8fe98
4,997
dinesykmeldte-backend
MIT License
starter/app/src/main/java/com/udacity/asteroidradar/main/MainRepository.kt
sergioat7
374,732,782
false
null
/* * Copyright (c) 2021 <NAME>. All rights reserved. * Created by <NAME> on 27/6/2021 */ package com.udacity.asteroidradar.main import com.udacity.asteroidradar.Constants import com.udacity.asteroidradar.PictureOfDay import com.udacity.asteroidradar.api.NasaApi import com.udacity.asteroidradar.api.getNextSevenDaysFormattedDates import com.udacity.asteroidradar.api.parseAsteroidsJsonResult import com.udacity.asteroidradar.database.AsteroidDatabase import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.json.JSONObject class MainRepository(private val database: AsteroidDatabase) { suspend fun getPictureOfDay(): PictureOfDay? { return withContext(Dispatchers.IO) { try { val imageOfTheDay = NasaApi.retrofitService.getImageOfTheDay(Constants.API_KEY) when (imageOfTheDay.mediaType) { "image" -> imageOfTheDay else -> null } } catch (e: Exception) { null } } } fun getWeeklyAsteroids() = database.asteroidDatabaseDao.getWeekly() fun getTodayAsteroids() = database.asteroidDatabaseDao.getToday() fun getSavedAsteroids() = database.asteroidDatabaseDao.getAll() suspend fun refreshTodayAsteroids() { withContext(Dispatchers.IO) { val objects = NasaApi.retrofitService.getNearEarthObjects( null, null, Constants.API_KEY ) val asteroids = parseAsteroidsJsonResult( JSONObject(objects), getNextSevenDaysFormattedDates() ) database.asteroidDatabaseDao.deleteAll() database.asteroidDatabaseDao.insertAll(*asteroids.toTypedArray()) } } }
0
Kotlin
0
0
01e642cbb0bf18ef1171ad4f8dfe5004a55ec390
1,828
Udacity-AsteroidRadar
MIT License
plugins/kotlin/idea/tests/testData/quickfix/convertLateinitPropertyToNotNullDelegate/basic2.kt
ingokegel
72,937,917
true
null
// "Convert to notNull delegate" "true" // WITH_STDLIB <caret>lateinit var x: Int // FUS_QUICKFIX_NAME: org.jetbrains.kotlin.idea.quickfix.ConvertLateinitPropertyToNotNullDelegateFix
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
182
intellij-community
Apache License 2.0
core/common/src/main/kotlin/com/wecanteen105/core/common/network/di/CoroutineScopeModule.kt
chongiscool
845,810,159
false
{"Kotlin": 44087}
package com.wecanteen105.core.common.network.di import com.wecanteen105.core.common.network.Dispatcher import com.wecanteen105.core.common.network.TmdDispatchers import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import javax.inject.Qualifier import javax.inject.Singleton @Retention(AnnotationRetention.RUNTIME) @Qualifier annotation class ApplicationScope @Module @InstallIn(SingletonComponent::class) internal object CoroutineScopeModule { @Provides @Singleton @ApplicationScope fun providesCoroutineScope ( @Dispatcher(TmdDispatchers.Default) dispatcher: CoroutineDispatcher, ): CoroutineScope = CoroutineScope(SupervisorJob() + dispatcher) }
0
Kotlin
0
0
c584aa021db90a760d3b813555cefb8b26113e09
875
tmdtv
Apache License 2.0
GIData/src/commonMain/kotlin/org/anime_game_servers/game_data_models/data/dungeon/DungeonStateType.kt
Hartie95
650,687,061
false
null
package org.anime_game_servers.game_data_models.data.dungeon import org.anime_game_servers.core.base.interfaces.IntKey enum class DungeonStateType(val id: Int) : IntKey { DUNGEON_STATE_NONE(0), DUNGEON_STATE_RELEASE(1), DUNGEON_STATE_TEST(2), DUNGEON_STATE_UNKNOWN(9999); override fun getIntKey() = id }
0
null
1
2
7820a4c8ec2d56d083f86034d15702789a523429
326
AnimeGameDataModels
MIT License
src/test/kotlin/TestAgilityPointer.kt
lindsaygelle
833,228,388
false
{"Kotlin": 238198}
import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals internal class TestAgilityPointer { private class AgilityPointer : dqbb.AgilityPointer { override var agility: Int = 0 } private lateinit var agilityAccumulator: dqbb.AgilityPointer @BeforeTest fun before() { agilityAccumulator = AgilityPointer() } @Test fun test() { for (agility in (0..100)) { agilityAccumulator.agility = agility assertEquals(agility, agilityAccumulator.agility) } } }
0
Kotlin
0
0
cf02a9e2ee8fb401598e720bffa22c21e8bfa470
570
dqbb
MIT License
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/log/ExecutionLogListener.kt
spinnaker-release
100,423,592
false
null
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.log import com.netflix.spinnaker.orca.events.* import org.springframework.context.ApplicationListener import org.springframework.stereotype.Component @Component class ExecutionLogListener( private val executionLogRepository: ExecutionLogRepository, private val currentInstanceId: String ) : ApplicationListener<ExecutionEvent> { override fun onApplicationEvent(event: ExecutionEvent) { executionLogRepository.save(event.toLogEntry()) } private fun ExecutionEvent.toLogEntry(): ExecutionLogEntry { val details = when (this) { is ExecutionComplete -> mapOf("status" to status.name) is StageStarted -> mapOf("stageId" to stageId, "type" to stageType, "name" to stageName) is StageComplete -> mapOf("stageId" to stageId, "type" to stageType, "name" to stageName, "status" to status.name) is TaskStarted -> mapOf("stageId" to stageId, "taskId" to taskId, "type" to taskType, "name" to taskName) is TaskComplete -> mapOf("stageId" to stageId, "taskId" to taskId, "type" to taskType, "name" to taskName, "status" to status.name) else -> emptyMap() } return ExecutionLogEntry( executionId, timestamp(), javaClass.simpleName, currentInstanceId, details ) } }
1
null
1
1
83757f4618be6088e8d8676b4fd8bdfce7d30c90
1,881
orca
Apache License 2.0
feature/note/src/main/java/com/example/feature/note/component/MoreMenuComponent.kt
llsit
827,324,299
false
{"Kotlin": 296104}
package com.example.feature.note.component import androidx.compose.foundation.layout.Box import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.Icon import androidx.compose.material3.IconButton 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 @Composable fun MoreMenuComponent( onEditClick: () -> Unit = {}, onDeleteClick: () -> Unit ) { Box { var expanded by remember { mutableStateOf(false) } IconButton(onClick = { expanded = true }) { Icon( imageVector = Icons.Default.MoreVert, contentDescription = "More options", tint = MaterialTheme.colorScheme.onSurfaceVariant ) } DropdownMenu( expanded = expanded, onDismissRequest = { expanded = false } ) { DropdownMenuItem( text = { Text("Edit") }, onClick = { expanded = false onEditClick() } ) DropdownMenuItem( text = { Text("Delete") }, onClick = { expanded = false onDeleteClick() } ) } } }
0
Kotlin
0
0
49a6c318a7514e46a2c97b281eb7e074b731907c
1,658
ItemNote
MIT License
app/src/main/kotlin/com/base/mvp/BaseView.kt
fahmidev013
151,547,245
false
null
package com.base.mvp /** * Created by Fahmi Hakim on 23.05.2017. */ interface BaseView { fun onError() fun setPresenter(presenter: BasePresenter<*>) }
0
Kotlin
1
0
d646f600cdb478ad2754c5017a7d9b5538ab883b
161
kotlin-mvp
MIT License
app/src/main/kotlin/com/base/mvp/BaseView.kt
fahmidev013
151,547,245
false
null
package com.base.mvp /** * Created by <NAME> on 23.05.2017. */ interface BaseView { fun onError() fun setPresenter(presenter: BasePresenter<*>) }
0
Kotlin
1
0
d646f600cdb478ad2754c5017a7d9b5538ab883b
156
kotlin-mvp
MIT License
app/src/main/java/com/thanosfisherman/grpcplayground/domain/usecases/LoginUseCase.kt
ThanosFisherman
528,540,686
false
{"Kotlin": 66718}
package com.thanosfisherman.grpcplayground.domain.usecases import com.thanosfisherman.grpcplayground.domain.models.DUserProfileModel import com.thanosfisherman.grpcplayground.domain.repos.PrefsRepo import com.thanosfisherman.grpcplayground.domain.states.LoginResultState import kotlinx.coroutines.CoroutineScope import java.util.* class LoginUseCase(private val prefsRepo: PrefsRepo) : BaseUseCase<String, LoginResultState<DUserProfileModel>>() { override val initialState: LoginResultState<DUserProfileModel> get() = LoginResultState.Idle override suspend fun execute(scope: CoroutineScope, vararg params: String) { when { params[0].isBlank() -> { stateResultMutable.value = LoginResultState.WrongEmail } !params[1].contains("@") -> { stateResultMutable.value = LoginResultState.WrongEmail } params[1].isBlank() -> { stateResultMutable.value = LoginResultState.WrongEmail } else -> { val userId = UUID.randomUUID().toString() val username = params[0] val email = params[1] val user = DUserProfileModel(userId, email, username) prefsRepo.storeUserProfile(user) stateResultMutable.value = LoginResultState.Success(user) } } } }
0
Kotlin
0
9
2c6b1177b7ddd096d944faf920f049cdc3af421c
1,411
gRPCPlayground
Apache License 2.0
src/main/kotlin/com/example/scraping/repository/content/model/CommentContent.kt
mobyleOfficial
440,164,730
false
{"Kotlin": 51657}
package com.example.scraping.repository.content.model data class CommentContent(val message: String)
0
Kotlin
0
0
3515cefe6b89848eda11bbf8595d53552c784b43
101
filmoow_api
MIT License
uisdk/src/main/java/tech/dojo/pay/uisdk/presentation/components/CheckBoxItem.kt
dojo-engineering
478,120,913
false
null
package tech.dojo.pay.uisdk.presentation.components import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.material.Icon import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Check import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import tech.dojo.pay.uisdk.presentation.components.theme.DojoTheme @Composable internal fun CheckBoxItem( modifier: Modifier = Modifier, itemText: String, isChecked: Boolean = true, onCheckedChange: (Boolean) -> Unit, ) { val checkedState = remember { mutableStateOf(isChecked) } Row( modifier = modifier .fillMaxWidth() .clickable { checkedState.value = !checkedState.value onCheckedChange(checkedState.value) }, verticalAlignment = Alignment.CenterVertically, ) { Box( modifier = Modifier .size(25.dp) .border( width = 1.dp, color = if (checkedState.value) DojoTheme.colors.inputElementActiveTintColor else DojoTheme.colors.headerButtonTintColor, shape = DojoTheme.shapes.small, ) .background(DojoTheme.colors.primarySurfaceBackgroundColor) .align(Alignment.Top), ) { if (checkedState.value) { Icon( Icons.Default.Check, contentDescription = "", tint = DojoTheme.colors.inputElementActiveTintColor, ) } } DojoSpacer(width = 12.dp) Box( modifier = Modifier .weight(1f) .wrapContentHeight() .align(Alignment.Top), ) { Text( text = itemText, overflow = TextOverflow.Ellipsis, softWrap = true, maxLines = 7, color = DojoTheme.colors.secondaryLabelTextColor, style = DojoTheme.typography.subtitle1, ) } } } @Preview("CheckBoxItem", group = "CheckBoxItem") @Composable internal fun PreviewCheckBoxItem() = DojoPreview { CheckBoxItem( itemText = "Save card for future use", onCheckedChange = {}, ) }
1
null
2
3
4f9e9be58189d22f5269a53bcc1a2b2028a777df
2,995
android-dojo-pay-sdk
MIT License
build-logic/conventions/src/main/kotlin/AndroidLibraryConventionPlugin.kt
GuilhE
576,783,011
false
null
@file:Suppress("UnstableApiUsage", "unused") import com.android.build.gradle.LibraryExtension import org.gradle.api.JavaVersion import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.artifacts.VersionCatalog import org.gradle.api.artifacts.VersionCatalogsExtension import org.gradle.kotlin.dsl.configure import org.gradle.kotlin.dsl.getByType class AndroidLibraryConventionPlugin : Plugin<Project> { override fun apply(target: Project) { with(target) { with(pluginManager) { apply("com.android.library") apply("org.jetbrains.kotlin.android") } extensions.configure<LibraryExtension> { addKotlinAndroidConfigurations(target.extensions.getByType<VersionCatalogsExtension>().named("libs")) addKotlinJvmOptions() // addProjectGlobalFlavorsAndDimension() } } } private fun LibraryExtension.addKotlinAndroidConfigurations(libs: VersionCatalog) { apply { compileSdk = libs.findVersion("androidCompileSdk").get().toString().toInt() defaultConfig { targetSdk = libs.findVersion("androidTargetSdk").get().toString().toInt() minSdk = libs.findVersion("androidMinSdk").get().toString().toInt() } compileOptions { sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 } lint { abortOnError = false } } } }
1
Kotlin
0
38
627e25707eb8ef1f3af13c08e316862ae0b0085a
1,599
JsonBroadcaster
Apache License 2.0
ktorfit-annotations/src/commonMain/kotlin/de/jensklingenberg/ktorfit/http/GET.kt
Foso
203,655,484
false
{"Kotlin": 330650, "Ruby": 2354, "Java": 692, "Swift": 345}
package de.jensklingenberg.ktorfit.http /** Make a GET request. * ``` * @GET("issue") * suspend fun getIssue(@Query("id") id: String) : Issue * ``` * @param value relative url path, if empty, you need to have a parameter with [Url] * */ @Target(AnnotationTarget.FUNCTION) annotation class GET(val value: String = "")
32
Kotlin
40
1,558
16d3481c25b151e5abb37d7cb2ee4e86c5db9d49
324
Ktorfit
Apache License 2.0
shared/src/main/kotlin/xlitekt/shared/resource/MapSquareResource.kt
runetopic
448,110,155
false
null
package xlitekt.shared.resource import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class MapSquareResource( val archive: Int, val group: Int, @SerialName("name_hash") val nameHash: Int, val name: String, val mapsquare: Int, val key: List<Int> )
2
Kotlin
3
8
8f88434e6c02e420f60dc9c42d3570b901b96b78
325
xlitekt
MIT License
src/main/kotlin/com/cognifide/gradle/aem/common/instance/LocalInstanceManager.kt
piotr-andruszkiewicz-wttech
267,069,008
true
{"Kotlin": 577980, "Shell": 5281, "Batchfile": 267}
package com.cognifide.gradle.aem.common.instance import com.cognifide.gradle.aem.AemException import com.cognifide.gradle.aem.AemExtension import com.cognifide.gradle.aem.AemVersion import com.cognifide.gradle.aem.common.instance.action.AwaitDownAction import com.cognifide.gradle.aem.common.instance.action.AwaitUpAction import com.cognifide.gradle.aem.common.instance.local.* import com.cognifide.gradle.aem.instance.LocalInstancePlugin import com.cognifide.gradle.aem.javaVersions import com.cognifide.gradle.common.pluginProject import com.cognifide.gradle.common.utils.onEachApply import com.cognifide.gradle.common.utils.using import org.buildobjects.process.ProcBuilder import org.gradle.api.JavaVersion import java.io.File import java.io.Serializable import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.TimeUnit class LocalInstanceManager(internal val aem: AemExtension) : Serializable { private val project = aem.project private val common = aem.common private val logger = aem.logger val base by lazy { aem.instanceManager } /** * Using local AEM instances is acceptable in any project so that lookup for project applying local instance plugin is required * Needed to determine e.g directory in which AEM quickstart will be stored and override files. */ val projectDir = aem.obj.dir { convention(aem.obj.provider { project.pluginProject(LocalInstancePlugin.ID)?.layout?.projectDirectory ?: throw LocalInstanceException( "Using local AEM instances requires having at least one project applying plugin '${LocalInstancePlugin.ID}'" + " or setting property 'localInstance.projectDir'!" ) }) aem.prop.string("localInstance.projectDir")?.let { set(project.rootProject.file(it)) } } /** * Path in which local AEM instances will be stored. */ val rootDir = aem.obj.dir { convention(projectDir.dir(".gradle/aem/localInstance/instance")) aem.prop.file("localInstance.rootDir")?.let { set(it) } } /** * Path for storing local AEM instances related resources. */ val configDir = aem.obj.dir { convention(projectDir.dir(aem.prop.string("localInstance.configPath") ?: "src/aem/localInstance")) aem.prop.file("localInstance.configDir")?.let { set(it) } } /** * Path from which e.g extra files for local AEM instances will be copied. * Useful for overriding default startup scripts ('start.bat' or 'start.sh') or providing some files inside 'crx-quickstart'. */ val overrideDir = aem.obj.dir { convention(configDir.dir("override")) aem.prop.file("localInstance.overrideDir")?.let { set(it) } } /** * Determines how instances will be created (from backup or quickstart built from the scratch). */ val source = aem.obj.typed<Source> { convention(Source.AUTO) aem.prop.string("localInstance.source")?.let { set(Source.of(it)) } } fun source(name: String) { source.set(Source.of(name)) } /** * Automatically open a web browser when instances are up. */ val openMode = aem.obj.typed<OpenMode> { convention(OpenMode.NEVER) aem.prop.string("localInstance.openMode")?.let { set(OpenMode.of(it)) } } /** * Maximum time to wait for browser open command response. */ val openTimeout = aem.obj.long { convention(TimeUnit.SECONDS.toMillis(30)) aem.prop.long("localInstance.openTimeout")?.let { set(it) } } fun openMode(name: String) { openMode.set(OpenMode.of(name)) } fun resolveFiles() { logger.info("Resolving local instance files") logger.info("Resolved local instance files:\n${sourceFiles.joinToString("\n")}") } /** * Maximum time to wait for status script response. */ val statusTimeout = aem.obj.long { convention(TimeUnit.SECONDS.toMillis(5)) aem.prop.long("localInstance.statusTimeout")?.let { set(it) } } /** * Collection of files potentially needed to create instance */ val sourceFiles = aem.obj.files { from(aem.obj.provider { listOfNotNull(backupZip) + quickstart.files + install.files }) } /** * Wildcard file name filter expression that is used to filter in which instance files properties can be injected. */ val expandFiles = aem.obj.strings { convention(listOf( "**/start.bat", "**/stop.bat", "**/start", "**/stop" )) } /** * Custom properties that can be injected into instance files. */ val expandProperties = aem.obj.map<String, Any> { convention(mapOf()) } val quickstart by lazy { QuickstartResolver(aem) } /** * Configure AEM source files when creating instances from the scratch. */ fun quickstart(options: QuickstartResolver.() -> Unit) = quickstart.using(options) /** * Configure AEM backup sources. */ val backup by lazy { BackupManager(aem) } fun backup(options: BackupManager.() -> Unit) = backup.using(options) val backupZip: File? get() { return when (source.get()) { Source.AUTO, Source.BACKUP_ANY -> backup.any Source.BACKUP_LOCAL -> backup.local Source.BACKUP_REMOTE -> backup.remote else -> null } } val install by lazy { InstallResolver(aem) } /** * Configure CRX packages, bundles to be pre-installed on instance(s). */ fun install(options: InstallResolver.() -> Unit) = install.using(options) internal var initOptions: LocalInstance.() -> Unit = {} /** * Configure action to be performed only once when instance is up first time. */ fun init(options: LocalInstance.() -> Unit) { this.initOptions = options } fun create(instance: LocalInstance) = create(listOf(instance)) fun create(instances: Collection<LocalInstance> = aem.localInstances): List<LocalInstance> { val uncreatedInstances = instances.filter { !it.created } if (uncreatedInstances.isEmpty()) { logger.lifecycle("No instances to create.") return listOf() } logger.info("Creating instances: ${uncreatedInstances.names}") createBySource(uncreatedInstances) return uncreatedInstances.filter { it.created } } @Suppress("ComplexMethod") fun createBySource(instances: Collection<LocalInstance> = aem.localInstances) = when (source.get()) { Source.AUTO -> { val backupZip = backup.any when { backupZip != null -> createFromBackup(instances, backupZip) else -> createFromScratch(instances) } } Source.BACKUP_ANY -> { val backupZip = backup.any when { backupZip != null -> createFromBackup(instances, backupZip) else -> throw LocalInstanceException("Cannot create instance(s) because no backups available!") } } Source.BACKUP_LOCAL -> { val backupZip = backup.local ?: throw LocalInstanceException("Cannot create instance(s) because no local backups available!") createFromBackup(instances, backupZip) } Source.BACKUP_REMOTE -> { val backupZip = backup.remote ?: throw LocalInstanceException("Cannot create instance(s) because no remote backups available!") createFromBackup(instances, backupZip) } Source.SCRATCH -> createFromScratch(instances) null -> {} } fun createFromBackup(instances: Collection<LocalInstance> = aem.localInstances, backupZip: File) { backup.restore(backupZip, rootDir.get().asFile, instances) val missingInstances = instances.filter { !it.created } if (missingInstances.isNotEmpty()) { logger.info("Backup ZIP '$backupZip' does not contain all instances. Creating from scratch: ${missingInstances.names}") createFromScratch(missingInstances) } common.progress(instances.size) { instances.onEachApply { increment("Customizing instance '$name'") { logger.info("Customizing: $this") customize() logger.info("Customized: $this") } } } } fun createFromScratch(instances: Collection<LocalInstance> = aem.localInstances) { if (quickstart.jar == null || quickstart.license == null) { throw LocalInstanceException("Cannot create instances due to lacking source files. " + "Ensure having specified local instance quickstart jar & license urls.") } common.progress(instances.size) { instances.onEachApply { increment("Creating instance '$name'") { if (created) { logger.info(("Instance already created: $this")) return@increment } logger.info("Creating: $this") prepare() logger.info("Created: $this") } } } } fun destroy(instance: LocalInstance): Boolean = destroy(listOf(instance)).isNotEmpty() fun destroy(instances: Collection<LocalInstance> = aem.localInstances): List<LocalInstance> { val createdInstances = instances.filter { it.touched } if (createdInstances.isEmpty()) { logger.lifecycle("No instances to destroy.") return listOf() } logger.info("Destroying instance(s): ${createdInstances.names}") common.progress(createdInstances.size) { createdInstances.onEachApply { increment("Destroying '$name'") { logger.info("Destroying: $this") delete() logger.info("Destroyed: $this") } } } return createdInstances } fun up(instance: LocalInstance, awaitUpOptions: AwaitUpAction.() -> Unit = {}) = up(listOf(instance), awaitUpOptions).isNotEmpty() fun up(instances: Collection<LocalInstance> = aem.localInstances, awaitUpOptions: AwaitUpAction.() -> Unit = {}): List<LocalInstance> { val downInstances = instances.filter { !it.running } if (downInstances.isEmpty()) { logger.lifecycle("No instances to turn on.") return listOf() } common.progress(downInstances.size) { downInstances.onEachApply { increment("Customizing instance '$name'") { logger.info("Customizing: $this") customize() logger.info("Customized: $this") } } } common.progress(downInstances.size) { common.parallel.with(downInstances) { increment("Starting instance '$name'") { if (!created) { logger.info("Instance not created, so it could not be up: $this") return@increment } val status = checkStatus() if (status == Status.RUNNING) { logger.info("Instance already running. No need to start: $this") return@increment } executeStartScript() } } } base.awaitUp(downInstances, awaitUpOptions) val uninitializedInstances = downInstances.filter { !it.initialized } common.progress(uninitializedInstances.size) { common.parallel.with(uninitializedInstances) { increment("Initializing instance '$name'") { logger.info("Initializing: $this") init(initOptions) } } } when { openMode.get() == OpenMode.ALWAYS -> open(downInstances) openMode.get() == OpenMode.ONCE -> open(uninitializedInstances) } return downInstances } fun down(instance: LocalInstance, awaitDownOptions: AwaitDownAction.() -> Unit = {}) = down(listOf(instance), awaitDownOptions).isNotEmpty() fun down(instances: Collection<LocalInstance> = aem.localInstances, awaitDownOptions: AwaitDownAction.() -> Unit = {}): List<LocalInstance> { val upInstances = instances.filter { it.running } if (upInstances.isEmpty()) { logger.lifecycle("No instances to turn off.") return listOf() } common.progress(upInstances.size) { common.parallel.with(upInstances) { increment("Stopping instance '$name'") { if (!created) { logger.info("Instance not created, so it could not be down: $this") return@increment } val status = checkStatus() if (status != Status.RUNNING) { logger.info("Instance is not running (reports status '$status'). No need to stop: $this") return@increment } executeStopScript() } } } base.awaitDown(upInstances, awaitDownOptions) return upInstances } fun open(instance: LocalInstance) = open(listOf(instance)) fun open(instances: Collection<LocalInstance> = aem.localInstances): List<LocalInstance> { val upInstances = instances.filter { it.running } if (upInstances.isEmpty()) { logger.lifecycle("No instances to open.") return listOf() } val openedInstances = CopyOnWriteArrayList<LocalInstance>() common.progress(upInstances.size) { common.parallel.with(upInstances) { increment("Opening instance '$name'") { try { aem.webBrowser.open(httpOpenUrl) { withTimeoutMillis(openTimeout.get()) } openedInstances += this@with } catch (e: AemException) { logger.debug("Instance '$name' open error", e) logger.warn("Cannot open instance '$name'! Cause: ${e.message}") } } } } if (openedInstances.isNotEmpty()) { logger.lifecycle("Opened instances (${openedInstances.size}) in web browser (tabs):\n" + openedInstances.joinToString("\n") { "Instance '${it.name}' at URL '${it.httpOpenUrl}'" }) } return openedInstances } fun kill(instance: LocalInstance) = kill(listOf(instance)) fun kill(instances: Collection<LocalInstance> = aem.localInstances): List<LocalInstance> { val killableInstances = instances.filter { it.pid > 0 } if (killableInstances.isEmpty()) { logger.lifecycle("No instances to kill.") return listOf() } val killedInstances = CopyOnWriteArrayList<LocalInstance>() common.progress(killableInstances.size) { common.parallel.with(killableInstances) { increment("Killing instance '$name'") { try { aem.processKiller.kill(pid) killedInstances += this@with } catch (e: AemException) { logger.debug("Instance '$name' kill error", e) logger.warn("Cannot kill instance '$name'! Cause: ${e.message}") } } } } if (killedInstances.isEmpty()) { logger.lifecycle("No instances killed!") } return killedInstances } fun examine(instances: Collection<LocalInstance> = aem.localInstances) = base.examine(instances) fun examinePrerequisites(instances: Collection<LocalInstance> = aem.localInstances) { examinePaths() examineJavaAvailable() examineJavaCompatibility(instances) examineRunningOther(instances) } fun examinePaths() { val rootDir = rootDir.get().asFile if (rootDir.path.contains(" ")) { throw LocalInstanceException("Local instances root path must not contain spaces: '$rootDir'!\n" + "AEM control scripts could run improperly with such paths.") } } /** * Pre-conditionally check if 'java' is available in shell scripts. * * Gradle is intelligently looking by its own for installed Java, but AEM control scripts * are just requiring 'java' command available in 'PATH' environment variable. */ @Suppress("TooGenericExceptionCaught", "MagicNumber") fun examineJavaAvailable() { try { logger.debug("Examining Java properly installed") val result = ProcBuilder("java", "-version") .withWorkingDirectory(rootDir.get().asFile.apply { mkdirs() }) .withTimeoutMillis(statusTimeout.get()) .withExpectedExitStatuses(0) .run() logger.debug("Installed Java:\n${result.outputString.ifBlank { result.errorString }}") } catch (e: Exception) { throw LocalInstanceException("Local instances support requires Java properly installed! Cause: '${e.message}'\n" + "Ensure having directory with 'java' executable listed in 'PATH' environment variable.", e) } } /** * Defines compatibility related to AEM versions and Java versions. * * AEM version is definable as range inclusive at a start, exclusive at an end. * Java Version is definable as list of supported versions pipe delimited. */ val javaCompatibility = aem.obj.map<String, String> { convention(mapOf( "6.0.0-6.5.0" to "1.7|1.8", "6.5.0-6.6.0" to "1.8|11" )) aem.prop.map("localInstance.javaCompatibility")?.let { set(it) } } fun examineJavaCompatibility(instances: Collection<LocalInstance> = aem.localInstances) { if (javaCompatibility.get().isEmpty()) { logger.debug("Examining Java compatibility skipped as configuration not provided!") return } logger.debug("Examining Java compatibility for configuration: ${javaCompatibility.get()}") val versionCurrent = JavaVersion.current() val errors = instances.fold(mutableListOf<String>()) { result, instance -> val aemVersion = instance.version javaCompatibility.get().forEach { (aemVersionRange, versionList) -> if (aemVersion in AemVersion.unclosedRange(aemVersionRange, "-")) { val versions = versionList.javaVersions("|") if (versionCurrent !in versions) { result.add("Instance '${instance.name}' at URL '${instance.httpUrl}' is AEM $aemVersion" + " and requires Java ${versions.joinToString("|")}!") } } } result } if (errors.isNotEmpty()) { throw LocalInstanceException("Some instances (${errors.size}) require different Java version than current $versionCurrent:\n" + errors.joinToString("\n") ) } } fun examineRunningOther(instances: Collection<LocalInstance> = aem.localInstances) { val running = instances.filter { it.runningOther } if (running.isNotEmpty()) { throw LocalInstanceException("Other instances (${running.size}) are running:\n" + running.joinToString("\n") { "Instance '${it.name}' at URL '${it.httpUrl}' located at path '${it.runningDir}'" } + "\n\n" + "Ensure having these instances down." ) } } }
0
null
0
0
966c8ae3b32ad0cfb0c4b14328c33d0690ebd96c
20,308
gradle-aem-plugin
Apache License 2.0
core/data/remote/src/main/java/com/lcabral/artseventh/core/data/remote/paging/MoviePagingSource.kt
LucianaCabral
706,897,860
false
{"Kotlin": 187343}
package com.lcabral.artseventh.core.data.remote.paging import androidx.paging.PagingSource import androidx.paging.PagingState import com.lcabral.artseventh.core.data.remote.model.toMovies import com.lcabral.artseventh.core.data.remote.source.RemoteDataSource import com.lcabral.artseventh.core.domain.model.Movie class MoviePagingSource( private val remoteDataSource: RemoteDataSource ) : PagingSource<Int, Movie>() { override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Movie> { return runCatching { val page = params.key ?: 1 val response = remoteDataSource.getMovies(page) val movies = response.results LoadResult.Page( data = movies.toMovies(), prevKey = if (page == 1) null else page.dec(), nextKey = if (movies.isEmpty()) null else page.inc() ) }.getOrElse { LoadResult.Error(throwable = it) } } // /** Verifica se a chave de paginação é válida:**/ // private fun ensureValidKey(key: Int) = max(STARTING_PAGE_INDEX, key) override fun getRefreshKey(state: PagingState<Int, Movie>): Int? { return state.anchorPosition?.let { anchorPosition -> val anchorPage = state.closestPageToPosition(anchorPosition) anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1) } } }
0
Kotlin
0
0
d0e9570062399b6016524dbc587255faa842da75
1,407
ArtSeventh
MIT License
src/main/kotlin/interfaces/SpecifiedModuleTableOutput.kt
JaggieGor
397,651,030
false
null
package interfaces interface SpecifiedModuleTableOutput : TableOutput { fun getModuleName():String }
0
Kotlin
0
0
a956cfd9ea1a4f896e3fef29a24286fdf33e24a7
105
NLSParser
Apache License 2.0
simplified-books-registry-api/src/main/java/org/nypl/simplified/books/book_registry/BookPreviewStatus.kt
ThePalaceProject
367,082,997
false
{"Kotlin": 3279542, "JavaScript": 853788, "Java": 374503, "CSS": 65407, "HTML": 49220, "Shell": 5017, "Ruby": 178}
package org.nypl.simplified.books.book_registry import one.irradia.mime.api.MIMEType import java.io.File import java.net.URL sealed class BookPreviewStatus { object None : BookPreviewStatus() open class HasPreview : BookPreviewStatus() { data class Downloading( val bytesPerSecond: Long?, val currentTotalBytes: Long?, val expectedTotalBytes: Long?, val detailMessage: String ) : HasPreview() class DownloadFailed : HasPreview() sealed class Ready : HasPreview() { data class Embedded(val url: URL) : Ready() data class BookPreview(val file: File, val mimeType: MIMEType) : Ready() data class AudiobookPreview(val file: File) : Ready() } } }
0
Kotlin
4
8
638d560ec98f0bc87fead8d28086098997c94e92
720
android-core
Apache License 2.0
common/src/main/java/com/yogeshpaliyal/common/utils/PasswordGenerator.kt
yogeshpaliyal
334,702,754
false
null
package com.yogeshpaliyal.common.utils class PasswordGenerator( private var length: Int, private var includeUpperCaseLetters: Boolean, private var includeLowerCaseLetters: Boolean, private var includeSymbols: Boolean, private var includeNumbers: Boolean ) { constructor() : this(10, true, true, true, true) private val UPPER_CASE = 0 private val LOWER_CASE = 1 private val NUMBERS = 2 private val SYMBOLS = 3 public fun generatePassword(): String { var password = "" val list = ArrayList<Int>() if (includeUpperCaseLetters) list.add(UPPER_CASE) if (includeLowerCaseLetters) list.add(LOWER_CASE) if (includeNumbers) list.add(NUMBERS) if (includeSymbols) list.add(SYMBOLS) for (i in 1..length) { if (list.isNotEmpty()) { when (list.random()) { UPPER_CASE -> password += ('A'..'Z').random().toString() LOWER_CASE -> password += ('a'..'z').random().toString() NUMBERS -> password += ('0'..'9').random().toString() SYMBOLS -> password += listOf('!', '@', '#', '$', '%', '&', '*', '+', '=', '-', '~', '?', '/', '_').random().toString() } } } return password } }
22
Kotlin
60
87
63a3e6e702b9cd28324cb6a8b06967ca3b456111
1,365
KeyPass
MIT License
test_runner/src/main/kotlin/ftl/args/yml/IYmlKeys.kt
Flank
84,221,974
false
{"Kotlin": 1748173, "Java": 101254, "Swift": 41229, "Shell": 10674, "Objective-C": 10006, "Dart": 9705, "HTML": 7235, "Gherkin": 4210, "TypeScript": 2717, "Ruby": 2272, "JavaScript": 1764, "SCSS": 1365, "Batchfile": 1183, "EJS": 1061, "Go": 159}
package ftl.args.yml import com.fasterxml.jackson.annotation.JsonProperty import kotlin.reflect.KClass import kotlin.reflect.KMutableProperty import kotlin.reflect.full.findAnnotation import kotlin.reflect.full.memberProperties interface IYmlKeys { val group: String val keys: List<String> object Group { const val FLANK = "flank" const val GCLOUD = "gcloud" } } val KClass<*>.ymlKeys get() = memberProperties .filterIsInstance<KMutableProperty<*>>() .mapNotNull { it.setter.findAnnotation<JsonProperty>() } .map { it.value } fun mergeYmlKeys( vararg keys: IYmlKeys ): Map<String, List<String>> = keys .groupBy(IYmlKeys::group, IYmlKeys::keys) .mapValues { (_, keys) -> keys.flatten() }
64
Kotlin
115
676
b40904b4e74a670cf72ee53dc666fc3a801e7a95
776
flank
Apache License 2.0
partiql-lang/src/test/kotlin/org/partiql/lang/eval/evaluatortestframework/PipelineEvaluatorTestAdapter.kt
partiql
186,474,394
false
null
package org.partiql.lang.eval.evaluatortestframework import org.junit.jupiter.api.Assertions.assertNotEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Assertions.assertNull import org.partiql.lang.ION import org.partiql.lang.errors.ErrorBehaviorInPermissiveMode import org.partiql.lang.eval.EvaluationSession import org.partiql.lang.eval.ExprValue import org.partiql.lang.eval.TypingMode import org.partiql.lang.eval.exprEquals import org.partiql.lang.eval.toIonValue internal class PipelineEvaluatorTestAdapter( private val pipelineFactory: PipelineFactory ) : EvaluatorTestAdapter { override fun runEvaluatorTestCase(tc: EvaluatorTestCase, session: EvaluationSession) { // Skip execution of this test case if it does not apply to the pipeline supplied by pipelineFactory. if (tc.targetPipeline != EvaluatorTestTarget.ALL_PIPELINES && pipelineFactory.target != tc.targetPipeline) { return } checkRedundantPermissiveMode(tc) // Compile options unmodified... This covers [TypingMode.LEGACY], unless the test explicitly // sets the typing mode. privateRunEvaluatorTestCase(tc, session, "${pipelineFactory.pipelineName} (compile options unaltered)") // Unless the test disables it, run again in permissive mode. if (tc.implicitPermissiveModeTest) { privateRunEvaluatorTestCase( tc.copy( compileOptionsBuilderBlock = { tc.compileOptionsBuilderBlock(this) typingMode(TypingMode.PERMISSIVE) } ), session, "${pipelineFactory.pipelineName} (compile options forced to PERMISSIVE mode)" ) } } /** * Runs the give test case once with the specified [session]. */ private fun privateRunEvaluatorTestCase( tc: EvaluatorTestCase, session: EvaluationSession, note: String, ) { val pipeline = pipelineFactory.createPipeline(tc, session) val actualExprValueResult: ExprValue = assertDoesNotThrow( EvaluatorTestFailureReason.FAILED_TO_EVALUATE_QUERY, { tc.testDetails(note = note) } ) { pipeline.evaluate(tc.query) } val (expectedResult, unexpectedResultErrorCode) = when (pipeline.typingMode) { TypingMode.LEGACY -> tc.expectedResult to EvaluatorTestFailureReason.UNEXPECTED_QUERY_RESULT TypingMode.PERMISSIVE -> tc.expectedPermissiveModeResult to EvaluatorTestFailureReason.UNEXPECTED_PERMISSIVE_MODE_RESULT } when (tc.expectedResultFormat) { ExpectedResultFormat.ION -> { val expectedIonResult = assertDoesNotThrow( EvaluatorTestFailureReason.FAILED_TO_PARSE_ION_EXPECTED_RESULT, { tc.testDetails(note = note) } ) { ION.singleValue(expectedResult) } val actualIonResult = actualExprValueResult.toIonValue(ION) assertEquals( expectedIonResult, actualIonResult, unexpectedResultErrorCode ) { tc.testDetails(note = note, actualResult = actualIonResult.toString()) } } ExpectedResultFormat.PARTIQL -> { val expectedExprValueResult = assertDoesNotThrow( EvaluatorTestFailureReason.FAILED_TO_EVALUATE_PARTIQL_EXPECTED_RESULT, { tc.testDetails(note = note) } ) { pipeline.evaluate(expectedResult) } if (!expectedExprValueResult.exprEquals(actualExprValueResult)) { throw EvaluatorAssertionFailedError( EvaluatorTestFailureReason.UNEXPECTED_QUERY_RESULT, tc.testDetails(note = note, actualResult = actualExprValueResult.toString()) ) } Unit } ExpectedResultFormat.STRICT -> { val expectedExprValueResult = assertDoesNotThrow( EvaluatorTestFailureReason.FAILED_TO_EVALUATE_PARTIQL_EXPECTED_RESULT, { tc.testDetails(note = note) } ) { pipeline.evaluate(expectedResult) } if (!expectedExprValueResult.strictEquals(actualExprValueResult)) { throw EvaluatorAssertionFailedError( EvaluatorTestFailureReason.UNEXPECTED_QUERY_RESULT, tc.testDetails(note = note, actualResult = actualExprValueResult.toString()) ) } Unit } }.let { } tc.extraResultAssertions(actualExprValueResult) } /** Runs an [EvaluatorErrorTestCase] once. */ private fun privateRunEvaluatorErrorTestCase( tc: EvaluatorErrorTestCase, session: EvaluationSession, note: String ) { val pipeline = pipelineFactory.createPipeline(tc, session) val ex = assertThrowsSqlException( EvaluatorTestFailureReason.EXPECTED_SQL_EXCEPTION_BUT_THERE_WAS_NONE, { tc.testDetails(note = note) } ) { // Note that an SqlException (usually a SemanticException or EvaluationException) might be thrown in // .compile OR in .eval. We currently don't make a distinction, so tests cannot assert that certain // errors are compile-time and others are evaluation-time. We really aught to create a way for tests to // indicate when the exception should be thrown. This is undone. // The call to .ionValue below is important since query execution won't actually begin otherwise. pipeline.evaluate(tc.query).toIonValue(ION) } assertEquals( tc.expectedErrorCode, ex.errorCode, EvaluatorTestFailureReason.UNEXPECTED_ERROR_CODE ) { tc.testDetails(note = note, actualErrorCode = ex.errorCode) } if (tc.expectedErrorContext != null) { assertEquals( tc.expectedErrorContext, ex.errorContext, EvaluatorTestFailureReason.UNEXPECTED_ERROR_CONTEXT ) { tc.testDetails(note = note, actualErrorContext = ex.errorContext) } } if (tc.expectedInternalFlag != null) { assertEquals( tc.expectedInternalFlag, ex.internal, EvaluatorTestFailureReason.UNEXPECTED_INTERNAL_FLAG ) { tc.testDetails(note = note, actualInternalFlag = ex.internal) } } tc.additionalExceptionAssertBlock(ex) } override fun runEvaluatorErrorTestCase(tc: EvaluatorErrorTestCase, session: EvaluationSession) { // Skip execution of this test case if it does not apply to the pipeline supplied by pipelineFactory. if (tc.targetPipeline != EvaluatorTestTarget.ALL_PIPELINES && pipelineFactory.target != tc.targetPipeline) { return } checkRedundantPermissiveMode(tc) // Run the query once with compile options unmodified. privateRunEvaluatorErrorTestCase( tc = tc.copy( compileOptionsBuilderBlock = { tc.compileOptionsBuilderBlock(this) typingMode(TypingMode.LEGACY) } ), session = session, note = "${pipelineFactory.pipelineName} (Typing mode forced to LEGACY)" ) when (tc.expectedErrorCode.errorBehaviorInPermissiveMode) { ErrorBehaviorInPermissiveMode.THROW_EXCEPTION -> { // The expected error code indicates that this error should also throw in permissive mode. assertNull( tc.expectedPermissiveModeResult, "An expectedPermissiveModeResult must not be specified when " + "ErrorCode.errorBehaviorInPermissiveMode is set to THROW_EXCEPTION" ) // Run the query once in permissive mode. privateRunEvaluatorErrorTestCase( tc.copy( compileOptionsBuilderBlock = { tc.compileOptionsBuilderBlock(this) typingMode(TypingMode.PERMISSIVE) } ), session, note = "${pipelineFactory.pipelineName} (typing mode forced to PERMISSIVE)" ) } ErrorBehaviorInPermissiveMode.RETURN_MISSING -> { // The expected error code indicates that this error should continue, but the expression should // return missing. assertNotNull( tc.expectedPermissiveModeResult, "Required non null expectedPermissiveModeResult when ErrorCode.errorBehaviorInPermissiveMode is " + "set to ErrorBehaviorInPermissiveMode.RETURN_MISSING" ) // Compute the expected return value val permissiveModePipeline = pipelineFactory.createPipeline(evaluatorTestDefinition = tc, session, forcePermissiveMode = true) val expectedExprValueForPermissiveMode = assertDoesNotThrow( EvaluatorTestFailureReason.FAILED_TO_EVALUATE_PARTIQL_EXPECTED_RESULT, { tc.testDetails(note = "Evaluating expected permissive mode result") } ) { permissiveModePipeline.evaluate(tc.expectedPermissiveModeResult!!) } val actualReturnValueForPermissiveMode = assertDoesNotThrow( EvaluatorTestFailureReason.FAILED_TO_EVALUATE_QUERY, { tc.testDetails( note = "PERMISSIVE typing mode forced. Query should throw in LEGACY mode but not in PERMISSIVE", ) } ) { permissiveModePipeline.evaluate(tc.query) } if (!expectedExprValueForPermissiveMode.exprEquals(actualReturnValueForPermissiveMode)) { throw EvaluatorAssertionFailedError( EvaluatorTestFailureReason.UNEXPECTED_PERMISSIVE_MODE_RESULT, tc.testDetails( note = "PERMISSIVE typing mode forced.", actualPermissiveModeResult = actualReturnValueForPermissiveMode.toString() ) ) } } } } private fun checkRedundantPermissiveMode(tc: EvaluatorTestDefinition) { if (tc.implicitPermissiveModeTest) { val pipeline = pipelineFactory.createPipeline(tc, EvaluationSession.standard()) assertNotEquals( TypingMode.PERMISSIVE, pipeline.typingMode, "Setting TypingMode.PERMISSIVE when implicit permissive mode testing is enabled is redundant" ) } } }
311
null
61
539
ac6cdfff46ba5749d4fc850b1a30bf625034bfc9
11,474
partiql-lang-kotlin
Apache License 2.0
app/src/main/java/com/jaimegc/covid19tracker/domain/usecase/GetCountry.kt
mmoreno1992
458,004,956
true
{"Kotlin": 1318013}
package com.jaimegc.covid19tracker.domain.usecase import arrow.core.Either import com.jaimegc.covid19tracker.data.repository.CovidTrackerRepository import com.jaimegc.covid19tracker.domain.model.DomainError import com.jaimegc.covid19tracker.domain.model.ListCountry import com.jaimegc.covid19tracker.domain.states.State import com.jaimegc.covid19tracker.domain.states.StateError import kotlinx.coroutines.flow.Flow class GetCountry( private val repository: CovidTrackerRepository ) { fun getCountries(): Flow<Either<StateError<DomainError>, State<ListCountry>>> = repository.getCountries() }
0
Kotlin
0
0
752b0948282c6d9ee6d2058cf7d7641069f389e6
610
Covid19Tracker
Apache License 2.0
core/navigation/src/main/java/com/goalpanzi/mission_mate/core/navigation/RouteModel.kt
Nexters
828,096,097
false
{"Kotlin": 469213, "Ruby": 1219}
package com.goalpanzi.mission_mate.core.navigation import kotlinx.serialization.Serializable sealed interface RouteModel { @Serializable data object Login : RouteModel @Serializable data object Onboarding : RouteModel @Serializable sealed interface Profile: RouteModel { @Serializable data object Create : Profile @Serializable data object Setting : Profile } @Serializable data object Setting : RouteModel @Serializable data class Board(val missionId : Long) : RouteModel } sealed interface OnboardingRouteModel { @Serializable data object BoardSetup : OnboardingRouteModel @Serializable data object BoardSetupSuccess : OnboardingRouteModel @Serializable data object InvitationCode : OnboardingRouteModel } sealed interface SettingRouteModel { @Serializable data object ServicePolicy : SettingRouteModel @Serializable data object PrivacyPolicy : SettingRouteModel }
1
Kotlin
0
3
912bebd2706d1206f38c910e85c79fece73e4213
993
goalpanzi-android
Apache License 2.0
math/src/main/kotlin/info/laht/threekt/math/Sphere.kt
markaren
196,544,572
false
null
package info.laht.threekt.math import info.laht.threekt.core.Cloneable import kotlin.jvm.JvmOverloads import kotlin.math.abs import kotlin.math.max import kotlin.math.sqrt data class Sphere @JvmOverloads constructor( val center: Vector3 = Vector3(), var radius: Float = 0f ) : Cloneable { fun set(center: Vector3, radius: Float): Sphere { this.center.copy(center) this.radius = radius return this } @JvmOverloads fun setFromPoints(points: List<Vector3>, optionalCenter: Vector3? = null): Sphere { val box = Box3() val center = this.center if (optionalCenter != null) { center.copy(optionalCenter) } else { box.setFromPoints(points).getCenter(center) } var maxRadiusSq = 0f points.forEach { point -> maxRadiusSq = max(maxRadiusSq, center.distanceToSquared(point)) } this.radius = sqrt(maxRadiusSq) return this } fun empty(): Boolean { return (this.radius <= 0) } fun containsPoint(point: Vector3): Boolean { return (point.distanceToSquared(this.center) <= (this.radius * this.radius)) } fun distanceToPoint(point: Vector3): Float { return (point.distanceTo(this.center) - this.radius) } fun intersectsSphere(sphere: Sphere): Boolean { val radiusSum = this.radius + sphere.radius return sphere.center.distanceToSquared(this.center) <= (radiusSum * radiusSum) } fun intersectsBox(box: Box3): Boolean { return box.intersectsSphere(this) } fun intersectsPlane(plane: Plane): Boolean { return abs(plane.distanceToPoint(this.center)) <= this.radius } fun clampPoint(point: Vector3, target: Vector3 = Vector3()): Vector3 { val deltaLengthSq = this.center.distanceToSquared(point) target.copy(point) if (deltaLengthSq > (this.radius * this.radius)) { target.sub(this.center).normalize() target.multiplyScalar(this.radius).add(this.center) } return target } @JvmOverloads fun getBoundingBox(target: Box3 = Box3()): Box3 { target.set(this.center, this.center) target.expandByScalar(this.radius) return target } fun applyMatrix4(matrix: Matrix4): Sphere { this.center.applyMatrix4(matrix) this.radius = this.radius * matrix.getMaxScaleOnAxis() return this } fun translate(offset: Vector3): Sphere { this.center.add(offset) return this } override fun clone(): Sphere { return Sphere().copy(this) } fun copy(sphere: Sphere): Sphere { this.center.copy(sphere.center) this.radius = sphere.radius return this } }
7
null
14
187
8dc6186d777182da6831cf1c79f39ee2d5960cd7
2,817
three.kt
MIT License
model/src/main/java/com/zj/model/model/BaseModel.kt
zhujiang521
265,420,729
false
null
package com.zj.model.model /** * 版权:Zhujiang 个人版权 * * @author zhujiang * 创建日期:2020/9/22 * 描述:PlayAndroid * */ data class BaseModel<T>( val `data`: T, val errorCode: Int, val errorMsg: String )
6
Kotlin
151
977
11111a15f4fa9f43668b4f6356074b531f134baf
213
PlayAndroid
MIT License
src/main/kotlin/org/rust/ide/typing/RsAngleBraceHandlers.kt
intellij-rust
42,619,487
false
null
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.typing import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.highlighter.HighlighterIterator import org.rust.lang.core.psi.RsElementTypes.* import org.rust.lang.core.psi.tokenSetOf private val GENERIC_NAMED_ENTITY_KEYWORDS = tokenSetOf(FN, STRUCT, ENUM, TRAIT, TYPE_KW) private val INVALID_INSIDE_TOKENS = tokenSetOf(LBRACE, RBRACE, SEMICOLON) class RsAngleBraceTypedHandler : RsBraceTypedHandler(AngleBraceHandler) class RsAngleBraceBackspaceHandler : RsBraceBackspaceHandler(AngleBraceHandler) object AngleBraceHandler : BraceHandler { override val opening: BraceKind = BraceKind('<', LT) override val closing: BraceKind = BraceKind('>', GT) override fun shouldComplete(editor: Editor): Boolean { val offset = editor.caretModel.offset val lexer = editor.createLexer(offset - 1) ?: return false return when (lexer.tokenType) { // manual function type specification COLONCOLON -> true // generic implementation block IMPL -> true IDENTIFIER -> { // don't complete angle braces inside identifier if (lexer.end != offset) return false // it considers that typical case is only one whitespace character // between keyword (fn, enum, etc.) and identifier if (lexer.start > 1) { lexer.retreat() lexer.retreat() if (lexer.tokenType in GENERIC_NAMED_ENTITY_KEYWORDS) return true lexer.advance() lexer.advance() } isTypeLikeIdentifier(offset, editor, lexer) } else -> false } } override fun calculateBalance(editor: Editor): Int { val offset = editor.caretModel.offset val iterator = (editor as EditorEx).highlighter.createIterator(offset) while (iterator.start > 0 && iterator.tokenType !in INVALID_INSIDE_TOKENS) { iterator.retreat() } if (iterator.tokenType in INVALID_INSIDE_TOKENS) { iterator.advance() } var balance = 0 while (!iterator.atEnd() && balance >= 0 && iterator.tokenType !in INVALID_INSIDE_TOKENS) { when (iterator.tokenType) { LT -> balance++ GT -> balance-- } iterator.advance() } return balance } private fun isTypeLikeIdentifier(offset: Int, editor: Editor, iterator: HighlighterIterator): Boolean { if (iterator.end != offset) return false val chars = editor.document.charsSequence if (!Character.isUpperCase(chars[iterator.start])) return false if (iterator.end == iterator.start + 1) return true return (iterator.start + 1 until iterator.end).any { Character.isLowerCase(chars[it]) } } }
1,841
null
380
4,528
c6657c02bb62075bf7b7ceb84d000f93dda34dc1
3,089
intellij-rust
MIT License
app/src/main/java/com/cipolat/droidbank/data/home/model/HomeBody.kt
sebacipolat
717,958,569
false
{"Kotlin": 97899}
package com.cipolat.droidbank.data.home.model import com.cipolat.droidbank.data.home.remote.model.Balance import com.cipolat.droidbank.data.home.remote.model.User import com.cipolat.droidbank.data.transactions.remote.model.TransactionItem data class HomeBody( val user: User, val balance: Balance, val transactions: List<TransactionItem> )
0
Kotlin
1
16
7876c59ab5cc007647502424dfa2d002294a6261
354
DroidBank
Apache License 2.0
android/beagle/src/main/java/br/com/zup/beagle/android/data/serializer/adapter/ComponentJsonAdapterFactory.kt
tyagi2141
295,206,658
true
{"Gradle": 32, "Gemfile.lock": 1, "Ruby": 10, "CODEOWNERS": 1, "Markdown": 12, "INI": 4, "Ignore List": 4, "Text": 51, "YAML": 22, "Dart": 3, "Java Properties": 22, "XML": 81, "Kotlin": 695, "OpenStep Property List": 32, "Objective-C": 12, "Swift": 361, "JSON": 56, "C++": 29, "C": 1, "Shell": 9, "Batchfile": 2, "EditorConfig": 2, "Proguard": 3, "Gradle Kotlin DSL": 2, "Java": 3, "HTML": 2, "sed": 2}
/* * 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.android.data.serializer.adapter import br.com.zup.beagle.android.components.Touchable import br.com.zup.beagle.android.components.form.FormInput import br.com.zup.beagle.android.components.form.FormSubmit import br.com.zup.beagle.android.components.form.InputWidget import br.com.zup.beagle.android.components.page.PageIndicatorComponent import br.com.zup.beagle.android.data.serializer.PolymorphicJsonAdapterFactory import br.com.zup.beagle.android.setup.BeagleEnvironment import br.com.zup.beagle.android.setup.InternalWidgetFactory import br.com.zup.beagle.android.widget.UndefinedWidget import br.com.zup.beagle.android.widget.WidgetView import br.com.zup.beagle.core.ServerDrivenComponent import br.com.zup.beagle.widget.Widget import java.util.Locale private const val BEAGLE_WIDGET_TYPE = "_beagleComponent_" private const val BEAGLE_NAMESPACE = "beagle" private const val CUSTOM_NAMESPACE = "custom" internal object ComponentJsonAdapterFactory { fun make(): PolymorphicJsonAdapterFactory<ServerDrivenComponent> { var factory = PolymorphicJsonAdapterFactory.of( ServerDrivenComponent::class.java, BEAGLE_WIDGET_TYPE ) factory = registerBaseSubTypes(factory) factory = registerUIClass(factory) factory = registerWidgets(factory, BEAGLE_NAMESPACE, InternalWidgetFactory.registeredWidgets()) factory = registerWidgets(factory, CUSTOM_NAMESPACE, BeagleEnvironment.beagleSdk.registeredWidgets()) factory = registerUndefinedWidget(factory) return factory } private fun registerBaseSubTypes( factory: PolymorphicJsonAdapterFactory<ServerDrivenComponent> ): PolymorphicJsonAdapterFactory<ServerDrivenComponent> { return factory.withBaseSubType(PageIndicatorComponent::class.java) .withBaseSubType(InputWidget::class.java) .withBaseSubType(Widget::class.java) } private fun registerUIClass( factory: PolymorphicJsonAdapterFactory<ServerDrivenComponent> ): PolymorphicJsonAdapterFactory<ServerDrivenComponent> { return factory .withSubtype(Touchable::class.java, createNamespaceFor<Touchable>()) .withSubtype(FormInput::class.java, createNamespaceFor<FormInput>()) .withSubtype(FormSubmit::class.java, createNamespaceFor<FormSubmit>()) } private fun registerWidgets( factory: PolymorphicJsonAdapterFactory<ServerDrivenComponent>, appName: String, widgets: List<Class<WidgetView>> ): PolymorphicJsonAdapterFactory<ServerDrivenComponent> { var newFactory = factory widgets.forEach { newFactory = newFactory.withSubtype(it, createNamespace(appName, it)) } return newFactory } private fun registerUndefinedWidget( factory: PolymorphicJsonAdapterFactory<ServerDrivenComponent> ): PolymorphicJsonAdapterFactory<ServerDrivenComponent> { return factory.withDefaultValue(UndefinedWidget()) } private inline fun <reified T : ServerDrivenComponent> createNamespaceFor(): String { return createNamespace(BEAGLE_NAMESPACE, T::class.java) } private fun createNamespace(appNamespace: String, clazz: Class<*>): String { val typeName = clazz.simpleName.toLowerCase(Locale.getDefault()) return "$appNamespace:$typeName" } }
0
null
0
1
d64c69511dbf7c8f6198ed14cc07c1fa15bf080e
4,018
beagle
Apache License 2.0
src/commonMain/kotlin/org.angproj.aux/pkg/arb/StructType.kt
angelos-project
677,039,667
false
{"Kotlin": 986392, "Python": 196308}
/** * Copyright (c) 2024 by Kristoffer Paulsson <kristoffer.paulsson@talenten.se>. * * This software is available under the terms of the MIT license. Parts are licensed * under different terms if stated. The legal terms are attached to the LICENSE file * and are made available on: * * https://opensource.org/licenses/MIT * * SPDX-License-Identifier: MIT * * Contributors: * Kristoffer Paulsson - initial implementation */ package org.angproj.aux.pkg.arb import org.angproj.aux.io.Readable import org.angproj.aux.io.Retrievable import org.angproj.aux.io.Storable import org.angproj.aux.io.Writable import org.angproj.aux.pkg.* import org.angproj.aux.pkg.type.BlockType import kotlin.jvm.JvmInline @JvmInline public value class StructType<P : BlockPackageable>(public val value: P) : Enfoldable { override val foldFormat: FoldFormat get() = TODO("Not yet implemented") override fun foldSize(foldFormat: FoldFormat): Long { val size = value.foldSize(foldFormat) return when (foldFormat) { FoldFormat.BLOCK -> size FoldFormat.STREAM -> size + Enfoldable.OVERHEAD_LENGTH } } public fun enfoldToBlock(outData: Storable, offset: Int = 0): Long { value.enfold(outData, offset) return foldSize(FoldFormat.BLOCK) } public fun enfoldToStream(outStream: Writable): Long { val block = BlockType(foldSize(FoldFormat.BLOCK)) enfoldToBlock(block, 0) return block.enfoldToStreamByConvention(outStream, conventionType) } public companion object : Unfoldable<StructType<BlockPackageable>> { override val foldFormatSupport: List<FoldFormat> = listOf(FoldFormat.BLOCK, FoldFormat.STREAM) override val conventionType: Convention = Convention.STRUCT override val atomicSize: Int = 0 public fun unfoldFromBlock( inData: Retrievable, unpack: (Retrievable, Int) -> BlockPackageable ): StructType<BlockPackageable> = unfoldFromBlock(inData, 0, unpack) public fun unfoldFromBlock( inData: Retrievable, offset: Int, unpack: (Retrievable, Int) -> BlockPackageable ): StructType<BlockPackageable> = StructType(unpack(inData, offset)) public fun unfoldFromStream( inStream: Readable, unpack: (Retrievable, Int) -> BlockPackageable ): StructType<BlockPackageable> { val block = BlockType.unfoldFromStreamByConvention(inStream, conventionType) return StructType(unpack(block, 0)) } } }
0
Kotlin
0
0
f9142bec995ef434cc7cdc02f01a7ed9ac3cd00b
2,556
angelos-project-aux
MIT License
korge/common/src/test/kotlin/com/soywiz/korge/component/list/ViewListTest.kt
egorz-eng
107,608,023
true
{"Kotlin": 958944, "Java": 182756, "ActionScript": 7295, "HTML": 174}
package com.soywiz.korge.component.list import com.soywiz.korge.tests.ViewsForTesting import com.soywiz.korim.color.Colors import com.soywiz.korma.geom.Rectangle import org.junit.Test import kotlin.test.assertEquals class ViewListTest : ViewsForTesting() { @Test fun createList() { val item0 = views.solidRect(10, 10, Colors.RED).apply { setXY(0, 0) } val item1 = views.solidRect(10, 10, Colors.RED).apply { setXY(20, 0) } views.stage.addChild(item0) views.stage.addChild(item1) val itemList = ViewList(item0, item1, 3) assertEquals(3, itemList.length) assertEquals(Rectangle(40, 0, 10, 10), itemList[2]?.globalBounds) } }
0
Kotlin
0
0
cee8132dd63f168cdcc186c5510afd6985a53b3f
642
korge
Apache License 2.0
fingerprint/src/test/java/com/fingerprintjs/android/fingerprint/signal_providers/RawDataTest.kt
fingerprintjs
305,740,280
false
{"Kotlin": 422778}
package com.fingerprintjs.android.fingerprint.signal_providers import org.junit.Assert.assertEquals import org.junit.Test class RawDataTest { @Test fun `Filtering by version is working`() { val ver2List = prepareSignalsList().filterByVersion(2) assertEquals(5, ver2List.size) } @Test fun `Filtering by stability level is working`() { val stableSignalsList = prepareSignalsList().filterByStabilityLevel(StabilityLevel.STABLE) val optimalSignalsList = prepareSignalsList().filterByStabilityLevel(StabilityLevel.OPTIMAL) val uniqueSignalsList = prepareSignalsList().filterByStabilityLevel(StabilityLevel.UNIQUE) assertEquals(2, stableSignalsList.size) assertEquals(7, optimalSignalsList.size) assertEquals(8, uniqueSignalsList.size) } private fun prepareSignalsList(): List<IdentificationSignal<*>> = listOf( createSignal(1, null, StabilityLevel.OPTIMAL), createSignal(1, 2, StabilityLevel.OPTIMAL), createSignal(1, 2, StabilityLevel.OPTIMAL), createSignal(2, null, StabilityLevel.OPTIMAL), createSignal(1, null, StabilityLevel.STABLE), createSignal(2, null, StabilityLevel.STABLE), createSignal(3, null, StabilityLevel.OPTIMAL), createSignal(1, null, StabilityLevel.UNIQUE) ) private fun createSignal( addedInVersion: Int, removedInVersion: Int?, stabilityLevel: StabilityLevel ): IdentificationSignal<String> { return object : IdentificationSignal<String>( addedInVersion, removedInVersion, stabilityLevel, "", "", "" ) { override fun toString() = "" } } }
4
Kotlin
76
534
a33e213daa8534a2d2d1e85636f6aba635e75dc1
1,771
fingerprintjs-android
MIT License
app/src/main/kotlin/org/wentura/locoway/compose/home/TimePicker.kt
AdrianMiozga
796,770,944
false
{"Kotlin": 223580}
package org.wentura.locoway.compose.home import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.rememberTimePickerState import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.ui.res.stringResource import org.wentura.locoway.R import java.time.LocalTime @Composable @OptIn(ExperimentalMaterial3Api::class) fun TimePicker( showTimePicker: MutableState<Boolean>, departureTime: MutableState<LocalTime>, ) { val timePickerState = rememberTimePickerState( departureTime.value.hour, departureTime.value.minute, ) TimePickerDialog( onDismissRequest = { showTimePicker.value = false }, confirmButton = { TextButton( onClick = { showTimePicker.value = false departureTime.value = LocalTime.of(timePickerState.hour, timePickerState.minute) }, ) { Text(stringResource(R.string.ok)) } }, dismissButton = { TextButton( onClick = { showTimePicker.value = false }, ) { Text(stringResource(R.string.cancel)) } }, ) { androidx.compose.material3.TimePicker(state = timePickerState) } }
0
Kotlin
0
0
d3b1cf3aa51691aee765bb11c3b5051e087eaabd
1,454
Locoway-Android
MIT License
Tutorial1-1Basics/src/main/java/com/smarttoolfactory/tutorial1_1basics/chapter3_layout/Tutorial3_11Tooltip2.kt
SmartToolFactory
326,400,374
false
null
@file:OptIn(ExperimentalMaterial3Api::class) package com.smarttoolfactory.tutorial1_1basics.chapter3_layout import androidx.compose.animation.core.MutableTransitionState import androidx.compose.foundation.MutatePriority import androidx.compose.foundation.MutatorMutex import androidx.compose.material3.BasicTooltipState import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.TooltipState import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntRect import androidx.compose.ui.unit.IntSize import kotlinx.coroutines.CancellableContinuation import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withTimeout @Composable fun rememberTooltipState( alignment: Alignment = Alignment.TopCenter, offset: IntOffset = IntOffset.Zero, initialIsVisible: Boolean = false, isPersistent: Boolean = true, mutatorMutex: MutatorMutex = BasicTooltipDefaults.GlobalMutatorMutex ) { remember( isPersistent, mutatorMutex, ) { TooltipStateImpl( alignment = alignment, offset = offset, initialIsVisible = initialIsVisible, isPersistent = isPersistent, mutatorMutex = mutatorMutex ) } } @Stable private class TooltipStateImpl( val alignment: Alignment, offset: IntOffset, initialIsVisible: Boolean, override val isPersistent: Boolean, private val mutatorMutex: MutatorMutex ) : TooltipState { override val transition: MutableTransitionState<Boolean> = MutableTransitionState(initialIsVisible) override val isVisible: Boolean get() = transition.currentState || transition.targetState /** * continuation used to clean up */ private var job: (CancellableContinuation<Unit>)? = null var popupAlignment by mutableStateOf(alignment) internal set var offset by mutableStateOf(offset) var contentRect by mutableStateOf(IntRect.Zero) internal set var windowSize by mutableStateOf(IntSize.Zero) internal set var statusBarHeight: Float = 0f internal set /** * Show the tooltip associated with the current [BasicTooltipState]. * When this method is called, all of the other tooltips associated * with [mutatorMutex] will be dismissed. * * @param mutatePriority [MutatePriority] to be used with [mutatorMutex]. */ override suspend fun show( mutatePriority: MutatePriority ) { val cancellableShow: suspend () -> Unit = { suspendCancellableCoroutine { continuation -> transition.targetState = true job = continuation } } // Show associated tooltip for [TooltipDuration] amount of time // or until tooltip is explicitly dismissed depending on [isPersistent]. mutatorMutex.mutate(mutatePriority) { try { if (isPersistent) { cancellableShow() } else { withTimeout(BasicTooltipDefaults.TooltipDuration) { cancellableShow() } } } finally { // timeout or cancellation has occurred // and we close out the current tooltip. dismiss() } } } /** * Dismiss the tooltip associated with * this [TooltipState] if it's currently being shown. */ override fun dismiss() { transition.targetState = false } /** * Cleans up [mutatorMutex] when the tooltip associated * with this state leaves Composition. */ override fun onDispose() { job?.cancel() } } /** * BasicTooltip defaults that contain default values for tooltips created. */ internal object BasicTooltipDefaults { /** * The global/default [MutatorMutex] used to sync Tooltips. */ val GlobalMutatorMutex: MutatorMutex = MutatorMutex() /** * The default duration, in milliseconds, that non-persistent tooltips * will show on the screen before dismissing. */ const val TooltipDuration = 1500L }
4
null
312
3,006
efea98b63e63a85b80f7dc1bd4ca6d769e35905d
4,505
Jetpack-Compose-Tutorials
Apache License 2.0
app/src/main/java/org/wikipedia/feed/news/NewsActivity.kt
wikimedia
13,862,999
false
{"Kotlin": 3495497, "Python": 24797, "Java": 4408, "Jinja": 533, "Shell": 521}
package org.wikipedia.feed.news import android.content.Context import android.content.Intent import android.graphics.Color import android.os.Bundle import org.wikipedia.Constants import org.wikipedia.R import org.wikipedia.activity.SingleFragmentActivity import org.wikipedia.dataclient.WikiSite import org.wikipedia.extensions.parcelableExtra import org.wikipedia.feed.news.NewsFragment.Companion.newInstance import org.wikipedia.util.ResourceUtil class NewsActivity : SingleFragmentActivity<NewsFragment>() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) window.statusBarColor = Color.TRANSPARENT } public override fun createFragment(): NewsFragment { return newInstance(intent.parcelableExtra(EXTRA_NEWS_ITEM)!!, intent.parcelableExtra(Constants.ARG_WIKISITE)!!) } fun updateNavigationBarColor() { setNavigationBarColor(ResourceUtil.getThemedColor(this, R.attr.paper_color)) } companion object { const val EXTRA_NEWS_ITEM = "item" fun newIntent(context: Context, item: NewsItem, wiki: WikiSite): Intent { return Intent(context, NewsActivity::class.java) .putExtra(EXTRA_NEWS_ITEM, item) .putExtra(Constants.ARG_WIKISITE, wiki) } } }
29
Kotlin
624
2,365
175db9fe3c28084af7290a934f38223eb14934ed
1,329
apps-android-wikipedia
Apache License 2.0
src/main/kotlin/com/emberjs/hbs/linter/ember-template-lint/TemplateLintSessionData.kt
patricklx
412,986,421
false
{"Kotlin": 637238, "JavaScript": 31431, "HTML": 8237, "Handlebars": 2507, "Java": 207, "Scala": 172, "CSS": 144, "SCSS": 96}
import com.intellij.javascript.nodejs.interpreter.NodeJsInterpreter import com.intellij.openapi.vfs.VirtualFile class TemplateLintSessionData( val interpreter: NodeJsInterpreter, val templateLintPackage: TemplateLintPackage, val workingDir: VirtualFile, val fileToLint: VirtualFile, val fileToLintContent: String ) { }
54
Kotlin
5
9
a5dcace3902fb2ccc70ae310a4d427d7037b8857
359
intellij-emberjs-experimental
Apache License 2.0
android/apollo/src/main/java/io/muun/apollo/domain/action/debug/ForceCrashReportAction.kt
muun
150,655,434
false
null
package io.muun.apollo.domain.action.debug import com.google.firebase.crashlytics.FirebaseCrashlytics import io.muun.apollo.data.external.Globals import io.muun.apollo.domain.action.base.BaseAsyncAction1 import rx.Observable import timber.log.Timber import javax.inject.Inject import javax.inject.Singleton @Singleton class ForceCrashReportAction @Inject constructor(): BaseAsyncAction1<String, Void>() { class ForcedCrashlyticsCall(origin: String): RuntimeException("Forced logException $origin v${Globals.INSTANCE.versionCode}") class ForcedTimberErrorCall(origin: String): RuntimeException("Forced Timber.e $origin v${Globals.INSTANCE.versionCode}") class ForcedBackgroundException(origin: String): RuntimeException("Forced throw $origin v${Globals.INSTANCE.versionCode}") /** * Forcibly send a crash report to Crashlytics, for testing purposes. */ override fun action(origin: String): Observable<Void> = Observable.defer { Timber.e(ForcedTimberErrorCall(origin)) FirebaseCrashlytics.getInstance().recordException(ForcedCrashlyticsCall(origin)) throw ForcedBackgroundException(origin) Observable.just<Void>(null) } }
39
null
46
256
86048fe9f8059c9617f2e6d32e7d41c460dfb785
1,246
apollo
MIT License
example/android/app/src/main/kotlin/com/example/dynamic_list_item_example/MainActivity.kt
sems
397,617,097
false
{"Dart": 17618, "HTML": 3729, "Swift": 404, "Kotlin": 142, "Objective-C": 38}
package com.example.dynamic_list_item_example import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
2
c62e430d8088cb6b6142f9d63f9299bee8f93128
142
dynamic_list_item
Apache License 2.0
src/main/kotlin/com/lykke/matching/engine/config/spring/JsonConfig.kt
LykkeCity
52,304,364
false
null
package com.lykke.matching.engine.config.spring import com.google.gson.* import org.springframework.beans.factory.config.ConfigurableBeanFactory import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Scope import springfox.documentation.spring.web.json.Json import java.lang.reflect.Type import java.math.BigDecimal import java.text.ParseException import java.text.SimpleDateFormat import java.util.* @Configuration class JsonConfig { @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) fun gson(): Gson { return GsonBuilder() .registerTypeAdapter(Date::class.java, GmtDateTypeAdapter()) .registerTypeAdapter(BigDecimal::class.java, BigDecimalAdapter()) .registerTypeAdapter(Json::class.java, SpringfoxJsonToGsonAdapter()) .create() } } class BigDecimalAdapter : JsonSerializer<BigDecimal> { override fun serialize(src: BigDecimal, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { return JsonPrimitive(src.stripTrailingZeros()) } } class GmtDateTypeAdapter : JsonSerializer<Date>, JsonDeserializer<Date> { override fun serialize(date: Date, type: Type, jsonSerializationContext: JsonSerializationContext): JsonElement { val dateFormat = tl.get() val dateFormatAsString = dateFormat.format(date) return JsonPrimitive(dateFormatAsString) } override fun deserialize(jsonElement: JsonElement, type: Type, jsonDeserializationContext: JsonDeserializationContext): Date { try { val dateFormat = tl.get() return dateFormat.parse(jsonElement.asString) } catch (e: ParseException) { throw JsonSyntaxException(jsonElement.asString, e) } } private val tl = object : ThreadLocal<SimpleDateFormat>() { override fun initialValue(): SimpleDateFormat { val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US) sdf.timeZone = TimeZone.getTimeZone("UTC") return sdf } } } class SpringfoxJsonToGsonAdapter : JsonSerializer<Json> { override fun serialize(json: Json, type: Type, context: JsonSerializationContext): JsonElement = JsonParser.parseString(json.value()) }
5
Kotlin
16
31
937b360b10d461e444ebc7133dd9ab6b64ae4cb5
2,422
MatchingEngine
MIT License
PopSeries/app/src/main/java/alifyz/com/popseries/database/entity/TrendingEntity.kt
Alifyz
93,462,362
false
null
package alifyz.com.popseries.database.entity import android.arch.persistence.room.Entity import android.arch.persistence.room.PrimaryKey import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName @Entity(tableName = "trending") data class TrendingEntity( @PrimaryKey var id: Int? = null, @SerializedName("original_name") @Expose var originalName: String? = null, @SerializedName("name") @Expose var name: String? = null, @SerializedName("popularity") @Expose var popularity: Double? = null, @SerializedName("vote_count") @Expose var voteCount: Int? = null, @SerializedName("vote_average") @Expose var voteAverage: Double? = null, @SerializedName("first_air_date") @Expose var firstAirDate: String? = null, @SerializedName("poster_path") @Expose var posterPath: String? = null, @SerializedName("genre_ids") @Expose var genreIds: List<Int>? = null, @SerializedName("original_language") @Expose var originalLanguage: String? = null, @SerializedName("backdrop_path") @Expose var backdropPath: String? = null, @SerializedName("overview") @Expose var overview: String? = null, @SerializedName("origin_country") @Expose var originCountry: List<String>? = null )
0
Java
6
16
5d881c7a5c99421d1163646706789edcdd6307d3
1,493
android-sample-apps
The Unlicense
src/main/kotlin/ch/unibas/dmi/dbis/cottontail/model/values/FloatVectorValue.kt
schoenja
215,837,340
true
{"Kotlin": 724765}
package ch.unibas.dmi.dbis.cottontail.model.values /** * This is an abstraction over a [FloatArray] and it represents a vector of [Float]s. * * @author Ralph Gasser * @version 1.1 */ inline class FloatVectorValue(override val value: FloatArray) : VectorValue<FloatArray> { constructor(input: List<Number>) : this(FloatArray(input.size) { input[it].toFloat() }) constructor(input: Array<Number>) : this(FloatArray(input.size) { input[it].toFloat() }) override val size: Int get() = this.value.size override val numeric: Boolean get() = false override fun compareTo(other: Value<*>): Int { throw IllegalArgumentException("FloatVectorValues can can only be compared for equality.") } /** * Returns the indices of this [FloatVectorValue]. * * @return The indices of this [FloatVectorValue] */ override val indices: IntRange get() = this.value.indices /** * Returns the i-th entry of this [FloatVectorValue]. * * @param i Index of the entry. * @return The value at index i. */ override fun get(i: Int): Number = this.value[i] /** * Returns the i-th entry of this [FloatVectorValue] as [Float]. * * @param i Index of the entry. * @return The value at index i. */ override fun getAsFloat(i: Int) = this.value[i] /** * Returns the i-th entry of this [FloatVectorValue] as [Boolean]. * * @param i Index of the entry. * @return The value at index i. */ override fun getAsBool(i: Int) = this.value[i] == 0.0f /** * Returns true, if this [FloatVectorValue] consists of all zeroes, i.e. [0, 0, ... 0] * * @return True, if this [FloatVectorValue] consists of all zeroes */ override fun allZeros(): Boolean = this.value.all { it == 0.0f } /** * Returns true, if this [FloatVectorValue] consists of all ones, i.e. [1, 1, ... 1] * * @return True, if this [FloatVectorValue] consists of all ones */ override fun allOnes(): Boolean = this.value.all { it == 1.0f } /** * Creates and returns a copy of this [FloatVectorValue]. * * @return Exact copy of this [FloatVectorValue]. */ override fun copy(): FloatVectorValue = FloatVectorValue(this.value.copyOf(this.size)) override operator fun plus(other: VectorValue<FloatArray>): VectorValue<FloatArray> { require(this.size == other.size) { "Only vector values of the same type and size can be added." } val out = FloatVectorValue(this.value.copyOf(this.size)) this.indices.forEach { out.value[it] += other.value[it] } return out } override operator fun minus(other: VectorValue<FloatArray>): VectorValue<FloatArray> { require(this.size == other.size) { "Only vector values of the same type and size can be added." } val out = FloatVectorValue(this.value.copyOf(this.size)) this.indices.forEach { out.value[it] -= other.value[it] } return out } override operator fun times(other: VectorValue<FloatArray>): VectorValue<FloatArray> { require(this.size == other.size) { "Only vector values of the same type and size can be added." } val out = FloatVectorValue(this.value.copyOf(this.size)) this.indices.forEach { out.value[it] *= other.value[it] } return out } override operator fun div(other: VectorValue<FloatArray>): VectorValue<FloatArray> { require(this.size == other.size) { "Only vector values of the same type and size can be added." } val out = FloatVectorValue(this.value.copyOf(this.size)) this.indices.forEach { out.value[it] /= other.value[it] } return out } override operator fun plus(other: Number): VectorValue<FloatArray> { val value = other.toFloat() val out = FloatVectorValue(this.value.copyOf(this.size)) this.indices.forEach { out.value[it] += value } return out } override operator fun minus(other: Number): VectorValue<FloatArray> { val value = other.toFloat() val out = FloatVectorValue(this.value.copyOf(this.size)) this.indices.forEach { out.value[it] -= value } return out } override operator fun times(other: Number): VectorValue<FloatArray> { val value = other.toFloat() val out = FloatVectorValue(this.value.copyOf(this.size)) this.indices.forEach { out.value[it] *= value } return out } override operator fun div(other: Number): VectorValue<FloatArray> { val value = other.toFloat() val out = FloatVectorValue(this.value.copyOf(this.size)) this.indices.forEach { out.value[it] /= value } return out } }
0
Kotlin
0
0
cf4d45fddec91b4167eafc1317acfc4f3df557d4
4,773
cottontaildb
MIT License
android/app/src/main/java/com/example/togglutopia/utils/DateExtensions.kt
simonrozsival
226,355,253
false
null
package com.example.togglutopia.utils import android.os.Handler import com.example.togglutopia.ui.TogglState import java.text.ParseException import java.text.SimpleDateFormat import java.util.* class DateExtensions { } /** * Created by semanticer on 2. 5. 2016. */ fun Calendar.getISO8601(): String { return ISO8601.fromCalendar(this) } object ISO8601 { /** Transform Calendar to ISO 8601 string. */ fun fromCalendar(calendar: Calendar): String { val date: Date = calendar.time val formatted: String = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") .format(date) return formatted.substring(0, 22) + ":" + formatted.substring(22) } /** Get current date and time formatted as ISO 8601 string. */ fun now(): String { return fromCalendar(GregorianCalendar.getInstance()) } /** Transform ISO 8601 string to Calendar. */ @Throws(ParseException::class) fun toCalendar(iso8601string: String?): Calendar { var iso8601string = iso8601string if (iso8601string == null || iso8601string == "") { iso8601string = "1977-10-21T17:43:56+02:00" // give it invalid but nonnull value } val calendar: Calendar = GregorianCalendar.getInstance() var s = iso8601string.replace("Z", "+00:00") s = try { s.substring(0, 22) + s.substring(23) // to get rid of the ":" } catch (e: IndexOutOfBoundsException) { throw ParseException("Invalid length", 0) } val date: Date = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(s) calendar.time = date return calendar } @Throws(ParseException::class) fun shiftISO(isoFrom: String?, timeShiftInMillis: Long): String { val calendar: Calendar = toCalendar(isoFrom) val newMillis: Long = calendar.timeInMillis + timeShiftInMillis calendar.timeInMillis = newMillis return fromCalendar(calendar) } } fun startTimer() { val handler = Handler() val timer = Timer(false) val timerTask: TimerTask = object : TimerTask() { override fun run() { handler.post { TogglState.currentTime = Date().time } } } timer.schedule(timerTask, 1000, 1000) // 1000 = 1 second. }
0
Rust
0
1
23a7ee33ae4d4237c97fe8c84470608676f1e222
2,308
toggl-utopia
MIT License
core/src/com/ore/infinium/components/AirComponent.kt
HanWenfang
60,321,795
true
{"Kotlin": 457818}
/** MIT License Copyright (c) 2016 <NAME> <<EMAIL>> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.ore.infinium.components import com.artemis.Component class AirComponent : Component() { //air amount that is decreased per each interval var decreaseRate = 10 var decreaseInterval = 500 var maxAir = 25000 //current air level var air = maxAir //amount to decrease health per interval, when run without air var healthDecreaseRate = 10 /** * copy a component (similar to copy constructor) * @param airComponent * * component to copy from, into this instance */ fun copyFrom(airComponent: AirComponent) { decreaseRate = airComponent.decreaseRate decreaseInterval = airComponent.decreaseInterval maxAir = airComponent.maxAir air = airComponent.air healthDecreaseRate = airComponent.healthDecreaseRate } override fun toString(): String { val c = javaClass.simpleName return """ $c.air: $air $c.maxAir: $air $c.decreaseRate: $decreaseRate $c.healthDecreaseRate: $healthDecreaseRate""" } }
0
Kotlin
0
0
dc58799cc17ee43263d43d92de40f67c6fd49d50
2,150
ore-infinium
MIT License
core/src/main/java/org/mhacks/app/core/di/AppModule.kt
mhacks
22,456,318
false
null
package org.mhacks.app.core.di import android.app.Application import android.content.Context import android.content.SharedPreferences import androidx.preference.PreferenceManager import dagger.Module import dagger.Provides import org.mhacks.app.core.ThemePrefProvider import javax.inject.Singleton @Module class AppModule { @Provides @Singleton fun provideContext(application: Application): Context = application @Provides @Singleton fun provideSharedPreferences(context: Context) = PreferenceManager.getDefaultSharedPreferences(context)!! @Provides @Singleton fun provideThemePrefProvider(sharedPreferences: SharedPreferences) = ThemePrefProvider(sharedPreferences) }
1
Kotlin
12
21
12309b463e51acc3f41c463df647f410e16a6261
735
mhacks-android
MIT License
node/src/test/kotlin/net/corda/node/services/network/NetworkMapCacheTest.kt
sighttviewliu
103,155,577
true
{"Kotlin": 3678128, "Java": 185815, "Groovy": 28681, "Shell": 320, "Batchfile": 106}
package net.corda.node.services.network import net.corda.core.node.services.NetworkMapCache import net.corda.core.node.services.ServiceInfo import net.corda.core.utilities.getOrThrow import net.corda.testing.ALICE import net.corda.testing.BOB import net.corda.testing.node.MockNetwork import org.assertj.core.api.Assertions.assertThat import org.junit.After import org.junit.Before import org.junit.Test import java.math.BigInteger import kotlin.test.assertEquals class NetworkMapCacheTest { lateinit var mockNet: MockNetwork @Before fun setUp() { mockNet = MockNetwork() } @After fun teardown() { mockNet.stopNodes() } @Test fun registerWithNetwork() { val nodes = mockNet.createSomeNodes(1) val n0 = nodes.mapNode val n1 = nodes.partyNodes[0] val future = n1.services.networkMapCache.addMapService(n1.network, n0.network.myAddress, false, null) mockNet.runNetwork() future.getOrThrow() } @Test fun `key collision`() { val entropy = BigInteger.valueOf(24012017L) val nodeA = mockNet.createNode(nodeFactory = MockNetwork.DefaultFactory, legalName = ALICE.name, entropyRoot = entropy, advertisedServices = ServiceInfo(NetworkMapService.type)) val nodeB = mockNet.createNode(nodeFactory = MockNetwork.DefaultFactory, legalName = BOB.name, entropyRoot = entropy, advertisedServices = ServiceInfo(NetworkMapService.type)) assertEquals(nodeA.info.legalIdentity, nodeB.info.legalIdentity) mockNet.runNetwork() // Node A currently knows only about itself, so this returns node A assertEquals(nodeA.services.networkMapCache.getNodeByLegalIdentityKey(nodeA.info.legalIdentity.owningKey), nodeA.info) nodeA.services.networkMapCache.addNode(nodeB.info) // The details of node B write over those for node A assertEquals(nodeA.services.networkMapCache.getNodeByLegalIdentityKey(nodeA.info.legalIdentity.owningKey), nodeB.info) } @Test fun `getNodeByLegalIdentity`() { val nodes = mockNet.createSomeNodes(1) val n0 = nodes.mapNode val n1 = nodes.partyNodes[0] val node0Cache: NetworkMapCache = n0.services.networkMapCache val expected = n1.info mockNet.runNetwork() val actual = node0Cache.getNodeByLegalIdentity(n1.info.legalIdentity) assertEquals(expected, actual) // TODO: Should have a test case with anonymous lookup } @Test fun `remove node from cache`() { val nodes = mockNet.createSomeNodes(1) val n0 = nodes.mapNode val n1 = nodes.partyNodes[0] val node0Cache = n0.services.networkMapCache as PersistentNetworkMapCache mockNet.runNetwork() n0.database.transaction { assertThat(node0Cache.getNodeByLegalIdentity(n1.info.legalIdentity) != null) node0Cache.removeNode(n1.info) assertThat(node0Cache.getNodeByLegalIdentity(n1.info.legalIdentity) == null) assertThat(node0Cache.getNodeByLegalIdentity(n0.info.legalIdentity) != null) assertThat(node0Cache.getNodeByLegalName(n1.info.legalIdentity.name) == null) } } }
1
Kotlin
1
1
bc6628a072746dad823a605d14ae3888bae16fab
3,228
corda
Apache License 2.0
TestAndroid/TestUnitarios/app/src/test/java/ec/com/paul/testunitarios/calculadora/CalculadoraTest.kt
PaulMarcelo
255,495,694
false
null
package ec.com.paul.testunitarios.calculadora import org.junit.After import org.junit.Test import org.junit.Assert.* import org.junit.Before import org.junit.Ignore import java.lang.ArithmeticException /** * Created by <NAME> on 20/8/2019. * <NAME> */ class CalculadoraTest { var calculadoraNull: Calculadora? = null var calculadora: Calculadora? = null @Before fun setUp() { calculadora = Calculadora() println("start setUp") } @Test fun calculadoraNotNullTest() { assertNotNull("Calculadora debe ser null", calculadora) println("start calculadoraNotNullTest") } @Test fun calculadoraNullTest() { //assertNotNull("Calculadora debe ser null", calculadora) assertNull("Calculadora debe ser null", calculadoraNull) println("start calculadoraNullTest") } @After fun tearDown() { calculadora = null println("start tearDown") } @Test fun sumarTestExplicado() { val calculadoraPrueba = Calculadora() val resultadoEsperado = 30 var resultadoActual = 0 resultadoActual = calculadoraPrueba.sumar(10, 20) assertEquals(resultadoEsperado, resultadoActual) assertEquals(30, calculadoraPrueba.sumar(10, 20)) println("start sumarTestExplicado") } @Test fun ejemploAssert() { } /* Método a Probar | Entrada | Salida Experarada sumar(int a, int b) |a = 10, b=20 |30 sumar(int a, int b) |a = 7, b=4 |11 restar(int a, int b) |a = 7, b=4 |3 restar(int a, int b) |a = 10, b=20 |-10 */ @Test @Throws fun sumar() { val a = 10 val b = 20 val resultadoEsperado = 30 val resultado: Int resultado = calculadora!!.sumar(a, b) assertEquals(resultadoEsperado, resultado) println("start sumar") } @Test fun sumar_ValidInput_ValidExpected_Test() { assertEquals(11, calculadora!!.sumar(7, 4)) println("start sumar_ValidInput_ValidExpected_Test") } @Test fun restar_ValidInput_ValidExpedted_Test() { assertEquals(3, calculadora!!.restar(7, 4)) println("start restar_ValidInput_ValidExpedted_Test") } @Test fun restar_ValidInput_ValidNegativeExpedted_Test() { assertEquals(-10, calculadora!!.restar(10, 20)) println("start restar_ValidInput_ValidNegativeExpedted_Test") } @Test fun dividir_ValidInput_ValidExpedted_Test() { assertEquals(2, calculadora!!.dividir(4, 2)) println("start dividir_ValidInput_ValidExpedted_Test") } @Test fun dividir_NotValidInput_Test() { calculadora!!.dividir(4, 0) println("start dividir_NotValidInput_Test") fail("Fallo detectado Manualmente - No se puede dividir por Cero") } @Test(expected = ArithmeticException::class) fun dividirPorCero_Novalidinput_ExpectedExceptionTest() { calculadora!!.dividirPorCero(5, 0) println("start dividirPorCero_Novalidinput_ExpectedExceptionTest") } @Test(timeout = 600) fun operacionLargaDuracion_TimeOut_Test() { calculadora!!.operacionLargaDuracion() } @Ignore("Metodo no listo. Ignorar por ahora. Esperando solucionar la división por cero") @Test fun dividir_NotValidInput_Ignore_Test(){ assertEquals(2, calculadora!!.dividir(5,0)); println("Se ha ejecutado el test operacionLargaDuracion_TimeOut_Test()") } }
0
Kotlin
0
0
5c363e7e5837eaec8c43c1edf6eafa69ab84725d
3,603
Android
Apache License 2.0
app/src/main/java/co/youverify/youhr/core/util/util.kt
sojious
674,516,085
false
null
package co.youverify.youhr.core.util import TaskProgressColor import android.icu.text.SimpleDateFormat import android.icu.util.Calendar import android.icu.util.TimeZone import android.text.format.DateUtils import androidx.compose.ui.graphics.Color import co.youverify.youhr.domain.model.Task import co.youverify.youhr.presentation.ui.task.TaskStatus import com.google.gson.JsonSyntaxException import org.json.JSONObject import retrofit2.HttpException import retrofit2.Response import java.io.IOException import java.text.ParseException import java.util.Locale val timeZone: TimeZone =TimeZone.getTimeZone("Africa/Lagos") private const val SECOND = 1 private const val MINUTE = 60 * SECOND private const val HOUR = 60 * MINUTE private const val DAY = 24 * HOUR private const val MONTH = 30 * DAY private const val YEAR = 12 * MONTH fun getLeavePeriod(startDate:String,endDate:String): String { val split1=startDate.split(' ') val startMonth=split1[1] val startYear=split1[3] val formattedStartDay= getFormattedDay(split1[2]) val split2=endDate.split(' ') val endMonth=split2[1] val endYear=split2[3] val formattedEndDay= getFormattedDay(split2[2]) return if (startYear==endYear) "$formattedStartDay $startMonth - $formattedEndDay $endMonth $startYear" else "$formattedStartDay $startMonth $startYear - $formattedEndDay $endMonth $endYear" } fun String.toDobFormat(): String { if (this.isEmpty()) return "N/A" val split1=this.split(' ') val month = split1[1] val year = split1[3] val day = split1[2] val numericMonth=when(month){ "Jan"-> "01" "Feb"-> "02" "Mar"-> "03" "Apr"-> "04" "May"-> "05" "Jun"-> "06" "Jul"-> "07" "Aug"-> "08" "Sep"-> "09" "Oct"-> "10" "Nov"-> "11" else -> "12" } return "$day/$numericMonth/$year" } fun getFormattedLeaveDate(dateString:String): String { val split=dateString.split(' ') return "${split[0]} ${split[1]} ${split[2]} ${split[3]}" } fun getGreetingMessage():String{ return when (Calendar.getInstance(TimeZone.getDefault()).get(Calendar.HOUR_OF_DAY)) { in 0..11 -> "Good Morning" in 12..15 -> "Good Afternoon" in 16..20 -> "Good Evening" in 21..23 -> "Good Night" else -> "Hello" } } fun String.toTimeAgo(isApprovalDate: Boolean=false): String { val time=this.toEpochMillis(isApprovalDate) val now = System.currentTimeMillis() val diff: Long = now - time return if (diff < DateUtils.WEEK_IN_MILLIS) { if (diff <= 1000) "just now" else DateUtils.getRelativeTimeSpanString( time, now, DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE ).toString() } else if (diff <= 4 * DateUtils.WEEK_IN_MILLIS) { val week = (diff / DateUtils.WEEK_IN_MILLIS).toInt() if (week > 1) "$week weeks ago" else "$week week ago" } else if (diff < DateUtils.YEAR_IN_MILLIS) { val month = (diff / (4 * DateUtils.WEEK_IN_MILLIS)).toInt() if (month > 1) "$month months ago" else "$month month ago" } else { val year = (diff / DateUtils.YEAR_IN_MILLIS).toInt() if (year > 1) "$year years ago" else "$year year ago" } } fun Task.getStatus(): TaskStatus { return when(status){ TaskStatus.COMPLETED.id -> TaskStatus.COMPLETED TaskStatus.IN_PROGRESS.id-> TaskStatus.IN_PROGRESS TaskStatus.OVER_DUE.id-> TaskStatus.OVER_DUE TaskStatus.TO_DO.id -> TaskStatus.TO_DO else ->TaskStatus.REVIEW } } fun TaskStatus.getColor(): Color { return when (this) { TaskStatus.COMPLETED -> TaskProgressColor.COMPLETED.value TaskStatus.IN_PROGRESS -> TaskProgressColor.IN_PROGRESS.value TaskStatus.OVER_DUE -> TaskProgressColor.OVERDUE.value TaskStatus.TO_DO -> TaskProgressColor.TO_DO.value else -> TaskProgressColor.REVIEW.value } } fun String.toCardinalDateFormat(): String { val split=split('-') val month=when(split[1]){ "01" -> "Jan" "02" -> "Feb" "03" -> "Mar" "04" -> "Apr" "05" -> "May" "06" -> "Jun" "07" -> "Jul" "08" -> "Aug" "09" -> "Sep" "10" -> "Oct" "11" -> "Nov" else -> "Dec" } return "$month ${split[2]},${split[0]}" } fun String.toCardinalDateFormat2(): String { val split1=split(' ') val split2=split1[0].split('-') val month=when(split2[1]){ "01" -> "Jan" "02" -> "Feb" "03" -> "Mar" "04" -> "Apr" "05" -> "May" "06" -> "Jun" "07" -> "Jul" "08" -> "Aug" "09" -> "Sep" "10" -> "Oct" "11" -> "Nov" else -> "Dec" } val formattedDay= getFormattedDay(split2[2]) return "$formattedDay $month ${split2[0]}" } fun getFormattedDay(dayString:String): String { return when(dayString){ "04", "05", "06", "07", "08", "09" -> "${dayString.last()}th" "01"->"${dayString.last()}st" "21"->"${dayString}st" "31"->"${dayString}st" "02"->"${dayString.last()}nd" "22"->"${dayString}nd" "03"->"${dayString.last()}rd" "23"->"${dayString}rd" else -> "${dayString}th" } } fun Long.toCardinalDateString():String{ val calendar = Calendar.getInstance(TimeZone.getDefault()); calendar.timeInMillis = this calendar.timeZone = timeZone val month = calendar.get(Calendar.MONTH) + 1; // Note: Month value in Calendar API is 0-based val year = calendar.get(Calendar.YEAR); val formattedDay=when(val day=calendar.get(Calendar.DAY_OF_MONTH)){ 1,21 -> "${day}st" 2,22 -> "${day}nd" 3,23->"${day}rd" else -> "${day}th" } val formattedMonth = getFormattedMonth(month,capitalize=true) return "$formattedMonth $formattedDay,$year" } fun Long.toOrdinalDateString(includeOf:Boolean=true):String{ val calendar = Calendar.getInstance(TimeZone.getDefault()) calendar.timeInMillis = this val month= calendar.get(Calendar.MONTH) + 1 // Note: Month value in Calendar API is 0-based val year= calendar.get(Calendar.YEAR) val formattedDay=when(val day=calendar.get(Calendar.DAY_OF_MONTH)){ 1,21 -> "${day}st" 2,22 -> "${day}nd" 3,23->"${day}rd" else -> "${day}th" } val formattedMonth = getFormattedMonth(month, true) return if (includeOf) "$formattedDay of $formattedMonth,$year" else "$formattedDay $formattedMonth,$year" } private fun getFormattedMonth(month: Int, capitalize: Boolean=false):String{ val monthString=when (month) { 1 -> "Jan" 2 -> "feb" 3 -> "Mar" 4 -> "Apr" 5 -> "May" 6 -> "Jun" 7 -> "Jul" 8 -> "Aug" 9 -> "Sep" 10 -> "Oct" 11 -> "Nov" else -> "Dec" } return if (capitalize) monthString.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.ROOT) else it.toString() } else monthString } fun getDateRange(startDateMillis:Long, endDateMillis:Long):String{ val calendar1 = Calendar.getInstance(timeZone) calendar1.timeInMillis = startDateMillis val calendar2: Calendar = Calendar.getInstance(timeZone) calendar2.timeInMillis = endDateMillis val startYear = calendar1[Calendar.YEAR] val endYear = calendar2[Calendar.YEAR] val startMonth = calendar1[Calendar.MONTH] + 1 // Note: Month value in Calendar API is 0-based val endMonth = calendar2[Calendar.MONTH] + 1 val startDay = calendar1[Calendar.DAY_OF_MONTH] val endDay = calendar2[Calendar.DAY_OF_MONTH] return if (startYear==endYear) "${getFormattedMonth(startMonth, true)} $startDay - ${getFormattedMonth(endMonth, true)} $endDay,$startYear" else "${getFormattedMonth(startMonth, true)} $startDay,$startYear - ${getFormattedMonth( endMonth, true )} $endDay,$endYear" } fun String.toEpochMillis(isApprovalDate: Boolean=false): Long { val formatter = if (isApprovalDate) SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",Locale.getDefault()) else SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",Locale.getDefault()) formatter.timeZone = TimeZone.getTimeZone("GMT") val time:Long try { time = formatter.parse(this).time } catch (e: ParseException) { e.printStackTrace() return 0; // or handle the parse exception accordingly } //val calendar = Calendar.getInstance() // calendar.timeZone= timeZone //calendar.time = date; //val epochMillis = calendar.timeInMillis; return time } fun String.capitalizeWords():String = split(" ").joinToString(" "){ word -> word.replaceFirstChar {character-> character.uppercase() } } fun Long.toFormattedDateString(pattern: String): String { val calendar = Calendar.getInstance(TimeZone.getDefault()); calendar.timeInMillis = this val formatter = SimpleDateFormat(pattern, Locale.ENGLISH) formatter.timeZone = timeZone return formatter.format(calendar.time) } fun Long.toHrFormattedDateString(): String { val calendar = Calendar.getInstance(TimeZone.getDefault()); calendar.timeInMillis = this val formattedDay= when(calendar[Calendar.DAY_OF_WEEK]){ 1->"Sun" 2->"Mon" 3->"Tue" 4->"Wed" 5->"Thu" 6->"Fri" else->"Sat" } val month= getFormattedMonth(calendar[Calendar.MONTH]+1) val dayOfMonth=calendar[Calendar.DAY_OF_MONTH] val year=calendar[Calendar.YEAR] return "$formattedDay $month $dayOfMonth $year" } suspend fun<T:Any> handleApi(callApi: suspend () -> Response<T>): Result<T> { return try{ val response=callApi() val body=response.body() //for a response with a body if (response.isSuccessful && body!=null) Result.Success(data = body) else //for a response with error message { var errorMessage = "" try { val jsOnErrorObject= JSONObject(response.errorBody()?.string()!!) errorMessage=jsOnErrorObject.getString("message") }catch (e:Exception){ e.printStackTrace() } Result.Error(code=response.code(), message = errorMessage) } //for exceptions }catch (exception:HttpException){ Result.Exception(e=exception, genericMessage = "Oops..Something went wrong") }catch (exception: IOException){ Result.Exception(e=exception, genericMessage = "Could not reach Server, Check your Internet Connection") }catch (exception:Throwable){ Result.Exception(e=exception, genericMessage = "Oops..An error occurred from the server") } catch (exception:JsonSyntaxException){ //Result.Exception(e=exception, genericMessage = "Oops..An error occurred from the server") throw exception } } //Extension function that encapsulates pagination logic
0
Kotlin
0
0
d9e79375a51cdac0d5364d84bbb8e5a5160eef65
11,196
YouHr
MIT License
lib/lib-network/src/main/kotlin/com/ihardanilchanka/sampleapp2/DelayRandomizer.kt
igordanilcenko
479,943,101
false
null
package com.ihardanilchanka.sampleapp2 import kotlinx.coroutines.delay /** * Makes an artificial delay while suspend function run. Sometimes simulates an error. */ suspend fun randomDelay() { val delaySeconds = (1..4).random() delay(delaySeconds * 1000L) if (delaySeconds == 4) { error("Some artificial error occurred!") } }
0
Kotlin
0
0
72b01119cbb38adc9e6fff204e8c81e3ff0fa278
352
popular-movie-list2
Apache License 2.0
plugin/src/main/kotlin/io/github/clayclaw/opensky/config/ConfigCache.kt
clayclaw
774,537,319
false
{"Kotlin": 34228}
package io.github.clayclaw.opensky.config data class ConfigCache( var endpoint: String = "localhost:6379", var username: String? = null, var password: String? = null, )
0
Kotlin
1
1
cabb2f27ea322f4b7c827e5aa114738eec907ba6
182
OpenSky
MIT License
app/src/main/java/com/kyberswap/android/domain/model/NotificationAlert.kt
KYRDTeam
181,612,742
false
null
package com.kyberswap.android.domain.model import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class NotificationAlert( @SerializedName("type") val type: String = "", @SerializedName("alert_id") val alertId: Long = 0L, @SerializedName("test_alert_id") val testAlertId: String = "", @SerializedName("base") val base: String = "", @SerializedName("token") val token: String = "", @SerializedName("notification_id") val notificationId: Long = 0 ) : Parcelable { constructor(notificationExt: NotificationExt) : this( base = notificationExt.base, token = if (notificationExt.base.isEmpty()) Token.ETH_SYMBOL else notificationExt.token, alertId = notificationExt.alertId ) val pair: String get() = StringBuilder() .append(token) .append("/") .append(base).toString() companion object { const val ALERT_PRICE = "alert_price" } }
1
null
10
26
abd4ab033d188918849e5224cc8204409776391b
1,054
android-app
MIT License
src/main/kotlin/com/kokasai/api/http/_dsl/inGroupFromParameter.kt
astralbrim
332,749,834
true
{"Kotlin": 69658}
package com.kokasai.api.http._dsl import com.kokasai.api.user.User import io.ktor.application.ApplicationCall import io.ktor.util.pipeline.PipelineContext suspend inline fun PipelineContext<Unit, ApplicationCall>.inGroupFromParameter( groupNameParameter: String, onSuccess: ( user: User, groupName: String ) -> Unit ) { parameter(groupNameParameter) { groupName -> inGroup(groupName) { user -> onSuccess(user, groupName) } } }
0
Kotlin
0
1
012fdf1c1b209e3d4ce9df8c021fe9d9454538fe
493
api.kokasai.com
Apache License 2.0
ui/src/commonMain/kotlin/com/popalay/barnee/ui/ComposeApp.kt
Popalay
349,051,151
false
null
/* * Copyright (c) 2023 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.popalay.barnee import android.content.res.Configuration import android.widget.Toast import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.MaterialTheme import androidx.compose.material.SnackbarHost import androidx.compose.material.SnackbarHostState import androidx.compose.material.SnackbarResult import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import cafe.adriel.voyager.core.annotation.ExperimentalVoyagerApi import cafe.adriel.voyager.navigator.LocalNavigatorSaver import cafe.adriel.voyager.navigator.Navigator import cafe.adriel.voyager.navigator.bottomSheet.BottomSheetNavigator import cafe.adriel.voyager.navigator.parcelableNavigatorSaver import com.google.accompanist.insets.ProvideWindowInsets import com.google.accompanist.insets.navigationBarsPadding import com.popalay.barnee.data.message.Message import com.popalay.barnee.data.message.MessagesProvider import com.popalay.barnee.domain.navigation.Router import com.popalay.barnee.domain.navigation.StackChange import com.popalay.barnee.navigation.HandleIntent import com.popalay.barnee.navigation.SlideTransition import com.popalay.barnee.ui.common.PrimarySnackbar import com.popalay.barnee.ui.navigation.NavigationHost import com.popalay.barnee.ui.screen.discovery.DiscoveryScreen import com.popalay.barnee.ui.screen.shaketodrink.ShakeToDrinkScreen import com.popalay.barnee.ui.theme.BarneeTheme import com.popalay.barnee.ui.util.LifecycleAwareLaunchedEffect import com.seiko.imageloader.ImageLoader import com.seiko.imageloader.LocalImageLoader import kotlinx.coroutines.cancelChildren import kotlinx.coroutines.launch import org.koin.compose.koinInject @OptIn(ExperimentalMaterialApi::class, ExperimentalVoyagerApi::class, ExperimentalAnimationApi::class) @Composable internal fun ComposeApp() { ProvideWindowInsets(windowInsetsAnimationsEnabled = true) { val imageLoader = koinInject<ImageLoader>() CompositionLocalProvider(LocalImageLoader provides imageLoader) { Box(modifier = Modifier.fillMaxSize()) { val snackbarHostState = remember { SnackbarHostState() } BottomSheetNavigator( sheetElevation = 1.dp, sheetBackgroundColor = MaterialTheme.colors.background, sheetContentColor = MaterialTheme.colors.onBackground, scrimColor = MaterialTheme.colors.background.copy(alpha = 0.7F), ) { bottomSheetNavigator -> CompositionLocalProvider(LocalNavigatorSaver provides parcelableNavigatorSaver()) { Navigator(DiscoveryScreen()) { navigator -> MessagesHost(snackbarHostState) HandleIntent() NavigationHost(navigator, bottomSheetNavigator) SlideTransition(navigator) ShakeToDrinkScreen().Content() } } } SnackbarHost( hostState = snackbarHostState, snackbar = { PrimarySnackbar(it) }, modifier = Modifier .align(Alignment.BottomCenter) .navigationBarsPadding() ) } } } } @Composable private fun MessagesHost(snackbarHostState: SnackbarHostState) { val context = LocalContext.current val messagesFlow = koinInject<MessagesProvider>().messageFlow val snackbarScope = rememberCoroutineScope() val router = koinInject<Router>() LifecycleAwareLaunchedEffect(messagesFlow) { message -> when (message) { is Message.SnackBar -> { snackbarScope.coroutineContext.cancelChildren() snackbarScope.launch { snackbarHostState.showSnackbar(message.content, actionLabel = message.action?.text).let { result -> if (result == SnackbarResult.ActionPerformed) { message.action?.destination?.let { router.updateStack(StackChange.Push(it)) } } } } } is Message.Toast -> { val duration = when (message.duration) { Message.Toast.Duration.Short -> Toast.LENGTH_SHORT Message.Toast.Duration.Long -> Toast.LENGTH_LONG } Toast.makeText(context, message.content, duration).show() } } } } @Preview("Light Theme", widthDp = 360, heightDp = 640) @Preview("Dark Theme", widthDp = 360, heightDp = 640, uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable fun ComposeAppPreview() { BarneeTheme { ComposeApp() } }
21
Kotlin
3
15
0d25ca9033065ff4c9b6f044550f7c02f96f97bd
6,449
Barnee
MIT License
app/src/test/java/com/canopas/yourspace/ui/flow/onboard/OnboardViewModelTest.kt
canopas
739,382,039
false
null
package com.canopas.yourspace.ui.flow.onboard import com.canopas.yourspace.MainCoroutineRule import com.canopas.yourspace.data.models.space.ApiSpace import com.canopas.yourspace.data.models.space.ApiSpaceInvitation import com.canopas.yourspace.data.models.user.ApiUser import com.canopas.yourspace.data.repository.SpaceRepository import com.canopas.yourspace.data.service.auth.AuthService import com.canopas.yourspace.data.service.space.SpaceInvitationService import com.canopas.yourspace.data.storage.UserPreferences import com.canopas.yourspace.data.utils.AppDispatcher import com.canopas.yourspace.ui.navigation.AppNavigator import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext import org.junit.Before import org.junit.Rule import org.junit.Test import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.mock import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoInteractions import org.mockito.kotlin.whenever @ExperimentalCoroutinesApi class OnboardViewModelTest { @get:Rule val coroutineRule = MainCoroutineRule() private lateinit var viewModel: OnboardViewModel private val userService = mock<AuthService>() private val userPreferences = mock<UserPreferences>() private val spaceRepository = mock<SpaceRepository>() private val navigator = mock<AppNavigator>() private val invitationService = mock<SpaceInvitationService>() private val testDispatcher = AppDispatcher(IO = UnconfinedTestDispatcher()) private val currentUser = ApiUser(first_name = "first", last_name = "last") @Before fun setup() { whenever(userService.currentUser).thenReturn(currentUser) viewModel = OnboardViewModel( userService, testDispatcher, spaceRepository, userPreferences, navigator, invitationService ) } @Test fun `on init should set first and last name`() { assert(viewModel.state.value.firstName == "first") assert(viewModel.state.value.lastName == "last") } @Test fun `onFirstNameChange should update first name`() { viewModel.onFirstNameChange("new first") assert(viewModel.state.value.firstName == "new first") } @Test fun `onLastNameChange should update last name`() { viewModel.onLastNameChange("new last") assert(viewModel.state.value.lastName == "new last") } @Test fun `navigateToSpaceInfo should not call updateUser if user detail is not updated`() = runTest { val user = ApiUser(first_name = "first", last_name = "last") assert(viewModel.state.value.firstName == "first") assert(viewModel.state.value.lastName == "last") viewModel.navigateToSpaceInfo() verify(userService, times(0)).updateUser(user) } @Test fun `navigateToSpaceInfo should call updateUser if user detail is updated`() = runTest { viewModel.onFirstNameChange("new first") viewModel.onLastNameChange("new last") val user = currentUser.copy(first_name = "<NAME>", last_name = "<NAME>") viewModel.navigateToSpaceInfo() verify(userService).updateUser(user) } @Test fun `navigateToSpaceInfo should set currentStep to SpaceIntro`() = runTest { viewModel.navigateToSpaceInfo() assert(viewModel.state.value.currentStep == OnboardItems.SpaceIntro) } @Test fun `navigateToSpaceInfo should set updatingUserName to false`() = runTest { viewModel.navigateToSpaceInfo() assert(!viewModel.state.value.updatingUserName) } @Test fun `navigateToJoinOrCreateSpace should set currentStep to JoinOrCreateSpace`() { viewModel.navigateToJoinOrCreateSpace() assert(viewModel.state.value.currentStep == OnboardItems.JoinOrCreateSpace) } @Test fun `navigateToCreateSpace should set currentStep to CreateSpace`() { viewModel.navigateToCreateSpace() assert(viewModel.state.value.currentStep == OnboardItems.CreateSpace) } @Test fun `createSpace should set creatingSpace state to true`() = runTest { whenever(spaceRepository.createSpaceAndGetInviteCode("space")).doSuspendableAnswer { withContext(Dispatchers.IO) { delay(1000) } return@doSuspendableAnswer "invitationCode" } viewModel.createSpace("space") assert(viewModel.state.value.creatingSpace) } @Test fun `createSpace should set spaceName`() = runTest { viewModel.createSpace("space") assert(viewModel.state.value.spaceName == "space") } @Test fun `createSpace should call createSpace`() = runTest { viewModel.createSpace("space") verify(spaceRepository).createSpaceAndGetInviteCode("space") } @Test fun `createSpace should set spaceCode`() = runTest { whenever(spaceRepository.createSpaceAndGetInviteCode("space")).thenReturn("invitationCode") viewModel.createSpace("space") assert(viewModel.state.value.spaceInviteCode == "invitationCode") } @Test fun `createSpace should set creatingSpace to false after space created`() = runTest { whenever(spaceRepository.createSpaceAndGetInviteCode("space")).thenReturn("invitationCode") viewModel.createSpace("space") assert(!viewModel.state.value.creatingSpace) } @Test fun `createSpace should set currentStep to ShareSpaceCodeOnboard after space created`() = runTest { whenever(spaceRepository.createSpaceAndGetInviteCode("space")).thenReturn("invitationCode") viewModel.createSpace("space") assert(viewModel.state.value.currentStep == OnboardItems.ShareSpaceCodeOnboard) } @Test fun `createSpace should set error state if createSpace throws exception`() = runTest { whenever(spaceRepository.createSpaceAndGetInviteCode("space")).thenThrow(RuntimeException("error")) viewModel.createSpace("space") assert(viewModel.state.value.error == "error") } @Test fun `navigateToPermission should set OnboardShown to true`() = runTest { viewModel.navigateToHome() verify(userPreferences).setOnboardShown(true) } @Test fun `navigateToHome should navigate to home screen`() = runTest { viewModel.navigateToHome() verify(navigator).navigateTo("home", "onboard", true) } @Test fun `onInviteCodeChange should update invite code`() { viewModel.onInviteCodeChanged("inviteCode") assert(viewModel.state.value.spaceInviteCode == "inviteCode") } @Test fun `onInviteCodeChange should call submitInviteCode when invite code length is 6`() = runTest { val invitation = mock<ApiSpaceInvitation>() whenever(invitationService.getInvitation("123456")).thenReturn(invitation) viewModel.onInviteCodeChanged("123456") verify(invitationService).getInvitation("123456") } @Test fun `submitInviteCode should set verifyingInviteCode to true`() = runTest { viewModel.onInviteCodeChanged("inviteCode") whenever(invitationService.getInvitation("inviteCode")).doSuspendableAnswer { withContext(Dispatchers.IO) { delay(1000) } return@doSuspendableAnswer null } viewModel.submitInviteCode() assert(viewModel.state.value.verifyingInviteCode) } @Test fun `submitInviteCode should call getInvitation`() = runTest { val invitation = mock<ApiSpaceInvitation>() viewModel.onInviteCodeChanged("inviteCode") whenever(invitationService.getInvitation("inviteCode")).thenReturn(invitation) viewModel.submitInviteCode() verify(invitationService).getInvitation("inviteCode") } @Test fun `submitInviteCode should set errorInvalidInviteCode state to true if invitation is null`() = runTest { viewModel.onInviteCodeChanged("inviteCode") whenever(invitationService.getInvitation("inviteCode")).thenReturn(null) viewModel.submitInviteCode() assert(viewModel.state.value.errorInvalidInviteCode) } @Test fun `submitInviteCode should not call getSpace if invitation is null`() = runTest { viewModel.onInviteCodeChanged("inviteCode") whenever(invitationService.getInvitation("inviteCode")).thenReturn(null) viewModel.submitInviteCode() verifyNoInteractions(spaceRepository) } @Test fun `submitInviteCode should set spaceName and spaceId`() = runTest { viewModel.onInviteCodeChanged("inviteCode") val invitation = mock<ApiSpaceInvitation>() whenever(invitation.space_id).thenReturn("spaceId") val space = mock<ApiSpace>() whenever(space.name).thenReturn("spaceName") whenever(invitationService.getInvitation("inviteCode")).thenReturn(invitation) whenever(spaceRepository.getSpace("spaceId")).thenReturn(space) viewModel.submitInviteCode() assert(viewModel.state.value.spaceName == space.name) assert(viewModel.state.value.spaceId == invitation.space_id) } @Test fun `submitInviteCode should set verifyingInviteCode and errorInvalidInviteCode to false`() = runTest { viewModel.onInviteCodeChanged("inviteCode") val invitation = mock<ApiSpaceInvitation>() whenever(invitation.space_id).thenReturn("spaceId") val space = mock<ApiSpace>() whenever(space.name).thenReturn("spaceName") whenever(invitationService.getInvitation("inviteCode")).thenReturn(invitation) whenever(spaceRepository.getSpace("spaceId")).thenReturn(space) viewModel.submitInviteCode() assert(!viewModel.state.value.verifyingInviteCode) assert(!viewModel.state.value.errorInvalidInviteCode) } @Test fun `submitInviteCode should set joinedSpace`() = runTest { viewModel.onInviteCodeChanged("inviteCode") val invitation = mock<ApiSpaceInvitation>() whenever(invitation.space_id).thenReturn("spaceId") val space = mock<ApiSpace>() whenever(space.name).thenReturn("spaceName") whenever(invitationService.getInvitation("inviteCode")).thenReturn(invitation) whenever(spaceRepository.getSpace("spaceId")).thenReturn(space) viewModel.submitInviteCode() assert(viewModel.state.value.joinedSpace == space) } @Test fun `submitInviteCode should set error state if getInvitation throws exception`() = runTest { viewModel.onInviteCodeChanged("inviteCode") whenever(invitationService.getInvitation("inviteCode")).thenThrow(RuntimeException("error")) viewModel.submitInviteCode() assert(viewModel.state.value.error == "error") } @Test fun `resetErrorState should reset error state`() { viewModel.resetErrorState() assert(viewModel.state.value.error == null) assert(!viewModel.state.value.errorInvalidInviteCode) } }
5
null
1
7
3ce744ea6663d632b2fff470f9293de72708291d
11,366
your-space-android
Apache License 2.0
app/src/main/java/com/msg/gcms/data/repository/AttendRepositoryImpl.kt
GSM-MSG
465,292,111
false
{"Kotlin": 321879}
package com.msg.gcms.data.repository import com.msg.gcms.data.remote.datasource.attend.AttendDataSource import com.msg.gcms.data.remote.dto.attend.request.PatchAttendStatusCollectivelyRequest import com.msg.gcms.data.remote.dto.attend.request.PatchAttendStatusRequest import com.msg.gcms.data.remote.dto.attend.request.PostAttendListRequest import com.msg.gcms.data.remote.dto.attend.response.toGetClubAttendListResponseData import com.msg.gcms.domain.data.attend.GetClubAttendListResponseData import com.msg.gcms.domain.data.attend.PatchAttendStatusCollectivelyRequestData import com.msg.gcms.domain.data.attend.PatchAttendStatusRequestData import com.msg.gcms.domain.data.attend.PostAttendListRequestData import com.msg.gcms.domain.repository.AttendRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import java.time.LocalDate import java.time.LocalTime import javax.inject.Inject class AttendRepositoryImpl @Inject constructor( private val attendDataSource: AttendDataSource ) : AttendRepository { override suspend fun getClubAttendList( clubId: Long, date: LocalDate, period: String ): Flow<GetClubAttendListResponseData> { return attendDataSource.getClubAttendList( clubId = clubId, date = date, period = period ).map { it.toGetClubAttendListResponseData() } } override suspend fun postAttendList(body: PostAttendListRequestData): Flow<Unit> { return attendDataSource.postAttendList( body = PostAttendListRequest( name = body.name, date = body.date, periods = body.periods ) ) } override suspend fun patchAttendStatus(body: PatchAttendStatusRequestData): Flow<Unit> { return attendDataSource.patchAttendStatus( body = PatchAttendStatusRequest( attendanceId = body.attendanceId, attendanceStatus = body.attendanceStatus ) ) } override suspend fun patchAttendStatusCollectively(body: PatchAttendStatusCollectivelyRequestData): Flow<Unit> { return attendDataSource.patchAttendStatusCollectively( body = PatchAttendStatusCollectivelyRequest( attendanceIds = body.attendanceIds, attendanceStatus = body.attendanceStatus ) ) } }
6
Kotlin
0
17
11da719df1f53226546724206b92cf9c90eb0893
2,431
GCMS-Android
MIT License
app/src/main/java/com/nordkaz/ds24test/ui/ViewModelFactory.kt
ekbandroid
144,299,832
false
null
package com.nordkaz.ds24test.ui import android.arch.lifecycle.ViewModel import android.arch.lifecycle.ViewModelProvider import com.nordkaz.ds24test.data.QuoteRepository class ViewModelFactory(private val repository: QuoteRepository) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(SearchRepositoriesViewModel::class.java)) { @Suppress("UNCHECKED_CAST") return SearchRepositoriesViewModel(repository) as T } throw IllegalArgumentException("Unknown ViewModel class") } }
0
Kotlin
0
0
efef3a436d82b628db79a2071f9eaa4300d9a536
604
DS24Test
Apache License 2.0
src/main/kotlin/com/github/treepat/target_tree/default_tree/DefaultTargetTree.kt
Treepat
240,806,251
false
null
package com.github.treepat.target_tree.default_tree import antlr.tree_format.TreeFormatLexer import antlr.tree_format.TreeFormatParser import com.github.treepat.grammars.antlr.tree_format.TreeFormatVisitorImplementation import com.github.treepat.target_tree.TargetTree import com.github.treepat.target_tree.TargetTreeNode import org.antlr.v4.runtime.CharStreams import org.antlr.v4.runtime.CommonTokenStream import org.antlr.v4.runtime.tree.ParseTree class DefaultTargetTree(override var root: TargetTreeNode? = null) : TargetTree { companion object Factory { fun createFromFile(treeFilePath: String): DefaultTargetTree { val lexer = TreeFormatLexer(CharStreams.fromFileName(treeFilePath)) val tokenStream = CommonTokenStream(lexer) val fileParser = TreeFormatParser(tokenStream) val tree: ParseTree = fileParser.subtree() val treeVisitor = TreeFormatVisitorImplementation() return DefaultTargetTree(treeVisitor.visit(tree)) } fun createFromString(treeString: String): DefaultTargetTree { val lexer = TreeFormatLexer(CharStreams.fromString(treeString)) val tokenStream = CommonTokenStream(lexer) val fileParser = TreeFormatParser(tokenStream) val tree: ParseTree = fileParser.subtree() val treeVisitor = TreeFormatVisitorImplementation() return DefaultTargetTree(treeVisitor.visit(tree)) } } }
2
Kotlin
1
2
ea0d403b712a50b0e81c673a7db1b4e8adb94e3a
1,483
Treepat
Apache License 2.0
kotlin-electron/src/jsMain/generated/electron/CPUUsage.kt
JetBrains
93,250,841
false
{"Kotlin": 12159121, "JavaScript": 330528}
// Generated by Karakum - do not modify it manually! package electron typealias CPUUsage = electron.core.CPUUsage
40
Kotlin
165
1,319
a8a1947d73e3ed26426f1e27b641bff427dfd6a0
118
kotlin-wrappers
Apache License 2.0
android/app/src/main/kotlin/com/example/my_project/MainActivity.kt
12amansharma
472,812,836
false
{"Dart": 146876, "HTML": 1535, "Ruby": 1353, "Swift": 404, "Kotlin": 141, "Objective-C": 38}
package xyz.indovators.mentalhealthcompanion import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
1
43653447fface12094e03151383d9fbffac4448d
141
mental_health_companion
MIT License
gradle-plugin/src/test/kotlin/org/eazyportal/plugin/release/gradle/project/GradleProjectActionsFactoryTest.kt
eazyportal
423,612,882
true
{"Kotlin": 194632, "Java": 52737, "HTML": 61}
package org.eazyportal.plugin.release.gradle.project import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.eazyportal.plugin.release.core.project.ProjectActions import org.eazyportal.plugin.release.core.project.exception.InvalidProjectTypeException import org.eazyportal.plugin.release.core.project.model.FileSystemProjectFile import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.CsvSource import java.io.File internal class GradleProjectActionsFactoryTest { @TempDir private lateinit var workingDir: File private lateinit var underTest: GradleProjectActionsFactory @BeforeEach fun setUp() { underTest = GradleProjectActionsFactory() } @CsvSource(value = ["build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts"]) @ParameterizedTest fun test_provide_GradleProject(fileName: String) { // GIVEN File(workingDir, fileName).createNewFile() // WHEN // THEN val actual: ProjectActions = underTest.create(FileSystemProjectFile(workingDir)) assertThat(actual).isInstanceOf(GradleProjectActions::class.java) } @Test fun test_provide_InvalidProject() { // GIVEN // WHEN // THEN assertThatThrownBy { underTest.create(FileSystemProjectFile(workingDir)) } .isInstanceOf(InvalidProjectTypeException::class.java) .hasMessageStartingWith("Unable to identify the project type in: ") } }
0
Kotlin
1
0
ca6029491c2ed1cdb70112f851e15e503044db33
1,682
eazyrelease-plugin
Apache License 2.0
control/src/main/kotlin/matt/fx/control/wrapper/buttonbar/buttonbar.kt
mgroth0
497,866,693
false
null
package matt.fx.control.wrapper.buttonbar import javafx.collections.ObservableList import javafx.scene.Node import javafx.scene.control.ButtonBar import matt.fx.control.inter.graphic import matt.fx.control.wrapper.control.ControlWrapperImpl import matt.fx.control.wrapper.control.button.ButtonWrapper import matt.fx.graphics.wrapper.ET import matt.fx.graphics.wrapper.node.NodeWrapper import matt.fx.graphics.wrapper.node.attachTo import matt.lang.assertions.require.requireNull import matt.obs.bindings.str.ObsS fun ET.buttonbar(buttonOrder: String? = null, op: (ButtonBarWrapper.()->Unit)) = ButtonBarWrapper().attachTo(this, op) { if (buttonOrder != null) it.buttonOrder = buttonOrder } class ButtonBarWrapper( node: ButtonBar = ButtonBar(), ): ControlWrapperImpl<ButtonBar>(node) { val buttons: ObservableList<Node> get() = node.buttons var buttonOrder: String? get() = node.buttonOrder set(value) { node.buttonOrder = value } override fun addChild(child: NodeWrapper, index: Int?) { requireNull(index) buttons.add(child.node) } // fun setButtonData() = node.butt fun button( text: String = "", type: ButtonBar.ButtonData? = null, graphic: NodeWrapper? = null, op: ButtonWrapper.()->Unit = {} ) = ButtonWrapper().apply { this.text = text }.also { if (type != null) ButtonBar.setButtonData(it.node, type) if (graphic != null) it.graphic = graphic buttons += it.node op(it) } fun button( text: ObsS, type: ButtonBar.ButtonData? = null, graphic: NodeWrapper? = null, op: ButtonWrapper.()->Unit = {} ) = ButtonWrapper().also { it.textProperty.bind(text) if (type != null) ButtonBar.setButtonData(it.node, type) if (graphic != null) it.graphic = graphic buttons += it.node op(it) } }
0
Kotlin
0
0
76938715fac546faa085aadbb372ae50f71c08de
1,746
fx
MIT License
sample/kotlin/src/main/kotlin/com/datadog/android/sample/about/AboutFragment.kt
DataDog
219,536,756
false
null
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2016-Present Datadog, Inc. */ package com.datadog.android.sample.about import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProviders import com.datadog.android.sample.R class AboutFragment : Fragment() { private lateinit var viewModel: AboutViewModel private lateinit var aboutText: TextView private lateinit var licenseText: TextView // region Fragment override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val rootView = inflater.inflate(R.layout.fragment_about, container, false) aboutText = rootView.findViewById(R.id.about_text) licenseText = rootView.findViewById(R.id.license_text) return rootView } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProviders.of(this).get(AboutViewModel::class.java) } override fun onResume() { super.onResume() val currentContext = context ?: return viewModel.getAboutText(currentContext) { aboutText.text = it } viewModel.getLicenseText(currentContext) { licenseText.text = it } } override fun onStop() { super.onStop() viewModel.stopAsyncOperations() } // endregion }
33
Kotlin
39
86
bcf0d12fd978df4e28848b007d5fcce9cb97df1c
1,770
dd-sdk-android
Apache License 2.0
base/layoutinspector/testSrc/com/android/layoutinspector/parser/DisplayInfoFactoryTest.kt
qiangxu1996
255,410,085
false
null
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.layoutinspector.parser import com.android.layoutinspector.getTestFile import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertTrue class DisplayInfoFactoryTest { @Test fun testV1ViewNodeParsing() { val file = getTestFile("LayoutCaptureV1.li") val node = LayoutFileDataParser.parseFromFile(file).node!! val displayInfo = DisplayInfoFactory.createDisplayInfoFromNode(node) assertEquals(1080, displayInfo.width) assertEquals(1920, displayInfo.height) assertTrue(displayInfo.willNotDraw) } @Test fun testV2ViewNodeParsing() { val file = getTestFile("LayoutCaptureV2.li") val node = LayoutFileDataParser.parseFromFile(file).node!! val displayInfo = DisplayInfoFactory.createDisplayInfoFromNode(node) assertEquals(1080, displayInfo.width) assertEquals(1920, displayInfo.height) assertTrue(displayInfo.willNotDraw) } }
0
null
1
1
3411c5436d0d34e6e2b84cbf0e9395ac8c55c9d4
1,601
vmtrace
Apache License 2.0
app/src/main/java/barissaglam/client/movieapp/presentation/search/SearchFragment.kt
barissaglam
265,227,674
false
{"Kotlin": 121777, "Java": 6231}
package barissaglam.client.movieapp.presentation.search import android.graphics.Color import android.transition.TransitionInflater import android.widget.TextView import androidx.navigation.fragment.findNavController import barissaglam.client.movieapp.R import barissaglam.client.movieapp.base.extension.clickSubmitButton import barissaglam.client.movieapp.base.extension.hideKeyboard import barissaglam.client.movieapp.base.extension.showKeyboard import barissaglam.client.movieapp.base.view.BaseFragment import barissaglam.client.movieapp.data.enum.MovieListPageType import barissaglam.client.movieapp.databinding.FragmentSearchBinding class SearchFragment : BaseFragment<FragmentSearchBinding, SearchViewModel>() { override val layoutResourceId: Int = R.layout.fragment_search override val classTypeOfViewModel: Class<SearchViewModel> = SearchViewModel::class.java override fun init() { context?.let { sharedElementEnterTransition = TransitionInflater.from(it).inflateTransition(android.R.transition.move) } setupSearchView() } override fun setupClickListeners() { binding.imageButtonBack.setOnClickListener { findNavController().popBackStack() } } private fun setupSearchView() { (binding.searchView.findViewById(androidx.appcompat.R.id.search_src_text) as TextView).setTextColor(Color.WHITE) binding.searchView.clickSubmitButton { query -> findNavController().navigate(SearchFragmentDirections.actionSearchFragmentToMovieListFragment(pageType = MovieListPageType.SEARCH, searchQuery = query)) } } override fun onStart() { super.onStart() binding.searchView.showKeyboard(requireActivity()) binding.searchView.onActionViewExpanded() } override fun onStop() { super.onStop() binding.searchView.hideKeyboard(requireActivity()) } }
2
Kotlin
6
44
e565a018c5eeed161b5baee206ba40f79387056d
1,890
Movie-App
MIT License
tabler-icons/src/commonMain/kotlin/compose/icons/tablericons/BookmarkOff.kt
DevSrSouza
311,134,756
false
null
package compose.icons.tablericons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Round import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.TablerIcons public val TablerIcons.BookmarkOff: ImageVector get() { if (_bookmarkOff != null) { return _bookmarkOff!! } _bookmarkOff = Builder(name = "BookmarkOff", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(3.0f, 3.0f) lineTo(21.0f, 21.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(17.0f, 17.0f) verticalLineToRelative(3.0f) lineToRelative(-5.0f, -3.0f) lineToRelative(-5.0f, 3.0f) verticalLineToRelative(-13.0f) moveToRelative(1.178f, -2.818f) curveToRelative(0.252f, -0.113f, 0.53f, -0.176f, 0.822f, -0.176f) horizontalLineToRelative(6.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, 2.0f) verticalLineToRelative(7.0f) } } .build() return _bookmarkOff!! } private var _bookmarkOff: ImageVector? = null
17
null
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
2,180
compose-icons
MIT License
src/jsMain/kotlin/baaahs/app/ui/AppDrawer.kt
lucgirardin
290,413,324
true
{"Kotlin": 1134726, "C++": 479123, "JavaScript": 365308, "GLSL": 120375, "C": 100546, "CMake": 25514, "HTML": 10796, "CSS": 10322, "Shell": 663}
package baaahs.app.ui import baaahs.io.Fs import baaahs.ui.on import baaahs.ui.unaryPlus import baaahs.ui.withEvent import baaahs.ui.xComponent import kotlinx.css.Direction import kotlinx.html.js.onChangeFunction import kotlinx.html.js.onClickFunction import materialui.* import materialui.components.divider.divider import materialui.components.drawer.drawer import materialui.components.drawer.enums.DrawerAnchor import materialui.components.drawer.enums.DrawerStyle import materialui.components.drawer.enums.DrawerVariant import materialui.components.formcontrollabel.formControlLabel import materialui.components.iconbutton.iconButton import materialui.components.list.list import materialui.components.listitem.listItem import materialui.components.listitemicon.listItemIcon import materialui.components.listitemtext.listItemText import materialui.components.switches.switch import materialui.components.typography.typographyH6 import materialui.styles.muitheme.direction import org.w3c.dom.events.Event import react.RBuilder import react.RHandler import react.RProps import react.child import react.dom.div val AppDrawer = xComponent<AppDrawerProps>("AppDrawer") { props -> val theme = useTheme() val themeStyles = ThemeStyles(theme) drawer( themeStyles.appDrawer on DrawerStyle.root, themeStyles.appDrawerPaper on DrawerStyle.paperAnchorLeft ) { attrs.variant = DrawerVariant.persistent attrs.anchor = DrawerAnchor.left attrs.open = props.open attrs.onClose = props.onClose.withEvent() div(+themeStyles.appDrawerHeader) { iconButton { attrs.onClickFunction = props.onClose.withEvent() if (theme.direction == Direction.ltr) { icon(ChevronLeft) } else { icon(ChevronRight) } } } divider {} list { listItem { attrs.button = true attrs.onClickFunction = props.onNewShow.withEvent() listItemIcon { icon(Add) } listItemText { attrs.primary { +"New Show…" } } } listItem { attrs.button = true attrs.onClickFunction = props.onOpenShow.withEvent() listItemIcon { icon(OpenInBrowser) } listItemText { attrs.primary { +if (props.showLoaded) "Switch To…" else "Open…" } } } listItem { attrs.button = true attrs.disabled = !props.showUnsaved || props.showFile == null attrs.onClickFunction = props.onSaveShow.withEvent() listItemIcon { icon(Save) } listItemText { attrs.primary { +"Save" } } } listItem { attrs.button = true attrs.onClickFunction = props.onSaveShowAs.withEvent() listItemIcon { icon(FileCopy) } listItemText { attrs.primary { +"Save As…" } } } listItem { attrs.button = true attrs.onClickFunction = props.onCloseShow.withEvent() listItemIcon { icon(Close) } listItemText { attrs.primary { +"Close" } } } divider {} listItem { formControlLabel { attrs.control { switch { attrs.checked = props.editMode attrs.onChangeFunction = props.onEditModeChange } } attrs.label { typographyH6 { +"Design Mode" } } } } listItem { attrs.button = true attrs.disabled = !props.editMode attrs.onClickFunction = props.onLayoutEditorDialogToggle listItemIcon { icon(Dashboard) } listItemText { attrs.primary { +"Layout Editor" } } } } divider {} list { listItem { formControlLabel { attrs.control { switch { attrs.checked = props.darkMode attrs.onChangeFunction = props.onDarkModeChange } } attrs.label { typographyH6 { +"Dark Mode" } } } } } } } external interface AppDrawerProps : RProps { var open: Boolean var onClose: () -> Unit var showLoaded: Boolean var showFile: Fs.File? var editMode: Boolean var showUnsaved: Boolean var onEditModeChange: (Event) -> Unit var onLayoutEditorDialogToggle: (Event) -> Unit var darkMode: Boolean var onDarkModeChange: (Event) -> Unit var onNewShow: () -> Unit var onOpenShow: () -> Unit var onSaveShow: () -> Unit var onSaveShowAs: () -> Unit var onCloseShow: () -> Unit } fun RBuilder.appDrawer(handler: RHandler<AppDrawerProps>) = child(AppDrawer, handler = handler)
0
null
0
0
80865b7141d4ab8fcaafcc1c58402afb02561ecc
5,156
sparklemotion
MIT License
src/main/kotlin/org/jetbrains/kotlinx/jupyter/repl/creating/MockJupyterConnection.kt
Kotlin
63,066,291
false
{"Kotlin": 864116, "JavaScript": 40044, "CSS": 16243, "Python": 14915, "Jupyter Notebook": 1290, "Shell": 74}
package org.jetbrains.kotlinx.jupyter.repl.creating import org.jetbrains.kotlinx.jupyter.JupyterExecutor import org.jetbrains.kotlinx.jupyter.api.libraries.JupyterSocketType import org.jetbrains.kotlinx.jupyter.api.libraries.RawMessage import org.jetbrains.kotlinx.jupyter.api.libraries.RawMessageCallback import org.jetbrains.kotlinx.jupyter.messaging.JupyterConnectionInternal import org.jetbrains.kotlinx.jupyter.messaging.JupyterSocketManager import org.jetbrains.kotlinx.jupyter.messaging.MessageFactory import org.jetbrains.kotlinx.jupyter.startup.KernelConfig import java.io.InputStream object MockJupyterConnection : JupyterConnectionInternal { override val config: KernelConfig get() = throw NotImplementedError() override val socketManager: JupyterSocketManager get() = throw NotImplementedError() override val messageFactory: MessageFactory get() = throw NotImplementedError() override val executor: JupyterExecutor get() = throw NotImplementedError() override val stdinIn: InputStream get() = throw NotImplementedError() override fun addMessageCallback(callback: RawMessageCallback): RawMessageCallback { throw NotImplementedError() } override fun removeMessageCallback(callback: RawMessageCallback) { throw NotImplementedError() } override fun send(socketName: JupyterSocketType, message: RawMessage) { throw NotImplementedError() } }
65
Kotlin
108
984
94794065fd0a616b757a8cabf4574bb63344facb
1,462
kotlin-jupyter
Apache License 2.0