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
pulsar-skeleton/src/main/kotlin/ai/platon/pulsar/crawl/parse/ParseResult.kt
owinfo
271,195,380
true
{"Text": 50, "Shell": 8, "Maven POM": 27, "SQL": 4, "Markdown": 4, "Ignore List": 2, "XML": 69, "Kotlin": 395, "Java": 1466, "JSON": 9, "Java Properties": 8, "HTML": 88, "INI": 1, "Java Server Pages": 20, "CSS": 1, "JavaScript": 8, "JAR Manifest": 1, "YAML": 1, "Rich Text Format": 1}
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ai.platon.pulsar.crawl.parse import ai.platon.pulsar.common.FlowState import ai.platon.pulsar.persist.HypeLink import ai.platon.pulsar.persist.ParseStatus import ai.platon.pulsar.persist.metadata.ParseStatusCodes import ai.platon.pulsar.persist.model.DomStatistics import ai.platon.pulsar.persist.model.LabeledHyperLink import java.util.* import java.util.concurrent.ConcurrentSkipListSet import kotlin.collections.HashSet class ParseResult : ParseStatus { val hypeLinks = mutableSetOf<HypeLink>() var domStatistics: DomStatistics? = null var parser: Parser? = null var flowStatus = FlowState.CONTINUE val shouldContinue get() = flowStatus == FlowState.CONTINUE val shouldBreak get() = flowStatus == FlowState.BREAK constructor() : super(NOTPARSED, SUCCESS_OK) constructor(majorCode: Short, minorCode: Int) : super(majorCode, minorCode) constructor(majorCode: Short, minorCode: Int, message: String?) : super(majorCode, minorCode, message) companion object { val labeledHypeLinks = ConcurrentSkipListSet<LabeledHyperLink>() fun failed(minorCode: Int, message: String?): ParseResult { return ParseResult(ParseStatusCodes.FAILED, minorCode, message) } fun failed(e: Throwable): ParseResult { return ParseResult(ParseStatusCodes.FAILED, ParseStatusCodes.FAILED_EXCEPTION, e.message) } } }
0
null
0
0
9b284ddde911307ec6011e490a3b843ed724ed61
2,285
pulsar
Apache License 2.0
shared/src/commonMain/kotlin/com/tiomamaster/espressif/dto/Security1.kt
tiomamaster
435,623,772
false
null
package com.tiomamaster.espressif.dto import kotlinx.serialization.Serializable import kotlinx.serialization.protobuf.ProtoNumber internal enum class Security1MessageType(val value: Int) { COMMAND_0(0), RESPONSE_0(1), COMMAND_1(2), RESPONSE_1(3) } @Serializable internal data class Security1Payload( @ProtoNumber(1) val msg: Security1MessageType, @ProtoNumber(20) val sessionCommand0: SessionCommand0? = null, @ProtoNumber(21) val sessionResponse0: SessionResponse0? = null, @ProtoNumber(22) val sessionCommand1: SessionCommand1? = null, @ProtoNumber(23) val sessionResponse1: SessionResponse1? = null ) @Suppress("ArrayInDataClass") @Serializable internal data class SessionCommand0(@ProtoNumber(1) val clientPublicKey: ByteArray) @Suppress("ArrayInDataClass") @Serializable internal data class SessionResponse0( @ProtoNumber(1) val status: Status = Status.SUCCESS, @ProtoNumber(2) val devicePublicKey: ByteArray, @ProtoNumber(3) val deviceRandom: ByteArray ) @Suppress("ArrayInDataClass") @Serializable internal data class SessionCommand1(@ProtoNumber(2) val clientVerifyData: ByteArray) @Suppress("ArrayInDataClass") @Serializable internal data class SessionResponse1( @ProtoNumber(1) val status: Status = Status.SUCCESS, @ProtoNumber(3) val deviceVerifyData: ByteArray )
0
Kotlin
0
0
fcb9cda7a79e8281cd2f2a5a9ac2dbbf303c02fb
1,338
esp-idf-provisioning
Apache License 2.0
data/watchproviders/implementation/src/commonMain/kotlin/com/thomaskioko/tvmaniac/data/watchproviders/implementation/DefaultWatchProviderDao.kt
thomaskioko
361,393,353
false
null
package com.thomaskioko.tvmaniac.data.watchproviders.implementation import app.cash.sqldelight.coroutines.asFlow import app.cash.sqldelight.coroutines.mapToList import com.thomaskioko.tvmaniac.core.db.TvManiacDatabase import com.thomaskioko.tvmaniac.core.db.WatchProviders import com.thomaskioko.tvmaniac.core.db.Watch_providers import com.thomaskioko.tvmaniac.data.watchproviders.api.WatchProviderDao import com.thomaskioko.tvmaniac.db.Id import com.thomaskioko.tvmaniac.util.model.AppCoroutineDispatchers import kotlinx.coroutines.flow.Flow import me.tatarka.inject.annotations.Inject @Inject class DefaultWatchProviderDao( private val database: TvManiacDatabase, private val dispatcher: AppCoroutineDispatchers, ) : WatchProviderDao { override fun upsert(entity: Watch_providers) { database.watch_providersQueries.upsert( id = entity.id, name = entity.name, logo_path = entity.logo_path, tmdb_id = entity.tmdb_id, ) } override fun fetchWatchProviders(id: Long): List<WatchProviders> = database.watch_providersQueries.watchProviders(Id(id)) .executeAsList() override fun observeWatchProviders(id: Long): Flow<List<WatchProviders>> = database.watch_providersQueries.watchProviders(Id(id)) .asFlow() .mapToList(dispatcher.io) override fun delete(id: Long) { database.watch_providersQueries.delete(Id(id)) } override fun deleteAll() { database.transaction { database.watch_providersQueries.deleteAll() } } }
7
null
28
282
8c83a0461c03a1975afdf709e9d9307a141c0ec3
1,606
tv-maniac
Apache License 2.0
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/macie/CfnCustomDataIdentifierProps.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 137826907}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.macie import io.cloudshiftdev.awscdk.CfnTag import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import kotlin.Number import kotlin.String import kotlin.Unit import kotlin.collections.List /** * Properties for defining a `CfnCustomDataIdentifier`. * * 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.macie.*; * CfnCustomDataIdentifierProps cfnCustomDataIdentifierProps = * CfnCustomDataIdentifierProps.builder() * .name("name") * .regex("regex") * // the properties below are optional * .description("description") * .ignoreWords(List.of("ignoreWords")) * .keywords(List.of("keywords")) * .maximumMatchDistance(123) * .tags(List.of(CfnTag.builder() * .key("key") * .value("value") * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-macie-customdataidentifier.html) */ public interface CfnCustomDataIdentifierProps { /** * A custom description of the custom data identifier. The description can contain 1-512 * characters. * * Avoid including sensitive data in the description. Users of the account might be able to see * the description, depending on the actions that they're allowed to perform in Amazon Macie . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-macie-customdataidentifier.html#cfn-macie-customdataidentifier-description) */ public fun description(): String? = unwrap(this).getDescription() /** * An array of character sequences ( *ignore words* ) to exclude from the results. * * If text matches the regular expression ( `Regex` ) but it contains a string in this array, * Amazon Macie ignores the text and doesn't include it in the results. * * The array can contain 1-10 ignore words. Each ignore word can contain 4-90 UTF-8 characters. * Ignore words are case sensitive. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-macie-customdataidentifier.html#cfn-macie-customdataidentifier-ignorewords) */ public fun ignoreWords(): List<String> = unwrap(this).getIgnoreWords() ?: emptyList() /** * An array of character sequences ( *keywords* ), one of which must precede and be in proximity ( * `MaximumMatchDistance` ) of the regular expression ( `Regex` ) to match. * * The array can contain 1-50 keywords. Each keyword can contain 3-90 UTF-8 characters. Keywords * aren't case sensitive. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-macie-customdataidentifier.html#cfn-macie-customdataidentifier-keywords) */ public fun keywords(): List<String> = unwrap(this).getKeywords() ?: emptyList() /** * The maximum number of characters that can exist between the end of at least one complete * character sequence specified by the `Keywords` array and the end of text that matches the regular * expression ( `Regex` ). * * If a complete keyword precedes all the text that matches the regular expression and the keyword * is within the specified distance, Amazon Macie includes the result. * * The distance can be 1-300 characters. The default value is 50. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-macie-customdataidentifier.html#cfn-macie-customdataidentifier-maximummatchdistance) */ public fun maximumMatchDistance(): Number? = unwrap(this).getMaximumMatchDistance() /** * A custom name for the custom data identifier. The name can contain 1-128 characters. * * Avoid including sensitive data in the name of a custom data identifier. Users of the account * might be able to see the name, depending on the actions that they're allowed to perform in Amazon * Macie . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-macie-customdataidentifier.html#cfn-macie-customdataidentifier-name) */ public fun name(): String /** * The regular expression ( *regex* ) that defines the text pattern to match. * * The expression can contain 1-512 characters. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-macie-customdataidentifier.html#cfn-macie-customdataidentifier-regex) */ public fun regex(): String /** * An array of key-value pairs to apply to the custom data identifier. * * For more information, see [Resource * tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-macie-customdataidentifier.html#cfn-macie-customdataidentifier-tags) */ public fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList() /** * A builder for [CfnCustomDataIdentifierProps] */ @CdkDslMarker public interface Builder { /** * @param description A custom description of the custom data identifier. The description can * contain 1-512 characters. * Avoid including sensitive data in the description. Users of the account might be able to see * the description, depending on the actions that they're allowed to perform in Amazon Macie . */ public fun description(description: String) /** * @param ignoreWords An array of character sequences ( *ignore words* ) to exclude from the * results. * If text matches the regular expression ( `Regex` ) but it contains a string in this array, * Amazon Macie ignores the text and doesn't include it in the results. * * The array can contain 1-10 ignore words. Each ignore word can contain 4-90 UTF-8 characters. * Ignore words are case sensitive. */ public fun ignoreWords(ignoreWords: List<String>) /** * @param ignoreWords An array of character sequences ( *ignore words* ) to exclude from the * results. * If text matches the regular expression ( `Regex` ) but it contains a string in this array, * Amazon Macie ignores the text and doesn't include it in the results. * * The array can contain 1-10 ignore words. Each ignore word can contain 4-90 UTF-8 characters. * Ignore words are case sensitive. */ public fun ignoreWords(vararg ignoreWords: String) /** * @param keywords An array of character sequences ( *keywords* ), one of which must precede and * be in proximity ( `MaximumMatchDistance` ) of the regular expression ( `Regex` ) to match. * The array can contain 1-50 keywords. Each keyword can contain 3-90 UTF-8 characters. Keywords * aren't case sensitive. */ public fun keywords(keywords: List<String>) /** * @param keywords An array of character sequences ( *keywords* ), one of which must precede and * be in proximity ( `MaximumMatchDistance` ) of the regular expression ( `Regex` ) to match. * The array can contain 1-50 keywords. Each keyword can contain 3-90 UTF-8 characters. Keywords * aren't case sensitive. */ public fun keywords(vararg keywords: String) /** * @param maximumMatchDistance The maximum number of characters that can exist between the end * of at least one complete character sequence specified by the `Keywords` array and the end of * text that matches the regular expression ( `Regex` ). * If a complete keyword precedes all the text that matches the regular expression and the * keyword is within the specified distance, Amazon Macie includes the result. * * The distance can be 1-300 characters. The default value is 50. */ public fun maximumMatchDistance(maximumMatchDistance: Number) /** * @param name A custom name for the custom data identifier. The name can contain 1-128 * characters. * Avoid including sensitive data in the name of a custom data identifier. Users of the account * might be able to see the name, depending on the actions that they're allowed to perform in * Amazon Macie . */ public fun name(name: String) /** * @param regex The regular expression ( *regex* ) that defines the text pattern to match. * The expression can contain 1-512 characters. */ public fun regex(regex: String) /** * @param tags An array of key-value pairs to apply to the custom data identifier. * For more information, see [Resource * tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html) * . */ public fun tags(tags: List<CfnTag>) /** * @param tags An array of key-value pairs to apply to the custom data identifier. * For more information, see [Resource * tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html) * . */ public fun tags(vararg tags: CfnTag) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.macie.CfnCustomDataIdentifierProps.Builder = software.amazon.awscdk.services.macie.CfnCustomDataIdentifierProps.builder() /** * @param description A custom description of the custom data identifier. The description can * contain 1-512 characters. * Avoid including sensitive data in the description. Users of the account might be able to see * the description, depending on the actions that they're allowed to perform in Amazon Macie . */ override fun description(description: String) { cdkBuilder.description(description) } /** * @param ignoreWords An array of character sequences ( *ignore words* ) to exclude from the * results. * If text matches the regular expression ( `Regex` ) but it contains a string in this array, * Amazon Macie ignores the text and doesn't include it in the results. * * The array can contain 1-10 ignore words. Each ignore word can contain 4-90 UTF-8 characters. * Ignore words are case sensitive. */ override fun ignoreWords(ignoreWords: List<String>) { cdkBuilder.ignoreWords(ignoreWords) } /** * @param ignoreWords An array of character sequences ( *ignore words* ) to exclude from the * results. * If text matches the regular expression ( `Regex` ) but it contains a string in this array, * Amazon Macie ignores the text and doesn't include it in the results. * * The array can contain 1-10 ignore words. Each ignore word can contain 4-90 UTF-8 characters. * Ignore words are case sensitive. */ override fun ignoreWords(vararg ignoreWords: String): Unit = ignoreWords(ignoreWords.toList()) /** * @param keywords An array of character sequences ( *keywords* ), one of which must precede and * be in proximity ( `MaximumMatchDistance` ) of the regular expression ( `Regex` ) to match. * The array can contain 1-50 keywords. Each keyword can contain 3-90 UTF-8 characters. Keywords * aren't case sensitive. */ override fun keywords(keywords: List<String>) { cdkBuilder.keywords(keywords) } /** * @param keywords An array of character sequences ( *keywords* ), one of which must precede and * be in proximity ( `MaximumMatchDistance` ) of the regular expression ( `Regex` ) to match. * The array can contain 1-50 keywords. Each keyword can contain 3-90 UTF-8 characters. Keywords * aren't case sensitive. */ override fun keywords(vararg keywords: String): Unit = keywords(keywords.toList()) /** * @param maximumMatchDistance The maximum number of characters that can exist between the end * of at least one complete character sequence specified by the `Keywords` array and the end of * text that matches the regular expression ( `Regex` ). * If a complete keyword precedes all the text that matches the regular expression and the * keyword is within the specified distance, Amazon Macie includes the result. * * The distance can be 1-300 characters. The default value is 50. */ override fun maximumMatchDistance(maximumMatchDistance: Number) { cdkBuilder.maximumMatchDistance(maximumMatchDistance) } /** * @param name A custom name for the custom data identifier. The name can contain 1-128 * characters. * Avoid including sensitive data in the name of a custom data identifier. Users of the account * might be able to see the name, depending on the actions that they're allowed to perform in * Amazon Macie . */ override fun name(name: String) { cdkBuilder.name(name) } /** * @param regex The regular expression ( *regex* ) that defines the text pattern to match. * The expression can contain 1-512 characters. */ override fun regex(regex: String) { cdkBuilder.regex(regex) } /** * @param tags An array of key-value pairs to apply to the custom data identifier. * For more information, see [Resource * tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html) * . */ override fun tags(tags: List<CfnTag>) { cdkBuilder.tags(tags.map(CfnTag.Companion::unwrap)) } /** * @param tags An array of key-value pairs to apply to the custom data identifier. * For more information, see [Resource * tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html) * . */ override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList()) public fun build(): software.amazon.awscdk.services.macie.CfnCustomDataIdentifierProps = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.macie.CfnCustomDataIdentifierProps, ) : CdkObject(cdkObject), CfnCustomDataIdentifierProps { /** * A custom description of the custom data identifier. The description can contain 1-512 * characters. * * Avoid including sensitive data in the description. Users of the account might be able to see * the description, depending on the actions that they're allowed to perform in Amazon Macie . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-macie-customdataidentifier.html#cfn-macie-customdataidentifier-description) */ override fun description(): String? = unwrap(this).getDescription() /** * An array of character sequences ( *ignore words* ) to exclude from the results. * * If text matches the regular expression ( `Regex` ) but it contains a string in this array, * Amazon Macie ignores the text and doesn't include it in the results. * * The array can contain 1-10 ignore words. Each ignore word can contain 4-90 UTF-8 characters. * Ignore words are case sensitive. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-macie-customdataidentifier.html#cfn-macie-customdataidentifier-ignorewords) */ override fun ignoreWords(): List<String> = unwrap(this).getIgnoreWords() ?: emptyList() /** * An array of character sequences ( *keywords* ), one of which must precede and be in proximity * ( `MaximumMatchDistance` ) of the regular expression ( `Regex` ) to match. * * The array can contain 1-50 keywords. Each keyword can contain 3-90 UTF-8 characters. Keywords * aren't case sensitive. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-macie-customdataidentifier.html#cfn-macie-customdataidentifier-keywords) */ override fun keywords(): List<String> = unwrap(this).getKeywords() ?: emptyList() /** * The maximum number of characters that can exist between the end of at least one complete * character sequence specified by the `Keywords` array and the end of text that matches the * regular expression ( `Regex` ). * * If a complete keyword precedes all the text that matches the regular expression and the * keyword is within the specified distance, Amazon Macie includes the result. * * The distance can be 1-300 characters. The default value is 50. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-macie-customdataidentifier.html#cfn-macie-customdataidentifier-maximummatchdistance) */ override fun maximumMatchDistance(): Number? = unwrap(this).getMaximumMatchDistance() /** * A custom name for the custom data identifier. The name can contain 1-128 characters. * * Avoid including sensitive data in the name of a custom data identifier. Users of the account * might be able to see the name, depending on the actions that they're allowed to perform in * Amazon Macie . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-macie-customdataidentifier.html#cfn-macie-customdataidentifier-name) */ override fun name(): String = unwrap(this).getName() /** * The regular expression ( *regex* ) that defines the text pattern to match. * * The expression can contain 1-512 characters. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-macie-customdataidentifier.html#cfn-macie-customdataidentifier-regex) */ override fun regex(): String = unwrap(this).getRegex() /** * An array of key-value pairs to apply to the custom data identifier. * * For more information, see [Resource * tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-macie-customdataidentifier.html#cfn-macie-customdataidentifier-tags) */ override fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): CfnCustomDataIdentifierProps { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.macie.CfnCustomDataIdentifierProps): CfnCustomDataIdentifierProps = CdkObjectWrappers.wrap(cdkObject) as? CfnCustomDataIdentifierProps ?: Wrapper(cdkObject) internal fun unwrap(wrapped: CfnCustomDataIdentifierProps): software.amazon.awscdk.services.macie.CfnCustomDataIdentifierProps = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.macie.CfnCustomDataIdentifierProps } }
4
Kotlin
0
4
9a242bcc59b2c1cf505be2f9d838f1cd8008fe12
19,351
kotlin-cdk-wrapper
Apache License 2.0
serialization/src/commonTest/kotlin/nl/adaptivity/xml/serialization/RecoveryTest.kt
pdvrieze
143,553,364
false
null
/* * Copyright (c) 2021. * * This file is part of xmlutil. * * This file is licenced to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You should have received a copy of the license with the source distribution. * Alternatively, 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 nl.adaptivity.xml.serialization import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.Serializable import kotlinx.serialization.SerializationException import kotlinx.serialization.decodeFromString import kotlinx.serialization.descriptors.StructureKind import nl.adaptivity.xmlutil.ExperimentalXmlUtilApi import nl.adaptivity.xmlutil.QName import nl.adaptivity.xmlutil.XmlReader import nl.adaptivity.xmlutil.isEquivalent import nl.adaptivity.xmlutil.serialization.* import nl.adaptivity.xmlutil.serialization.structure.XmlDescriptor import kotlin.test.Test import kotlin.test.assertContains import kotlin.test.assertEquals import kotlin.test.assertFailsWith class RecoveryTest { @Serializable data class Data(val a: String, val b: String) @Serializable @XmlSerialName("Container", "", "") data class Container(val stat: Stat) @Serializable @XmlSerialName("Stat", "SomeNs", "link") data class Stat(val value: String) @Test fun testDeserializeNonRecovering() { val input = "<Container><link:Stat xmlns:link=\"SomeNs\" value=\"foo\"/></Container>" val parsed = XML.decodeFromString<Container>(input) assertEquals(Container(Stat("foo")), parsed) } /** * Test in response to #160 */ @Test fun testDeserializeRecoveringWithParser() { val xml = XML { policy = object: DefaultXmlSerializationPolicy(Builder().apply { pedantic = true }) { @ExperimentalXmlUtilApi override fun handleUnknownContentRecovering( input: XmlReader, inputKind: InputKind, descriptor: XmlDescriptor, name: QName?, candidates: Collection<Any> ): List<XML.ParsedData<*>> { XmlSerializationPolicy.recoverNullNamespaceUse(inputKind, descriptor, name)?.let { return it } return super.handleUnknownContentRecovering(input, inputKind, descriptor, name, candidates) } } } val input = "<Container><Stat value=\"foo\"/></Container>" val parsed = xml.decodeFromString<Container>(input) assertEquals(Container(Stat("foo")), parsed) } @OptIn(ExperimentalXmlUtilApi::class, ExperimentalSerializationApi::class) @Test fun testDeserializeRecovering() { val serialized = "<Data a=\"foo\" c=\"bar\" />" val xml = XML { defaultPolicy { unknownChildHandler = UnknownChildHandler { input, inputKind, descriptor, name, candidates -> assertEquals(QName("c"), name) assertEquals(InputKind.Attribute, inputKind) assertEquals(StructureKind.CLASS, descriptor.kind) assertEquals(QName("a"), descriptor.getElementDescriptor(0).tagName) assertEquals(QName("b"), descriptor.getElementDescriptor(1).tagName) assertEquals( listOf( PolyInfo(QName("a"), 0, descriptor.getElementDescriptor(0)), PolyInfo(QName("b"), 1, descriptor.getElementDescriptor(1)) ), candidates ) listOf(XML.ParsedData(1, input.getAttributeValue(name!!))) } } } val parsed: Data = xml.decodeFromString(serialized) val expected = Data("foo", "bar") assertEquals(expected, parsed) } @OptIn(ExperimentalXmlUtilApi::class) @Test fun testDeserializeRecoveringNotProvidingRequired() { val serialized = "<Data a=\"foo\" c=\"bar\" />" val xml = XML { defaultPolicy { unknownChildHandler = UnknownChildHandler { _, _, _, name, _ -> assertEquals(QName("c"), name) emptyList() } } } val e = assertFailsWith<SerializationException> { xml.decodeFromString<Data>(serialized) } assertContains(e.message!!, "Field 'b' is required") assertContains(e.message!!, ", but it was missing") } @OptIn(ExperimentalXmlUtilApi::class) @Test fun testDeserializeRecoveringDuplicateData() { val serialized = "<Data a=\"foo\" c=\"bar\" />" val xml = XML { defaultPolicy { unknownChildHandler = UnknownChildHandler { input, _, _, name, _ -> assertEquals(QName("c"), name) listOf( XML.ParsedData(1, input.getAttributeValue(name!!)), XML.ParsedData(1, "baz"), ) } } } val d = xml.decodeFromString<Data>(serialized) assertEquals("baz", d.b) } }
35
null
31
378
c4053519a8b6c90af9e1683a5fe0e9e2b2c0db79
5,662
xmlutil
Apache License 2.0
app/src/main/java/com/AERYZ/treasurefind/main/OnSwipeTouchListener.kt
eddyspaghette
669,456,723
false
{"Kotlin": 405201}
package com.musical.instrument.simulator.app.utils import android.content.Context import android.view.GestureDetector import android.view.GestureDetector.SimpleOnGestureListener import android.view.MotionEvent import android.view.View import android.view.View.OnTouchListener import kotlin.math.abs internal open class OnSwipeTouchListener(c: Context?) : OnTouchListener { private val gestureDetector: GestureDetector override fun onTouch(view: View, motionEvent: MotionEvent): Boolean { return gestureDetector.onTouchEvent(motionEvent) } private inner class GestureListener : SimpleOnGestureListener() { private val SWIPE_THRESHOLD: Int = 100 private val SWIPE_VELOCITY_THRESHOLD: Int = 100 override fun onDown(e: MotionEvent): Boolean { return true } override fun onSingleTapUp(e: MotionEvent): Boolean { onClick() return super.onSingleTapUp(e) } override fun onDoubleTap(e: MotionEvent): Boolean { onDoubleClick() return super.onDoubleTap(e) } override fun onLongPress(e: MotionEvent) { onLongClick() super.onLongPress(e) } override fun onFling( e1: MotionEvent?, e2: MotionEvent, velocityX: Float, velocityY: Float ): Boolean { try { val e1 = e1 ?: return false val diffY = e2.y - e1.y val diffX = e2.x - e1.x if (abs(diffX) > abs(diffY)) { if (abs(diffX) > SWIPE_THRESHOLD && abs( velocityX ) > SWIPE_VELOCITY_THRESHOLD ) { if (diffX > 0) { onSwipeRight() } else { onSwipeLeft() } } } else { if (abs(diffY) > SWIPE_THRESHOLD && abs( velocityY ) > SWIPE_VELOCITY_THRESHOLD ) { if (diffY < 0) { onSwipeUp() } else { onSwipeDown() } } } } catch (exception: Exception) { exception.printStackTrace() } return false } } open fun onSwipeRight() {} open fun onSwipeLeft() {} open fun onSwipeUp() {} open fun onSwipeDown() {} private fun onClick() {} private fun onDoubleClick() {} private fun onLongClick() {} init { gestureDetector = GestureDetector(c, GestureListener()) } }
8
Kotlin
4
2
81ff85a85293e997daf72c9d51fed64a981385a9
2,834
TreasureFind
MIT License
app/src/main/java/com/AERYZ/treasurefind/main/OnSwipeTouchListener.kt
eddyspaghette
669,456,723
false
{"Kotlin": 405201}
package com.musical.instrument.simulator.app.utils import android.content.Context import android.view.GestureDetector import android.view.GestureDetector.SimpleOnGestureListener import android.view.MotionEvent import android.view.View import android.view.View.OnTouchListener import kotlin.math.abs internal open class OnSwipeTouchListener(c: Context?) : OnTouchListener { private val gestureDetector: GestureDetector override fun onTouch(view: View, motionEvent: MotionEvent): Boolean { return gestureDetector.onTouchEvent(motionEvent) } private inner class GestureListener : SimpleOnGestureListener() { private val SWIPE_THRESHOLD: Int = 100 private val SWIPE_VELOCITY_THRESHOLD: Int = 100 override fun onDown(e: MotionEvent): Boolean { return true } override fun onSingleTapUp(e: MotionEvent): Boolean { onClick() return super.onSingleTapUp(e) } override fun onDoubleTap(e: MotionEvent): Boolean { onDoubleClick() return super.onDoubleTap(e) } override fun onLongPress(e: MotionEvent) { onLongClick() super.onLongPress(e) } override fun onFling( e1: MotionEvent?, e2: MotionEvent, velocityX: Float, velocityY: Float ): Boolean { try { val e1 = e1 ?: return false val diffY = e2.y - e1.y val diffX = e2.x - e1.x if (abs(diffX) > abs(diffY)) { if (abs(diffX) > SWIPE_THRESHOLD && abs( velocityX ) > SWIPE_VELOCITY_THRESHOLD ) { if (diffX > 0) { onSwipeRight() } else { onSwipeLeft() } } } else { if (abs(diffY) > SWIPE_THRESHOLD && abs( velocityY ) > SWIPE_VELOCITY_THRESHOLD ) { if (diffY < 0) { onSwipeUp() } else { onSwipeDown() } } } } catch (exception: Exception) { exception.printStackTrace() } return false } } open fun onSwipeRight() {} open fun onSwipeLeft() {} open fun onSwipeUp() {} open fun onSwipeDown() {} private fun onClick() {} private fun onDoubleClick() {} private fun onLongClick() {} init { gestureDetector = GestureDetector(c, GestureListener()) } }
8
Kotlin
4
2
81ff85a85293e997daf72c9d51fed64a981385a9
2,834
TreasureFind
MIT License
app/src/test/java/io/freshdroid/vinyl/features/album/AlbumDetailsViewModelTest.kt
gm4s
175,840,667
false
null
package io.freshdroid.vinyl.features.album import android.content.Intent import io.freshdroid.vinyl.RobolectricTestCase import io.freshdroid.vinyl.commons.models.Album import io.freshdroid.vinyl.core.rx.Irrelevant import io.freshdroid.vinyl.factories.AlbumFactory import io.freshdroid.vinyl.features.album.viewmodels.AlbumDetailsViewModel import io.freshdroid.vinyl.features.album.views.AlbumDetailsActivity import io.reactivex.subscribers.TestSubscriber import org.junit.Test internal class AlbumDetailsViewModelTest : RobolectricTestCase() { @Test fun testBack() { val vm = AlbumDetailsViewModel(scopeProvider()) val back = TestSubscriber<Irrelevant>() vm.outputs.back().subscribe(back::onNext) vm.inputs.onBackClick() back.assertValueCount(1) } @Test fun testAlbum() { val vm = AlbumDetailsViewModel(scopeProvider()) val album = TestSubscriber<Album>() vm.outputs.album().subscribe(album::onNext) val albumDetailsIntent = Intent() albumDetailsIntent.putExtra(AlbumDetailsActivity.KEY_ALBUM, AlbumFactory.create()) vm.intent(albumDetailsIntent) album.assertValue { it.id == "id" } } }
1
Kotlin
1
1
36e6d69aa15b7eff1981fe549bb8606df06a0410
1,214
Vinyl
Apache License 2.0
app/src/main/java/com/example/finvin/IncomeActivity.kt
Vinayakoo7
871,296,549
false
{"Kotlin": 16822}
package com.example.finvin class IncomeActivity { }
0
Kotlin
0
0
25993bb6b3eac0b2b1b29fd5689d06641ae1588a
52
FinVin
MIT License
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/twotone/Brush2.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.twotone import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Round import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import moe.tlaster.icons.vuesax.vuesaxicons.TwotoneGroup public val TwotoneGroup.Brush2: ImageVector get() { if (_brush2 != null) { return _brush2!! } _brush2 = Builder(name = "Brush2", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(10.9707f, 2.0f) horizontalLineTo(8.9707f) curveTo(3.9707f, 2.0f, 1.9707f, 4.0f, 1.9707f, 9.0f) verticalLineTo(15.0f) curveTo(1.9707f, 20.0f, 3.9707f, 22.0f, 8.9707f, 22.0f) horizontalLineTo(14.9707f) curveTo(19.9707f, 22.0f, 21.9707f, 20.0f, 21.9707f, 15.0f) verticalLineTo(13.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(21.8795f, 3.5602f) curveTo(20.6495f, 6.6302f, 17.5595f, 10.8102f, 14.9795f, 12.8802f) lineTo(13.3995f, 14.1402f) curveTo(13.1995f, 14.2902f, 12.9995f, 14.4102f, 12.7695f, 14.5002f) curveTo(12.7695f, 14.3502f, 12.7595f, 14.2002f, 12.7395f, 14.0402f) curveTo(12.6495f, 13.3702f, 12.3495f, 12.7402f, 11.8095f, 12.2102f) curveTo(11.2595f, 11.6602f, 10.5995f, 11.3502f, 9.9194f, 11.2602f) curveTo(9.7594f, 11.2502f, 9.5995f, 11.2402f, 9.4395f, 11.2502f) curveTo(9.5295f, 11.0002f, 9.6594f, 10.7702f, 9.8294f, 10.5802f) lineTo(11.0895f, 9.0002f) curveTo(13.1595f, 6.4202f, 17.3495f, 3.3102f, 20.4095f, 2.0802f) curveTo(20.8795f, 1.9002f, 21.3395f, 2.0402f, 21.6295f, 2.3302f) curveTo(21.9295f, 2.6302f, 22.0695f, 3.0902f, 21.8795f, 3.5602f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.7801f, 14.49f) curveTo(12.7801f, 15.37f, 12.4401f, 16.21f, 11.8101f, 16.85f) curveTo(11.3201f, 17.34f, 10.6601f, 17.68f, 9.8701f, 17.78f) lineTo(7.9001f, 17.99f) curveTo(6.8301f, 18.11f, 5.9101f, 17.2f, 6.0301f, 16.11f) lineTo(6.2401f, 14.14f) curveTo(6.4301f, 12.39f, 7.8901f, 11.27f, 9.4501f, 11.24f) curveTo(9.6101f, 11.23f, 9.7701f, 11.24f, 9.9301f, 11.25f) curveTo(10.6101f, 11.34f, 11.2701f, 11.65f, 11.8201f, 12.2f) curveTo(12.3601f, 12.74f, 12.6601f, 13.36f, 12.7501f, 14.03f) curveTo(12.7701f, 14.19f, 12.7801f, 14.35f, 12.7801f, 14.49f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), fillAlpha = 0.4f, strokeAlpha = 0.4f, strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(15.8193f, 11.9799f) curveTo(15.8193f, 9.8899f, 14.1293f, 8.1899f, 12.0293f, 8.1899f) } } .build() return _brush2!! } private var _brush2: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
4,613
VuesaxIcons
MIT License
Lista 5/Zadanie 1/NeonPong/app/src/main/java/com/example/pongGame/PointColor.kt
SzymonGlab
182,572,867
false
null
package com.example.pongGame import android.graphics.Paint class PointsColor (val name : String) : Paint() { var pointsC = Paint() init { pointsC.textSize = 100f when (name) { "pink" -> pointsC.setARGB(150,255, 25, 151) "red" -> pointsC.setARGB(150,221, 8, 47) "yellow" -> pointsC.setARGB(150,255, 248, 58) "green" -> pointsC.setARGB(150,28, 255, 50) "cyan" -> pointsC.setARGB(150,65, 220, 244) "blue" -> pointsC.setARGB(150,55, 55, 242) "grey" -> pointsC.setARGB(150,160, 160, 160) "purple" -> pointsC.setARGB(150,60, 160, 160) } } }
0
Kotlin
0
0
b15dafb0e52a0da23dc8898d2ec7992e8c6aee18
671
Aplikacje-Mobilne
MIT License
common/src/commonMain/kotlin/com/artemchep/keyguard/feature/navigation/Navigation.kt
AChep
669,697,660
false
{"Kotlin": 5516822, "HTML": 45876}
package com.artemchep.keyguard.feature.navigation import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.staticCompositionLocalOf internal val LocalBackHost = staticCompositionLocalOf<Boolean> { false } internal val LocalRoute = staticCompositionLocalOf<Route> { throw IllegalStateException("Home layout must be initialized!") } @Stable interface RouteForResult<T> { @Composable fun Content(transmitter: RouteResultTransmitter<T>) } @Stable interface DialogRouteForResult<T> : RouteForResult<T> fun <T> registerRouteResultReceiver( route: RouteForResult<T>, block: (T) -> Unit, ): Route { val transmitter: RouteResultTransmitter<T> = object : RouteResultTransmitter<T> { override fun invoke(unit: T) { block(unit) } } return object : Route { @Composable override fun Content() { route.Content( transmitter = transmitter, ) } } } fun <T> registerRouteResultReceiver( route: DialogRouteForResult<T>, block: (T) -> Unit, ): DialogRoute { val transmitter: RouteResultTransmitter<T> = object : RouteResultTransmitter<T> { override fun invoke(unit: T) { block(unit) } } return object : DialogRoute { @Composable override fun Content() { route.Content( transmitter = transmitter, ) } } } /** * A callback to pass the result back * to a caller. */ interface RouteResultTransmitter<T> : (T) -> Unit
66
Kotlin
31
995
557bf42372ebb19007e3a8871e3f7cb8a7e50739
1,608
keyguard-app
Linux Kernel Variant of OpenIB.org license
shared/src/commonMain/kotlin/com/ma/basloq/data/repo/source/UserRemoteDataSource.kt
mosayeb-a
758,119,843
false
{"Kotlin": 122909, "Swift": 342}
package com.ma.basloq.data.repo.source import com.ma.basloq.service.UserService import com.ma.basloq.common.BasloqException import com.ma.basloq.common.Result import com.ma.basloq.common.basloqExceptionMapper import com.ma.basloq.common.handleRequestException import com.ma.basloq.data.model.SessionTokenResponse import com.ma.basloq.data.model.UserTokenResponse class UserRemoteDataSource( private val userService: UserService ) : UserDataSource { override suspend fun createUser( username: String, email: String, password: String ): UserTokenResponse = userService.createUser(username = username, email = email, password = <PASSWORD>) override suspend fun createSession(username: String, password: String): SessionTokenResponse = userService.login(username = username, password = <PASSWORD>) override suspend fun destroySession(): String = userService.logout() override fun loadSessionToken() { TODO("Not yet implemented") } override fun saveSessionToken(token: String) { TODO("Not yet implemented") } override fun loadUserToken() { TODO("Not yet implemented") } override fun saveUserToken(token: String) { TODO("Not yet implemented") } override fun saveUsername(username: String) { TODO("Not yet implemented") } override fun getUsername() : String { TODO("Not yet implemented") } override fun saveUserPassword(password: String) { TODO("Not yet implemented") } override fun getUserPassword() : String { TODO("Not yet implemented") } }
0
Kotlin
0
0
41dcff88efe6ee0a5e7a3253491984e9e171d957
1,646
Basloq
Apache License 2.0
src/test/kotlin/no/nav/forms/recipients/RecipientsControllerTest.kt
navikt
862,880,104
false
{"Kotlin": 20904, "Dockerfile": 240}
package no.nav.forms.recipients import no.nav.forms.ApplicationTest import no.nav.forms.model.NewRecipientRequest import no.nav.forms.model.RecipientDto import no.nav.forms.model.UpdateRecipientRequest import no.nav.forms.testutils.createTokenFor import no.nav.forms.testutils.toURI import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import org.springframework.boot.test.web.client.getForEntity import org.springframework.http.HttpEntity import org.springframework.http.HttpHeaders import org.springframework.http.HttpMethod import org.springframework.http.HttpStatus import org.springframework.util.MultiValueMap class RecipientsControllerTest : ApplicationTest() { private val testUserName = "Navnesen, Navn" @Test fun testGetRecipients() { val url = "$baseUrl/v1/recipients" val response = restTemplate.getForEntity<List<RecipientDto>>(url.toURI()) assertEquals(2, response.body?.size) } @Test fun testPostRecipient() { val url = "$baseUrl/v1/recipients" val requestBody = NewRecipientRequest( "NAV Skanning", "Postboks 1", "0591", "Oslo", ) val response = restTemplate.exchange( url.toURI(), HttpMethod.POST, HttpEntity(requestBody, httpHeaders(mockOAuth2Server.createTokenFor(userName = testUserName))), RecipientDto::class.java ) assertTrue(response.statusCode.is2xxSuccessful) assertNotNull(response.body?.recipientId) assertEquals(requestBody.name, response.body?.name) assertEquals(testUserName, response.body?.createdBy) } @Test fun testPutRecipient() { val url = "$baseUrl/v1/recipients/1" val requestBody = UpdateRecipientRequest( "NAV Nytt navn", "Postboks 99", "6425", "Molde", ) val response = restTemplate.exchange( url.toURI(), HttpMethod.PUT, HttpEntity(requestBody, httpHeaders(mockOAuth2Server.createTokenFor(userName = testUserName))), String::class.java ) assertTrue(response.statusCode.is2xxSuccessful) val getResponse = restTemplate.getForEntity<RecipientDto>(url.toURI()) assertNotNull(getResponse.body?.recipientId) assertEquals(requestBody.name, getResponse.body?.name) assertEquals(requestBody.poBoxAddress, getResponse.body?.poBoxAddress) assertEquals(requestBody.postalCode, getResponse.body?.postalCode) assertEquals(requestBody.postalName, getResponse.body?.postalName) assertEquals(testUserName, getResponse.body?.changedBy) } private fun httpHeaders(token: String): MultiValueMap<String, String> { val headers = HttpHeaders() headers.add("Authorization", "Bearer $token") return headers; } @Test fun testPutRecipientWithoutToken() { val url = "$baseUrl/v1/recipients/1" val requestBody = UpdateRecipientRequest( "NAV Nytt navn", "Postboks 99", "6425", "Molde", ) val response = restTemplate.exchange( url.toURI(), HttpMethod.PUT, HttpEntity(requestBody), String::class.java ) assertEquals(HttpStatus.UNAUTHORIZED.value(), response.statusCode.value()) } }
1
Kotlin
0
0
8f4cc93c7352e250446c6cfc194a4bc28c27c086
2,978
forms-api
MIT License
app/src/main/java/com/elacqua/geotask/data/model/Direction.kt
etasdemir
382,923,471
false
null
package com.elacqua.geotask.data.model import com.google.gson.annotations.SerializedName data class Direction( @SerializedName("routes") val polylines: List<Polyline> = listOf() )
0
Kotlin
0
0
80473250967c20488362c635d8971ca0233a1832
189
GeoTask
Apache License 2.0
app/src/main/kotlin/hr/kbratko/instakt/domain/persistence/SocialMediaLinkPersistence.kt
karlobratko
802,886,736
false
{"Kotlin": 290357, "Makefile": 613}
package hr.kbratko.instakt.domain.persistence import arrow.core.Either import hr.kbratko.instakt.domain.DomainError import hr.kbratko.instakt.domain.model.SocialMediaLink import hr.kbratko.instakt.domain.model.User interface SocialMediaLinkPersistence { suspend fun insert(link: SocialMediaLink.New): Either<DomainError, SocialMediaLink> suspend fun select(userId: User.Id): Set<SocialMediaLink> suspend fun update(data: SocialMediaLink.Edit): Either<DomainError, SocialMediaLink> suspend fun delete(data: SocialMediaLink.Delete): Either<DomainError, SocialMediaLink.Id> }
5
Kotlin
0
0
e39e316a813b5657315c74440409a7af3ae6e3dc
593
instakt
MIT License
sdk/src/main/java/com/exponea/sdk/repository/PushNotificationRepositoryImpl.kt
exponea
134,699,893
false
null
package com.exponea.sdk.repository import com.exponea.sdk.preferences.ExponeaPreferences import com.exponea.sdk.util.fromJson import com.google.gson.Gson class PushNotificationRepositoryImpl( private val preferences: ExponeaPreferences ) : PushNotificationRepository { private val KEY = "ExponeaPushNotificationInitiated" private val KEY_EXTRA_DATA = "ExponeaPushNotificationExtraData" override fun get(): Boolean { return preferences.getBoolean(KEY, false) } override fun set(boolean: Boolean) { preferences.setBoolean(KEY, boolean) } override fun getExtraData(): Map<String, String>? { val dataString = preferences.getString(KEY_EXTRA_DATA, "") if (dataString.isEmpty()) { return null } return Gson().fromJson(dataString) } override fun setExtraData(data: Map<String, String>) { val dataString = Gson().toJson(data) preferences.setString(KEY_EXTRA_DATA, dataString) } override fun clearExtraData() { preferences.remove(KEY_EXTRA_DATA) } }
0
null
16
16
1de71a8ec212494f617bca3fa56a0837825e538e
1,089
exponea-android-sdk
MIT License
src/main/kotlin/xyz/magentaize/dynamicdata/cache/ObservableCache.kt
Magentaize
290,133,754
false
null
package xyz.magentaize.dynamicdata.cache import io.reactivex.rxjava3.disposables.Disposable import xyz.magentaize.dynamicdata.kernel.Optional interface ObservableCache<K, V> : ConnectableCache<K, V>, Disposable { val size: Int val items: Iterable<V> val keys: Iterable<K> val keyValues: Map<K, V> fun lookup(key: K): Optional<V> }
0
Kotlin
0
3
dda522f335a6ab3847cc90ff56e8429c15834800
353
dynamicdata-kotlin
MIT License
ui/src/main/java/pl/kubisiak/ui/recyclerview/ViewModelAdapter.kt
szymonkubisiak
222,223,106
false
null
package pl.kubisiak.ui.recyclerview import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.databinding.ObservableList import androidx.databinding.ViewDataBinding import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.findViewTreeLifecycleOwner import androidx.recyclerview.widget.RecyclerView import pl.kubisiak.ui.BaseSubViewModel import pl.kubisiak.ui.R import pl.kubisiak.ui.items.* import java.lang.ref.WeakReference open class ViewModelAdapter<VM : BaseSubViewModel>(protected open val items: List<VM>) : RecyclerView.Adapter<ViewModelViewHolder>() { override fun getItemCount(): Int = items.size override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewModelViewHolder { val inflater = LayoutInflater.from(parent.context) val binding = DataBindingUtil.inflate<ViewDataBinding>(inflater, viewType, parent, false) binding.lifecycleOwner = parent.findViewTreeLifecycleOwner() ?: parent.context as LifecycleOwner return ViewModelViewHolder(binding) } override fun onBindViewHolder(holder: ViewModelViewHolder, position: Int) { holder.bind(items[position]) } override fun getItemViewType(position: Int): Int { return getLayoutIdForPosition(position) } //TODO: replace with DataTemplateSelector private fun getLayoutIdForPosition(position: Int): Int { return when (items[position]) { is ImageItemViewModel -> R.layout.item_image is SimpleItemViewModel -> R.layout.item_simpletest is PostItemViewModel -> R.layout.item_post is LoadingItemViewModel -> R.layout.item_loader else -> -1 } } init { stateRestorationPolicy = StateRestorationPolicy.PREVENT_WHEN_EMPTY } } class ViewModelObserverAdapter<VM : BaseSubViewModel>(override val items: ObservableList<VM>) : ViewModelAdapter<VM>(items) { private val eventTranslator = ListChangedEventTranslator<VM>(this) fun <VM : BaseSubViewModel> isListSame(newItems: ObservableList<VM>?): Boolean { return newItems === items } init { eventTranslator.subscribeTo(items) } //TODO: research using onAttached instead of init // override fun onAttachedToRecyclerView(recyclerView: RecyclerView) { // eventTranslator.subscribeTo(items) // } override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) { eventTranslator.unsubscribeFrom(items) } } /** * ListChangedEventTranslator * This class implements ObservableList.OnListChangedCallback and translates its "content changed" events to corresponding RecyclerView events. */ //TODO: Needs more research if the weak observing breaks anything. internal class ListChangedEventTranslator<T>(strongAdapter: RecyclerView.Adapter<*>) : ObservableList.OnListChangedCallback<ObservableList<T>>() { private val weakAdapter = WeakReference(strongAdapter) private fun getAdapter(list: ObservableList<T>?): RecyclerView.Adapter<*>? { val retval = weakAdapter.get() if (retval == null) { unsubscribeFrom(list) } return retval } @SuppressLint("NotifyDataSetChanged") override fun onChanged(sender: ObservableList<T>?) { getAdapter(sender)?.notifyDataSetChanged() } override fun onItemRangeChanged(sender: ObservableList<T>?, positionStart: Int, itemCount: Int) { getAdapter(sender)?.notifyItemRangeChanged(positionStart, itemCount) } override fun onItemRangeInserted(sender: ObservableList<T>?, positionStart: Int, itemCount: Int) { getAdapter(sender)?.notifyItemRangeInserted(positionStart, itemCount) } @SuppressLint("NotifyDataSetChanged") override fun onItemRangeMoved(sender: ObservableList<T>?, fromPosition: Int, toPosition: Int, itemCount: Int) { if (itemCount == 1) getAdapter(sender)?.notifyItemMoved(fromPosition, toPosition) else getAdapter(sender)?.notifyDataSetChanged() } override fun onItemRangeRemoved(sender: ObservableList<T>?, positionStart: Int, itemCount: Int) { getAdapter(sender)?.notifyItemRangeRemoved(positionStart, itemCount) } fun subscribeTo(list: ObservableList<T>?) = list?.addOnListChangedCallback(this) fun unsubscribeFrom(list: ObservableList<T>?) = list?.removeOnListChangedCallback(this) }
0
Kotlin
0
0
d498fe5d18d7a02b87e8240a0429a32de2845614
4,496
demo-android
MIT License
database/src/main/java/info/metadude/android/eventfahrplan/database/repositories/MetaDatabaseRepository.kt
grote
114,628,676
false
null
package info.metadude.android.eventfahrplan.database.repositories import android.content.ContentValues import android.database.Cursor import android.database.SQLException import android.database.sqlite.SQLiteException import android.util.Log import info.metadude.android.eventfahrplan.database.contract.FahrplanContract.MetasTable import info.metadude.android.eventfahrplan.database.contract.FahrplanContract.MetasTable.Columns.* import info.metadude.android.eventfahrplan.database.extensions.delete import info.metadude.android.eventfahrplan.database.extensions.insert import info.metadude.android.eventfahrplan.database.extensions.read import info.metadude.android.eventfahrplan.database.models.Meta import info.metadude.android.eventfahrplan.database.sqliteopenhelper.MetaDBOpenHelper class MetaDatabaseRepository( private val sqLiteOpenHelper: MetaDBOpenHelper ) { fun insert(values: ContentValues) = with(sqLiteOpenHelper.writableDatabase) { try { beginTransaction() delete(MetasTable.NAME) insert(MetasTable.NAME, values) setTransactionSuccessful() } catch (ignore: SQLException) { // Fail silently } finally { endTransaction() close() sqLiteOpenHelper.close() } } fun query(): Meta { var meta = Meta() val database = sqLiteOpenHelper.readableDatabase val cursor: Cursor try { cursor = database.read(MetasTable.NAME) } catch (e: SQLiteException) { e.printStackTrace() database.close() sqLiteOpenHelper.close() return meta } if (cursor.count > 0) { cursor.moveToFirst() val columnIndexNumDays = cursor.getColumnIndex(NUM_DAYS) if (cursor.columnCount > columnIndexNumDays) { meta = meta.copy(numDays = cursor.getInt(columnIndexNumDays)) } val columnIndexVersion = cursor.getColumnIndex(VERSION) if (cursor.columnCount > columnIndexVersion) { meta = meta.copy(version = cursor.getString(columnIndexVersion)) } val columnIndexTitle = cursor.getColumnIndex(TITLE) if (cursor.columnCount > columnIndexTitle) { meta = meta.copy(title = cursor.getString(columnIndexTitle)) } val columnIndexSubTitle = cursor.getColumnIndex(SUBTITLE) if (cursor.columnCount > columnIndexSubTitle) { meta = meta.copy(subtitle = cursor.getString(columnIndexSubTitle)) } val columnIndexDayChangeHour = cursor.getColumnIndex(DAY_CHANGE_HOUR) if (cursor.columnCount > columnIndexDayChangeHour) { meta = meta.copy(dayChangeHour = cursor.getInt(columnIndexDayChangeHour)) } val columnIndexDayChangeMinute = cursor.getColumnIndex(DAY_CHANGE_MINUTE) if (cursor.columnCount > columnIndexDayChangeMinute) { meta = meta.copy(dayChangeMinute = cursor.getInt(columnIndexDayChangeMinute)) } val columnIndexEtag = cursor.getColumnIndex(ETAG) if (cursor.columnCount > columnIndexEtag) { meta = meta.copy(eTag = cursor.getString(columnIndexEtag)) } } Log.d(javaClass.name, "query(): $meta") cursor.close() database.close() sqLiteOpenHelper.close() return meta } }
0
null
1
3
761d339bf804698760db17ba00990e164f90cff2
3,530
EventFahrplan
Apache License 2.0
FtcRobotController/src/main/java/org/firstinspires/ftc/robotcontroller/internal/Core/Utility/TelMet.kt
Team5893
102,680,601
true
{"Java": 1277580, "Kotlin": 70411}
/* Team 5893 Direct Current Authors: <NAME> Date Created: 2017-11-01 Please adhere to these units when working in this project: Time: Milliseconds Distance: Centimeters Angle: Degrees (mathematical orientation) */ @file:Suppress("PackageDirectoryMismatch") package org.directcurrent.core import org.firstinspires.ftc.robotcore.external.Telemetry /** * Small Kotlin wrapper class for telemetry, allows non-OpMode classes to output telemetry */ @Suppress("unused") @Deprecated("Robot base LinearOpModes can now be accessed- just use that instead") class TelMet(private val _telMet: Telemetry) { /** * Writes message to OpMode telemetry with tag. * * Output looks like this: * tag: msg */ fun<T> tagWrite(tag: String, msg: T) { _telMet.addData(tag , msg) } /** * Writes message to OpMode telemetry and then appends newline */ fun write(msg: String) { _telMet.addLine(msg) } /** * Adds a new line to OpMode telemetry */ fun newLine() { _telMet.addLine() } /** * Clears OpMode telemetry */ fun clear() { _telMet.clear() } /** * Updates OpMode telemetry * * Call this in a loop- by default, telemetry only updates at the * end of the OpMode loop */ fun update() { _telMet.update() } }
1
Java
4
3
b1e236c53fecf8d86579a1aff27a830dc529f314
1,424
TeamCode
MIT License
app/src/main/java/cn/lvsong/lib/demo/CustomToolbarActivity.kt
Jooyer
243,921,264
false
null
package cn.lvsong.lib.demo import android.view.View import android.widget.Toast import cn.lvsong.lib.demo.databinding.ActivityCustomToolbarBinding import cn.lvsong.lib.ui.BaseActivity import cn.lvsong.lib.ui.BaseViewModel /** * 展示自定义Toolbar */ class CustomToolbarActivity : BaseActivity<ActivityCustomToolbarBinding, BaseViewModel>() { override fun needUseImmersive() = 1 override fun getLayoutId() = R.layout.activity_custom_toolbar override fun getViewBinging(view: View): ActivityCustomToolbarBinding { return ActivityCustomToolbarBinding.bind(view) } override fun setLogic() { } override fun bindEvent() { mBinding?.ct1?.setRightImageListener(View.OnClickListener { Toast.makeText(this,"点击右侧图片",Toast.LENGTH_SHORT).show() mBinding?.ct1?.alpha = 0.5f }) mBinding?.ct2?.setRightImageListener(View.OnClickListener { Toast.makeText(this,"点击右侧第一个图片",Toast.LENGTH_SHORT).show() }) mBinding?.ct2?.setRightImage2Listener(View.OnClickListener { Toast.makeText(this,"点击右侧倒数第二个图片",Toast.LENGTH_SHORT).show() }) mBinding?.ct3?.setMoreViewListener(View.OnClickListener { Toast.makeText(this,"点击了更多按钮",Toast.LENGTH_SHORT).show() }) mBinding?.ct12?.setRightImageListener(View.OnClickListener { // ct_13.setRightImageChecked(!ct_13.getRightImageChecked()) if (mBinding!!.ct12.getRightImageChecked()) { mBinding?.ct12?.setRightImageDrawable(R.drawable.normal) }else{ mBinding?.ct12?.setRightImageCheckedDrawable(R.drawable.select) } }) mBinding?.ct12?.setRightImage2Listener(View.OnClickListener { // ct_13.setRightImage2Checked(!ct_13.getRightImage2Checked()) if (mBinding!!.ct12.getRightImage2Checked()) { mBinding?.ct12?.setRightImage2Drawable(R.drawable.normal) }else{ mBinding?.ct12?.setRightImage2CheckedDrawable(R.drawable.select) } }) } }
0
Kotlin
3
9
da74777556a9cd278ba7a36f30db18393874caee
2,106
Basics
Apache License 2.0
plugins/completion-ml-ranking-models/src/com/jetbrains/completion/ml/ranker/ExperimentSwiftMLRankingProvider.kt
ingokegel
72,937,917
true
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.completion.ml.ranker import com.intellij.completion.ml.ranker.ExperimentModelProvider import com.intellij.internal.ml.catboost.CatBoostJarCompletionModelProvider import com.intellij.lang.Language class ExperimentSwiftMLRankingProvider : CatBoostJarCompletionModelProvider( CompletionRankingModelsBundle.message("ml.completion.experiment.model.swift"), "swift_features_exp", "swift_model_exp"), ExperimentModelProvider { override fun isLanguageSupported(language: Language): Boolean = language.id.compareTo("Swift", ignoreCase = true) == 0 override fun experimentGroupNumber(): Int = 13 }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
761
intellij-community
Apache License 2.0
mockup-processor/src/main/kotlin/mir/oslav/mockup/processor/generation/KSTypeExtensions.kt
miroslavhybler
691,973,907
false
{"Kotlin": 81659}
package mir.oslav.mockup.processor.generation import com.google.devtools.ksp.symbol.KSType import java.io.OutputStream /** * @author <NAME> <br> * created on 15.09.2023 */ operator fun OutputStream.plusAssign(other: String) { this.write(other.toByteArray()) } /** * True if this type is [Short] number, false otherwise * @since 1.0.0 */ val KSType.isShort: Boolean get() = declaration.qualifiedName?.asString() == "kotlin.Short" /** * True if this type is [Int] number, false otherwise * @since 1.0.0 */ val KSType.isInt: Boolean get() = declaration.qualifiedName?.asString() == "kotlin.Int" /** * True if this type is [Long] number, false otherwise * @since 1.0.0 */ val KSType.isLong: Boolean get() = declaration.qualifiedName?.asString() == "kotlin.Long" /** * True if this type is [Float] number, false otherwise * @since 1.0.0 */ val KSType.isFloat: Boolean get() = declaration.qualifiedName?.asString() == "kotlin.Float" /** * True if this type is [Double] number, false otherwise * @since 1.0.0 */ val KSType.isDouble: Boolean get() = declaration.qualifiedName?.asString() == "kotlin.Double" /** * True if this type is [Boolean], false otherwise * @since 1.0.0 */ val KSType.isBoolean: Boolean get() = declaration.qualifiedName?.asString() == "kotlin.Boolean" val KSType.isByte: Boolean get() = declaration.qualifiedName?.asString() == "kotlin.Byte" /** * True if this type is [String], false otherwise * @since 1.0.0 */ val KSType.isString: Boolean get() = declaration.qualifiedName?.asString() == "kotlin.String" /** * True if this type is [List], false otherwise * @since 1.0.0 */ val KSType.isList: Boolean get() = declaration.qualifiedName?.asString() == "kotlin.collections.List" /** * True if this type is [Array], false otherwise * @since 1.0.0 */ val KSType.isArray: Boolean get() = declaration.qualifiedName?.asString() == "kotlin.Array" /** * True if this type is [ShortArray], false otherwise * @since 1.0.0 */ val KSType.isShortArray: Boolean get() = declaration.qualifiedName?.asString() == "kotlin.ShortArray" /** * True if this type is [IntArray], false otherwise * @since 1.0.0 */ val KSType.isIntArray: Boolean get() = declaration.qualifiedName?.asString() == "kotlin.IntArray" /** * True if this type is [LongArray], false otherwise * @since 1.0.0 */ val KSType.isLongArray: Boolean get() = declaration.qualifiedName?.asString() == "kotlin.LongArray" /** * True if this type is [FloatArray], false otherwise * @since 1.0.0 */ val KSType.isFloatArray: Boolean get() = declaration.qualifiedName?.asString() == "kotlin.FloatArray" /** * True if this type is [DoubleArray], false otherwise * @since 1.0.0 */ val KSType.isDoubleArray: Boolean get() = declaration.qualifiedName?.asString() == "kotlin.DoubleArray" /** * True if this type is [CharArray], false otherwise * @since 1.0.0 */ val KSType.isCharArray: Boolean get() = declaration.qualifiedName?.asString() == "kotlin.CharArray" /** * True if this type is [ByteArray], false otherwise * @since 1.0.0 */ val KSType.isByteArray: Boolean get() = declaration.qualifiedName?.asString() == "kotlin.ByteArray" /** * True if this type is [BooleanArray], false otherwise * @since 1.0.0 */ val KSType.isBooleanArray: Boolean get() = declaration.qualifiedName?.asString() == "kotlin.BooleanArray" /** * @since 1.0.0 */ val KSType.isSimpleType: Boolean get() = this.isShort || this.isInt || this.isLong || this.isFloat || this.isDouble || this.isBoolean || this.isByte || this.isString /** * @since 1.0.0 */ val KSType.isFixedArrayType: Boolean get() = this.isShortArray || this.isIntArray || this.isLongArray || this.isFloatArray || this.isDoubleArray || this.isBooleanArray || this.isByteArray /** * @since 1.0.0 */ val KSType.isGenericCollectionType: Boolean get() = this.isArray || this.isList
0
Kotlin
0
0
ddd43bf9618bb242d74c393bbf025898b56509c5
4,124
ksp-mockup-processor
Apache License 2.0
kt/godot-library/src/main/kotlin/godot/gen/godot/PrimitiveMesh.kt
utopia-rise
289,462,532
false
null
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! @file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier", "UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST", "RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT", "RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate") package godot import godot.`annotation`.CoreTypeHelper import godot.`annotation`.CoreTypeLocalCopy import godot.`annotation`.GodotBaseType import godot.core.AABB import godot.core.TypeManager import godot.core.VariantArray import godot.core.VariantParser.ARRAY import godot.core.VariantParser.BOOL import godot.core.VariantParser.DOUBLE import godot.core.VariantParser.NIL import godot.core.VariantParser.OBJECT import godot.core.memory.TransferContext import godot.util.VoidPtr import kotlin.Any import kotlin.Boolean import kotlin.Double import kotlin.Float import kotlin.Int import kotlin.NotImplementedError import kotlin.Suppress import kotlin.Unit import kotlin.jvm.JvmName /** * Base class for all primitive meshes. Handles applying a [Material] to a primitive mesh. Examples * include [BoxMesh], [CapsuleMesh], [CylinderMesh], [PlaneMesh], [PrismMesh], and [SphereMesh]. */ @GodotBaseType public open class PrimitiveMesh : Mesh() { /** * The current [Material] of the primitive mesh. */ public final inline var material: Material? @JvmName("materialProperty") get() = getMaterial() @JvmName("materialProperty") set(`value`) { setMaterial(value) } /** * Overrides the [AABB] with one defined by user for use with frustum culling. Especially useful * to avoid unexpected culling when using a shader to offset vertices. */ @CoreTypeLocalCopy public final inline var customAabb: AABB @JvmName("customAabbProperty") get() = getCustomAabb() @JvmName("customAabbProperty") set(`value`) { setCustomAabb(value) } /** * If set, the order of the vertices in each triangle are reversed resulting in the backside of * the mesh being drawn. * This gives the same result as using [BaseMaterial3D.CULL_FRONT] in [BaseMaterial3D.cullMode]. */ public final inline var flipFaces: Boolean @JvmName("flipFacesProperty") get() = getFlipFaces() @JvmName("flipFacesProperty") set(`value`) { setFlipFaces(value) } /** * If set, generates UV2 UV coordinates applying a padding using the [uv2Padding] setting. UV2 is * needed for lightmapping. */ public final inline var addUv2: Boolean @JvmName("addUv2Property") get() = getAddUv2() @JvmName("addUv2Property") set(`value`) { setAddUv2(value) } /** * If [addUv2] is set, specifies the padding in pixels applied along seams of the mesh. Lower * padding values allow making better use of the lightmap texture (resulting in higher texel * density), but may introduce visible lightmap bleeding along edges. * If the size of the lightmap texture can't be determined when generating the mesh, UV2 is * calculated assuming a texture size of 1024x1024. */ public final inline var uv2Padding: Float @JvmName("uv2PaddingProperty") get() = getUv2Padding() @JvmName("uv2PaddingProperty") set(`value`) { setUv2Padding(value) } public override fun new(scriptIndex: Int): Unit { callConstructor(ENGINECLASS_PRIMITIVEMESH, scriptIndex) } /** * Overrides the [AABB] with one defined by user for use with frustum culling. Especially useful * to avoid unexpected culling when using a shader to offset vertices. * * This is a helper function to make dealing with local copies easier. * * For more information, see our * [documentation](https://godot-kotl.in/en/stable/user-guide/api-differences/#core-types). * * Allow to directly modify the local copy of the property and assign it back to the Object. * * Prefer that over writing: * `````` * val myCoreType = primitivemesh.customAabb * //Your changes * primitivemesh.customAabb = myCoreType * `````` */ @CoreTypeHelper public final fun customAabbMutate(block: AABB.() -> Unit): AABB = customAabb.apply{ block(this) customAabb = this } /** * Override this method to customize how this primitive mesh should be generated. Should return an * [Array] where each element is another Array of values required for the mesh (see the * [Mesh.ArrayType] constants). */ public open fun _createMeshArray(): VariantArray<Any?> { throw NotImplementedError("_create_mesh_array is not implemented for PrimitiveMesh") } public final fun setMaterial(material: Material?): Unit { TransferContext.writeArguments(OBJECT to material) TransferContext.callMethod(rawPtr, MethodBindings.setMaterialPtr, NIL) } public final fun getMaterial(): Material? { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getMaterialPtr, OBJECT) return (TransferContext.readReturnValue(OBJECT) as Material?) } /** * Returns mesh arrays used to constitute surface of [Mesh]. The result can be passed to * [ArrayMesh.addSurfaceFromArrays] to create a new surface. For example: * * gdscript: * ```gdscript * var c = CylinderMesh.new() * var arr_mesh = ArrayMesh.new() * arr_mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, c.get_mesh_arrays()) * ``` * csharp: * ```csharp * var c = new CylinderMesh(); * var arrMesh = new ArrayMesh(); * arrMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, c.GetMeshArrays()); * ``` */ public final fun getMeshArrays(): VariantArray<Any?> { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getMeshArraysPtr, ARRAY) return (TransferContext.readReturnValue(ARRAY) as VariantArray<Any?>) } public final fun setCustomAabb(aabb: AABB): Unit { TransferContext.writeArguments(godot.core.VariantParser.AABB to aabb) TransferContext.callMethod(rawPtr, MethodBindings.setCustomAabbPtr, NIL) } public final fun getCustomAabb(): AABB { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getCustomAabbPtr, godot.core.VariantParser.AABB) return (TransferContext.readReturnValue(godot.core.VariantParser.AABB) as AABB) } public final fun setFlipFaces(flipFaces: Boolean): Unit { TransferContext.writeArguments(BOOL to flipFaces) TransferContext.callMethod(rawPtr, MethodBindings.setFlipFacesPtr, NIL) } public final fun getFlipFaces(): Boolean { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getFlipFacesPtr, BOOL) return (TransferContext.readReturnValue(BOOL) as Boolean) } public final fun setAddUv2(addUv2: Boolean): Unit { TransferContext.writeArguments(BOOL to addUv2) TransferContext.callMethod(rawPtr, MethodBindings.setAddUv2Ptr, NIL) } public final fun getAddUv2(): Boolean { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getAddUv2Ptr, BOOL) return (TransferContext.readReturnValue(BOOL) as Boolean) } public final fun setUv2Padding(uv2Padding: Float): Unit { TransferContext.writeArguments(DOUBLE to uv2Padding.toDouble()) TransferContext.callMethod(rawPtr, MethodBindings.setUv2PaddingPtr, NIL) } public final fun getUv2Padding(): Float { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getUv2PaddingPtr, DOUBLE) return (TransferContext.readReturnValue(DOUBLE) as Double).toFloat() } /** * Request an update of this primitive mesh based on its properties. */ public final fun requestUpdate(): Unit { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.requestUpdatePtr, NIL) } public companion object internal object MethodBindings { public val setMaterialPtr: VoidPtr = TypeManager.getMethodBindPtr("PrimitiveMesh", "set_material", 2757459619) public val getMaterialPtr: VoidPtr = TypeManager.getMethodBindPtr("PrimitiveMesh", "get_material", 5934680) public val getMeshArraysPtr: VoidPtr = TypeManager.getMethodBindPtr("PrimitiveMesh", "get_mesh_arrays", 3995934104) public val setCustomAabbPtr: VoidPtr = TypeManager.getMethodBindPtr("PrimitiveMesh", "set_custom_aabb", 259215842) public val getCustomAabbPtr: VoidPtr = TypeManager.getMethodBindPtr("PrimitiveMesh", "get_custom_aabb", 1068685055) public val setFlipFacesPtr: VoidPtr = TypeManager.getMethodBindPtr("PrimitiveMesh", "set_flip_faces", 2586408642) public val getFlipFacesPtr: VoidPtr = TypeManager.getMethodBindPtr("PrimitiveMesh", "get_flip_faces", 36873697) public val setAddUv2Ptr: VoidPtr = TypeManager.getMethodBindPtr("PrimitiveMesh", "set_add_uv2", 2586408642) public val getAddUv2Ptr: VoidPtr = TypeManager.getMethodBindPtr("PrimitiveMesh", "get_add_uv2", 36873697) public val setUv2PaddingPtr: VoidPtr = TypeManager.getMethodBindPtr("PrimitiveMesh", "set_uv2_padding", 373806689) public val getUv2PaddingPtr: VoidPtr = TypeManager.getMethodBindPtr("PrimitiveMesh", "get_uv2_padding", 1740695150) public val requestUpdatePtr: VoidPtr = TypeManager.getMethodBindPtr("PrimitiveMesh", "request_update", 3218959716) } }
49
null
45
634
ac2a1bd5ea931725e2ed19eb5093dea171962e3f
9,517
godot-kotlin-jvm
MIT License
kplotandroidlib/src/test/java/dev/curlybraces/kplot/LineChartViewLogicTests.kt
PravSonawane
223,865,951
false
null
package dev.curlybraces.kplot import android.os.Build import android.view.View.MeasureSpec.* import dev.curlybraces.kplotandroidlib.R import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(sdk = [Build.VERSION_CODES.O_MR1]) class LineChartViewLogicTests { @Test fun given_exact_width_greater_than_screen_width_when_measured_should_use_given_width() { val testActivity = Robolectric.buildActivity(TestActivity::class.java).create().start().resume().get() val newLineChartView = testActivity.findViewById<LineChartView>(R.id.lineChart) val expectedWidth = getScreenWidthPx(testActivity.resources) + 20 newLineChartView.onMeasure(makeMeasureSpec(expectedWidth, EXACTLY), makeMeasureSpec(12, EXACTLY)) assertEquals(expectedWidth, newLineChartView.measuredWidth) } @Test fun given_exact_height_greater_than_screen_height_when_measured_should_use_given_height() { val testActivity = Robolectric.buildActivity(TestActivity::class.java).create().start().resume().get() val newLineChartView = testActivity.findViewById<LineChartView>(R.id.lineChart) val expectedHeight = getScreenHeightPx(testActivity.resources) + 20 newLineChartView.onMeasure(makeMeasureSpec(12, EXACTLY), makeMeasureSpec(expectedHeight, EXACTLY)) assertEquals(expectedHeight, newLineChartView.measuredHeight) } @Test fun given_exact_width_less_than_screen_width_when_measured_should_use_given_width() { val testActivity = Robolectric.buildActivity(TestActivity::class.java).create().start().resume().get() val newLineChartView = testActivity.findViewById<LineChartView>(R.id.lineChart) val expectedWidth = getScreenWidthPx(testActivity.resources) - 20 newLineChartView.onMeasure(makeMeasureSpec(expectedWidth, EXACTLY), makeMeasureSpec(12, EXACTLY)) assertEquals(expectedWidth, newLineChartView.measuredWidth) } @Test fun given_exact_height_less_than_screen_height_when_measured_should_use_given_height() { val testActivity = Robolectric.buildActivity(TestActivity::class.java).create().start().resume().get() val newLineChartView = testActivity.findViewById<LineChartView>(R.id.lineChart) val expectedHeight = getScreenHeightPx(testActivity.resources) - 20 newLineChartView.onMeasure(makeMeasureSpec(12, EXACTLY), makeMeasureSpec(expectedHeight, EXACTLY)) assertEquals(expectedHeight, newLineChartView.measuredHeight) } @Test fun given_exact_width_equal_to_screen_width_when_measured_should_use_given_width() { val testActivity = Robolectric.buildActivity(TestActivity::class.java).create().start().resume().get() val newLineChartView = testActivity.findViewById<LineChartView>(R.id.lineChart) val expectedWidth = getScreenWidthPx(testActivity.resources) newLineChartView.onMeasure(makeMeasureSpec(expectedWidth, EXACTLY), makeMeasureSpec(12, EXACTLY)) assertEquals(expectedWidth, newLineChartView.measuredWidth) } @Test fun given_exact_height_equal_to_screen_height_when_measured_should_use_given_height() { val testActivity = Robolectric.buildActivity(TestActivity::class.java).create().start().resume().get() val newLineChartView = testActivity.findViewById<LineChartView>(R.id.lineChart) val expectedHeight = getScreenHeightPx(testActivity.resources) newLineChartView.onMeasure(makeMeasureSpec(12, EXACTLY), makeMeasureSpec(expectedHeight, EXACTLY)) assertEquals(expectedHeight, newLineChartView.measuredHeight) } @Test fun given_at_most_width_when_measured_should_use_available_width() { val testActivity = Robolectric.buildActivity(TestActivity::class.java).create().start().resume().get() val newLineChartView = testActivity.findViewById<LineChartView>(R.id.lineChart) val expectedWidth = getScreenWidthPx(testActivity.resources) newLineChartView.onMeasure(makeMeasureSpec(expectedWidth, AT_MOST), makeMeasureSpec(12, EXACTLY)) assertEquals(expectedWidth, newLineChartView.measuredWidth) } @Test fun given_at_most_height_when_measured_should_use_available_height() { val testActivity = Robolectric.buildActivity(TestActivity::class.java).create().start().resume().get() val newLineChartView = testActivity.findViewById<LineChartView>(R.id.lineChart) val expectedHeight = getScreenHeightPx(testActivity.resources) newLineChartView.onMeasure(makeMeasureSpec(12, EXACTLY), makeMeasureSpec(expectedHeight, AT_MOST)) assertEquals(expectedHeight, newLineChartView.measuredHeight) } }
1
Kotlin
0
0
516e35f3fc7679a59d01b113cbb3305f9de6da40
4,876
kplot
Apache License 2.0
core/src/commonMain/kotlin/work/socialhub/kslack/api/methods/request/usergroups/UsergroupsUpdateRequest.kt
uakihir0
794,979,552
false
{"Kotlin": 1210021, "Ruby": 2164, "Shell": 2095, "Makefile": 316}
package com.github.seratch.jslack.api.methods.request.usergroups import com.github.seratch.jslack.api.methods.SlackApiRequest class UsergroupsUpdateRequest internal constructor( /** * Authentication token. Requires scope: `usergroups:write` */ override var token: String?, /** * The encoded ID of the User Group to update. */ var usergroup: String?, /** * A name for the User Group. Must be unique among User Groups. */ var name: String?, /** * A mention handle. Must be unique among channels, users and User Groups. */ var handle: String?, /** * A short description of the User Group. */ var description: String?, /** * A comma separated string of encoded channel IDs for which the User Group uses as a default. */ var channels: Array<String>?, /** * Include the number of users in the User Group. */ var isIncludeCount: Boolean ) : SlackApiRequest { class UsergroupsUpdateRequestBuilder internal constructor() { private var token: String? = null private var usergroup: String? = null private var name: String? = null private var handle: String? = null private var description: String? = null private var channels: Array<String>? = null private var includeCount = false fun token(token: String?): UsergroupsUpdateRequestBuilder { this.token = token return this } fun usergroup(usergroup: String?): UsergroupsUpdateRequestBuilder { this.usergroup = usergroup return this } fun name(name: String?): UsergroupsUpdateRequestBuilder { this.name = name return this } fun handle(handle: String?): UsergroupsUpdateRequestBuilder { this.handle = handle return this } fun description(description: String?): UsergroupsUpdateRequestBuilder { this.description = description return this } fun channels(channels: Array<String>?): UsergroupsUpdateRequestBuilder { this.channels = channels return this } fun includeCount(includeCount: Boolean): UsergroupsUpdateRequestBuilder { this.includeCount = includeCount return this } fun build(): UsergroupsUpdateRequest { return UsergroupsUpdateRequest(token, usergroup, name, handle, description, channels, includeCount) } override fun toString(): String { return "UsergroupsUpdateRequest.UsergroupsUpdateRequestBuilder(token=" + this.token + ", usergroup=" + this.usergroup + ", name=" + this.name + ", handle=" + this.handle + ", description=" + this.description + ", channels=" + this.channels + ", includeCount=" + this.includeCount + ")" } } companion object { fun builder(): UsergroupsUpdateRequestBuilder { return UsergroupsUpdateRequestBuilder() } } }
5
Kotlin
0
0
4d1299164adc8b8e638b02e0ca7e46afb10709f8
3,060
kslack
MIT License
eec-core/src/main/kotlin/com/eec_cn/client4k/beans/global.kt
ExplodingDragon
357,027,345
false
{"Kotlin": 41451, "CSS": 27960}
package com.eec_cn.client4k.beans import kotlinx.serialization.Serializable @Serializable data class DataWrapperBean( val code: Int, var `data`: String, val message: String, val status: Int, val success: Boolean ) @Serializable data class NothingBean(val nothing:String = "")
0
Kotlin
0
0
53fe3ba93ae3fe1958c4737d39f99acc81ca01f2
299
EecTools
MIT License
app/src/main/java/pl/poznan/put/fc/tutorial01/MainActivity.kt
writ3it
187,470,182
false
null
package pl.poznan.put.fc.tutorial01 import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import pl.poznan.put.fc.tutorial01.Tracking.Track class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Track.initialize(applicationContext) setContentView(R.layout.activity_main) } fun onClickMeBtn(view: View?){ Track.buttonClicked("Click Me!") val intent = Intent(this, SecondActivity::class.java) startActivity(intent) } }
0
Kotlin
0
0
a134de010dcb1f14d5bc1d42e39c0fa7d52ab333
635
android-firebase-tutorial01
MIT License
demo-app/src/main/java/io/opentelemetry/android/demo/theme/Color.kt
open-telemetry
669,220,109
false
{"Java": 473958, "Kotlin": 74861}
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.android.demo.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
52
Java
20
97
f2fe8aea1b4eb5a1e7e28e3045e6fb4aed400155
377
opentelemetry-android
Apache License 2.0
sample/subc/src/main/java/club/fdawei/nrouter/sample/subc/CActivity.kt
fangdawei
188,443,333
false
null
package club.fdawei.nrouter.sample.subc import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.app.AppCompatActivity import club.fdawei.nrouter.annotation.Autowired import club.fdawei.nrouter.annotation.Route import club.fdawei.nrouter.api.NRouter import club.fdawei.nrouter.sample.base.IPageLogger import kotlinx.android.synthetic.main.activity_c.* @Route(path = "/subc/page/home", desc = "C页面") class CActivity : AppCompatActivity() { @Autowired var from: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_c) NRouter.injector().inject(this) tvFrom.text = String.format("from %s", from ?: "unknown") tvMainPageBtn.setOnClickListener { NRouter.route("/main/page/home").go() } tvAPageBtn.setOnClickListener { NRouter.route("/suba/page/home").go() } tvBPageBtn.setOnClickListener { NRouter.route("/subb/page/home").go() } tvFinishBtn.setOnClickListener { setResult(10000) finish() } val mainFragment = NRouter.route("/main/fragment/home") .withString("from", "CActivity") .get(Fragment::class) if (mainFragment != null) { supportFragmentManager .beginTransaction() .add(R.id.flContainer, mainFragment) .commit() } NRouter.route("/common/page/logger").get(IPageLogger::class)?.logPage("CActivity") } }
0
Kotlin
1
3
3fcab2bdfbea45a322daaaeaab79bae844d1b2ec
1,620
NRouter
Apache License 2.0
shared/src/commonMain/kotlin/com/fmmobile/upcomingmovieskmp/data/datasource/source/remote/response/GenreListResponse.kt
FelipeFMMobile
639,450,039
false
{"Kotlin": 51051, "Swift": 12441}
package com.fmmobile.upcomingmovieskmp.data.datasource.source.remote.response import com.fmmobile.upcomingmovieskmp.data.datasource.models.IGenreListModel import com.fmmobile.upcomingmovieskmp.data.datasource.models.IGenreModel import kotlinx.serialization.Serializable @Serializable data class GenreListResponse( override val genres: List<GenreResponse> ): IGenreListModel @Serializable data class GenreResponse( override val id: Long, override val name: String ): IGenreModel
0
Kotlin
0
0
9a946928c39d461b7e508e8685a9532b8f1d7a32
492
UpcomingMoviesKMP
Apache License 2.0
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/xquery/XQueryCompAttrConstructorPsiImpl.kt
rhdunn
62,201,764
false
{"Kotlin": 8262637, "XQuery": 996770, "HTML": 39377, "XSLT": 6853}
/* * Copyright (C) 2016, 2020-2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 uk.co.reecedunn.intellij.plugin.xquery.psi.impl.xquery import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import uk.co.reecedunn.intellij.plugin.core.sequences.children import uk.co.reecedunn.intellij.plugin.xdm.types.XdmElementNode import uk.co.reecedunn.intellij.plugin.xdm.types.XdmNode import uk.co.reecedunn.intellij.plugin.xdm.types.XsAnyAtomicType import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathExpr import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryCompAttrConstructor class XQueryCompAttrConstructorPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), XQueryCompAttrConstructor { // region XpmExpression override val expressionElement: PsiElement? = null // endregion // region XdmAttributeNode override val nodeName: XsQNameValue? get() = children().filterIsInstance<XsQNameValue>().firstOrNull() override val parentNode: XdmNode? get() = when (val parent = parent) { is XdmElementNode -> parent is XPathExpr -> parent.parent as? XdmElementNode else -> null } override val stringValue: String? get() = null override val typedValue: XsAnyAtomicType? get() = null // endregion }
49
Kotlin
9
25
d8d460d31334e8b2376a22f3832a20b2845bacab
1,974
xquery-intellij-plugin
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsadjudicationsinsightsapi/config/ApiExceptionHandler.kt
ministryofjustice
643,829,689
false
null
package uk.gov.justice.digital.hmpps.hmppsadjudicationsinsightsapi.config import com.amazonaws.services.s3.model.AmazonS3Exception import com.fasterxml.jackson.annotation.JsonInclude import io.swagger.v3.oas.annotations.media.Schema import jakarta.validation.ValidationException import org.slf4j.LoggerFactory import org.springframework.http.HttpStatus import org.springframework.http.HttpStatus.BAD_REQUEST import org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.ExceptionHandler import org.springframework.web.bind.annotation.RestControllerAdvice @RestControllerAdvice class ApiExceptionHandler { @ExceptionHandler(ValidationException::class) fun handleValidationException(e: Exception): ResponseEntity<ErrorResponse> { log.info("Validation exception: {}", e.message) return ResponseEntity .status(BAD_REQUEST) .body( ErrorResponse( status = BAD_REQUEST, userMessage = "Validation failure: ${e.message}", developerMessage = e.message, ), ) } @ExceptionHandler(java.lang.Exception::class) fun handleException(e: java.lang.Exception): ResponseEntity<ErrorResponse?>? { log.error("Unexpected exception", e) return ResponseEntity .status(INTERNAL_SERVER_ERROR) .body( ErrorResponse( status = INTERNAL_SERVER_ERROR, userMessage = "Unexpected error: ${e.message}", developerMessage = e.message, ), ) } @ExceptionHandler(AmazonS3Exception::class) fun handleValidationAmazonS3Exception(e: AmazonS3Exception): ResponseEntity<ErrorResponse> { log.info("Amazon S3 Bucket exception: {}", e.message) return ResponseEntity .status(INTERNAL_SERVER_ERROR) .body( ErrorResponse( status = INTERNAL_SERVER_ERROR, userMessage = "Amazon S3 Bucket failure: ${e.message}", developerMessage = e.message, ), ) } companion object { private val log = LoggerFactory.getLogger(this::class.java) } } @JsonInclude(JsonInclude.Include.NON_NULL) @Schema(description = "Error Response") data class ErrorResponse( @Schema(description = "Status of Error", example = "500", required = true) val status: Int, @Schema(description = "Error Code", example = "500", required = false) val errorCode: Int? = null, @Schema(description = "User Message of error", example = "Bad Data", required = false, maxLength = 200, pattern = "^[a-zA-Z\\d. _-]{1,200}\$") val userMessage: String? = null, @Schema(description = "More detailed error message", example = "This is a stack trace", required = false, maxLength = 4000, pattern = "^[a-zA-Z\\d. _-]*\$") val developerMessage: String? = null, @Schema(description = "More information about the error", example = "More info", required = false, maxLength = 4000, pattern = "^[a-zA-Z\\d. _-]*\$") val moreInfo: String? = null, ) { constructor( status: HttpStatus, errorCode: Int? = null, userMessage: String? = null, developerMessage: String? = null, moreInfo: String? = null, ) : this(status.value(), errorCode, userMessage, developerMessage, moreInfo) }
1
Kotlin
0
0
7c2a29af2377433cebf759be87a771f06a3d59b5
3,251
hmpps-adjudications-insights-api
MIT License
feature-game/src/main/java/com/mityushovn/miningquiz/game_feature/api/QuizActivity.kt
NikitaMityushov
431,692,189
false
{"Kotlin": 281441}
package com.mityushovn.miningquiz.game_feature.api import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.PersistableBundle import android.widget.Toast import androidx.activity.viewModels import com.mityushovn.miningquiz.game_feature.R import com.mityushovn.miningquiz.game_feature.internal.di.components.DaggerGameComponent import com.mityushovn.miningquiz.game_feature.internal.di.components.GameComponent import com.mityushovn.miningquiz.game_feature.internal.presentation.GameEngine import com.mityushovn.miningquiz.game_feature.internal.presentation.GameEngineFactory import com.mityushovn.miningquiz.module_injector.extensions.findDependencies import com.mityushovn.miningquiz.utils.collectEventOnLifecycle import javax.inject.Inject private const val EXAM_OR_TOPIC_ID = "exam_or_topic_id" private const val GAME_MODE = "game_mode" private const val GAME_STARTED = "game_started" class QuizActivity : AppCompatActivity() { private var _component: GameComponent? = null internal val component: GameComponent get() = _component!! // essential to init because view model is shared with GameFragment @Inject internal lateinit var vmFactory: GameEngineFactory private val gameEngine by viewModels<GameEngine> { vmFactory } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val gameMode = intent.extras?.get(GAME_MODE) as GameMode val examOrTopicId = intent.extras?.get(EXAM_OR_TOPIC_ID) as Int _component = DaggerGameComponent.factory() .create(findDependencies(), application, gameMode, examOrTopicId) _component?.inject(this) setContentView(R.layout.activity_quiz) // configure DI if (savedInstanceState == null) { // start game, you must pass id of topic or exam and game mode in the startGame method of GameEngine gameEngine.startGame() } gameEngine.showIsAttemptAddedToast.collectEventOnLifecycle(this) { showIsAttemptAddedToast(it) } } override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) { super.onSaveInstanceState(outState, outPersistentState) outState.putBoolean(GAME_STARTED, true) } override fun onBackPressed() { // disable } /** * Creates Toast depends on boolean argument of successfully added attempt. */ private fun showIsAttemptAddedToast(it: Boolean) { if (it) { Toast.makeText( this, application.resources.getString(R.string.attempt_succ_added), Toast.LENGTH_SHORT ).show() // Attempt successfully added } else { Toast.makeText( this, application.resources.getString(R.string.attempt_failed_saved), Toast.LENGTH_SHORT ).show() // Attempt would not be saved } } override fun onDestroy() { super.onDestroy() _component = null } }
10
Kotlin
0
0
9013e560b6d9434da4c263ccaa9f033bd0831855
3,115
MiningQuiz
MIT License
app/src/main/java/com/kansus/teammaker/android/ui/games/GamesAdapter.kt
CharlesNascimento
181,741,814
false
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 80, "XML": 30, "Java": 1}
package com.kansus.teammaker.android.ui.games import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.kansus.teammaker.R import com.kansus.teammaker.android.Navigator import com.kansus.teammaker.android.extension.inflate import com.kansus.teammaker.domain.model.Game import kotlinx.android.synthetic.main.fragment_games_item.view.* import kotlin.properties.Delegates /** * */ class GamesAdapter( games: List<Game>, internal var selectionListener: (Game, Navigator.Extras) -> Unit = { _, _ -> } ) : RecyclerView.Adapter<GamesAdapter.ViewHolder>() { internal var mValues: List<Game> by Delegates.observable(emptyList()) { _, _, _ -> notifyDataSetChanged() } init { mValues = games } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder(parent.inflate(R.layout.fragment_games_item)) override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) = viewHolder.bind(mValues[position], selectionListener) override fun getItemCount(): Int = mValues.size inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(movieView: Game, clickListener: (Game, Navigator.Extras) -> Unit) { itemView.item_number.text = movieView.id.toString() itemView.content.text = movieView.name itemView.setOnClickListener { clickListener(movieView, Navigator.Extras(itemView.item_number)) } } } }
0
Kotlin
0
1
db123b4e65d012eb65a2da4f787fa8ddf278e193
1,525
TeamMaker
MIT License
ok-marketplace-mp-common-cor/src/commonTest/kotlin/CorBaseTest.kt
otuskotlin
375,767,209
false
null
package com.polyakovworkbox.tasktracker.common.handlers import com.polyakovworkbox.tasktracker.common.cor.ICorChainDsl import kotlin.test.Test class CorBaseTest { @Test fun createCor() { } companion object { val chain = com.polyakovworkbox.tasktracker.common.cor.chain<TestContext> { worker { title = "Инициализация статуса" description = "При старте обработки цепочки, статус еще не установлен. Проверяем его" on { status == CorStatuses.NONE } handle { status = CorStatuses.RUNNING } except { status = CorStatuses.ERROR } } chain { on { status == CorStatuses.RUNNING } worker( title = "Лямбда обработчик", description = "Пример использования обработчика в виде лямбды" ) { some += 4 } } parallel { on { some < 15 } worker(title = "Increment some") { some++ } } printResult() }.build() } } private fun ICorChainDsl<TestContext>.printResult() = worker(title = "Print example") { println("some = $some") } data class TestContext( var status: CorStatuses = CorStatuses.NONE, var some: Int = Int.MIN_VALUE ) { } enum class CorStatuses { NONE, RUNNING, FAILING, DONE, ERROR }
1
null
5
9
f7b000e861fb35b5e0a641782fb7fe746814da31
1,548
202105-otuskotlin-marketplace
MIT License
app/src/main/java/vn/thailam/wheresmyremote/di/DatabaseModule.kt
ngthailam
629,044,502
false
null
package vn.thailam.wheresmyremote.di import android.content.Context import androidx.room.Room import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import vn.thailam.wheresmyremote.data.db.AppRoomDatabase import vn.thailam.wheresmyremote.data.db.MIGRATION_2_3 import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object DatabaseModule { @Singleton @Provides fun provideAppRoomDatabase( @ApplicationContext app: Context ) = Room.databaseBuilder( app, AppRoomDatabase::class.java, AppRoomDatabase.NAME ) .addMigrations(MIGRATION_2_3) // .fallbackToDestructiveMigration() .build() @Provides fun providePlaceDao(db: AppRoomDatabase) = db.placeDao() @Provides fun provideItemDao(db: AppRoomDatabase) = db.itemDao() }
0
Kotlin
0
0
dc3f7a5337dd6df5e8b51bc24ed7108cb4bb3ff0
955
WheresMyRemote
MIT License
src/test/kotlin/br/com/jiratorio/testlibrary/extension/ArchUnitExtension.kt
jirareport
126,883,660
false
{"Kotlin": 628412, "Dockerfile": 302}
package br.com.jiratorio.testlibrary.extension import com.tngtech.archunit.base.DescribedPredicate import com.tngtech.archunit.core.domain.JavaClass import com.tngtech.archunit.core.domain.JavaModifier import com.tngtech.archunit.lang.syntax.elements.ClassesThat import com.tngtech.archunit.lang.syntax.elements.GivenMethodsConjunction import com.tngtech.archunit.lang.syntax.elements.MethodsThat fun <CONJUNCTION> ClassesThat<CONJUNCTION>.areNotInnerClass(): CONJUNCTION = areNotAssignableTo(AreInnerClass) private object AreInnerClass : DescribedPredicate<JavaClass>("inner class") { override fun apply(input: JavaClass): Boolean = input.isInnerClass || input.name.contains("$") } fun <CONJUNCTION : GivenMethodsConjunction> MethodsThat<CONJUNCTION>.areNotSynthetic(): CONJUNCTION = this.doNotHaveModifier(JavaModifier.SYNTHETIC)
12
Kotlin
12
21
845540e238f47fbd05c1f7f6839152545521c63e
858
jirareport
MIT License
agent-instrumentation/src/jvmMain/kotlin/com/epam/drill/agent/instrument/reactor/transformers/SchedulersTransformerObject.kt
Drill4J
598,096,157
false
{"Kotlin": 1348086, "C": 329462, "C++": 295093, "HTML": 5568}
/** * Copyright 2020 - 2022 EPAM Systems * * 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.epam.drill.agent.instrument.reactor.transformers import com.epam.drill.agent.instrument.TransformerObject import com.epam.drill.agent.instrument.AbstractTransformerObject import com.epam.drill.agent.instrument.reactor.PropagatedDrillRequestRunnable import com.epam.drill.agent.instrument.servers.SCHEDULERS_CLASS_NAME import com.epam.drill.common.agent.request.DrillRequest import com.epam.drill.common.agent.request.RequestHolder import javassist.CtBehavior import javassist.CtClass import mu.KotlinLogging /** * Transformer for {@link reactor.core.scheduler.Schedulers}. * It propagates {@link DrillRequest} using {@link PropagatedDrillRequestRunnable} on the method {@link Schedulers#onSchedule}. */ abstract class SchedulersTransformerObject : TransformerObject, RequestHolder, AbstractTransformerObject() { override val logger = KotlinLogging.logger {} override fun permit(className: String?, superName: String?, interfaces: Array<String?>) = className == SCHEDULERS_CLASS_NAME override fun transform(className: String, ctClass: CtClass) { ctClass.getDeclaredMethod("onSchedule").insertCatching( CtBehavior::insertBefore, """ ${DrillRequest::class.java.name} drillRequest = ${this::class.java.name}.INSTANCE.${RequestHolder::retrieve.name}(); if (drillRequest != null) $1 = new ${PropagatedDrillRequestRunnable::class.java.name}(drillRequest, ${this::class.java.name}.INSTANCE, $1); """.trimIndent() ) } }
4
Kotlin
0
1
27dc5ada546a3c738ea62ebaa0cefcc28e5e23ee
2,205
lib-jvm-shared
Apache License 2.0
app/src/main/java/com/example/emafoods/feature/pending/presentation/PendingFoodScreen.kt
vladr7
625,532,633
false
null
package com.example.emafoods.feature.pending.presentation import android.content.Context import android.widget.Toast import androidx.compose.animation.animateColorAsState import androidx.compose.animation.animateContentSize import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.Spring import androidx.compose.animation.core.spring import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.detectTransformGestures import androidx.compose.foundation.gestures.draggable import androidx.compose.foundation.gestures.rememberDraggableState 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.heightIn import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.Card import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Check import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Pinch import androidx.compose.material.icons.filled.SwipeLeft import androidx.compose.material.icons.filled.SwipeRight import androidx.compose.material.icons.outlined.Pinch import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme 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.draw.alpha import androidx.compose.ui.draw.shadow import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shadow import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import coil.compose.SubcomposeAsyncImage import coil.request.ImageRequest import com.example.emafoods.R import com.example.emafoods.core.presentation.animations.LottieAnimationContent import com.example.emafoods.core.presentation.animations.bounceClick import com.example.emafoods.core.presentation.features.addfood.BasicTitle import com.example.emafoods.core.presentation.models.FoodViewData import com.example.emafoods.feature.addfood.presentation.ingredients.models.IngredientViewData import com.example.emafoods.feature.addfood.presentation.insert.CategoryTypeRow import com.example.emafoods.feature.addfood.presentation.insert.IngredientsReadOnlyContent import com.example.emafoods.feature.game.presentation.ScrollArrow import com.example.emafoods.feature.generatefood.presentation.LoadingCookingAnimation import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlin.random.Random @Composable fun PendingFoodRoute( modifier: Modifier = Modifier, viewModel: PendingFoodViewModel = hiltViewModel() ) { val context = LocalContext.current val state by viewModel.state.collectAsStateWithLifecycle() PendingFoodScreen( modifier = modifier, food = state.currentFood, error = state.error, showError = state.showError, onSwipeLeft = { viewModel.onSwipeLeft() }, onSwipeRight = { viewModel.onSwipeRight() }, context = context, onErrorShown = { viewModel.onResetMessageStates() }, showMovedSuccessfully = state.showMovedSuccessfully, showDeletedSuccessfully = state.showDeleteSuccessfully, ingredientsList = state.currentFood.ingredients, ) } @Composable fun PendingFoodScreen( modifier: Modifier = Modifier, food: FoodViewData, onSwipeLeft: () -> Unit, onSwipeRight: () -> Unit, error: String, context: Context, showError: Boolean, onErrorShown: () -> Unit, showMovedSuccessfully: Boolean, showDeletedSuccessfully: Boolean, ingredientsList: List<IngredientViewData>, ) { if (showError) { Toast.makeText(context, error, Toast.LENGTH_SHORT).show() onErrorShown() } if (showMovedSuccessfully) { Toast.makeText( context, stringResource(R.string.recipe_has_been_accepted), Toast.LENGTH_SHORT ).show() onErrorShown() } if (showDeletedSuccessfully) { Toast.makeText( context, stringResource(R.string.recipe_has_been_declined), Toast.LENGTH_SHORT ).show() onErrorShown() } val scrollState = rememberScrollState() val coroutineScope = rememberCoroutineScope() PendingFoodBackground(imageId = R.drawable.pendingbackground) Box( modifier = modifier .fillMaxSize() ) { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = modifier .verticalScroll(scrollState) ) { FoodItem( food = food, modifier = modifier, isCategoryTypeVisible = food.id.isNotEmpty() ) if (ingredientsList.isNotEmpty()) { Box( modifier = modifier .fillMaxWidth() ) { PendingSwipeTips( modifier = modifier ) PendingSwipe( modifier = modifier, onSwipeRight = onSwipeRight, onSwipeLeft = onSwipeLeft, ) } } else { val random: Float = 0.5f + Random.nextFloat() * (0.8f - 0.5f) LottieAnimationContent( animationId = R.raw.cutedancingchicken, speed = random, modifier = modifier .fillMaxWidth() .height(250.dp) ) } } if (ingredientsList.isNotEmpty() && scrollState.canScrollForward && scrollState.maxValue > 100) { ScrollArrow( modifier = modifier .align(Alignment.BottomCenter) .offset(y = 10.dp) .size(80.dp), visible = scrollState.value == 0, onClick = { coroutineScope.launch { scrollState.animateScrollTo(scrollState.maxValue) } } ) } } } @Composable fun FoodItem( food: FoodViewData, modifier: Modifier = Modifier, isCategoryTypeVisible: Boolean = false, ) { val color by animateColorAsState( targetValue = MaterialTheme.colorScheme.secondary, label = "" ) Card( modifier = modifier .heightIn(max = 5500.dp) .padding(16.dp), elevation = 8.dp, shape = RoundedCornerShape(8.dp) ) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxWidth() .background(color) .animateContentSize( animationSpec = spring( dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessMediumLow ) ) ) { FoodImage(imageUri = food.imageRef) if (isCategoryTypeVisible) { CategoryTypeRow(categoryType = food.categoryType) } FoodTitle(text = food.title) if (food.ingredients.isNotEmpty()) { Box( modifier = Modifier .fillMaxWidth() ) { IngredientsReadOnlyContent( ingredients = food.ingredients, onEditClick = { }, isEditButtonVisible = false, ) FoodAuthor( author = food.author, modifier = Modifier .align(Alignment.TopEnd) ) } Spacer(modifier = Modifier.height(12.dp)) Row( modifier = Modifier .fillMaxWidth(), horizontalArrangement = Arrangement.Start, ) { BasicTitle( modifier = Modifier, text = stringResource(id = R.string.description_title) ) } } if (food.description.isNotEmpty()) { FoodDescription(description = food.description) } else { EmptyDescriptionMessage( message = stringResource(id = R.string.for_the_moment_there_are_no_more_pending_foods) ) } Spacer(modifier = Modifier.height(8.dp)) } } } @Composable fun FoodTitle( modifier: Modifier = Modifier, text: String, fontSize: TextUnit = 20.sp, ) { Text( text = text, fontSize = fontSize, fontFamily = MaterialTheme.typography.titleLarge.fontFamily, fontWeight = FontWeight.Bold, textAlign = TextAlign.Start, color = MaterialTheme.colorScheme.onSecondary, style = TextStyle( shadow = Shadow( color = Color.Yellow, blurRadius = 4f, offset = Offset(1f, 1f) ) ), modifier = modifier .fillMaxWidth() .padding(start = 20.dp, end = 20.dp, bottom = 10.dp, top = 10.dp) ) } @Composable fun EmptyDescriptionMessage( modifier: Modifier = Modifier, message: String, ) { Text( text = message, fontFamily = MaterialTheme.typography.titleSmall.fontFamily, fontWeight = FontWeight.Bold, fontSize = 16.sp, textAlign = TextAlign.Left, color = MaterialTheme.colorScheme.onSecondary, modifier = modifier .fillMaxWidth() .heightIn(max = 250.dp) .verticalScroll(rememberScrollState()) .padding( start = 25.dp, end = 20.dp, top = 5.dp, bottom = 10.dp ), ) } @Composable fun PendingSwipeTips( modifier: Modifier = Modifier, ) { Row( modifier = modifier .fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically ) { SwipeLeftTip() SwipeRightTip() } } @Composable fun PendingSwipe( modifier: Modifier = Modifier, onSwipeRight: () -> Unit, onSwipeLeft: () -> Unit, ) { Row( modifier = modifier .fillMaxWidth() .padding(start = 26.dp, end = 26.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { RejectFood() SwipableFood( onSwipeLeft = onSwipeLeft, onSwipeRight = onSwipeRight, ) AcceptFood() } } @Composable fun SwipeLeftTip() { Icon( Icons.Filled.SwipeLeft, contentDescription = "Swipe Left", modifier = Modifier .height(30.dp) .width(30.dp) .alpha(0.5f), tint = MaterialTheme.colorScheme.onSecondary ) } @Composable fun SwipeRightTip() { Icon( Icons.Filled.SwipeRight, contentDescription = "Swipe Right", modifier = Modifier .height(30.dp) .width(30.dp) .alpha(0.5f), tint = MaterialTheme.colorScheme.onSecondary ) } @Composable fun RejectFood() { Icon( Icons.Filled.Close, contentDescription = "Reject Food", modifier = Modifier .height(50.dp) .width(50.dp), tint = MaterialTheme.colorScheme.onSecondary ) } @Composable fun SwipableFood( modifier: Modifier = Modifier, onSwipeLeft: () -> Unit, onSwipeRight: () -> Unit, ) { val coroutineScope = rememberCoroutineScope() val offsetX = remember { Animatable(0f) } Image( painterResource(id = R.drawable.foodswipe), contentDescription = "Swipable Food", modifier = Modifier .bounceClick() .offset( x = (offsetX.value.toInt() * 2).dp, ) .draggable( state = rememberDraggableState { delta -> coroutineScope.launch { offsetX.animateTo(offsetX.value + delta) } }, orientation = Orientation.Horizontal, onDragStarted = { }, onDragStopped = { if ((offsetX.value.toInt() * 2) < -80f) { onSwipeLeft() } if ((offsetX.value.toInt() * 2) > 80f) { onSwipeRight() } coroutineScope.launch { offsetX.animateTo(0f) } } ) .background( brush = Brush.radialGradient( colors = listOf( MaterialTheme.colorScheme.secondary, Color.Transparent ) ), alpha = 0.5f, ) .padding(20.dp) .height(70.dp) .width(70.dp), ) } @Composable fun AcceptFood() { Icon( Icons.Filled.Check, contentDescription = "Accept Food", modifier = Modifier .height(50.dp) .width(50.dp), tint = MaterialTheme.colorScheme.onSecondary ) } @Composable fun FoodAuthor( modifier: Modifier = Modifier, author: String ) { Row( modifier = modifier .clickable { } .width(200.dp) .padding( start = 25.dp, end = 20.dp, ), horizontalArrangement = Arrangement.End ) { Text( text = author, fontFamily = MaterialTheme.typography.bodyMedium.fontFamily, fontWeight = FontWeight.Bold, fontSize = 12.sp, textAlign = TextAlign.End, color = MaterialTheme.colorScheme.onSecondary, ) } } @Composable fun FoodImage( modifier: Modifier = Modifier, imageUri: String, ) { var scale by remember { mutableStateOf(1f) } var offsetX by remember { mutableStateOf(0f) } var offsetY by remember { mutableStateOf(0f) } var zoomEnabled by remember { mutableStateOf(false) } var imageModifier = modifier .fillMaxWidth() .height(300.dp) .padding(10.dp) .shadow(elevation = 16.dp, shape = RoundedCornerShape(8.dp)) .graphicsLayer( scaleX = scale, scaleY = scale, translationX = offsetX, translationY = offsetY ) if (zoomEnabled) { imageModifier = imageModifier.pointerInput(Unit) { detectTransformGestures { _, pan, zoom, _ -> scale *= zoom scale = scale.coerceIn(1.0f, 3f) offsetX += pan.x offsetY += pan.y } } } Box(modifier = modifier) { SubcomposeAsyncImage( modifier = imageModifier, model = ImageRequest.Builder(LocalContext.current) .data(imageUri.ifEmpty { R.drawable.radish }) .crossfade(true) .build(), contentDescription = null, contentScale = ContentScale.Crop, loading = { LoadingCookingAnimation() } ) val icon = if (zoomEnabled) Icons.Filled.Pinch else Icons.Outlined.Pinch Icon( imageVector = icon, contentDescription = "Zoom Icon", modifier = Modifier .bounceClick { zoomEnabled = !zoomEnabled if(!zoomEnabled) { scale = 1f offsetX = 0f offsetY = 0f } else { scale = 1.2f } } .padding(16.dp) .align(Alignment.BottomEnd) .size(35.dp), tint = MaterialTheme.colorScheme.onSecondary ) } } @Composable fun FoodDescription( description: String, modifier: Modifier = Modifier ) { var descriptionDisplay by remember { mutableStateOf("") } val minHeight = 0.6f * description.length LaunchedEffect( key1 = description, ) { description.forEachIndexed { charIndex, _ -> descriptionDisplay = description .substring( startIndex = 0, endIndex = charIndex + 1, ) delay(2) } } Text( text = descriptionDisplay, fontFamily = MaterialTheme.typography.titleSmall.fontFamily, fontWeight = FontWeight.Bold, fontSize = 16.sp, textAlign = TextAlign.Left, color = MaterialTheme.colorScheme.onSecondary, modifier = modifier .fillMaxWidth() .heightIn(min = minHeight.dp, max = 1500.dp) .verticalScroll(rememberScrollState()) .padding( start = 25.dp, end = 20.dp, top = 5.dp, bottom = 10.dp ), ) } @Composable fun PendingFoodBackground( modifier: Modifier = Modifier, imageId: Int, ) { var sizeImage by remember { mutableStateOf(IntSize.Zero) } val gradient = Brush.verticalGradient( colors = listOf( Color.Transparent, MaterialTheme.colorScheme.secondary ), startY = 900f, endY = sizeImage.height.toFloat(), ) Box() { Image( painter = painterResource(id = imageId), contentDescription = null, contentScale = ContentScale.FillHeight, modifier = modifier .onGloballyPositioned { sizeImage = it.size } .fillMaxSize(), alpha = 0.35f ) Box( modifier = Modifier .matchParentSize() .alpha(0.90f) .background(gradient) ) } }
0
Kotlin
0
4
a65fc01c1f64f5cbf939812d4e54efba6a973842
20,332
EmaFoods
Apache License 2.0
src/main/kotlin/com/digitalarchitects/route/file/FileItemExt.kt
Digital-Architects-Avans
737,889,862
false
{"Kotlin": 62312}
package com.digitalarchitects.route.file import io.ktor.http.content.* import java.io.File fun PartData.FileItem.save(path: String, fileName: String): String { val fileBytes = streamProvider().readBytes() val folder = File(path) folder.mkdirs() File("$path$fileName").writeBytes(fileBytes) return fileName }
0
Kotlin
0
0
3a1dbdb09fe8a9bb7bb7fed87da0fa5c42098470
329
rmc-api-2
Apache License 2.0
plugins/kotlin/code-insight/inspections-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/inspections/expressions/ReplaceSizeZeroCheckWithIsEmptyInspection.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.k2.codeinsight.inspections.expressions import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.applicable.inspections.KotlinModCommandQuickFix import org.jetbrains.kotlin.idea.codeinsight.utils.isOneIntegerConstant import org.jetbrains.kotlin.idea.codeinsight.utils.isZeroIntegerConstant import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtBinaryExpression import org.jetbrains.kotlin.psi.KtExpression internal class ReplaceSizeCheckWithIsNotEmptyInspection : ReplaceSizeCheckInspectionBase() { override val methodToReplaceWith = EmptinessCheckMethod.IS_NOT_EMPTY override fun createQuickFix( element: KtBinaryExpression, context: ReplacementInfo, ): KotlinModCommandQuickFix<KtBinaryExpression> = object : ReplaceSizeCheckQuickFixBase(context) { override fun getFamilyName(): String = KotlinBundle.message("replace.size.check.with.isnotempty") override fun getName(): String = KotlinBundle.message("replace.size.check.with.0", context.fixMessage()) } override fun getProblemDescription(element: KtBinaryExpression, context: ReplacementInfo) = KotlinBundle.message("inspection.replace.size.check.with.is.not.empty.display.name") override fun extractTargetExpressionFromPsi(expr: KtBinaryExpression): KtExpression? = when (expr.operationToken) { KtTokens.EXCLEQ -> when { expr.right?.isZeroIntegerConstant() == true -> expr.left expr.left?.isZeroIntegerConstant() == true -> expr.right else -> null } KtTokens.GTEQ -> if (expr.right?.isOneIntegerConstant() == true) expr.left else null KtTokens.GT -> if (expr.right?.isZeroIntegerConstant() == true) expr.left else null KtTokens.LTEQ -> if (expr.left?.isOneIntegerConstant() == true) expr.right else null KtTokens.LT -> if (expr.left?.isZeroIntegerConstant() == true) expr.right else null else -> null } }
284
null
5162
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
2,233
intellij-community
Apache License 2.0
app/src/main/java/com/costular/atomtasks/ui/AtomTasksApp.kt
costular
379,913,052
false
null
package com.costular.atomtasks.ui import android.app.Application import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.os.Build import androidx.hilt.work.HiltWorkerFactory import androidx.work.Configuration import com.costular.atomtasks.BuildConfig import com.costular.atomtasks.R import com.costular.atomtasks.ui.util.ChannelReminders import dagger.hilt.android.HiltAndroidApp import timber.log.Timber import javax.inject.Inject @HiltAndroidApp class AtomTasksApp : Application(), Configuration.Provider { @Inject lateinit var workerFactory: HiltWorkerFactory override fun onCreate() { super.onCreate() init() createNotificationChannels() } private fun init() { if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } } private fun createNotificationChannels() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val name = getString(R.string.notification_channel_reminders_title) val descriptionText = getString(R.string.notification_channel_reminders_description) val importance = NotificationManager.IMPORTANCE_HIGH val reminders = NotificationChannel(ChannelReminders, name, importance).apply { description = descriptionText } val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(reminders) } } override fun getWorkManagerConfiguration() = Configuration.Builder() .setWorkerFactory(workerFactory) .build() }
3
Kotlin
0
1
7854d00b7dc90cbea5169dbfab2adea04d415f6e
1,761
atom-habits
Apache License 2.0
modules/meta/arrow-meta/src/test/java/arrow/ap/tests/ProductTest.kt
clojj
343,913,289
true
{"Kotlin": 2978660, "CSS": 85678, "JavaScript": 26157, "HTML": 22172, "Scala": 8073, "Java": 4465, "Shell": 3043, "Ruby": 1598}
package arrow.ap.tests import arrow.generic.ProductProcessor class ProductTest : APTest("arrow.ap.objects.generic", enforcePackage = false) { init { testProcessor( AnnotationProcessor( name = "Product instances cannot be generated for huge classes", sourceFiles = listOf("ProductXXL.java"), errorMessage = "arrow.ap.objects.generic.ProductXXL up to 22 constructor parameters is supported", processor = ProductProcessor() ) ) testProcessor( AnnotationProcessor( name = "Product instances generation requires companion object declaration", sourceFiles = listOf("ProductWithoutCompanion.java"), errorMessage = "@product annotated class arrow.ap.objects.generic.ProductWithoutCompanion needs to declare companion object.", processor = ProductProcessor() ) ) testProcessor( AnnotationProcessor( name = "Semigroup instance will be generated for data class annotated with @product([DerivingTarget.SEMIGROUP])", sourceFiles = listOf("Semigroup.java"), destFile = "Semigroup.kt", processor = ProductProcessor() ) ) testProcessor( AnnotationProcessor( name = "Semigroup and Monoid instances will be generated for data class annotated with @product([DerivingTarget.MONOID])", sourceFiles = listOf("Monoid.java"), destFile = "Monoid.kt", processor = ProductProcessor() ) ) testProcessor( AnnotationProcessor( name = "Method `.tupled()` will be generated for data class annotated with @product([DerivingTarget.TUPLED])", sourceFiles = listOf("Tupled.java"), destFile = "Tupled.kt", processor = ProductProcessor() ) ) testProcessor( AnnotationProcessor( name = "Method `.toHList()` will be generated for data class annotated with @product([DerivingTarget.HLIST])", sourceFiles = listOf("HList.java"), destFile = "HList.kt", processor = ProductProcessor() ) ) testProcessor( AnnotationProcessor( name = "Applicative instance and method `.tupled()` will be generated for data class annotated with @product([DerivingTarget.APPLICATIVE])", sourceFiles = listOf("Applicative.java"), destFile = "Applicative.kt", processor = ProductProcessor() ) ) testProcessor( AnnotationProcessor( name = "Eq instance will be generated for data class annotated with @product([DerivingTarget.EQ])", sourceFiles = listOf("Eq.java"), destFile = "Eq.kt", processor = ProductProcessor() ) ) testProcessor( AnnotationProcessor( name = "Show instance will be generated for data class annotated with @product([DerivingTarget.SHOw])", sourceFiles = listOf("Show.java"), destFile = "Show.kt", processor = ProductProcessor() ) ) } }
0
null
0
0
5eae605bbaeb2b911f69a5bccf3fa45c42578416
2,972
arrow
Apache License 2.0
server/src/main/kotlin/com/heerkirov/hedge/server/components/service/IllustService.kt
HeerKirov
298,201,781
false
null
package com.heerkirov.hedge.server.components.service import com.heerkirov.hedge.server.components.backend.exporter.AlbumMetadataExporterTask import com.heerkirov.hedge.server.components.backend.exporter.BackendExporter import com.heerkirov.hedge.server.components.backend.exporter.IllustMetadataExporterTask import com.heerkirov.hedge.server.components.database.DataRepository import com.heerkirov.hedge.server.components.database.transaction import com.heerkirov.hedge.server.components.kit.IllustKit import com.heerkirov.hedge.server.components.manager.* import com.heerkirov.hedge.server.components.manager.query.QueryManager import com.heerkirov.hedge.server.dao.album.AlbumImageRelations import com.heerkirov.hedge.server.dao.album.Albums import com.heerkirov.hedge.server.dao.collection.FolderImageRelations import com.heerkirov.hedge.server.dao.collection.Folders import com.heerkirov.hedge.server.dao.illust.* import com.heerkirov.hedge.server.dao.meta.Authors import com.heerkirov.hedge.server.dao.meta.Tags import com.heerkirov.hedge.server.dao.meta.Topics import com.heerkirov.hedge.server.dao.illust.FileRecords import com.heerkirov.hedge.server.dao.source.SourceImages import com.heerkirov.hedge.server.dao.source.SourceTagRelations import com.heerkirov.hedge.server.dao.source.SourceTags import com.heerkirov.hedge.server.dto.* import com.heerkirov.hedge.server.exceptions.* import com.heerkirov.hedge.server.model.illust.Illust import com.heerkirov.hedge.server.model.meta.Tag import com.heerkirov.hedge.server.utils.business.* import com.heerkirov.hedge.server.utils.DateTime import com.heerkirov.hedge.server.utils.DateTime.parseDateTime import com.heerkirov.hedge.server.utils.DateTime.toMillisecond import com.heerkirov.hedge.server.utils.ktorm.OrderTranslator import com.heerkirov.hedge.server.utils.ktorm.firstOrNull import com.heerkirov.hedge.server.utils.ktorm.orderBy import com.heerkirov.hedge.server.utils.runIf import com.heerkirov.hedge.server.utils.types.* import org.ktorm.dsl.* import org.ktorm.entity.filter import org.ktorm.entity.first import org.ktorm.entity.firstOrNull import org.ktorm.entity.sequenceOf import org.ktorm.expression.BinaryExpression import kotlin.math.roundToInt class IllustService(private val data: DataRepository, private val kit: IllustKit, private val illustManager: IllustManager, private val albumManager: AlbumManager, private val associateManager: AssociateManager, private val folderManager: FolderManager, private val fileManager: FileManager, private val sourceManager: SourceImageManager, private val partitionManager: PartitionManager, private val queryManager: QueryManager, private val backendExporter: BackendExporter) { private val orderTranslator = OrderTranslator { "id" to Illusts.id "createTime" to Illusts.createTime "updateTime" to Illusts.updateTime "orderTime" to Illusts.orderTime "score" to Illusts.exportedScore nulls last } fun list(filter: IllustQueryFilter): ListResult<IllustRes> { val schema = if(filter.query.isNullOrBlank()) null else { queryManager.querySchema(filter.query, QueryManager.Dialect.ILLUST).executePlan ?: return ListResult(0, emptyList()) } return data.db.from(Illusts) .innerJoin(FileRecords, Illusts.fileId eq FileRecords.id) .let { schema?.joinConditions?.fold(it) { acc, join -> if(join.left) acc.leftJoin(join.table, join.condition) else acc.innerJoin(join.table, join.condition) } ?: it } .let { if(filter.topic == null) it else it.innerJoin(IllustTopicRelations, (IllustTopicRelations.illustId eq Illusts.id) and (IllustTopicRelations.topicId eq filter.topic)) } .let { if(filter.author == null) it else it.innerJoin(IllustAuthorRelations, (IllustAuthorRelations.illustId eq Illusts.id) and (IllustAuthorRelations.authorId eq filter.author)) } .select(Illusts.id, Illusts.type, Illusts.exportedScore, Illusts.favorite, Illusts.tagme, Illusts.orderTime, Illusts.cachedChildrenCount, FileRecords.id, FileRecords.folder, FileRecords.extension, FileRecords.status) .whereWithConditions { it += when(filter.type) { Illust.IllustType.COLLECTION -> (Illusts.type eq Illust.Type.COLLECTION) or (Illusts.type eq Illust.Type.IMAGE) Illust.IllustType.IMAGE -> (Illusts.type eq Illust.Type.IMAGE) or (Illusts.type eq Illust.Type.IMAGE_WITH_PARENT) } if(filter.partition != null) { it += Illusts.partitionTime eq filter.partition } if(filter.favorite != null) { it += if(filter.favorite) Illusts.favorite else Illusts.favorite.not() } if(schema != null && schema.whereConditions.isNotEmpty()) { it.addAll(schema.whereConditions) } } .runIf(schema?.distinct == true) { groupBy(Illusts.id) } .limit(filter.offset, filter.limit) .orderBy(orderTranslator, filter.order, schema?.orderConditions, default = descendingOrderItem("orderTime")) .toListResult { val id = it[Illusts.id]!! val type = if(it[Illusts.type]!! == Illust.Type.COLLECTION) Illust.IllustType.COLLECTION else Illust.IllustType.IMAGE val score = it[Illusts.exportedScore] val favorite = it[Illusts.favorite]!! val tagme = it[Illusts.tagme]!! val orderTime = it[Illusts.orderTime]!!.parseDateTime() val (file, thumbnailFile) = takeAllFilepath(it) val childrenCount = it[Illusts.cachedChildrenCount]!!.takeIf { type == Illust.IllustType.COLLECTION } IllustRes(id, type, childrenCount, file, thumbnailFile, score, favorite, tagme, orderTime) } } fun findByIds(imageIds: List<Int>): List<IllustRes> { return data.db.from(Illusts) .innerJoin(FileRecords, Illusts.fileId eq FileRecords.id) .select(Illusts.id, Illusts.type, Illusts.exportedScore, Illusts.favorite, Illusts.tagme, Illusts.orderTime, Illusts.cachedChildrenCount, FileRecords.id, FileRecords.folder, FileRecords.extension, FileRecords.status) .where { Illusts.id inList imageIds } .map { val id = it[Illusts.id]!! val type = if(it[Illusts.type]!! == Illust.Type.COLLECTION) Illust.IllustType.COLLECTION else Illust.IllustType.IMAGE val score = it[Illusts.exportedScore] val favorite = it[Illusts.favorite]!! val tagme = it[Illusts.tagme]!! val orderTime = it[Illusts.orderTime]!!.parseDateTime() val (file, thumbnailFile) = takeAllFilepath(it) val childrenCount = it[Illusts.cachedChildrenCount]!!.takeIf { type == Illust.IllustType.COLLECTION } id to IllustRes(id, type, childrenCount, file, thumbnailFile, score, favorite, tagme, orderTime) } .toMap() .let { r -> imageIds.mapNotNull { r[it] } } } /** * @throws NotFound 请求对象不存在 */ fun get(id: Int, type: Illust.IllustType): IllustDetailRes { val row = data.db.from(Illusts) .innerJoin(FileRecords, FileRecords.id eq Illusts.fileId) .select( FileRecords.id, FileRecords.folder, FileRecords.extension, FileRecords.status, Illusts.description, Illusts.score, Illusts.exportedDescription, Illusts.exportedScore, Illusts.favorite, Illusts.tagme, Illusts.partitionTime, Illusts.orderTime, Illusts.createTime, Illusts.updateTime) .where { retrieveCondition(id, type) } .firstOrNull() ?: throw be(NotFound()) val fileId = row[FileRecords.id]!! val (file, thumbnailFile) = takeAllFilepath(row) val originDescription = row[Illusts.description]!! val originScore = row[Illusts.score] val description = row[Illusts.exportedDescription]!! val score = row[Illusts.exportedScore] val favorite = row[Illusts.favorite]!! val tagme = row[Illusts.tagme]!! val partitionTime = row[Illusts.partitionTime]!! val orderTime = row[Illusts.orderTime]!!.parseDateTime() val createTime = row[Illusts.createTime]!! val updateTime = row[Illusts.updateTime]!! val authorColors = data.metadata.meta.authorColors val topicColors = data.metadata.meta.topicColors val topics = data.db.from(Topics) .innerJoin(IllustTopicRelations, IllustTopicRelations.topicId eq Topics.id) .select(Topics.id, Topics.name, Topics.type, IllustTopicRelations.isExported) .where { IllustTopicRelations.illustId eq id } .orderBy(Topics.type.asc(), Topics.id.asc()) .map { val topicType = it[Topics.type]!! val color = topicColors[topicType] TopicSimpleRes(it[Topics.id]!!, it[Topics.name]!!, topicType, it[IllustTopicRelations.isExported]!!, color) } val authors = data.db.from(Authors) .innerJoin(IllustAuthorRelations, IllustAuthorRelations.authorId eq Authors.id) .select(Authors.id, Authors.name, Authors.type, IllustAuthorRelations.isExported) .where { IllustAuthorRelations.illustId eq id } .orderBy(Authors.type.asc(), Authors.id.asc()) .map { val authorType = it[Authors.type]!! val color = authorColors[authorType] AuthorSimpleRes(it[Authors.id]!!, it[Authors.name]!!, authorType, it[IllustAuthorRelations.isExported]!!, color) } val tags = data.db.from(Tags) .innerJoin(IllustTagRelations, IllustTagRelations.tagId eq Tags.id) .select(Tags.id, Tags.name, Tags.color, IllustTagRelations.isExported) .where { (IllustTagRelations.illustId eq id) and (Tags.type eq Tag.Type.TAG) } .orderBy(Tags.globalOrdinal.asc()) .map { TagSimpleRes(it[Tags.id]!!, it[Tags.name]!!, it[Tags.color], it[IllustTagRelations.isExported]!!) } return IllustDetailRes( id, fileId, file, thumbnailFile, topics, authors, tags, description, score, favorite, tagme, originDescription, originScore, partitionTime, orderTime, createTime, updateTime ) } /** * @throws NotFound 请求对象不存在 * @throws ResourceNotExist ("topics", number[]) 部分topics资源不存在。给出不存在的topic id列表 * @throws ResourceNotExist ("authors", number[]) 部分authors资源不存在。给出不存在的author id列表 * @throws ResourceNotExist ("tags", number[]) 部分tags资源不存在。给出不存在的tag id列表 * @throws ResourceNotSuitable ("tags", number[]) 部分tags资源不适用。地址段不适用于此项。给出不适用的tag id列表 * @throws ConflictingGroupMembersError 发现标签冲突组 */ fun update(id: Int, form: IllustImageUpdateForm) { val illust = data.db.sequenceOf(Illusts).firstOrNull { Illusts.id eq id } ?: throw be(NotFound()) if(illust.type == Illust.Type.COLLECTION) { updateCollection(id, form, illust) }else{ updateImage(id, form, illust) } } /** * @throws NotFound 请求对象不存在 */ fun getCollectionRelatedItems(id: Int, filter: LimitFilter): IllustCollectionRelatedRes { val row = data.db.from(Illusts) .select(Illusts.associateId) .where { retrieveCondition(id, Illust.IllustType.COLLECTION) } .firstOrNull() ?: throw be(NotFound()) val associateId = row[Illusts.associateId] val associate = associateManager.query(associateId, filter.limit) return IllustCollectionRelatedRes(associate) } fun getCollectionImages(id: Int, filter: LimitAndOffsetFilter): ListResult<IllustRes> { return data.db.from(Illusts) .innerJoin(FileRecords, Illusts.fileId eq FileRecords.id) .select(Illusts.id, Illusts.type, Illusts.exportedScore, Illusts.favorite, Illusts.tagme, Illusts.orderTime, FileRecords.id, FileRecords.folder, FileRecords.extension, FileRecords.status) .where { (Illusts.parentId eq id) and (Illusts.type eq Illust.Type.IMAGE_WITH_PARENT) } .limit(filter.offset, filter.limit) .orderBy(Illusts.orderTime.asc()) .toListResult { val itemId = it[Illusts.id]!! val type = if(it[Illusts.type]!! == Illust.Type.COLLECTION) Illust.IllustType.COLLECTION else Illust.IllustType.IMAGE val score = it[Illusts.exportedScore] val favorite = it[Illusts.favorite]!! val tagme = it[Illusts.tagme]!! val orderTime = it[Illusts.orderTime]!!.parseDateTime() val (file, thumbnailFile) = takeAllFilepath(it) IllustRes(itemId, type, null, file, thumbnailFile, score, favorite, tagme, orderTime) } } /** * @throws NotFound 请求对象不存在 */ fun getImageRelatedItems(id: Int, filter: LimitFilter): IllustImageRelatedRes { val row = data.db.from(Illusts) .select(Illusts.associateId, Illusts.parentId) .where { retrieveCondition(id, Illust.IllustType.IMAGE) } .firstOrNull() ?: throw be(NotFound()) val parentId = row[Illusts.parentId] val associateId = row[Illusts.associateId] val parent = if(parentId == null) null else data.db.from(Illusts) .innerJoin(FileRecords, FileRecords.id eq Illusts.fileId) .select(Illusts.id, Illusts.cachedChildrenCount, FileRecords.id, FileRecords.folder, FileRecords.extension, FileRecords.status) .where { Illusts.id eq parentId } .firstOrNull() ?.let { IllustParent(it[Illusts.id]!!, takeThumbnailFilepath(it), it[Illusts.cachedChildrenCount]!!) } val albums = data.db.from(Albums) .innerJoin(AlbumImageRelations, AlbumImageRelations.albumId eq Albums.id) .select(Albums.id, Albums.title) .where { AlbumImageRelations.imageId eq id } .map { AlbumSimpleRes(it[Albums.id]!!, it[Albums.title]!!) } val folders = data.db.from(Folders) .innerJoin(FolderImageRelations, FolderImageRelations.folderId eq Folders.id) .select(Folders.id, Folders.title, Folders.parentAddress, Folders.type) .where { FolderImageRelations.imageId eq id } .map { FolderSimpleRes(it[Folders.id]!!, (it[Folders.parentAddress] ?: emptyList()) + it[Folders.title]!!, it[Folders.type]!!) } val associate = associateManager.query(associateId, filter.limit) return IllustImageRelatedRes(parent, albums, folders, associate) } /** * @throws NotFound 请求对象不存在 */ fun getImageOriginData(id: Int): IllustImageOriginRes { val row = data.db.from(Illusts) .select(Illusts.source, Illusts.sourceId, Illusts.sourcePart) .where { retrieveCondition(id, Illust.IllustType.IMAGE) } .firstOrNull() ?: throw be(NotFound()) val source = row[Illusts.source] val sourceId = row[Illusts.sourceId] val sourcePart = row[Illusts.sourcePart] return if(source != null && sourceId != null) { val sourceTitle = data.metadata.source.sites.find { it.name == source }?.title val sourceRow = data.db.from(SourceImages).select() .where { (SourceImages.source eq source) and (SourceImages.sourceId eq sourceId) } .firstOrNull() if(sourceRow != null) { val sourceRowId = sourceRow[SourceImages.id]!! val sourceTags = data.db.from(SourceTags).innerJoin(SourceTagRelations, (SourceTags.id eq SourceTagRelations.tagId) and (SourceTagRelations.sourceId eq sourceRowId)) .select() .map { SourceTags.createEntity(it) } .map { SourceTagDto(it.name, it.displayName, it.type) } val relation = sourceRow[SourceImages.relations] IllustImageOriginRes(source, sourceTitle ?: source, sourceId, sourcePart, sourceRow[SourceImages.title] ?: "", sourceRow[SourceImages.description] ?: "", sourceTags, relation?.pools ?: emptyList(), relation?.children ?: emptyList(), relation?.parents ?: emptyList()) }else{ IllustImageOriginRes(source, sourceTitle ?: source, sourceId, sourcePart, "", "", emptyList(), emptyList(), emptyList(), emptyList()) } }else{ IllustImageOriginRes(null, null, null, null, null, null, null, null, null, null) } } /** * @throws NotFound 请求对象不存在 */ fun getImageFileInfo(id: Int): IllustImageFileInfoRes { val row = data.db.from(Illusts) .innerJoin(FileRecords, FileRecords.id eq Illusts.fileId) .select(FileRecords.columns) .where { retrieveCondition(id, Illust.IllustType.IMAGE) } .firstOrNull() ?: throw be(NotFound()) val file = takeFilepath(row) val fileRecord = FileRecords.createEntity(row) return IllustImageFileInfoRes(file, fileRecord.extension, fileRecord.size, fileRecord.thumbnailSize.takeIf { it > 0 }, fileRecord.resolutionWidth, fileRecord.resolutionHeight, fileRecord.createTime) } /** * @throws ResourceNotExist ("images", number[]) 给出的部分images不存在。给出不存在的image id列表 */ fun createCollection(form: IllustCollectionCreateForm): Int { if(form.score != null) kit.validateScore(form.score) data.db.transaction { return illustManager.newCollection(form.images, form.description ?: "", form.score, form.favorite, form.tagme) } } /** * @throws NotFound 请求对象不存在 * @throws ResourceNotExist ("topics", number[]) 部分topics资源不存在。给出不存在的topic id列表 * @throws ResourceNotExist ("authors", number[]) 部分authors资源不存在。给出不存在的author id列表 * @throws ResourceNotExist ("tags", number[]) 部分tags资源不存在。给出不存在的tag id列表 * @throws ResourceNotSuitable ("tags", number[]) 部分tags资源不适用。地址段不适用于此项。给出不适用的tag id列表 * @throws ConflictingGroupMembersError 发现标签冲突组 */ fun updateCollection(id: Int, form: IllustCollectionUpdateForm, preIllust: Illust? = null) { data.db.transaction { val illust = preIllust ?: data.db.sequenceOf(Illusts).firstOrNull { retrieveCondition(id, Illust.IllustType.COLLECTION) } ?: throw be(NotFound()) form.score.alsoOpt { if(it != null) kit.validateScore(it) } val newExportedScore = form.score.letOpt { it ?: data.db.from(Illusts) .select(count(Illusts.id).aliased("count"), avg(Illusts.score).aliased("score")) .where { (Illusts.parentId eq id) and (Illusts.score.isNotNull()) } .firstOrNull()?.run { if(getInt("count") > 0) getDouble("score").roundToInt() else null } } val newDescription = form.description.letOpt { it ?: "" } if(anyOpt(form.tags, form.authors, form.topics)) { kit.updateMeta(id, newTags = form.tags, newAuthors = form.authors, newTopics = form.topics, copyFromChildren = true) } val newTagme = if(form.tagme.isPresent) form.tagme else if(data.metadata.meta.autoCleanTagme && anyOpt(form.tags, form.authors, form.topics)) { Opt(illust.tagme .runIf(form.tags.isPresent) { this - Illust.Tagme.TAG } .runIf(form.authors.isPresent) { this - Illust.Tagme.AUTHOR } .runIf(form.topics.isPresent) { this - Illust.Tagme.TOPIC } ) }else undefined() if(anyOpt(newTagme, newDescription, form.score, form.favorite)) { data.db.update(Illusts) { where { it.id eq id } newTagme.applyOpt { set(it.tagme, this) } newDescription.applyOpt { set(it.description, this) set(it.exportedDescription, this) } form.score.applyOpt { set(it.score, this) } newExportedScore.applyOpt { set(it.exportedScore, this) } form.favorite.applyOpt { set(it.favorite, this) } } } if(anyOpt(form.tags, form.authors, form.topics, form.description, form.score)) { val children = data.db.from(Illusts).select(Illusts.id).where { Illusts.parentId eq id }.map { it[Illusts.id]!! } backendExporter.add(children.map { IllustMetadataExporterTask(it, exportScore = form.score.isPresent, exportDescription = form.description.isPresent, exportMetaTag = anyOpt(form.tags, form.topics, form.authors)) }) } } } /** * @throws NotFound 请求对象不存在 * @throws ResourceNotExist ("associateId", number) 新id指定的associate不存在。给出id */ fun updateCollectionRelatedItems(id: Int, form: IllustCollectionRelatedUpdateForm) { data.db.transaction { val illust = data.db.sequenceOf(Illusts).firstOrNull { retrieveCondition(id, Illust.IllustType.COLLECTION) } ?: throw be(NotFound()) form.associateId.alsoOpt { newAssociateId -> if(illust.associateId != newAssociateId) { associateManager.changeAssociate(illust, newAssociateId) } } } } /** * @throws NotFound 请求对象不存在 * @throws ResourceNotExist ("images", number[]) 给出的部分images不存在。给出不存在的image id列表 */ fun updateCollectionImages(id: Int, imageIds: List<Int>) { data.db.transaction { val illust = data.db.sequenceOf(Illusts).filter { retrieveCondition(id, Illust.IllustType.COLLECTION) }.firstOrNull() ?: throw be(NotFound()) val images = illustManager.unfoldImages(imageIds, sorted = false) val (fileId, scoreFromSub, partitionTime, orderTime) = kit.getExportedPropsFromList(images) data.db.update(Illusts) { where { it.id eq id } set(it.fileId, fileId) set(it.cachedChildrenCount, images.size) set(it.exportedScore, illust.score ?: scoreFromSub) set(it.partitionTime, partitionTime) set(it.orderTime, orderTime) set(it.updateTime, DateTime.now()) } illustManager.updateSubImages(id, images) kit.refreshAllMeta(id, copyFromChildren = true) } } /** * @throws NotFound 请求对象不存在 * @throws ResourceNotExist ("topics", number[]) 部分topics资源不存在。给出不存在的topic id列表 * @throws ResourceNotExist ("authors", number[]) 部分authors资源不存在。给出不存在的author id列表 * @throws ResourceNotExist ("tags", number[]) 部分tags资源不存在。给出不存在的tag id列表 * @throws ResourceNotSuitable ("tags", number[]) 部分tags资源不适用。地址段不适用于此项。给出不适用的tag id列表 * @throws ConflictingGroupMembersError 发现标签冲突组 */ fun updateImage(id: Int, form: IllustImageUpdateForm, preIllust: Illust? = null) { data.db.transaction { val illust = preIllust ?: data.db.sequenceOf(Illusts).firstOrNull { retrieveCondition(id, Illust.IllustType.IMAGE) } ?: throw be(NotFound()) val parent by lazy { if(illust.parentId == null) null else data.db.sequenceOf(Illusts).first { (Illusts.type eq Illust.Type.COLLECTION) and (Illusts.id eq illust.parentId) } } form.score.alsoOpt { if(it != null) kit.validateScore(it) } //处理属性导出 val newDescription = form.description.letOpt { it ?: "" } val newExportedDescription = newDescription.letOpt { it.ifEmpty { parent?.description ?: "" } } val newExportedScore = form.score.letOpt { it ?: parent?.score } //处理metaTag导出 if(anyOpt(form.tags, form.authors, form.topics)) { kit.updateMeta(id, newTags = form.tags, newAuthors = form.authors, newTopics = form.topics, copyFromParent = illust.parentId) } //处理tagme变化 val newTagme = if(form.tagme.isPresent) form.tagme else if(data.metadata.meta.autoCleanTagme && anyOpt(form.tags, form.authors, form.topics)) { Opt(illust.tagme .runIf(form.tags.isPresent) { this - Illust.Tagme.TAG } .runIf(form.authors.isPresent) { this - Illust.Tagme.AUTHOR } .runIf(form.topics.isPresent) { this - Illust.Tagme.TOPIC } ) }else undefined() //处理partition变化 form.partitionTime.alsoOpt { if(illust.partitionTime != it) partitionManager.updateItemPartition(illust.partitionTime, it) } //主体属性更新 if(anyOpt(newTagme, newDescription, newExportedDescription, form.score, newExportedScore, form.favorite, form.partitionTime, form.orderTime)) { data.db.update(Illusts) { where { it.id eq id } newTagme.applyOpt { set(it.tagme, this) } newDescription.applyOpt { set(it.description, this) } newExportedDescription.applyOpt { set(it.exportedDescription, this) } form.score.applyOpt { set(it.score, this) } newExportedScore.applyOpt { set(it.exportedScore, this) } form.favorite.applyOpt { set(it.favorite, this) } form.partitionTime.applyOpt { set(it.partitionTime, this) } form.orderTime.applyOpt { set(it.orderTime, this.toMillisecond()) } } } //触发parent的exporter task if(illust.parentId != null) { //当更改了score,且parent的score未设置时,重新导出score val exportScore = form.score.isPresent && parent!!.score == null //当更改了metaTag,且parent不存在任何notExported metaTag时,重新导出metaTag val exportMeta = anyOpt(form.tags, form.authors, form.topics) && !kit.anyNotExportedMetaExists(illust.parentId) //当改变了time,且parent的first child就是自己时,重新导出first cover val exportFirstCover = anyOpt(form.orderTime, form.partitionTime) && kit.getFirstChildOfCollection(illust.parentId).id == id //添加task if(exportScore || exportMeta || exportFirstCover) { backendExporter.add(IllustMetadataExporterTask(illust.parentId, exportScore = exportScore, exportMetaTag = exportMeta, exportFirstCover = exportFirstCover)) } } //触发album的exporter task val albumIds = data.db.from(Albums) .innerJoin(AlbumImageRelations, AlbumImageRelations.albumId eq Albums.id) .select(Albums.id) .where { AlbumImageRelations.imageId eq id } .map { it[Albums.id]!! } if(albumIds.isNotEmpty()) { val exportMeta = anyOpt(form.tags, form.authors, form.topics) if(exportMeta) { for (albumId in albumIds) { backendExporter.add(AlbumMetadataExporterTask(albumId, exportMetaTag = true)) } } } } } /** * @throws NotFound 请求对象不存在 * @throws ResourceNotExist ("collectionId", number) 新id指定的parent不存在。给出collection id * @throws ResourceNotExist ("associateId", number) 新id指定的associate不存在。给出id */ fun updateImageRelatedItems(id: Int, form: IllustImageRelatedUpdateForm) { data.db.transaction { val illust = data.db.sequenceOf(Illusts).firstOrNull { retrieveCondition(id, Illust.IllustType.IMAGE) } ?: throw be(NotFound()) form.associateId.alsoOpt { newAssociateId -> if(illust.associateId != newAssociateId) { associateManager.changeAssociate(illust, newAssociateId) } } form.collectionId.alsoOpt { newParentId -> if(illust.parentId != newParentId) { val newParent = if(newParentId == null) null else { data.db.sequenceOf(Illusts).firstOrNull { (it.id eq newParentId) and (it.type eq Illust.Type.COLLECTION) } ?: throw be(ResourceNotExist("collectionId", newParentId)) } //处理属性导出 val exportedScore = illust.score ?: newParent?.score val exportedDescription = illust.description.ifEmpty { newParent?.description ?: "" } val anyNotExportedMetaExists = kit.anyNotExportedMetaExists(id) if(!anyNotExportedMetaExists) { kit.refreshAllMeta(id, copyFromParent = newParentId) } //处理主体属性变化 data.db.update(Illusts) { where { it.id eq id } set(it.parentId, newParentId) set(it.type, if(newParentId != null) Illust.Type.IMAGE_WITH_PARENT else Illust.Type.IMAGE) set(it.exportedScore, exportedScore) set(it.exportedDescription, exportedDescription) } //更换image的parent时,需要对三个方面重导出:image自己; 旧parent; 新parent val now = DateTime.now() if(newParent != null) { illustManager.processCollectionChildrenAdded(newParent.id, illust, now, exportMetaTags = anyNotExportedMetaExists, exportScore = illust.score != null) } if(illust.parentId != null) { //处理旧parent illustManager.processCollectionChildrenRemoved(illust.parentId, listOf(illust), now, exportMetaTags = anyNotExportedMetaExists, exportScore = illust.score != null) } } } } } /** * @throws NotFound 请求对象不存在 * @throws ResourceNotExist ("source", string) 给出的source不存在 */ fun updateImageOriginData(id: Int, form: IllustImageOriginUpdateForm) { data.db.transaction { val row = data.db.from(Illusts).select(Illusts.source, Illusts.sourceId, Illusts.sourcePart, Illusts.tagme) .where { retrieveCondition(id, Illust.IllustType.IMAGE) } .firstOrNull() ?: throw be(NotFound()) val source = row[Illusts.source] val sourceId = row[Illusts.sourceId] val sourcePart = row[Illusts.sourcePart] val tagme = row[Illusts.tagme]!! if(form.source.isPresent || form.sourceId.isPresent || form.sourcePart.isPresent) { val newSourcePart = form.sourcePart.unwrapOr { sourcePart } val (newSourceImageId, newSource, newSourceId) = sourceManager.checkSource(form.source.unwrapOr { source }, form.sourceId.unwrapOr { sourceId }, newSourcePart) ?.let { (source, sourceId) -> sourceManager.createOrUpdateSourceImage(source, sourceId, form.title, form.description, form.tags, form.pools, form.children, form.parents) } ?: Triple(null, null, null) data.db.update(Illusts) { where { it.id eq id } set(it.sourceImageId, newSourceImageId) set(it.source, newSource) set(it.sourceId, newSourceId) set(it.sourcePart, newSourcePart) if(data.metadata.meta.autoCleanTagme && Illust.Tagme.SOURCE in tagme) set(it.tagme, tagme - Illust.Tagme.SOURCE) } }else{ sourceManager.checkSource(source, sourceId, sourcePart)?.let { (source, sourceId) -> sourceManager.createOrUpdateSourceImage(source, sourceId, form.title, form.description, form.tags, form.pools, form.children, form.parents) } } } } /** * @throws NotFound 请求对象不存在 */ fun delete(id: Int, type: Illust.IllustType? = null) { data.db.transaction { val illust = data.db.from(Illusts).select() .where { retrieveCondition(id, type) } .firstOrNull() ?.let { Illusts.createEntity(it) } ?: throw be(NotFound()) val anyNotExportedMetaExists = kit.anyNotExportedMetaExists(id) data.db.delete(Illusts) { it.id eq id } data.db.delete(IllustTagRelations) { it.illustId eq id } data.db.delete(IllustAuthorRelations) { it.illustId eq id } data.db.delete(IllustTopicRelations) { it.illustId eq id } data.db.delete(IllustAnnotationRelations) { it.illustId eq id } //移除illust时,执行「从associate移除一个项目」的检查流程,修改并检查引用计数 associateManager.removeFromAssociate(illust) if(illust.type != Illust.Type.COLLECTION) { //从所有album中移除并重导出 albumManager.removeItemInAllAlbums(id, exportMetaTags = anyNotExportedMetaExists) //从所有folder中移除 folderManager.removeItemInAllFolders(id) //关联的partition的计数-1 partitionManager.deleteItemInPartition(illust.partitionTime) //对parent的导出处理 if(illust.parentId != null) illustManager.processCollectionChildrenRemoved(illust.parentId, listOf(illust)) //删除关联的file fileManager.trashFile(illust.fileId) }else{ val children = data.db.from(Illusts).select(Illusts.id) .where { Illusts.parentId eq id } .map { it[Illusts.id]!! } data.db.update(Illusts) { where { it.parentId eq id } set(it.parentId, null) set(it.type, Illust.Type.IMAGE) } //对children做重导出 backendExporter.add(children.map { IllustMetadataExporterTask(it, exportDescription = illust.description.isNotEmpty(), exportScore = illust.score != null, exportMetaTag = anyNotExportedMetaExists) }) } } } /** * 克隆图像的属性。 * @throws ResourceNotExist ("from" | "to", number) 源或目标不存在 * @throws ResourceNotSuitable ("from" | "to", number) 源或目标类型不适用,不能使用集合 */ fun cloneImageProps(form: ImagePropsCloneForm) { data.db.transaction { val props = form.props val fromIllust = data.db.sequenceOf(Illusts).firstOrNull { it.id eq form.from } ?: throw be(ResourceNotExist("from", form.from)) val toIllust = data.db.sequenceOf(Illusts).firstOrNull { it.id eq form.to } ?: throw be(ResourceNotExist("to", form.to)) if(fromIllust.type == Illust.Type.COLLECTION) throw be(ResourceNotSuitable("from", form.from)) if(toIllust.type == Illust.Type.COLLECTION) throw be(ResourceNotSuitable("to", form.to)) //根据是否更改了parent,有两种不同的处理路径 val parentChanged = props.collection && fromIllust.parentId != toIllust.parentId val newParent = if(parentChanged && fromIllust.parentId != null) data.db.sequenceOf(Illusts).first { (it.id eq fromIllust.parentId) and (it.type eq Illust.Type.COLLECTION) } else null val parentId = if(parentChanged) toIllust.parentId else fromIllust.parentId data.db.update(Illusts) { where { it.id eq toIllust.id } if(parentChanged) { set(it.parentId, newParent?.id) set(it.type, if(newParent != null) Illust.Type.IMAGE_WITH_PARENT else Illust.Type.IMAGE) set(it.exportedScore, if(props.score) { fromIllust.score }else{ toIllust.score } ?: newParent?.score) set(it.exportedDescription, if(props.description) { fromIllust.description }else{ toIllust.description }.ifEmpty { newParent?.description ?: "" }) } if(props.favorite) set(it.favorite, fromIllust.favorite) if(props.tagme) set(it.tagme, if(form.merge) { fromIllust.tagme + toIllust.tagme }else{ fromIllust.tagme }) if(props.score) set(it.score, fromIllust.score) if(props.description) set(it.description, fromIllust.description) if(props.orderTime) set(it.orderTime, fromIllust.orderTime) if(props.partitionTime && fromIllust.partitionTime != toIllust.partitionTime) { set(it.partitionTime, fromIllust.partitionTime) partitionManager.addItemInPartition(fromIllust.partitionTime) } if(props.source) { set(it.source, fromIllust.source) set(it.sourceId, fromIllust.sourceId) set(it.sourcePart, fromIllust.sourcePart) set(it.sourceImageId, fromIllust.sourceImageId) } } if(parentChanged) { //刷新新旧parent的时间&封面、导出属性 (metaTag不包含在其中,它稍后处理) val now = DateTime.now() if(newParent != null) illustManager.processCollectionChildrenAdded(newParent.id, toIllust, now, exportScore = true) if(toIllust.parentId != null) illustManager.processCollectionChildrenRemoved(toIllust.parentId, listOf(toIllust), now, exportScore = true) }else{ //刷新parent的导出属性,适时刷新封面&时间 (metaTag不包含在其中,它稍后处理) if(toIllust.parentId != null) { val exportScore = props.score val exportMeta = !kit.anyNotExportedMetaExists(toIllust.parentId) val exportFirstCover = (props.orderTime || props.partitionTime) && kit.getFirstChildOfCollection(toIllust.parentId).id == toIllust.id if(exportScore || exportMeta || exportFirstCover) { backendExporter.add(IllustMetadataExporterTask(toIllust.parentId, exportScore = exportScore, exportMetaTag = exportMeta, exportFirstCover = exportFirstCover)) } } } if(props.metaTags) { val tagIds = data.db.from(IllustTagRelations).select(IllustTagRelations.tagId) .where { (IllustTagRelations.illustId eq fromIllust.id) and IllustTagRelations.isExported.not() } .map { it[IllustTagRelations.tagId]!! } val topicIds = data.db.from(IllustTopicRelations).select(IllustTopicRelations.topicId) .where { (IllustTopicRelations.illustId eq fromIllust.id) and IllustTopicRelations.isExported.not() } .map { it[IllustTopicRelations.topicId]!! } val authorIds = data.db.from(IllustAuthorRelations).select(IllustAuthorRelations.authorId) .where { (IllustAuthorRelations.illustId eq fromIllust.id) and IllustAuthorRelations.isExported.not() } .map { it[IllustAuthorRelations.authorId]!! } if(form.merge) { val originTagIds = data.db.from(IllustTagRelations).select(IllustTagRelations.tagId) .where { (IllustTagRelations.illustId eq toIllust.id) and IllustTagRelations.isExported.not() } .map { it[IllustTagRelations.tagId]!! } val originTopicIds = data.db.from(IllustTopicRelations).select(IllustTopicRelations.topicId) .where { (IllustTopicRelations.illustId eq toIllust.id) and IllustTopicRelations.isExported.not() } .map { it[IllustTopicRelations.topicId]!! } val originAuthorIds = data.db.from(IllustAuthorRelations).select(IllustAuthorRelations.authorId) .where { (IllustAuthorRelations.illustId eq toIllust.id) and IllustAuthorRelations.isExported.not() } .map { it[IllustAuthorRelations.authorId]!! } kit.updateMeta(toIllust.id, optOf((tagIds + originTagIds).distinct()), optOf((topicIds + originTopicIds).distinct()), optOf((authorIds + originAuthorIds).distinct()), copyFromParent = parentId) }else{ kit.updateMeta(toIllust.id, optOf(tagIds), optOf(topicIds), optOf(authorIds), copyFromParent = parentId) } if(parentChanged) { //如果复制了parent,那么需要处理新旧parent的重导出 if(newParent != null) backendExporter.add(IllustMetadataExporterTask(newParent.id, exportMetaTag = true)) if(toIllust.parentId != null) backendExporter.add(IllustMetadataExporterTask(toIllust.parentId, exportMetaTag = true)) }else if(toIllust.parentId != null && !kit.anyNotExportedMetaExists(toIllust.parentId)) { //如果没有复制,那么当parent没有任何not exported meta时,处理parent的重导出 backendExporter.add(IllustMetadataExporterTask(toIllust.parentId, exportMetaTag = true)) } }else if(parentChanged) { //即使没有选择复制metaTags,但是如果选择复制了parent,那么也仍然需要处理新旧parent的重导出 //尽管这可以作为processCollection的一部分,但为了代码清晰起见把它们分开了 if(kit.anyNotExportedMetaExists(toIllust.id)) { //只有当toIllust包含not exported meta时,才有必要处理parent的重导出 if(newParent != null) backendExporter.add(IllustMetadataExporterTask(newParent.id, exportMetaTag = true)) if(toIllust.parentId != null) backendExporter.add(IllustMetadataExporterTask(toIllust.parentId, exportMetaTag = true)) } } if(props.associate) { associateManager.changeAssociate(toIllust, fromIllust.associateId) } if(props.albums) { val albums = data.db.from(AlbumImageRelations) .select(AlbumImageRelations.albumId, AlbumImageRelations.ordinal) .where { AlbumImageRelations.imageId eq fromIllust.id } .map { Pair(it[AlbumImageRelations.albumId]!!, it[AlbumImageRelations.ordinal]!! + 1 /* +1 使新项插入到旧项后面 */) } if(form.merge) { val existsAlbums = data.db.from(AlbumImageRelations) .select(AlbumImageRelations.albumId) .where { AlbumImageRelations.imageId eq toIllust.id } .map { it[AlbumImageRelations.albumId]!! } .toSet() val newAlbums = albums.filter { (id, _) -> id !in existsAlbums } if(newAlbums.isNotEmpty()) albumManager.addItemInFolders(toIllust.id, newAlbums, exportMetaTags = true) }else{ albumManager.removeItemInAllAlbums(toIllust.id, exportMetaTags = true) albumManager.addItemInFolders(toIllust.id, albums, exportMetaTags = true) } } if(props.folders) { val folders = data.db.from(FolderImageRelations) .select(FolderImageRelations.folderId, FolderImageRelations.ordinal) .where { FolderImageRelations.imageId eq fromIllust.id } .map { Pair(it[FolderImageRelations.folderId]!!, it[FolderImageRelations.ordinal]!! + 1 /* +1 使新项插入到旧项后面 */) } if(form.merge) { val existsFolders = data.db.from(FolderImageRelations) .select(FolderImageRelations.folderId) .where { FolderImageRelations.imageId eq toIllust.id } .map { it[FolderImageRelations.folderId]!! } .toSet() val newFolders = folders.filter { (id, _) -> id !in existsFolders } if(newFolders.isNotEmpty()) folderManager.addItemInFolders(toIllust.id, newFolders) }else{ folderManager.removeItemInAllFolders(toIllust.id) folderManager.addItemInFolders(toIllust.id, folders) } } if(form.deleteFrom) { delete(fromIllust.id, Illust.IllustType.IMAGE) } } } private fun retrieveCondition(id: Int, type: Illust.IllustType?): BinaryExpression<Boolean> { return (Illusts.id eq id).runIf(type != null) { this and if(type!! == Illust.IllustType.COLLECTION) { Illusts.type eq Illust.Type.COLLECTION }else{ (Illusts.type eq Illust.Type.IMAGE_WITH_PARENT) or (Illusts.type eq Illust.Type.IMAGE) } } } }
0
TypeScript
0
1
8140cd693759a371dc5387c4a3c7ffcef6fb14b2
45,492
Hedge-v2
MIT License
features/src/main/java/com/ahmet/features/dialogs/adduser/AddUserDialogViewModel.kt
AhmetOcak
492,814,409
false
{"Kotlin": 128173}
package com.ahmet.features.dialogs.adduser import android.util.Log import androidx.lifecycle.MutableLiveData import com.ahmet.core.base.BaseViewModel import com.ahmet.features.utils.helpers.EmailController import com.ahmet.data.usecase.user.GetCurrentUserEmail import com.ahmet.data.usecase.friend.SendFriendRequest import com.ahmet.features.utils.Constants import dagger.hilt.android.lifecycle.HiltViewModel import java.lang.Exception import javax.inject.Inject @HiltViewModel class AddUserDialogViewModel @Inject constructor( private val sendFriendRequest: SendFriendRequest, getCurrentUserEmail: GetCurrentUserEmail, ) : BaseViewModel() { val friendEmail = MutableLiveData<String?>() private val userEmail = MutableLiveData<String?>() var errorMessage = MutableLiveData<String?>() var firebaseMessage = MutableLiveData<String?>() init { userEmail.value = getCurrentUserEmail.getCurrentUser() } private fun checkEmailField(): Boolean { return if (friendEmail.value.isNullOrEmpty()) { errorMessage.value = Constants.EMPTY_FIELD_MESSAGE false } else { true } } private fun checkEmail(): Boolean { return if (EmailController.emailController(friendEmail.value.toString())) { true } else { errorMessage.value = Constants.EMAIL_MESSAGE false } } // user can't add himself/herself :D private fun isUserEmail(): Boolean { return if (userEmail.value == friendEmail.value) { errorMessage.value = "You can't add yourself" false } else { return true } } suspend fun sendFriendRequest() { try { if (checkEmailField() && checkEmail() && isUserEmail()) { firebaseMessage.value = sendFriendRequest.sendRequest(userEmail.value!!, friendEmail.value!!) clearFields() } } catch (e: Exception) { Log.e("send friend request exception", e.toString()) } } private fun clearFields() { friendEmail.value = null } }
0
Kotlin
0
1
c8c9f9d4d4dab816bec976ae65e30b530e62b239
2,164
KotlinChatApp
MIT License
app/src/main/java/me/tandeneck/tanutils/model/place/County.kt
ahaliulang
323,002,178
false
null
package me.tandeneck.tanutils.model.place import androidx.room.Entity import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName @Entity class County( @SerializedName("name") val countyName: String, @SerializedName("weather_id") val weatherId: String ) { @PrimaryKey @Transient val id = 0 var cityId = 0 }
0
Kotlin
0
0
ed39c975e03860caed711cf17f42377c754c58b3
354
TanUtils
Apache License 2.0
common-ui-compose/src/main/java/app/tivi/common/compose/ui/SwipeDismissSnackbar.kt
chrisbanes
100,624,553
false
null
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.common.compose.ui import androidx.compose.material.DismissDirection import androidx.compose.material.DismissValue import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.Snackbar import androidx.compose.material.SnackbarData import androidx.compose.material.SnackbarHost import androidx.compose.material.SnackbarHostState import androidx.compose.material.SwipeToDismiss import androidx.compose.material.rememberDismissState import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier /** * Wrapper around [Snackbar] to make it swipe-dismissable, * using [SwipeToDismiss]. */ @OptIn(ExperimentalMaterialApi::class) @Composable fun SwipeDismissSnackbar( data: SnackbarData, onDismiss: (() -> Unit)? = null, snackbar: @Composable (SnackbarData) -> Unit = { Snackbar(it) }, ) { val dismissState = rememberDismissState { if (it != DismissValue.Default) { // First dismiss the snackbar data.dismiss() // Then invoke the callback onDismiss?.invoke() } true } SwipeToDismiss( state = dismissState, directions = setOf(DismissDirection.StartToEnd, DismissDirection.EndToStart), background = {}, dismissContent = { snackbar(data) } ) } @Composable fun SwipeDismissSnackbarHost( hostState: SnackbarHostState, modifier: Modifier = Modifier, onDismiss: () -> Unit = { hostState.currentSnackbarData?.dismiss() }, snackbar: @Composable (SnackbarData) -> Unit = { data -> SwipeDismissSnackbar( data = data, onDismiss = onDismiss, ) }, ) { SnackbarHost( hostState = hostState, snackbar = snackbar, modifier = modifier, ) }
39
Kotlin
740
5,312
70124c20a482cd83ddfe735802f77064c2ba8f20
2,401
tivi
Apache License 2.0
core/descriptors/src/org/jetbrains/kotlin/types/flexibleTypes.kt
msdgwzhy6
421,687,586
true
{"Markdown": 32, "XML": 692, "Ant Build System": 45, "Git Attributes": 1, "Ignore List": 7, "Maven POM": 51, "Kotlin": 23506, "Java": 4612, "JavaScript": 64, "JSON": 1, "Groovy": 23, "Shell": 11, "Batchfile": 10, "Java Properties": 14, "Gradle": 75, "HTML": 184, "INI": 18, "CSS": 2, "Text": 5151, "ANTLR": 1, "Protocol Buffer": 7, "JAR Manifest": 3, "Roff": 151, "Roff Manpage": 18, "Proguard": 1, "JFlex": 2}
/* * Copyright 2010-2015 JetBrains s.r.o. * * 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 org.jetbrains.kotlin.types import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.types.checker.KotlinTypeChecker interface FlexibleTypeCapabilities { fun <T: TypeCapability> getCapability(capabilityClass: Class<T>, jetType: KotlinType, flexibility: Flexibility): T? val id: String object NONE : FlexibleTypeCapabilities { override fun <T : TypeCapability> getCapability(capabilityClass: Class<T>, jetType: KotlinType, flexibility: Flexibility): T? = null override val id: String get() = "NONE" } } interface Flexibility : TypeCapability, SubtypingRepresentatives { companion object { // This is a "magic" classifier: when type resolver sees it in the code, e.g. ft<Foo, Foo?>, instead of creating a normal type, // it creates a flexible type, e.g. (Foo..Foo?). // This is used in tests and Evaluate Expression to have flexible types in the code, // but normal users should not be referencing this classifier val FLEXIBLE_TYPE_CLASSIFIER: ClassId = ClassId.topLevel(FqName("kotlin.internal.flexible.ft")) } // lowerBound is a subtype of upperBound val lowerBound: KotlinType val upperBound: KotlinType val extraCapabilities: FlexibleTypeCapabilities override val subTypeRepresentative: KotlinType get() = lowerBound override val superTypeRepresentative: KotlinType get() = upperBound override fun sameTypeConstructor(type: KotlinType) = false } fun KotlinType.isFlexible(): Boolean = this.getCapability(Flexibility::class.java) != null fun KotlinType.flexibility(): Flexibility = this.getCapability(Flexibility::class.java)!! fun KotlinType.isNullabilityFlexible(): Boolean { val flexibility = this.getCapability(Flexibility::class.java) ?: return false return TypeUtils.isNullableType(flexibility.lowerBound) != TypeUtils.isNullableType(flexibility.upperBound) } // This function is intended primarily for sets: since KotlinType.equals() represents _syntactical_ equality of types, // whereas KotlinTypeChecker.DEFAULT.equalsTypes() represents semantic equality // A set of types (e.g. exact bounds etc) may contain, for example, X, X? and X! // These are not equal syntactically (by KotlinType.equals()), but X! is _compatible_ with others as exact bounds, // moreover, X! is a better fit. // // So, we are looking for a type among this set such that it is equal to all others semantically // (by KotlinTypeChecker.DEFAULT.equalsTypes()), and fits at least as well as they do. fun Collection<KotlinType>.singleBestRepresentative(): KotlinType? { if (this.size == 1) return this.first() return this.firstOrNull { candidate -> this.all { other -> // We consider error types equal to anything here, so that intersections like // {Array<String>, Array<[ERROR]>} work correctly candidate == other || KotlinTypeChecker.ERROR_TYPES_ARE_EQUAL_TO_ANYTHING.equalTypes(candidate, other) } } } fun Collection<TypeProjection>.singleBestRepresentative(): TypeProjection? { if (this.size == 1) return this.first() val projectionKinds = this.map { it.projectionKind }.toSet() if (projectionKinds.size != 1) return null val bestType = this.map { it.type }.singleBestRepresentative() if (bestType == null) return null return TypeProjectionImpl(projectionKinds.single(), bestType) } fun KotlinType.lowerIfFlexible(): KotlinType = if (this.isFlexible()) this.flexibility().lowerBound else this fun KotlinType.upperIfFlexible(): KotlinType = if (this.isFlexible()) this.flexibility().upperBound else this interface NullAwareness : TypeCapability { fun makeNullableAsSpecified(nullable: Boolean): KotlinType fun computeIsNullable(): Boolean } interface FlexibleTypeDelegation : TypeCapability { val delegateType: KotlinType } open class DelegatingFlexibleType protected constructor( override val lowerBound: KotlinType, override val upperBound: KotlinType, override val extraCapabilities: FlexibleTypeCapabilities ) : DelegatingType(), NullAwareness, Flexibility, FlexibleTypeDelegation { companion object { internal val capabilityClasses = hashSetOf( NullAwareness::class.java, Flexibility::class.java, SubtypingRepresentatives::class.java, FlexibleTypeDelegation::class.java ) @JvmStatic fun create(lowerBound: KotlinType, upperBound: KotlinType, extraCapabilities: FlexibleTypeCapabilities): KotlinType { if (lowerBound == upperBound) return lowerBound return DelegatingFlexibleType(lowerBound, upperBound, extraCapabilities) } @JvmField var RUN_SLOW_ASSERTIONS = false } // These assertions are needed for checking invariants of flexible types. // // Unfortunately isSubtypeOf is running resolve for lazy types. // Because of this we can't run these assertions when we are creating this type. See EA-74904 // // Also isSubtypeOf is not a very fast operation, so we are running assertions only if ASSERTIONS_ENABLED. See KT-7540 private var assertionsDone = false private fun runAssertions() { if (!RUN_SLOW_ASSERTIONS || assertionsDone) return assertionsDone = true assert (!lowerBound.isFlexible()) { "Lower bound of a flexible type can not be flexible: $lowerBound" } assert (!upperBound.isFlexible()) { "Upper bound of a flexible type can not be flexible: $upperBound" } assert (lowerBound != upperBound) { "Lower and upper bounds are equal: $lowerBound == $upperBound" } assert (KotlinTypeChecker.DEFAULT.isSubtypeOf(lowerBound, upperBound)) { "Lower bound $lowerBound of a flexible type must be a subtype of the upper bound $upperBound" } } override fun <T : TypeCapability> getCapability(capabilityClass: Class<T>): T? { val extra = extraCapabilities.getCapability(capabilityClass, this, this) if (extra != null) return extra @Suppress("UNCHECKED_CAST") if (capabilityClass in capabilityClasses) return this as T return super<DelegatingType>.getCapability(capabilityClass) } override fun makeNullableAsSpecified(nullable: Boolean): KotlinType { return create( TypeUtils.makeNullableAsSpecified(lowerBound, nullable), TypeUtils.makeNullableAsSpecified(upperBound, nullable), extraCapabilities) } override fun computeIsNullable() = delegateType.isMarkedNullable override fun isMarkedNullable(): Boolean = getCapability(NullAwareness::class.java)!!.computeIsNullable() override val delegateType: KotlinType get() { runAssertions() return lowerBound } override fun getDelegate() = getCapability(FlexibleTypeDelegation::class.java)!!.delegateType override fun toString() = "('$lowerBound'..'$upperBound')" }
0
Java
0
1
f713adc96e9adeacb1373fc170a5ece1bf2fc1a2
7,758
kotlin
Apache License 2.0
app/src/main/java/com/example/application/ui/bottomsheet/BottomSheetScreen.kt
greenlabsfin
576,161,902
false
{"Kotlin": 341944, "Shell": 610}
package com.example.application.ui.bottomsheet import androidx.compose.foundation.Canvas import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.KeyboardArrowRight import androidx.compose.material3.Surface import androidx.compose.runtime.Composable 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.geometry.CornerRadius import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.example.application.R import com.example.application.ui.theme.SeedSampleTheme import com.example.application.util.ThemedPreview import co.seedglobal.design.component.SeedBottomSheetState import co.seedglobal.design.component.SeedBottomSheetValue import co.seedglobal.design.component.SeedButton import co.seedglobal.design.component.SeedButtonDefaults import co.seedglobal.design.component.SeedCheckbox import co.seedglobal.design.component.SeedIcon import co.seedglobal.design.component.SeedText import co.seedglobal.design.component.SeedTextButton import co.seedglobal.design.component.rememberSeedBottomSheetState import co.seedglobal.design.component.util.DecorateBackground import co.seedglobal.design.core.SeedTheme import co.seedglobal.design.core.color.gray30 import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch @Composable fun BottomSheetScreen( onShowBottomSheet: (content: @Composable () -> Unit, isFixed: Boolean) -> Unit, ) { DecorateBackground( SeedTheme.colorScheme.container.neutralTertiary ) { val bottomSheetState = rememberSeedBottomSheetState(initialValue = SeedBottomSheetValue.Hidden) val scope = rememberCoroutineScope() Column( modifier = Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(10.dp) ) { Spacer(modifier = Modifier.height(50.dp)) Surface( modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(12.dp), color = Color(0xFF2B2C32) ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .padding(horizontal = 10.dp, vertical = 10.dp) .clickable( interactionSource = MutableInteractionSource(), indication = null ) { onShowBottomSheet( { SelectMonthContentLayout() }, false ) scope.launch { bottomSheetState.show() } } ) { Image( modifier = Modifier.size(50.dp), painter = painterResource(id = R.drawable.ic_launcher_foreground), contentDescription = "launcher" ) Spacer(modifier = Modifier.width(10.dp)) Column( ) { SeedText( text = "Marketing Title", style = SeedTheme.typoScheme.body.smallBold, color = SeedTheme.colorScheme.contents.onPrimary ) SeedText( text = "Marketing description, description", style = SeedTheme.typoScheme.caption.xSmallRegular, color = SeedTheme.colorScheme.contents.onPrimary ) } } } } } } @Composable fun SelectMonthContentLayout() { val density = LocalDensity.current Column { Box( modifier = Modifier .fillMaxWidth() .height(32.dp), contentAlignment = Alignment.Center ) { Canvas(modifier = Modifier.size(width = 40.dp, height = 4.dp), onDraw = { drawRoundRect( color = gray30, size = Size( width = with(density) { 40.dp.toPx() }, height = with(density) { 4.dp.toPx() } ), cornerRadius = CornerRadius(with(density) { 2.dp.toPx() }) ) }) } SeedText( modifier = Modifier .height(58.dp) .padding(horizontal = 20.dp), text = "월 선택하기", style = SeedTheme.typoScheme.body.largeBold ) LazyColumn( contentPadding = PaddingValues(horizontal = 20.dp) ) { val year = 2022 val month = 11 for (i in 0 until 33) { var targetMonth = month.minus(i) var targetYear = year while (targetMonth < 1) { targetYear-- targetMonth += 12 } item { SeedText( modifier = Modifier .fillMaxWidth() .height(58.dp), text = "${targetYear}년 ${targetMonth}월", style = SeedTheme.typoScheme.body.mediumRegular ) } } } } } @Composable private fun SheetContentLayout( maxHeight: Dp, bottomSheetState: SeedBottomSheetState = rememberSeedBottomSheetState(initialValue = SeedBottomSheetValue.Hidden), scope: CoroutineScope = rememberCoroutineScope(), ) { Column( modifier = Modifier .heightIn(min = 0.dp, max = maxHeight) .padding(bottom = 34.dp, start = 20.dp, end = 20.dp) ) { SeedText( modifier = Modifier .height(60.dp) .padding(top = 4.dp), text = "Terms of usage", style = SeedTheme.typoScheme.body.mediumBold ) LazyColumn( modifier = Modifier .weight(1f, true) .padding(bottom = 16.dp) ) { items(40) { Row( modifier = Modifier .fillMaxWidth() .defaultMinSize(minHeight = 58.dp), verticalAlignment = Alignment.CenterVertically, ) { var checked by remember { mutableStateOf(false) } SeedCheckbox( // modifier = Modifier.weight(1f, true), checked = checked, onCheckedChange = { checked = it }, text = "Term of something", textStyle = SeedTheme.typoScheme.body.mediumRegular, ) Spacer(modifier = Modifier.width(8.dp)) SeedIcon( imageVector = Icons.Default.KeyboardArrowRight, contentDescription = "", tint = SeedTheme.colorScheme.contents.neutralTertiary, ) } } } SeedButton( // modifier = Modifier.fillMaxWidth(), size = SeedButton.Size.Large, colors = SeedButtonDefaults.Colors.containerPrimary(), text = "동의하고 시작하기" ) { scope.launch { bottomSheetState.hide() } } } } @Composable fun PlccBannerContent( bottomSheetState: SeedBottomSheetState = rememberSeedBottomSheetState(initialValue = SeedBottomSheetValue.Hidden), scope: CoroutineScope = rememberCoroutineScope(), ) { Column( modifier = Modifier.wrapContentHeight() ) { Surface( color = SeedTheme.colorScheme.contents.neutralPrimary ) { Box( modifier = Modifier .fillMaxWidth() .height(270.dp) ) { Column(modifier = Modifier .align(Alignment.BottomStart) .padding(bottom = 37.dp, start = 20.dp, end = 20.dp) ) { SeedText(text = "Marketing\nThis is marketing", style = SeedTheme.typoScheme.body.xLargeBold, color = SeedTheme.colorScheme.contents.onPrimary) Spacer(modifier = Modifier.height(23.dp)) SeedText(text = "Marketing description, description is good", style = SeedTheme.typoScheme.caption.xSmallRegular, color = SeedTheme.colorScheme.contents.onPrimary) } } } Row( modifier = Modifier.padding(start = 20.dp, end = 20.dp, top = 16.dp, bottom = 34.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically ) { SeedTextButton( modifier = Modifier .padding(horizontal = 6.dp) .weight(.1f, false), text = "다음에", style = SeedTheme.typoScheme.body.mediumMedium, color = SeedTheme.colorScheme.contents.neutralSecondary, ) { scope.launch { bottomSheetState.hide() } } SeedButton( modifier = Modifier.weight(.2f, true), size = SeedButton.Size.Large, colors = SeedButtonDefaults.Colors.tintNeutral(), text = "알아보기", ) { scope.launch { bottomSheetState.hide() } } } } } @ThemedPreview @Composable fun BottomSheetScreenPreview() { SeedSampleTheme { Surface(color = SeedTheme.colorScheme.container.background) { // BottomSheetScreen() PlccBannerContent() } } }
0
Kotlin
0
2
00df62e84ee656b06cc645e93386c3d771c2c034
11,527
seed-android-design-system
Apache License 2.0
feature-wallet-impl/src/main/java/jp/co/soramitsu/wallet/impl/data/repository/WalletRepositoryImpl.kt
soramitsu
278,060,397
false
{"Kotlin": 4752568, "Java": 18796}
package jp.co.soramitsu.wallet.impl.data.repository import com.opencsv.CSVReaderHeaderAware import java.math.BigDecimal import java.math.BigInteger import jp.co.soramitsu.account.api.domain.model.MetaAccount import jp.co.soramitsu.account.api.domain.model.accountId import jp.co.soramitsu.common.compose.component.NetworkIssueItemState import jp.co.soramitsu.common.compose.component.NetworkIssueType import jp.co.soramitsu.common.data.network.HttpExceptionHandler import jp.co.soramitsu.common.data.network.coingecko.CoingeckoApi import jp.co.soramitsu.common.data.network.config.AppConfigRemote import jp.co.soramitsu.common.data.network.config.RemoteConfigFetcher import jp.co.soramitsu.common.domain.GetAvailableFiatCurrencies import jp.co.soramitsu.common.mixin.api.NetworkStateMixin import jp.co.soramitsu.common.mixin.api.UpdatesMixin import jp.co.soramitsu.common.mixin.api.UpdatesProviderUi import jp.co.soramitsu.common.utils.orZero import jp.co.soramitsu.coredb.dao.OperationDao import jp.co.soramitsu.coredb.dao.PhishingDao import jp.co.soramitsu.coredb.dao.emptyAccountIdValue import jp.co.soramitsu.coredb.model.AssetUpdateItem import jp.co.soramitsu.coredb.model.AssetWithToken import jp.co.soramitsu.coredb.model.OperationLocal import jp.co.soramitsu.coredb.model.PhishingLocal import jp.co.soramitsu.fearless_utils.runtime.AccountId import jp.co.soramitsu.fearless_utils.runtime.extrinsic.ExtrinsicBuilder import jp.co.soramitsu.runtime.ext.accountIdOf import jp.co.soramitsu.runtime.ext.addressOf import jp.co.soramitsu.runtime.ext.utilityAsset import jp.co.soramitsu.runtime.multiNetwork.ChainRegistry import jp.co.soramitsu.runtime.multiNetwork.chain.model.Chain import jp.co.soramitsu.runtime.multiNetwork.chain.model.ChainId import jp.co.soramitsu.wallet.api.data.cache.AssetCache import jp.co.soramitsu.wallet.impl.data.mappers.mapAssetLocalToAsset import jp.co.soramitsu.wallet.impl.data.network.blockchain.SubstrateRemoteSource import jp.co.soramitsu.wallet.impl.data.network.phishing.PhishingApi import jp.co.soramitsu.wallet.impl.domain.interfaces.WalletConstants import jp.co.soramitsu.wallet.impl.domain.interfaces.WalletRepository import jp.co.soramitsu.wallet.impl.domain.model.Asset import jp.co.soramitsu.wallet.impl.domain.model.Asset.Companion.createEmpty import jp.co.soramitsu.wallet.impl.domain.model.AssetWithStatus import jp.co.soramitsu.wallet.impl.domain.model.Fee import jp.co.soramitsu.wallet.impl.domain.model.Transfer import jp.co.soramitsu.wallet.impl.domain.model.TransferValidityStatus import jp.co.soramitsu.wallet.impl.domain.model.amountFromPlanks import jp.co.soramitsu.wallet.impl.domain.model.planksFromAmount import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.withContext import jp.co.soramitsu.core.models.Asset as CoreAsset class WalletRepositoryImpl( private val substrateSource: SubstrateRemoteSource, private val operationDao: OperationDao, private val httpExceptionHandler: HttpExceptionHandler, private val phishingApi: PhishingApi, private val assetCache: AssetCache, private val walletConstants: WalletConstants, private val phishingDao: PhishingDao, private val coingeckoApi: CoingeckoApi, private val chainRegistry: ChainRegistry, private val availableFiatCurrencies: GetAvailableFiatCurrencies, private val updatesMixin: UpdatesMixin, private val remoteConfigFetcher: RemoteConfigFetcher, private val networkStateMixin: NetworkStateMixin ) : WalletRepository, UpdatesProviderUi by updatesMixin { companion object { private const val COINGECKO_REQUEST_DELAY_MILLIS = 60 * 1000 } private val coingeckoCache = mutableMapOf<String, MutableMap<String, Pair<Long, BigDecimal>>>() override fun assetsFlow(meta: MetaAccount): Flow<List<AssetWithStatus>> { return combine( chainRegistry.chainsById, assetCache.observeAssets(meta.id) ) { chainsById, assetsLocal -> val chainAccounts = meta.chainAccounts.values.toList() val updatedAssets = assetsLocal.mapNotNull { asset -> mapAssetLocalToAsset(chainsById, asset)?.let { val hasChainAccount = asset.asset.chainId in chainAccounts.mapNotNull { it.chain?.id } AssetWithStatus( asset = it, hasAccount = !it.accountId.contentEquals(emptyAccountIdValue), hasChainAccount = hasChainAccount ) } } val assetsByChain: List<AssetWithStatus> = chainsById.values .flatMap { chain -> chain.assets.map { AssetWithStatus( asset = createEmpty( chainAsset = it, metaId = meta.id, accountId = meta.accountId(chain) ?: emptyAccountIdValue, minSupportedVersion = chain.minSupportedVersion, enabled = chain.nodes.isNotEmpty() ), hasAccount = !chain.isEthereumBased || meta.ethereumPublicKey != null, hasChainAccount = chain.id in chainAccounts.mapNotNull { it.chain?.id } ) } } val assetsByUniqueAccounts = chainAccounts .mapNotNull { chainAccount -> createEmpty(chainAccount)?.let { asset -> AssetWithStatus( asset = asset, hasAccount = true, hasChainAccount = false ) } } val notUpdatedAssetsByUniqueAccounts = assetsByUniqueAccounts.filter { unique -> !updatedAssets.any { it.asset.token.configuration.chainToSymbol == unique.asset.token.configuration.chainToSymbol && it.asset.accountId.contentEquals(unique.asset.accountId) } } val notUpdatedAssets = assetsByChain.filter { it.asset.token.configuration.chainToSymbol !in updatedAssets.map { it.asset.token.configuration.chainToSymbol } } val assetsWithProblems = notUpdatedAssetsByUniqueAccounts + notUpdatedAssets val issues = buildNetworkIssues(assetsWithProblems) networkStateMixin.notifyAssetsProblem(issues) updatedAssets + notUpdatedAssetsByUniqueAccounts + notUpdatedAssets } } private fun buildNetworkIssues(items: List<AssetWithStatus>): Set<NetworkIssueItemState> { return items.map { NetworkIssueItemState( iconUrl = it.asset.token.configuration.iconUrl, title = "${it.asset.token.configuration.chainName} ${it.asset.token.configuration.name}", type = NetworkIssueType.Node, chainId = it.asset.token.configuration.chainId, chainName = it.asset.token.configuration.chainName, assetId = it.asset.token.configuration.id, priceId = it.asset.token.configuration.priceId ) }.toSet() } override suspend fun getAssets(metaId: Long): List<Asset> = withContext(Dispatchers.Default) { val chainsById = chainRegistry.chainsById.first() val assetsLocal = assetCache.getAssets(metaId) assetsLocal.mapNotNull { mapAssetLocalToAsset(chainsById, it) } } private fun mapAssetLocalToAsset( chainsById: Map<ChainId, Chain>, assetLocal: AssetWithToken ): Asset? { val (chain, chainAsset) = try { val chain = chainsById.getValue(assetLocal.asset.chainId) val asset = chain.assetsById.getValue(assetLocal.asset.id) chain to asset } catch (e: Exception) { return null } return mapAssetLocalToAsset(assetLocal, chainAsset, chain.minSupportedVersion) } override suspend fun syncAssetsRates(currencyId: String) { val chains = chainRegistry.currentChains.first() val priceIds = chains.map { it.assets.mapNotNull { it.priceId } }.flatten().toSet() val priceStats = getAssetPriceCoingecko(*priceIds.toTypedArray(), currencyId = currencyId) updatesMixin.startUpdateTokens(priceIds) priceIds.forEach { priceId -> val stat = priceStats[priceId] ?: return@forEach val price = stat[currencyId] val changeKey = "${currencyId}_24h_change" val change = stat[changeKey] val fiatCurrency = availableFiatCurrencies[currencyId] updateAssetRates(priceId, fiatCurrency?.symbol, price, change) } updatesMixin.finishUpdateTokens(priceIds) } override fun assetFlow(metaId: Long, accountId: AccountId, chainAsset: CoreAsset, minSupportedVersion: String?): Flow<Asset> { return assetCache.observeAsset(metaId, accountId, chainAsset.chainId, chainAsset.id) .mapNotNull { it } .mapNotNull { mapAssetLocalToAsset(it, chainAsset, minSupportedVersion) } } override suspend fun getAsset(metaId: Long, accountId: AccountId, chainAsset: CoreAsset, minSupportedVersion: String?): Asset? { val assetLocal = assetCache.getAsset(metaId, accountId, chainAsset.chainId, chainAsset.id) return assetLocal?.let { mapAssetLocalToAsset(it, chainAsset, minSupportedVersion) } } override suspend fun updateAssetHidden( metaId: Long, accountId: AccountId, isHidden: Boolean, chainAsset: CoreAsset ) { val updateItems = listOf( AssetUpdateItem( metaId = metaId, chainId = chainAsset.chainId, accountId = accountId, id = chainAsset.id, sortIndex = Int.MAX_VALUE, // Int.MAX_VALUE on sorting because we don't use it anymore - just random value enabled = !isHidden, tokenPriceId = chainAsset.priceId ) ) assetCache.updateAsset(updateItems) } override suspend fun getTransferFee( chain: Chain, transfer: Transfer, additional: (suspend ExtrinsicBuilder.() -> Unit)?, batchAll: Boolean ): Fee { val fee = substrateSource.getTransferFee(chain, transfer, additional, batchAll) return Fee( transferAmount = transfer.amount, feeAmount = chain.utilityAsset.amountFromPlanks(fee) ) } override suspend fun performTransfer( accountId: AccountId, chain: Chain, transfer: Transfer, fee: BigDecimal, tip: BigInteger?, additional: (suspend ExtrinsicBuilder.() -> Unit)?, batchAll: Boolean ): String { val operationHash = substrateSource.performTransfer(accountId, chain, transfer, tip, additional, batchAll) val accountAddress = chain.addressOf(accountId) val operation = createOperation( operationHash, transfer, accountAddress, fee, OperationLocal.Source.APP ) operationDao.insert(operation) return operationHash } override suspend fun checkTransferValidity( metaId: Long, accountId: AccountId, chain: Chain, transfer: Transfer, additional: (suspend ExtrinsicBuilder.() -> Unit)?, batchAll: Boolean ): TransferValidityStatus { val feeResponse = getTransferFee(chain, transfer, additional, batchAll) val chainAsset = transfer.chainAsset val recipientAccountId = chain.accountIdOf(transfer.recipient) val totalRecipientBalanceInPlanks = substrateSource.getTotalBalance(chainAsset, recipientAccountId) val totalRecipientBalance = chainAsset.amountFromPlanks(totalRecipientBalanceInPlanks) val assetLocal = assetCache.getAsset(metaId, accountId, chainAsset.chainId, chainAsset.id)!! val asset = mapAssetLocalToAsset(assetLocal, chainAsset, chain.minSupportedVersion) val existentialDepositInPlanks = walletConstants.existentialDeposit(chainAsset).orZero() val existentialDeposit = chainAsset.amountFromPlanks(existentialDepositInPlanks) val utilityAssetLocal = assetCache.getAsset(metaId, accountId, chainAsset.chainId, chain.utilityAsset.id)!! val utilityAsset = mapAssetLocalToAsset(utilityAssetLocal, chain.utilityAsset, chain.minSupportedVersion) val utilityExistentialDepositInPlanks = walletConstants.existentialDeposit(chain.utilityAsset).orZero() val utilityExistentialDeposit = chain.utilityAsset.amountFromPlanks(utilityExistentialDepositInPlanks) val tipInPlanks = kotlin.runCatching { walletConstants.tip(chain.id) }.getOrNull() val tip = tipInPlanks?.let { chain.utilityAsset.amountFromPlanks(it) } return transfer.validityStatus( senderTransferable = asset.transferable, senderTotal = asset.total.orZero(), fee = feeResponse.feeAmount, recipientBalance = totalRecipientBalance, existentialDeposit = existentialDeposit, isUtilityToken = chainAsset.isUtility, senderUtilityBalance = utilityAsset.total.orZero(), utilityExistentialDeposit = utilityExistentialDeposit, tip = tip ) } override suspend fun updatePhishingAddresses() = withContext(Dispatchers.Default) { val phishingAddresses = phishingApi.getPhishingAddresses() val phishingLocal = CSVReaderHeaderAware(phishingAddresses.byteStream().bufferedReader()).mapNotNull { try { PhishingLocal( name = it[0], address = it[1], type = it[2], subtype = it[3] ) } catch (e: Exception) { e.printStackTrace() null } } phishingDao.clearTable() phishingDao.insert(phishingLocal) } override suspend fun isAddressFromPhishingList(address: String) = withContext(Dispatchers.Default) { val phishingAddresses = phishingDao.getAllAddresses().map { it.lowercase() } phishingAddresses.contains(address.lowercase()) } override suspend fun getPhishingInfo(address: String): PhishingLocal? { return phishingDao.getPhishingInfo(address) } override suspend fun getAccountFreeBalance(chainAsset: CoreAsset, accountId: AccountId) = substrateSource.getAccountFreeBalance(chainAsset, accountId) override suspend fun getEquilibriumAssetRates(chainAsset: CoreAsset) = substrateSource.getEquilibriumAssetRates(chainAsset) override suspend fun getEquilibriumAccountInfo(asset: CoreAsset, accountId: AccountId) = substrateSource.getEquilibriumAccountInfo(asset, accountId) override suspend fun updateAssets(newItems: List<AssetUpdateItem>) { assetCache.updateAsset(newItems) } private fun createOperation( hash: String, transfer: Transfer, senderAddress: String, fee: BigDecimal, source: OperationLocal.Source ) = OperationLocal.manualTransfer( hash = hash, address = senderAddress, chainAssetId = transfer.chainAsset.id, chainId = transfer.chainAsset.chainId, amount = transfer.amountInPlanks, senderAddress = senderAddress, receiverAddress = transfer.recipient, fee = transfer.chainAsset.planksFromAmount(fee), status = OperationLocal.Status.PENDING, source = source ) private suspend fun updateAssetRates( priceId: String, fiatSymbol: String?, price: BigDecimal?, change: BigDecimal? ) = assetCache.updateTokenPrice(priceId) { cached -> cached.copy( fiatRate = price, fiatSymbol = fiatSymbol, recentRateChange = change ) } override suspend fun getSingleAssetPriceCoingecko(priceId: String, currency: String): BigDecimal? { coingeckoCache[priceId]?.get(currency)?.let { (cacheUntilMillis, cachedValue) -> if (System.currentTimeMillis() <= cacheUntilMillis) { return cachedValue } } val apiValue = apiCall { coingeckoApi.getSingleAssetPrice(priceIds = priceId, currency = currency) }.getOrDefault(priceId, null)?.getOrDefault(currency, null)?.toBigDecimal() apiValue?.let { val currencyMap = coingeckoCache[priceId] ?: mutableMapOf() val cacheUntilMillis = System.currentTimeMillis() + COINGECKO_REQUEST_DELAY_MILLIS currencyMap[currency] = cacheUntilMillis to apiValue coingeckoCache[priceId] = currencyMap } return apiValue } private suspend fun getAssetPriceCoingecko(vararg priceId: String, currencyId: String): Map<String, Map<String, BigDecimal>> { return apiCall { coingeckoApi.getAssetPrice(priceId.joinToString(","), currencyId, true) } } private suspend fun <T> apiCall(block: suspend () -> T): T = httpExceptionHandler.wrap(block) override suspend fun getRemoteConfig(): Result<AppConfigRemote> { return kotlin.runCatching { remoteConfigFetcher.getAppConfig() } } override fun chainRegistrySyncUp() { chainRegistry.syncUp() } }
9
Kotlin
22
75
a1eb05228f80c3a7a1997295ae411ec130ad20ba
17,906
fearless-Android
Apache License 2.0
idea/testData/intentions/objectLiteralToLambda/SingleReturn.kt
JakeWharton
99,388,807
false
null
// WITH_RUNTIME import java.io.File import java.io.FileFilter fun foo(filter: FileFilter) {} fun bar() { foo(<caret>object: FileFilter { override fun accept(file: File): Boolean { return file.name.startsWith("a") } }) }
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
258
kotlin
Apache License 2.0
kotlin_springboot_maven/src/main/kotlin/com/yzq/kotlin_springboot_maven/dao/mapper/UserMapper.kt
yuzhiqiang1993
164,573,948
false
{"Java": 148136, "Kotlin": 67556, "TypeScript": 7572, "JavaScript": 3117, "HTML": 580, "CSS": 188}
package com.yzq.kotlin_springboot_maven.dao.mapper import com.baomidou.mybatisplus.core.mapper.BaseMapper import com.yzq.kotlin_springboot_maven.dao.data.User import org.apache.ibatis.annotations.Mapper import org.apache.ibatis.annotations.Param @Mapper interface UserMapper : BaseMapper<User> { fun updateBatch(list: List<User>): Int fun batchInsert(@Param("list") list: List<User>): Int fun insertOrUpdate(record: User): Int fun insertOrUpdateSelective(record: User): Int fun queryCount(@Param("searchKey") searchKey: String): Long fun pageList( @Param("searchKey") searchKey: String, @Param("start") start: Long, @Param("pageSize") pageSize: Long, ): List<User> }
4
Java
0
0
f085e24260c0d274c08ef61c80c7d6f464f1f778
720
JavaWebStudy
MIT License
shared/schedule/schedule-info/src/commonMain/kotlin/io/edugma/features/schedule/scheduleInfo/lessonInfo/LessonInfoViewModel.kt
Edugma
474,423,768
false
null
package io.edugma.features.schedule.scheduleInfo.lessonInfo import io.edugma.core.arch.mvi.updateState import io.edugma.core.arch.mvi.viewmodel.BaseViewModel import io.edugma.core.arch.mvi.viewmodel.prop import io.edugma.core.navigation.schedule.ScheduleInfoScreens import io.edugma.core.utils.viewmodel.launchCoroutine import io.edugma.features.schedule.domain.model.lesson.LessonInfo import io.edugma.features.schedule.domain.model.teacher.TeacherInfo import io.edugma.features.schedule.domain.usecase.ScheduleUseCase import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.first class LessonInfoViewModel( private val scheduleUseCase: ScheduleUseCase, ) : BaseViewModel<LessonInfoState>(LessonInfoState()) { init { launchCoroutine { state.prop { lessonInfo } .collectLatest { val teachers = it?.lesson?.teachers?.map { scheduleUseCase.getTeacher(it.id).first() }?.filterNotNull() ?: emptyList() updateState { copy( teachers = teachers, ) } } } } fun onLessonInfo(lessonInfo: LessonInfo?) { updateState { copy(lessonInfo = lessonInfo) } } fun onTeacherClick(id: String) { router.navigateTo(ScheduleInfoScreens.TeacherInfo(id)) } fun onGroupClick(id: String) { router.navigateTo(ScheduleInfoScreens.GroupInfo(id)) } fun onPlaceClick(id: String) { router.navigateTo(ScheduleInfoScreens.PlaceInfo(id)) } } data class LessonInfoState( val lessonInfo: LessonInfo? = null, val teachers: List<TeacherInfo> = emptyList(), )
1
Kotlin
0
2
d84fec0ecc682a97ae4ac385c5e1a9a8565df4a8
1,791
app
MIT License
feature/discover/src/main/java/org/hxl/discover/menu/charcater/adapter/CharacterViewHolder.kt
hexley21
657,343,982
false
null
package org.hxl.discover.menu.charcater.adapter import org.hxl.common.base.BaseViewHolder import org.hxl.discover.databinding.CharacterItemBinding import org.hxl.model.Character class CharacterViewHolder( private val favLogic: (isAdd: Boolean, id: Int) -> Unit, binding: CharacterItemBinding ): BaseViewHolder<CharacterItemBinding, Character>(binding) { override fun accept(t: Character) { binding.character = t binding.cbFavorite.setOnCheckedChangeListener { _, isChecked -> favLogic(isChecked, t.id) } } }
1
Kotlin
0
0
44941d167e70d5bc28a5fcd15be4bd99f250df5e
562
ForceFacts
Apache License 2.0
src/main/kotlin/org/letses/persistence/AggregateRepository.kt
masayoshi-louis
680,742,400
false
null
/* * Copyright (c) 2022 LETSES.org * * 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 org.letses.persistence import org.letses.domain.AggregateMsgHandlerContext import org.letses.domain.EventSourcedAggregate import org.letses.entity.EntityState import org.letses.messaging.Event import org.letses.persistence.publisher.EventPublisher class AggregateRepository<S : EntityState, E : Event>( model: EventSourcedAggregate<S, E>, eventStore: EventStore<E>, snapshotStore: SnapshotStore<S>? = null, eventPublisher: EventPublisher<E>? = null, consistentSnapshotTxManager: ConsistentSnapshotTxManager = ConsistentSnapshotTxManager.PSEUDO, ) : AbstractRepository<S, E, AggregateMsgHandlerContext>( model, eventStore, snapshotStore, eventPublisher, consistentSnapshotTxManager )
0
Kotlin
0
0
92d597568f45e1b336325d5f84080196d32e51d4
1,331
letses
Apache License 2.0
app/src/main/java/vn/loitp/up/a/cv/layout/transformation/TransformationActivity.kt
tplloi
126,578,283
false
null
package vn.loitp.up.a.cv.layout.transformation import android.os.Bundle import androidx.viewpager.widget.ViewPager import com.loitp.annotation.IsFullScreen import com.loitp.annotation.LogTag import com.loitp.core.base.BaseActivityFont import com.loitp.core.common.NOT_FOUND import com.skydoves.transformationlayout.onTransformationStartContainer import vn.loitp.R import vn.loitp.databinding.ATransformationMainBinding // https://github.com/skydoves/TransformationLayout @LogTag("TransformationActivity") @IsFullScreen(false) class TransformationActivity : BaseActivityFont() { private lateinit var binding: ATransformationMainBinding override fun setLayoutResourceId(): Int { return NOT_FOUND } override fun onCreate(savedInstanceState: Bundle?) { onTransformationStartContainer() super.onCreate(savedInstanceState) binding = ATransformationMainBinding.inflate(layoutInflater) setContentView(binding.root) with(binding.mainViewPager) { adapter = TransformationPagerAdapter(supportFragmentManager) offscreenPageLimit = 3 addOnPageChangeListener( object : ViewPager.OnPageChangeListener { override fun onPageScrollStateChanged(state: Int) = Unit override fun onPageScrolled( position: Int, positionOffset: Float, positionOffsetPixels: Int ) = Unit override fun onPageSelected(position: Int) { binding.mainBottomNavigation.menu.getItem(position).isChecked = true } } ) } binding.mainBottomNavigation.setOnItemSelectedListener { when (it.itemId) { R.id.actionHome -> { binding.mainViewPager.currentItem = 0 } R.id.actionLibray -> { binding.mainViewPager.currentItem = 1 } R.id.actionRadio -> { binding.mainViewPager.currentItem = 2 } } true } } }
1
null
1
9
1bf1d6c0099ae80c5f223065a2bf606a7542c2b9
2,214
base
Apache License 2.0
features/detail/domain/src/main/kotlin/com/manuelnunez/apps/features/detail/domain/repository/DetailRepository.kt
manununhez
783,961,200
false
{"Kotlin": 208528}
package com.manuelnunez.apps.features.detail.domain.repository import com.manuelnunez.apps.core.domain.model.Item import kotlinx.coroutines.flow.Flow interface DetailRepository { suspend fun saveFavoriteItem(favoriteItem: Item) suspend fun removeFavoriteItem(favoriteItem: Item) fun isItemFavorite(itemPhotoId: String): Flow<Boolean> }
0
Kotlin
0
0
9c031f9f026a90cb92b19716e65994c4b5b0ac1d
346
purrfect-pics
MIT License
src/main/kotlin/com.franzmandl.fileadmin/model/config/DirectoryVersioned.kt
franzmandl
570,884,978
false
null
package com.franzmandl.fileadmin.model.config import com.franzmandl.fileadmin.common.CommonUtil import com.franzmandl.fileadmin.vfs.SafePath import com.franzmandl.fileadmin.vfs.UnsafePath import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.Transient import java.nio.file.Path import java.nio.file.PathMatcher @Serializable sealed class ConfigRoot { abstract val imports: List<UnsafePath?>? } @Serializable sealed class ConfigValue : ConfigRoot() @Serializable sealed class DirectoryVersioned : ConfigRoot() { abstract fun toLatestVersion(): DirectoryVersion1 } @Serializable @SerialName("DirectoryVersion1") data class DirectoryVersion1( val filter: FilterVersioned? = null, override val imports: List<UnsafePath?>? = null, val tags: List<TagVersioned?>? = null, val values: List<ConfigValue?>? = null, ) : DirectoryVersioned() { override fun toLatestVersion(): DirectoryVersion1 = this } @Serializable sealed class DirectoryValueVersioned : ConfigValue() { abstract fun toLatestVersion(): DirectoryValueVersion1 } @Serializable @SerialName("DirectoryValueVersion1") data class DirectoryValueVersion1( val condition: ConditionVersioned? = null, override val imports: List<UnsafePath?>? = null, val nameCursorPosition: Int? = null, val newInodeTemplate: NewInodeVersioned? = null, val runLast: RunLastVersioned? = null, val tasks: TasksVersioned? = null, ) : DirectoryValueVersioned() { override fun toLatestVersion(): DirectoryValueVersion1 = this } @Serializable sealed class ConditionVersioned { abstract fun toLatestVersion(): ConditionVersion1 } class CompiledCondition( val nameGlobs: List<PathMatcher>?, val nameRegex: Regex?, val pathRegex: Regex?, ) { constructor( nameGlobString: String?, nameRegexString: String?, pathRegexString: String?, ) : this( nameGlobString?.split(orSeparator)?.map { CommonUtil.createGlob(it) }, nameRegexString?.let { Regex(it) }, pathRegexString?.let { Regex(it) }, ) fun evaluate(path: SafePath): Boolean = nameGlobs?.let { CommonUtil.evaluateGlobs(it, Path.of(path.name)) } ?: false || nameRegex?.containsMatchIn(path.name) ?: false || pathRegex?.containsMatchIn(path.absoluteString) ?: false companion object { private const val orSeparator = '|' } } @Serializable @SerialName("ConditionVersion1") data class ConditionVersion1( val directoryNameGlob: String? = null, val directoryNameRegex: String? = null, val directoryPathRegex: String? = null, val fileNameGlob: String? = null, val fileNameRegex: String? = null, val filePathRegex: String? = null, /** * 0 ... The parent directory of the config file. * 1 ... Siblings of the config file and config file itself. * 2 ... And so forth. */ val nameGlob: String? = null, val nameRegex: String? = null, val minDepth: Int? = null, val maxDepth: Int? = null, val pathRegex: String? = null, ) : ConditionVersioned() { @Transient val commonCondition = CompiledCondition(nameGlob, nameRegex, pathRegex) @Transient val directoryCondition = CompiledCondition(directoryNameGlob, directoryNameRegex, directoryPathRegex) @Transient val fileCondition = CompiledCondition(fileNameGlob, fileNameRegex, filePathRegex) @Transient val defaultMinDepth = minDepth ?: 0 @Transient val defaultMaxDepth = maxDepth ?: defaultMinDepth override fun toLatestVersion(): ConditionVersion1 = this companion object { val default = ConditionVersion1() } } @Serializable sealed class NewInodeVersioned : ConfigValue() { abstract fun toLatestVersion(): NewInodeVersion1 } @Serializable @SerialName("NewInodeVersion1") data class NewInodeVersion1( val condition: ConditionVersioned? = null, val isFile: Boolean? = null, val name: String? = null, override val imports: List<UnsafePath?>? = null, ) : NewInodeVersioned() { override fun toLatestVersion(): NewInodeVersion1 = this } @Serializable sealed class RunLastVersioned : ConfigValue() { abstract fun toLatestVersion(): RunLastVersion1 } @Serializable @SerialName("RunLastVersion1") data class RunLastVersion1( val condition: ConditionVersioned? = null, val enable: Boolean? = null, override val imports: List<UnsafePath?>? = null, ) : RunLastVersioned() { override fun toLatestVersion(): RunLastVersion1 = this } @Serializable sealed class TasksVersioned : ConfigValue() { abstract fun toLatestVersion(): TasksVersion1 } @Serializable @SerialName("TasksVersion1") data class TasksVersion1( val condition: ConditionVersioned? = null, val enable: Boolean? = null, override val imports: List<UnsafePath?>? = null, ) : TasksVersioned() { override fun toLatestVersion(): TasksVersion1 = this }
0
Kotlin
0
0
9e7a3f2876688627b24a98a2fe58027b4d733ce2
4,967
fileadmin-server
MIT License
src/main/kotlin/me/jakejmattson/anytoimage/utils/ImageWriter.kt
JakeJMattson
117,714,118
false
null
package me.jakejmattson.anytoimage.utils import java.awt.image.BufferedImage import java.io.* import javax.imageio.ImageIO class ImageWriter(dimensions: Int) { private var image: BufferedImage = BufferedImage(dimensions, dimensions, BufferedImage.TYPE_INT_RGB) private var row: Int = 0 private var col: Int = 0 fun writePixel(pixel: Int) { image.setRGB(row, col, pixel) row++ if (row == image.width) { row = 0 col++ } } fun saveImage(outputFile: File) { try { ImageIO.write(image, "png", outputFile) } catch (e: IOException) { Logger.displayException(e, "Error creating image!") } } }
1
Kotlin
1
12
86566fc40ebcd0f0afe85ee94c9436d7d53a1f2a
721
AnyToImage
MIT License
src/main/kotlin/ua/pp/lumivoid/redstonehelper/gui/MacroScreen.kt
Bumer-32
779,465,671
false
null
package ua.pp.lumivoid.redstonehelper.gui import io.wispforest.owo.ui.base.BaseUIModelScreen import io.wispforest.owo.ui.component.ButtonComponent import io.wispforest.owo.ui.component.CheckboxComponent import io.wispforest.owo.ui.component.Components import io.wispforest.owo.ui.component.LabelComponent import io.wispforest.owo.ui.container.Containers import io.wispforest.owo.ui.container.FlowLayout import io.wispforest.owo.ui.core.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import net.minecraft.client.MinecraftClient import net.minecraft.client.gui.screen.Screen import net.minecraft.text.Text import net.minecraft.util.Identifier import net.minecraft.util.Util import org.lwjgl.system.MemoryStack import org.lwjgl.util.tinyfd.TinyFileDialogs import ua.pp.lumivoid.redstonehelper.Constants import ua.pp.lumivoid.redstonehelper.keybindings.MacrosKeyBindings import ua.pp.lumivoid.redstonehelper.owocomponents.TexturedButton import ua.pp.lumivoid.redstonehelper.util.Macro import ua.pp.lumivoid.redstonehelper.util.features.Macros import java.util.concurrent.CompletableFuture class MacroScreen(private val parent: Screen?): BaseUIModelScreen<FlowLayout>(FlowLayout::class.java, DataSource.asset(Identifier.of(Constants.MOD_ID, "macro_ui_model"))) { private val logger = Constants.LOGGER private var macrosLayout: FlowLayout? = null private var loading: LabelComponent? = null override fun build(rootComponent: FlowLayout) { logger.debug("Building MacroScreen UI") // val mainPanel = rootComponent.childById(FlowLayout::class.java, "main-panel") loading = rootComponent.childById(LabelComponent::class.java, "loading") val instrumentsContainer = rootComponent.childById(FlowLayout::class.java, "instruments_container") val newMacroButton = rootComponent.childById(ButtonComponent::class.java, "new_macro_button") val doneButton = rootComponent.childById(ButtonComponent::class.java, "done_button") macrosLayout = rootComponent.childById(FlowLayout::class.java, "macros_panel") instrumentsContainer.child(0, TexturedButton(Identifier.of(Constants.MOD_ID, "export_all")) { export(Macros.listMacros().map { it.name }.toMutableList()) }.sizing(Sizing.fixed(20)).tooltip(Text.translatable(Constants.LOCALIZEIDS.FEATURE_MACRO_TOOLTIP_EXPORTALL)).margins(Insets.right(5)) ) instrumentsContainer.child(1, TexturedButton(Identifier.of(Constants.MOD_ID, "import")) { import() }.sizing(Sizing.fixed(20)).tooltip(Text.translatable(Constants.LOCALIZEIDS.FEATURE_MACRO_TOOLTIP_IMPORT)).margins(Insets.right(5)) ) macrosLayout!!.gap(1) update() newMacroButton.onPress { this.client!!.setScreen(MacroEditScreen(this, "My Super Macro", true)) } doneButton.onPress { if (parent == null) { this.close() } else { this.client!!.setScreen(parent) } } } private fun addMacro(name: String, enabled: Boolean) { @Suppress("DuplicatedCode") macrosLayout!!.child( Containers.horizontalFlow(Sizing.fill(), Sizing.fixed(32)) .child( Containers.horizontalFlow(Sizing.fixed(450), Sizing.fill()) .child( Containers.horizontalFlow(Sizing.content(), Sizing.content()) .configure { layout: FlowLayout -> layout.positioning(Positioning.relative(100, 50)) layout.margins(Insets.right(10)) layout.child( TexturedButton(Identifier.of(Constants.MOD_ID, "export")) { export(mutableListOf(name)) }.sizing(Sizing.fixed(20), Sizing.fixed(20)) .margins(Insets.right(5)) .tooltip(Text.translatable(Constants.LOCALIZEIDS.FEATURE_MACRO_TOOLTIP_EXPORT)) ) layout.child( TexturedButton(Identifier.of(Constants.MOD_ID, "pencil")) { this.client!!.setScreen(MacroEditScreen(this, name, false)) }.sizing(Sizing.fixed(20), Sizing.fixed(20)) .margins(Insets.right(5)) .tooltip(Text.translatable(Constants.LOCALIZEIDS.FEATURE_MACRO_TOOLTIP_EDIT)) ) layout.child( TexturedButton(Identifier.of(Constants.MOD_ID, "cross")) { Macros.removeMacro(name) update() }.sizing(Sizing.fixed(20), Sizing.fixed(20)) .tooltip(Text.translatable(Constants.LOCALIZEIDS.FEATURE_MACRO_TOOLTIP_DELETE)) ) } ) .child( Containers.horizontalFlow(Sizing.fixed(350), Sizing.content()) .child( Components.checkbox(Text.empty()) .tooltip(Text.translatable(Constants.LOCALIZEIDS.FEATURE_MACRO_TOOLTIP_ENABLEDFORKEYBINDS)) .margins(Insets.top(1)) .configure { val checkBox = it as CheckboxComponent checkBox.checked(enabled) checkBox.onChanged { checked -> logger.debug("Macro $name enabled: $checked") val macro = Macros.readMacro(name) macro!!.enabled = checked Macros.editMacro(name, macro) MacrosKeyBindings.updateMacros() update() } } ) .child( Components.label(Text.literal(name)) .margins(Insets.of(5, 0, 5, 0)) //checkbox buggy and already has margin ) .positioning(Positioning.relative(0, 50)) .margins(Insets.left(10)) ) .surface(Surface.flat(0xFF0F0F0F.toInt())) .verticalAlignment(VerticalAlignment.CENTER) ) .horizontalAlignment(HorizontalAlignment.CENTER) .id(name) ) } private fun import() { val checkList = Macros.listMacros().toString() // Importing CompletableFuture.runAsync({ MemoryStack.stackPush().use { stack -> val filters = stack.mallocPointer(1) filters.put(stack.UTF8("*.json")) filters.flip() // animation var animateLoading = true CoroutineScope(Dispatchers.Default).launch { MinecraftClient.getInstance().submit { loading!!.text(Text.literal("●")) } while (animateLoading) { loading!!.positioning().animate(1000, Easing.EXPO, Positioning.relative(55, 50)).forwards() delay(1000) loading!!.positioning().animate(1000, Easing.EXPO, Positioning.relative(45, 50)).forwards() delay(1000) } loading!!.positioning().animate(1000, Easing.EXPO, Positioning.relative(50, 50)).forwards() delay(1000) MinecraftClient.getInstance().submit { loading!!.text(Text.literal("")) } } // File chooser var path = TinyFileDialogs.tinyfd_openFileDialog( Text.translatable(Constants.LOCALIZEIDS.FEATURE_MACRO_DIALOG_IMPORT).string, null, null, Text.translatable(Constants.LOCALIZEIDS.FEATURE_MACRO_DIALOG_FILENAME).string, true ) if (path != null) { val paths = path.split("|") paths.forEach { macroPath -> logger.info("Importing macros from $macroPath") val importedMacros = Macros.importMacro(macroPath) importedMacros?.forEach { macro -> macro.enabled = false // Import ALWAYS disabled macro.name = generateSequence(macro.name) { it + "_1" } // Don't allow to create macros with same name .first { Macros.readMacro(it) == null } Macros.addMacro(macro) } } } else { logger.info("Import canceled") } animateLoading = false } }, Util.getMainWorkerExecutor()).whenComplete { unused, throwable -> logger.info("End of import") if (checkList != Macros.listMacros().toString()) { MinecraftClient.getInstance().submit { // In RENDER THREAD!!! IT'S VERY IMPORTANT logger.info("Update") update() } } } } private fun export(macros: MutableList<String>) { // Exporting CompletableFuture.runAsync({ MemoryStack.stackPush().use { stack -> val filters = stack.mallocPointer(1) filters.put(stack.UTF8("*.json")) filters.flip() val path: String? = TinyFileDialogs.tinyfd_saveFileDialog( Text.translatable(Constants.LOCALIZEIDS.FEATURE_MACRO_DIALOG_EXPORT).string, null, filters, Text.translatable(Constants.LOCALIZEIDS.FEATURE_MACRO_DIALOG_FILENAME).string ) if (path != null) { macros.forEachIndexed { index, macro -> logger.info("Exporting macro $macro to $path:$index") } Macros.exportMacro(path, macros) } else { logger.info("Export canceled") } } }, Util.getMainWorkerExecutor()).whenComplete { unused, throwable -> logger.info("End of export") } } fun update() { macrosLayout!!.clearChildren() Macros.listMacros().forEach { macro: Macro -> addMacro(macro.name, macro.enabled) } } }
0
null
1
3
45d9e9611bb766939dd4aef87200256d665c7405
11,719
Redstone-Helper
Apache License 2.0
core/src/main/kotlin/spp/jetbrains/instrument/presentation/LiveVariableNode.kt
sourceplusplus
173,253,271
false
{"Kotlin": 1227211, "Java": 190403, "JavaScript": 3929, "Groovy": 3042, "Python": 2564}
/* * Source++, the continuous feedback platform for developers. * Copyright (C) 2022-2024 CodeBrig, 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 spp.jetbrains.instrument.presentation import com.intellij.ui.treeStructure.SimpleNode import com.intellij.xdebugger.impl.ui.DebuggerUIUtil import io.vertx.core.json.JsonArray import io.vertx.core.json.JsonObject import org.apache.commons.lang3.EnumUtils import spp.protocol.instrument.variable.LiveVariable import spp.protocol.instrument.variable.LiveVariableScope /** * todo: description. * * @since 0.7.0 * @author [Brandon Fergerson](mailto:[email protected]) */ abstract class LiveVariableNode( val variable: LiveVariable, private val nodeMap: MutableMap<String, Array<SimpleNode>> ) : SimpleNode() { val scheme = DebuggerUIUtil.getColorScheme(null) abstract fun createVariableNode( variable: LiveVariable, nodeMap: MutableMap<String, Array<SimpleNode>> ): SimpleNode override fun getChildren(): Array<SimpleNode> { if (variable.liveIdentity != null && nodeMap.containsKey(variable.liveIdentity)) { //found reference, use children of referenced node return nodeMap[variable.liveIdentity!!] ?: arrayOf() } val children = if (variable.value is JsonArray) { (variable.value as JsonArray).map { JsonObject.mapFrom(it) }.map { if (it.getString("@skip") != null) { ErrorVariableSimpleNode(JsonObject.mapFrom(it).map) } else { createVariableNode(toLiveVariable(it), nodeMap) } }.toList().toTypedArray() } else if (variable.value is LiveVariable) { arrayOf(createVariableNode(variable.value as LiveVariable, nodeMap)) } else { emptyArray() } //add children to nodeMap for reference lookup if (variable.liveIdentity != null && children.isNotEmpty()) { nodeMap[variable.liveIdentity!!] = children } return children } private fun toLiveVariable(it: JsonObject): LiveVariable { var varValue = it.getValue("value") if (varValue is JsonArray && varValue.size() == 1 && (varValue.first() as JsonObject).containsKey("liveClazz") ) { varValue = toLiveVariable(varValue.first() as JsonObject) } return LiveVariable( name = it.getString("name"), value = varValue, lineNumber = it.getInteger("lineNumber") ?: -1, scope = EnumUtils.getEnum(LiveVariableScope::class.java, it.getString("scope")), liveClazz = it.getString("liveClazz"), liveIdentity = it.getString("liveIdentity") ) } override fun getEqualityObjects(): Array<Any> = arrayOf(variable) override fun toString(): String = variable.name }
2
Kotlin
13
87
199006a410529d961dc184f0740a5d845bd87899
3,432
interface-jetbrains
Apache License 2.0
src/main/kotlin/insyncwithfoo/ryecharm/ruff/lsp4ij/RuffServerFactory.kt
InSyncWithFoo
849,672,176
false
null
package insyncwithfoo.ryecharm.ruff.lsp4ij import com.intellij.openapi.project.Project import com.redhat.devtools.lsp4ij.LanguageServerEnablementSupport import com.redhat.devtools.lsp4ij.LanguageServerFactory import com.redhat.devtools.lsp4ij.client.LanguageClientImpl import com.redhat.devtools.lsp4ij.client.features.LSPClientFeatures import com.redhat.devtools.lsp4ij.server.StreamConnectionProvider import insyncwithfoo.ryecharm.configurations.add import insyncwithfoo.ryecharm.configurations.changeRuffConfigurations import insyncwithfoo.ryecharm.configurations.changeRuffOverrides import insyncwithfoo.ryecharm.configurations.ruff.RunningMode import insyncwithfoo.ryecharm.configurations.ruff.ruffConfigurations import insyncwithfoo.ryecharm.configurations.ruffExecutable internal const val SERVER_ID = "ryecharm/ruff" internal class RuffServerFactory : LanguageServerFactory, LanguageServerEnablementSupport { override fun isEnabled(project: Project): Boolean { val configurations = project.ruffConfigurations val runningModeIsLSP4IJ = configurations.runningMode == RunningMode.LSP4IJ val executable = project.ruffExecutable return runningModeIsLSP4IJ && executable != null } override fun setEnabled(enabled: Boolean, project: Project) { project.changeRuffConfigurations { runningMode = when { enabled -> RunningMode.LSP4IJ else -> RunningMode.COMMAND_LINE } project.changeRuffOverrides { add(::runningMode.name) } } } override fun createConnectionProvider(project: Project): StreamConnectionProvider { return RuffServerConnectionProvider.create(project) } override fun createLanguageClient(project: Project): LanguageClientImpl { return RuffServerClient(project) } @Suppress("UnstableApiUsage") override fun createClientFeatures() = LSPClientFeatures().apply { hoverFeature = HoverFeature() diagnosticFeature = DiagnosticFeature() codeActionFeature = CodeActionFeature() formattingFeature = FormattingFeature() } }
2
null
1
7
c1a04b622fbfb02a2fb155d8c9aa069520eda23e
2,188
ryecharm
MIT License
simple_form/src/main/java/com/pradeep/form/simple_form/form_items/MultiLineTextFormItem.kt
lspradeep
360,256,350
false
null
package com.pradeep.form.simple_form.form_items import android.text.InputFilter import androidx.core.widget.doAfterTextChanged import com.pradeep.form.simple_form.adapter.SimpleFormAdapter import com.pradeep.form.simple_form.databinding.ItemMultiLineTextBinding import com.pradeep.form.simple_form.model.Form class MultiLineTextFormItem( private val binding: ItemMultiLineTextBinding, private val adapter: SimpleFormAdapter ) : BaseFormItem(binding.root, adapter) { override fun bind(form: Form) { binding.editAnswer.filters = emptyArray() if (form.charLimit != -1 && form.charLimit > 0) { binding.editAnswer.filters = arrayOf(InputFilter.LengthFilter(form.charLimit)) binding.inputAnswer.counterMaxLength = form.charLimit binding.inputAnswer.isCounterEnabled = true } else { binding.inputAnswer.isCounterEnabled = false } form.hint?.let { binding.inputAnswer.hint = it.toString() } form.answer?.let { answer -> if (answer.isNotBlank()) { binding.editAnswer.setText(answer) } else { binding.editAnswer.text = null binding.inputAnswer.isErrorEnabled=false } } ?: run { binding.editAnswer.text = null binding.inputAnswer.isErrorEnabled=false } binding.editAnswer.doAfterTextChanged { input -> adapter.getData()[adapterPosition].apply { if (isMandatory && input.isNullOrBlank()) { binding.inputAnswer.error = errorMessage } else { answer = input.toString() binding.inputAnswer.isErrorEnabled=false } } } if (!form.isValid) { binding.editAnswer.requestFocus() form.apply { if (isMandatory && answer.isNullOrBlank()) { binding.inputAnswer.error = errorMessage } else { binding.inputAnswer.isErrorEnabled=false } } } else { binding.inputAnswer.isErrorEnabled=false } } }
1
Kotlin
0
4
2b2d8362031b42a4f36239be79d5ca75f1ddbaac
2,242
simple-form
MIT License
preference/preference/src/androidTest/java/androidx/preference/tests/PreferenceViewHolderStateTest.kt
RikkaW
389,105,112
false
null
/* * Copyright 2020 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.preference.tests import android.content.Context import android.graphics.drawable.Drawable import android.widget.TextView import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceViewHolder import androidx.preference.test.R import androidx.preference.tests.helpers.PreferenceTestHelperActivity import androidx.test.annotation.UiThreadTest import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.repeatedlyUntil import androidx.test.espresso.action.ViewActions.swipeUp import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.hasDescendant import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** Test for resetting [PreferenceViewHolder] state. */ @RunWith(AndroidJUnit4::class) @LargeTest class PreferenceViewHolderStateTest { @Suppress("DEPRECATION") @get:Rule val activityRule = androidx.test.rule.ActivityTestRule(PreferenceTestHelperActivity::class.java) private lateinit var fragment: PreferenceFragmentCompat @Before @UiThreadTest fun setUp() { fragment = activityRule.activity.setupPreferenceHierarchy() } @Test fun testReusingViewHolder_unselectablePreference_stateReset() { val preferenceScreen = fragment.preferenceScreen val copyableTitle = "Copyable" // Add 20 unselectable + copyable Preferences. This is so that when we add a new item, it // will be offscreen, and when scrolling to it RecyclerView will attempt to reuse an // existing cached ViewHolder. val preferences = (1..20).map { index -> TestPreference(fragment.context!!).apply { title = copyableTitle + index summary = "Summary to copy" isCopyingEnabled = true isSelectable = false } } activityRule.runOnUiThread { preferences.forEach { preferenceScreen.addPreference(it) } } // Wait for a Preference to be visible onView(withText("${copyableTitle}1")).check(matches(isDisplayed())) // The title color should be the same as the summary color for unselectable Preferences val unselectableTitleColor = preferences[0].titleColor val unselectableSummaryColor = preferences[0].summaryColor assertEquals(unselectableTitleColor!!, unselectableSummaryColor!!) val normalTitle = "Normal" // Add a normal, selectable Preference to the end. This will currently be displayed off // screen, and not yet bound. val normalPreference = TestPreference(fragment.context!!).apply { title = normalTitle summary = "Normal summary" } // Assert that we haven't bound this Preference yet assertNull(normalPreference.background) assertNull(normalPreference.titleColor) assertNull(normalPreference.summaryColor) activityRule.runOnUiThread { preferenceScreen.addPreference(normalPreference) } val maxAttempts = 10 // Scroll until we find the new Preference, which will trigger RecyclerView to rebind an // existing cached ViewHolder, so we can ensure that the state is reset. We use swipeUp // here instead of scrolling directly to the item, as we need to allow time for older // views to be cached first, instead of instantly snapping to the item. onView(withId(R.id.recycler_view)) .perform(repeatedlyUntil(swipeUp(), hasDescendant(withText(normalTitle)), maxAttempts)) // We should have a ripple / state list drawable as the background assertNotNull(normalPreference.background) // The title color should be different from the title of the unselected Preference assertNotEquals(unselectableTitleColor, normalPreference.titleColor) // The summary color should be the same as the unselected Preference assertEquals(unselectableSummaryColor, normalPreference.summaryColor) } @Test fun testReusingViewHolder_disabledPreference_stateReset() { val preferenceScreen = fragment.preferenceScreen val disabledTitle = "Disabled" // Add 40 disabled Preferences. The ones at the end haven't been bound yet, and we want // to ensure that when they are bound, reusing a ViewHolder, they should have the correct // disabled state. val preferences = (1..40).map { index -> TestPreference(fragment.context!!).apply { title = disabledTitle + index isEnabled = false } } activityRule.runOnUiThread { preferences.forEach { preferenceScreen.addPreference(it) } } // Wait for a Preference to be visible onView(withText("${disabledTitle}1")).check(matches(isDisplayed())) val expectedTitleColor = preferences[0].titleColor val maxAttempts = 10 // Scroll until the end, ensuring all Preferences have been bound. onView(withId(R.id.recycler_view)) .perform( repeatedlyUntil( swipeUp(), hasDescendant(withText("${disabledTitle}40")), maxAttempts ) ) // All preferences should have the correct title color preferences.forEach { preference -> assertEquals(expectedTitleColor, preference.titleColor) } } } /** * Testing [Preference] class that records the background [Drawable] and the color of its title and * summary once bound. */ private class TestPreference(context: Context) : Preference(context) { var background: Drawable? = null var titleColor: Int? = null var summaryColor: Int? = null override fun onBindViewHolder(holder: PreferenceViewHolder) { super.onBindViewHolder(holder) background = holder.itemView.background titleColor = (holder.findViewById(android.R.id.title) as TextView).currentTextColor summaryColor = (holder.findViewById(android.R.id.summary) as TextView).currentTextColor } }
29
null
16
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
7,372
androidx
Apache License 2.0
compiler/test-infrastructure/tests/org/jetbrains/kotlin/test/TestRunner.kt
IVIanuu
333,718,537
false
{"Markdown": 70, "Gradle": 729, "Gradle Kotlin DSL": 570, "Java Properties": 15, "Shell": 10, "Ignore List": 12, "Batchfile": 9, "Git Attributes": 8, "Kotlin": 61867, "Protocol Buffer": 12, "Java": 6670, "Proguard": 12, "XML": 1607, "Text": 13214, "INI": 178, "JavaScript": 287, "JAR Manifest": 2, "Roff": 213, "Roff Manpage": 38, "AsciiDoc": 1, "HTML": 495, "SVG": 50, "Groovy": 33, "JSON": 186, "JFlex": 3, "Maven POM": 107, "CSS": 5, "JSON with Comments": 9, "Ant Build System": 50, "Graphviz (DOT)": 77, "C": 1, "Ruby": 5, "Objective-C": 8, "OpenStep Property List": 5, "Swift": 5, "Scala": 1, "YAML": 16}
/* * 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.test import com.intellij.openapi.util.Disposer import com.intellij.testFramework.TestDataFile import org.jetbrains.kotlin.test.model.* import org.jetbrains.kotlin.test.services.* class TestRunner(private val testConfiguration: TestConfiguration) { private val failedAssertions = mutableListOf<AssertionError>() fun runTest(@TestDataFile testDataFileName: String) { try { runTestImpl(testDataFileName) } finally { Disposer.dispose(testConfiguration.rootDisposable) } } private fun runTestImpl(@TestDataFile testDataFileName: String) { val services = testConfiguration.testServices @Suppress("NAME_SHADOWING") val testDataFileName = testConfiguration.metaTestConfigurators.fold(testDataFileName) { fileName, configurator -> configurator.transformTestDataPath(fileName) } val moduleStructure = testConfiguration.moduleStructureExtractor.splitTestDataByModules( testDataFileName, testConfiguration.directives, ).also { services.register(TestModuleStructure::class, it) } testConfiguration.metaTestConfigurators.forEach { if (it.shouldSkipTest()) return } val globalMetadataInfoHandler = testConfiguration.testServices.globalMetadataInfoHandler globalMetadataInfoHandler.parseExistingMetadataInfosFromAllSources() val modules = moduleStructure.modules val dependencyProvider = DependencyProviderImpl(services, modules) services.registerDependencyProvider(dependencyProvider) var failedException: Throwable? = null try { for (module in modules) { processModule(module, dependencyProvider, moduleStructure) } } catch (e: Throwable) { failedException = e } for (handler in testConfiguration.getAllHandlers()) { withAssertionCatching { handler.processAfterAllModules(failedAssertions.isNotEmpty()) } } if (testConfiguration.metaInfoHandlerEnabled) { withAssertionCatching { globalMetadataInfoHandler.compareAllMetaDataInfos() } } if (failedException != null) { failedAssertions.add(0, ExceptionFromTestError(failedException)) } testConfiguration.afterAnalysisCheckers.forEach { withAssertionCatching { it.check(failedAssertions) } } val filteredFailedAssertions = testConfiguration.afterAnalysisCheckers .fold<AfterAnalysisChecker, List<AssertionError>>(failedAssertions) { assertions, checker -> checker.suppressIfNeeded(assertions) } services.assertions.assertAll(filteredFailedAssertions) } private fun processModule( module: TestModule, dependencyProvider: DependencyProviderImpl, moduleStructure: TestModuleStructure ) { val sourcesArtifact = ResultingArtifact.Source() val frontendKind = module.frontendKind if (!frontendKind.shouldRunAnalysis) return val frontendArtifacts: ResultingArtifact.FrontendOutput<*> = testConfiguration.getFacade(SourcesKind, frontendKind) .transform(module, sourcesArtifact).also { dependencyProvider.registerArtifact(module, it) } val frontendHandlers: List<AnalysisHandler<*>> = testConfiguration.getHandlers(frontendKind) for (frontendHandler in frontendHandlers) { withAssertionCatching { frontendHandler.hackyProcess(module, frontendArtifacts) } } val backendKind = module.backendKind if (!backendKind.shouldRunAnalysis) return val backendInputInfo = testConfiguration.getFacade(frontendKind, backendKind) .hackyTransform(module, frontendArtifacts).also { dependencyProvider.registerArtifact(module, it) } val backendHandlers: List<AnalysisHandler<*>> = testConfiguration.getHandlers(backendKind) for (backendHandler in backendHandlers) { withAssertionCatching { backendHandler.hackyProcess(module, backendInputInfo) } } for (artifactKind in moduleStructure.getTargetArtifactKinds(module)) { if (!artifactKind.shouldRunAnalysis) continue val binaryArtifact = testConfiguration.getFacade(backendKind, artifactKind) .hackyTransform(module, backendInputInfo).also { dependencyProvider.registerArtifact(module, it) } val binaryHandlers: List<AnalysisHandler<*>> = testConfiguration.getHandlers(artifactKind) for (binaryHandler in binaryHandlers) { withAssertionCatching { binaryHandler.hackyProcess(module, binaryArtifact) } } } } private inline fun withAssertionCatching(block: () -> Unit) { try { block() } catch (e: AssertionError) { failedAssertions += e } } } // ---------------------------------------------------------------------------------------------------------------- /* * Those `hackyProcess` methods are needed to hack kotlin type system. In common test case * we have artifact of type ResultingArtifact<*> and handler of type AnalysisHandler<*> and actually * at runtime types under `*` are same (that achieved by grouping handlers and facades by * frontend/backend/artifact kind). But there is no way to tell that to compiler, so I unsafely cast types with `*` * to types with Empty artifacts to make it compile. Since unsafe cast has no effort at runtime, it's safe to use it */ private fun AnalysisHandler<*>.hackyProcess(module: TestModule, artifact: ResultingArtifact<*>) { @Suppress("UNCHECKED_CAST") (this as AnalysisHandler<ResultingArtifact.Source>) .processModule(module, artifact as ResultingArtifact<ResultingArtifact.Source>) } private fun <A : ResultingArtifact<A>> AnalysisHandler<A>.processModule(module: TestModule, artifact: ResultingArtifact<A>) { @Suppress("UNCHECKED_CAST") processModule(module, artifact as A) } private fun AbstractTestFacade<*, *>.hackyTransform( module: TestModule, artifact: ResultingArtifact<*> ): ResultingArtifact<*> { @Suppress("UNCHECKED_CAST") return (this as AbstractTestFacade<ResultingArtifact.Source, ResultingArtifact.Source>) .transform(module, artifact as ResultingArtifact<ResultingArtifact.Source>) } private fun <I : ResultingArtifact<I>, O : ResultingArtifact<O>> AbstractTestFacade<I, O>.transform( module: TestModule, inputArtifact: ResultingArtifact<I> ): O { @Suppress("UNCHECKED_CAST") return transform(module, inputArtifact as I) }
1
null
1
1
f49cf2d5cabf8fb9833ec95e1151a00b8b53d087
7,047
kotlin
Apache License 2.0
app/src/main/java/com/example/sudoku/view/Solver.kt
xdHawkeye
289,899,939
false
null
package com.example.sudoku.view import android.content.Intent import android.graphics.Color import android.os.Bundle import android.view.View import android.widget.Button import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.example.sudoku.R import com.example.sudoku.game.Cell import com.example.sudoku.view.custom.SudokuSolverBoardView import com.example.sudoku.viewmodel.SudokuViewModel import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.activity_main.eightbutton import kotlinx.android.synthetic.main.activity_main.fivebutton import kotlinx.android.synthetic.main.activity_main.fourbutton import kotlinx.android.synthetic.main.activity_main.ninebutton import kotlinx.android.synthetic.main.activity_main.onebutton import kotlinx.android.synthetic.main.activity_main.sevenbutton import kotlinx.android.synthetic.main.activity_main.sixbutton import kotlinx.android.synthetic.main.activity_main.threebutton import kotlinx.android.synthetic.main.activity_main.twobutton import kotlinx.android.synthetic.main.activity_main2.* class Solver : AppCompatActivity(), SudokuSolverBoardView.OnTouchListener { private lateinit var viewModel : SudokuViewModel private lateinit var numberButtons: List<Button> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) SudokuSolverBoardView.registerListener(this) viewModel = ViewModelProviders.of(this).get(SudokuViewModel::class.java) viewModel.sudokuSolver.selectedCellLiveData.observe(this, Observer { updateSelectedCellUI(it) }) viewModel.sudokuSolver.cellsLiveData.observe(this, Observer { updateCells(it) }) viewModel.sudokuSolver.highlightedKeysLiveData.observe(this, Observer { updateHighlightedKeys(it)}) val numberButtons = listOf(onebutton, twobutton, threebutton, fourbutton, fivebutton, sixbutton, sevenbutton, eightbutton, ninebutton) numberButtons.forEachIndexed { index, button -> button.setOnClickListener { viewModel.sudokuSolver.handleInput(index + 1) } } delete_img.setOnClickListener { viewModel.sudokuSolver.delete() } deleteAll.setOnClickListener { viewModel.sudokuSolver.deleteAll() } solve_img.setOnClickListener { viewModel.sudokuSolver.sudokuSolverAlgorithm() } } private fun updateCells(cells: List<Cell>?) = cells?.let { SudokuSolverBoardView.updateCells(cells) } private fun updateSelectedCellUI(cell: Pair<Int, Int>?) = cell?.let { SudokuSolverBoardView.updateSelectedCellUI(cell.first, cell.second) } private fun updateHighlightedKeys(set: Set<Int>?) = set?.let { numberButtons.forEachIndexed { index, button -> val color = if (set.contains(index + 1)) ContextCompat.getColor( this, R.color.white ) else Color.LTGRAY button.setBackgroundColor(color) } } override fun onCellTouched(row: Int, col: Int) { viewModel.sudokuSolver.updateSelectedCell(row, col) } // fun mainActivity(view: View) { // val intent = Intent(this, MainActivity::class.java) // startActivity(intent) // } fun textShow(view: View?) { showText.visibility = View.VISIBLE } }
0
Kotlin
0
0
93c534dca0c23e187f96562fa48eb7d721aef39e
3,510
SudokuApp
MIT License
analysis/low-level-api-fir/src/org/jetbrains/kotlin/analysis/low/level/api/fir/api/FirModuleResolveState.kt
JetBrains
3,432,266
false
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.analysis.low.level.api.fir.api import com.intellij.openapi.project.Project import org.jetbrains.kotlin.analysis.api.impl.barebone.annotations.InternalForInline import org.jetbrains.kotlin.analysis.low.level.api.fir.file.builder.ModuleFileCache import org.jetbrains.kotlin.analysis.low.level.api.fir.lazy.resolve.ResolveType import org.jetbrains.kotlin.analysis.project.structure.KtModule import org.jetbrains.kotlin.diagnostics.KtPsiDiagnostic import org.jetbrains.kotlin.fir.FirElement import org.jetbrains.kotlin.fir.FirSession import org.jetbrains.kotlin.fir.declarations.FirDeclaration import org.jetbrains.kotlin.fir.declarations.FirFile import org.jetbrains.kotlin.fir.declarations.FirResolvePhase import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtLambdaExpression abstract class FirModuleResolveState { abstract val project: Project abstract val rootModuleSession: FirSession abstract val module: KtModule internal abstract fun getSessionFor(module: KtModule): FirSession /** * Build fully resolved FIR node for requested element. * This operation could be performance affective because it create FIleStructureElement and resolve non-local declaration into BODY phase, use * @see tryGetCachedFirFile to get [FirFile] in undefined phase */ internal abstract fun getOrBuildFirFor(element: KtElement): FirElement? /** * Get or build or get cached [FirFile] for requested file in undefined phase */ internal abstract fun getOrBuildFirFile(ktFile: KtFile): FirFile /** * Try get [FirFile] from the cache in undefined phase */ internal abstract fun tryGetCachedFirFile(declaration: FirDeclaration, cache: ModuleFileCache): FirFile? internal abstract fun getDiagnostics(element: KtElement, filter: DiagnosticCheckerFilter): List<KtPsiDiagnostic> internal abstract fun collectDiagnosticsForFile(ktFile: KtFile, filter: DiagnosticCheckerFilter): Collection<KtPsiDiagnostic> @InternalForInline abstract fun findSourceFirDeclaration( ktDeclaration: KtDeclaration, ): FirDeclaration @InternalForInline abstract fun findSourceFirDeclaration( ktDeclaration: KtLambdaExpression, ): FirDeclaration /** * Looks for compiled non-local [ktDeclaration] declaration by querying its classId/callableId from the SymbolProvider. * * Works only if [ktDeclaration] is compiled (i.e. comes from .class file). */ @InternalForInline abstract fun findSourceFirCompiledDeclaration( ktDeclaration: KtDeclaration ): FirDeclaration internal abstract fun <D : FirDeclaration> resolveFirToPhase(declaration: D, toPhase: FirResolvePhase): D internal abstract fun <D : FirDeclaration> resolveFirToResolveType(declaration: D, type: ResolveType): D }
5
null
4903
39,894
0ad440f112f353cd2c72aa0a0619f3db2e50a483
3,164
kotlin
Apache License 2.0
demo/src/desktopMain/kotlin/org/pushingpixels/aurora/demo/svg/tango/computer.kt
kirill-grouchnikov
297,981,405
false
{"Kotlin": 2202922, "Shell": 7752, "templ": 4389, "Batchfile": 191}
package org.pushingpixels.aurora.demo.svg.tango import androidx.compose.ui.geometry.* import androidx.compose.ui.graphics.* import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Fill import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.drawscope.clipRect import androidx.compose.ui.graphics.drawscope.translate import androidx.compose.ui.graphics.drawscope.withTransform import androidx.compose.ui.graphics.painter.Painter import java.lang.ref.WeakReference import java.util.* import kotlin.math.min /** * This class has been automatically generated using * <a href="https://github.com/kirill-grouchnikov/aurora">Aurora SVG transcoder</a>. */ class computer : Painter() { @Suppress("UNUSED_VARIABLE") private var shape: Outline? = null @Suppress("UNUSED_VARIABLE") private var generalPath: Path? = null @Suppress("UNUSED_VARIABLE") private var brush: Brush? = null @Suppress("UNUSED_VARIABLE") private var stroke: Stroke? = null @Suppress("UNUSED_VARIABLE") private var clip: Shape? = null private var alpha = 1.0f private var blendMode = DrawScope.DefaultBlendMode private var alphaStack = mutableListOf(1.0f) private var blendModeStack = mutableListOf(DrawScope.DefaultBlendMode) @Suppress("UNUSED_VARIABLE", "UNUSED_VALUE", "VARIABLE_WITH_REDUNDANT_INITIALIZER", "UNNECESSARY_NOT_NULL_ASSERTION") private fun _paint0(drawScope : DrawScope) { var shapeText: Outline? var generalPathText: Path? = null var alphaText = 0.0f var blendModeText = DrawScope.DefaultBlendMode with(drawScope) { // alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver // _0 alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver // _0_0 alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver withTransform({ transform( Matrix(values=floatArrayOf( 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.3689320087432861f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -1.978553056716919f, -13.617130279541016f, 0.0f, 1.0f) ))}){ // _0_0_0 if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(41.10058f, 35.051105f) cubicTo(41.127632f, 36.682228f, 37.915836f, 38.192577f, 32.681362f, 39.010254f) cubicTo(27.446886f, 39.827927f, 20.989925f, 39.827927f, 15.755449f, 39.010254f) cubicTo(10.520973f, 38.192577f, 7.3091793f, 36.682228f, 7.336233f, 35.051105f) cubicTo(7.3091793f, 33.419983f, 10.520973f, 31.909634f, 15.755449f, 31.091959f) cubicTo(20.989925f, 30.274284f, 27.446886f, 30.274284f, 32.681362f, 31.091959f) cubicTo(37.915836f, 31.909634f, 41.127632f, 33.419983f, 41.10058f, 35.051105f) close() } shape = Outline.Generic(generalPath!!) brush = Brush.radialGradient(0.0f to Color(0, 0, 0, 255), 1.0f to Color(0, 0, 0, 0), center = Offset(24.218403f, 35.051075f), radius = 16.882172f, tileMode = TileMode.Clamp) drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode) } alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver withTransform({ transform( Matrix(values=floatArrayOf( 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 57.533390045166016f, 3.2034270763397217f, 0.0f, 1.0f) ))}){ // _0_0_1 if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(-26.263968f, 29.716238f) cubicTo(-26.248913f, 31.127916f, -28.036179f, 32.43507f, -30.949007f, 33.14274f) cubicTo(-33.861835f, 33.850407f, -37.45494f, 33.850407f, -40.367767f, 33.14274f) cubicTo(-43.280594f, 32.43507f, -45.06786f, 31.127916f, -45.052807f, 29.716238f) cubicTo(-45.06786f, 28.30456f, -43.280594f, 26.997404f, -40.367767f, 26.289736f) cubicTo(-37.45494f, 25.582067f, -33.861835f, 25.582067f, -30.949007f, 26.289736f) cubicTo(-28.036179f, 26.997404f, -26.248913f, 28.30456f, -26.263968f, 29.716238f) close() } shape = Outline.Generic(generalPath!!) brush = SolidColor(Color(173, 176, 170, 255)) drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode) brush = SolidColor(Color(75, 77, 74, 255)) stroke = Stroke(width=1.0f, cap=StrokeCap.Butt, join=StrokeJoin.Miter, miter=4.0f) if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(-26.263968f, 29.716238f) cubicTo(-26.248913f, 31.127916f, -28.036179f, 32.43507f, -30.949007f, 33.14274f) cubicTo(-33.861835f, 33.850407f, -37.45494f, 33.850407f, -40.367767f, 33.14274f) cubicTo(-43.280594f, 32.43507f, -45.06786f, 31.127916f, -45.052807f, 29.716238f) cubicTo(-45.06786f, 28.30456f, -43.280594f, 26.997404f, -40.367767f, 26.289736f) cubicTo(-37.45494f, 25.582067f, -33.861835f, 25.582067f, -30.949007f, 26.289736f) cubicTo(-28.036179f, 26.997404f, -26.248913f, 28.30456f, -26.263968f, 29.716238f) close() } shape = Outline.Generic(generalPath!!) drawOutline(outline = shape!!, style = stroke!!, brush=brush!!, alpha = alpha, blendMode = blendMode) } alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver withTransform({ transform( Matrix(values=floatArrayOf( 0.9402729868888855f, 0.0f, 0.0f, 0.0f, 0.0f, 0.9402729868888855f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 55.40361022949219f, 4.271193981170654f, 0.0f, 1.0f) ))}){ // _0_0_2 brush = SolidColor(Color(123, 127, 122, 255)) stroke = Stroke(width=1.0f, cap=StrokeCap.Butt, join=StrokeJoin.Miter, miter=4.0f) if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(-26.263968f, 29.716238f) cubicTo(-26.248913f, 31.127916f, -28.036179f, 32.43507f, -30.949007f, 33.14274f) cubicTo(-33.861835f, 33.850407f, -37.45494f, 33.850407f, -40.367767f, 33.14274f) cubicTo(-43.280594f, 32.43507f, -45.06786f, 31.127916f, -45.052807f, 29.716238f) cubicTo(-45.06786f, 28.30456f, -43.280594f, 26.997404f, -40.367767f, 26.289736f) cubicTo(-37.45494f, 25.582067f, -33.861835f, 25.582067f, -30.949007f, 26.289736f) cubicTo(-28.036179f, 26.997404f, -26.248913f, 28.30456f, -26.263968f, 29.716238f) close() } shape = Outline.Generic(generalPath!!) drawOutline(outline = shape!!, style = stroke!!, brush=brush!!, alpha = alpha, blendMode = blendMode) } alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver withTransform({ transform( Matrix(values=floatArrayOf( 0.9402729868888855f, 0.0f, 0.0f, 0.0f, 0.0f, 0.9402729868888855f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 55.40361022949219f, 3.5211939811706543f, 0.0f, 1.0f) ))}){ // _0_0_3 brush = Brush.linearGradient(0.0f to Color(216, 223, 214, 255), 1.0f to Color(216, 223, 214, 0), start = Offset(-35.658363f, 33.460922f), end = Offset(-35.658363f, 30.06203f), tileMode = TileMode.Clamp) stroke = Stroke(width=0.6806534f, cap=StrokeCap.Butt, join=StrokeJoin.Miter, miter=4.0f) if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(-26.263968f, 29.716238f) cubicTo(-26.248913f, 31.127916f, -28.036179f, 32.43507f, -30.949007f, 33.14274f) cubicTo(-33.861835f, 33.850407f, -37.45494f, 33.850407f, -40.367767f, 33.14274f) cubicTo(-43.280594f, 32.43507f, -45.06786f, 31.127916f, -45.052807f, 29.716238f) cubicTo(-45.06786f, 28.30456f, -43.280594f, 26.997404f, -40.367767f, 26.289736f) cubicTo(-37.45494f, 25.582067f, -33.861835f, 25.582067f, -30.949007f, 26.289736f) cubicTo(-28.036179f, 26.997404f, -26.248913f, 28.30456f, -26.263968f, 29.716238f) close() } shape = Outline.Generic(generalPath!!) drawOutline(outline = shape!!, style = stroke!!, brush=brush!!, alpha = alpha, blendMode = blendMode) } alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver // _0_0_4 if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(25.6875f, 28.766243f) lineTo(25.625f, 29.766243f) cubicTo(25.625f, 29.766243f, 29.949108f, 33.36541f, 34.625f, 33.96875f) cubicTo(36.962948f, 34.27042f, 39.378674f, 34.67116f, 41.375f, 35.15625f) cubicTo(43.371326f, 35.64134f, 44.963356f, 36.275856f, 45.5f, 36.8125f) cubicTo(45.81041f, 37.12291f, 45.95106f, 37.38614f, 46.0f, 37.59375f) cubicTo(46.04894f, 37.80136f, 46.038216f, 37.948566f, 45.90625f, 38.15625f) cubicTo(45.64232f, 38.57162f, 44.826393f, 39.1239f, 43.4375f, 39.5625f) cubicTo(40.659714f, 40.439693f, 35.717075f, 41.0f, 28.875f, 41.0f) lineTo(28.875f, 42.0f) cubicTo(35.770996f, 42.0f, 40.738667f, 41.47233f, 43.71875f, 40.53125f) cubicTo(45.208794f, 40.06071f, 46.24369f, 39.515564f, 46.75f, 38.71875f) cubicTo(47.003155f, 38.320343f, 47.107323f, 37.8303f, 47.0f, 37.375f) cubicTo(46.892677f, 36.9197f, 46.615444f, 36.490444f, 46.21875f, 36.09375f) cubicTo(45.34118f, 35.21618f, 43.68191f, 34.68731f, 41.625f, 34.1875f) cubicTo(39.56809f, 33.68769f, 37.109264f, 33.27317f, 34.75f, 32.96875f) cubicTo(30.031473f, 32.35991f, 25.6875f, 28.766243f, 25.6875f, 28.766243f) close() } shape = Outline.Generic(generalPath!!) brush = SolidColor(Color(208, 208, 208, 255)) drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode) brush = SolidColor(Color(151, 151, 151, 255)) stroke = Stroke(width=0.4f, cap=StrokeCap.Butt, join=StrokeJoin.Round, miter=4.0f) if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(25.6875f, 28.766243f) lineTo(25.625f, 29.766243f) cubicTo(25.625f, 29.766243f, 29.949108f, 33.36541f, 34.625f, 33.96875f) cubicTo(36.962948f, 34.27042f, 39.378674f, 34.67116f, 41.375f, 35.15625f) cubicTo(43.371326f, 35.64134f, 44.963356f, 36.275856f, 45.5f, 36.8125f) cubicTo(45.81041f, 37.12291f, 45.95106f, 37.38614f, 46.0f, 37.59375f) cubicTo(46.04894f, 37.80136f, 46.038216f, 37.948566f, 45.90625f, 38.15625f) cubicTo(45.64232f, 38.57162f, 44.826393f, 39.1239f, 43.4375f, 39.5625f) cubicTo(40.659714f, 40.439693f, 35.717075f, 41.0f, 28.875f, 41.0f) lineTo(28.875f, 42.0f) cubicTo(35.770996f, 42.0f, 40.738667f, 41.47233f, 43.71875f, 40.53125f) cubicTo(45.208794f, 40.06071f, 46.24369f, 39.515564f, 46.75f, 38.71875f) cubicTo(47.003155f, 38.320343f, 47.107323f, 37.8303f, 47.0f, 37.375f) cubicTo(46.892677f, 36.9197f, 46.615444f, 36.490444f, 46.21875f, 36.09375f) cubicTo(45.34118f, 35.21618f, 43.68191f, 34.68731f, 41.625f, 34.1875f) cubicTo(39.56809f, 33.68769f, 37.109264f, 33.27317f, 34.75f, 32.96875f) cubicTo(30.031473f, 32.35991f, 25.6875f, 28.766243f, 25.6875f, 28.766243f) close() } shape = Outline.Generic(generalPath!!) drawOutline(outline = shape!!, style = stroke!!, brush=brush!!, alpha = alpha, blendMode = blendMode) alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver withTransform({ transform( Matrix(values=floatArrayOf( 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.3689320087432861f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -1.978553056716919f, -19.021259307861328f, 0.0f, 1.0f) ))}){ // _0_0_5 if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(41.10058f, 35.051105f) cubicTo(41.127632f, 36.682228f, 37.915836f, 38.192577f, 32.681362f, 39.010254f) cubicTo(27.446886f, 39.827927f, 20.989925f, 39.827927f, 15.755449f, 39.010254f) cubicTo(10.520973f, 38.192577f, 7.3091793f, 36.682228f, 7.336233f, 35.051105f) cubicTo(7.3091793f, 33.419983f, 10.520973f, 31.909634f, 15.755449f, 31.091959f) cubicTo(20.989925f, 30.274284f, 27.446886f, 30.274284f, 32.681362f, 31.091959f) cubicTo(37.915836f, 31.909634f, 41.127632f, 33.419983f, 41.10058f, 35.051105f) close() } shape = Outline.Generic(generalPath!!) brush = Brush.radialGradient(0.0f to Color(0, 0, 0, 255), 1.0f to Color(0, 0, 0, 0), center = Offset(24.218403f, 35.051075f), radius = 16.882172f, tileMode = TileMode.Clamp) drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode) } alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver // _0_0_6 shape = Outline.Rectangle(rect = Rect(left = 17.472396850585938f, top = 30.703611373901367f, right = 26.512069702148438f, bottom = 33.443650245666504f)) brush = Brush.linearGradient(0.0f to Color(88, 89, 86, 255), 1.0f to Color(187, 190, 184, 255), start = Offset(22.171595f, 29.474092f), end = Offset(22.028107f, 35.72697f), tileMode = TileMode.Clamp) drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode) alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver // _0_0_7 if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(7.0809026f, 1.6956221f) lineTo(36.669098f, 1.6956221f) cubicTo(37.58044f, 1.6956221f, 38.293243f, 2.279104f, 38.33585f, 3.0972092f) lineTo(39.667892f, 28.675323f) cubicTo(39.7261f, 29.793058f, 38.766838f, 30.695627f, 37.647587f, 30.695627f) lineTo(6.102412f, 30.695627f) cubicTo(4.983163f, 30.695627f, 4.023898f, 29.793058f, 4.0821066f, 28.675323f) lineTo(5.4141507f, 3.0972092f) cubicTo(5.4544344f, 2.3236744f, 5.961653f, 1.6956221f, 7.0809026f, 1.6956221f) close() } shape = Outline.Generic(generalPath!!) brush = Brush.linearGradient(0.0f to Color(221, 225, 217, 255), 1.0f to Color(202, 205, 198, 255), start = Offset(8.104956f, 5.0940657f), end = Offset(37.67669f, 28.203438f), tileMode = TileMode.Clamp) drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode) brush = Brush.linearGradient(0.0f to Color(143, 143, 143, 255), 1.0f to Color(73, 73, 73, 255), start = Offset(11.4755f, 4.8730407f), end = Offset(35.93357f, 28.292397f), tileMode = TileMode.Clamp) stroke = Stroke(width=1.0f, cap=StrokeCap.Butt, join=StrokeJoin.Miter, miter=4.0f) if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(7.0809026f, 1.6956221f) lineTo(36.669098f, 1.6956221f) cubicTo(37.58044f, 1.6956221f, 38.293243f, 2.279104f, 38.33585f, 3.0972092f) lineTo(39.667892f, 28.675323f) cubicTo(39.7261f, 29.793058f, 38.766838f, 30.695627f, 37.647587f, 30.695627f) lineTo(6.102412f, 30.695627f) cubicTo(4.983163f, 30.695627f, 4.023898f, 29.793058f, 4.0821066f, 28.675323f) lineTo(5.4141507f, 3.0972092f) cubicTo(5.4544344f, 2.3236744f, 5.961653f, 1.6956221f, 7.0809026f, 1.6956221f) close() } shape = Outline.Generic(generalPath!!) drawOutline(outline = shape!!, style = stroke!!, brush=brush!!, alpha = alpha, blendMode = blendMode) alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver // _0_0_8 if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(8.410535f, 4.305827f) lineTo(7.1683397f, 26.351145f) lineTo(34.81873f, 26.351145f) lineTo(33.48371f, 4.3992558f) lineTo(8.410535f, 4.305827f) close() } shape = Outline.Generic(generalPath!!) brush = Brush.linearGradient(0.0f to Color(91, 91, 151, 255), 1.0f to Color(27, 27, 67, 255), start = Offset(23.207052f, 29.510551f), end = Offset(19.878864f, 7.051256f), tileMode = TileMode.Clamp) drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode) brush = SolidColor(Color(0, 0, 121, 255)) stroke = Stroke(width=0.5f, cap=StrokeCap.Butt, join=StrokeJoin.Round, miter=4.0f) if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(8.410535f, 4.305827f) lineTo(7.1683397f, 26.351145f) lineTo(34.81873f, 26.351145f) lineTo(33.48371f, 4.3992558f) lineTo(8.410535f, 4.305827f) close() } shape = Outline.Generic(generalPath!!) drawOutline(outline = shape!!, style = stroke!!, brush=brush!!, alpha = alpha, blendMode = blendMode) alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver // _0_0_9 brush = Brush.linearGradient(0.0f to Color(0, 0, 0, 63), 1.0f to Color(0, 0, 0, 0), start = Offset(22.149012f, 29.344574f), end = Offset(22.14901f, 27.79497f), tileMode = TileMode.Clamp) stroke = Stroke(width=0.9961812f, cap=StrokeCap.Round, join=StrokeJoin.Miter, miter=4.0f) if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(6.177433f, 28.735788f) lineTo(37.60591f, 28.735788f) } shape = Outline.Generic(generalPath!!) drawOutline(outline = shape!!, style = stroke!!, brush=brush!!, alpha = alpha, blendMode = blendMode) alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver // _0_0_10 brush = Brush.linearGradient(0.0f to Color(255, 255, 255, 179), 1.0f to Color(255, 255, 255, 0), start = Offset(20.610981f, 12.736387f), end = Offset(39.75421f, 50.81708f), tileMode = TileMode.Clamp) stroke = Stroke(width=0.99999964f, cap=StrokeCap.Butt, join=StrokeJoin.Miter, miter=4.0f) if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(6.9145985f, 2.7063396f) lineTo(36.7601f, 2.6685383f) cubicTo(37.043797f, 2.668179f, 37.319405f, 2.9057882f, 37.342205f, 3.321082f) lineTo(38.704098f, 28.12433f) cubicTo(38.76214f, 29.18136f, 38.16435f, 29.9102f, 37.10573f, 29.9102f) lineTo(6.5817585f, 29.9102f) cubicTo(5.5231357f, 29.9102f, 4.988744f, 29.18141f, 5.045887f, 28.12433f) lineTo(6.3699775f, 3.6301632f) cubicTo(6.4086733f, 2.9143326f, 6.5363626f, 2.7068188f, 6.9145985f, 2.7063396f) close() } shape = Outline.Generic(generalPath!!) drawOutline(outline = shape!!, style = stroke!!, brush=brush!!, alpha = alpha, blendMode = blendMode) alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 0.5314286f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver // _0_0_11 if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(8.711536f, 4.7463627f) lineTo(7.909007f, 22.616693f) cubicTo(18.953646f, 20.216063f, 19.33047f, 12.124494f, 33.063038f, 9.469943f) lineTo(32.901566f, 4.8124266f) lineTo(8.711536f, 4.7463627f) close() } shape = Outline.Generic(generalPath!!) brush = Brush.linearGradient(0.0f to Color(255, 255, 255, 255), 1.0f to Color(252, 252, 255, 0), start = Offset(14.829169f, 0.15016854f), end = Offset(21.900234f, 22.616693f), tileMode = TileMode.Clamp) drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode) alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver withTransform({ transform( Matrix(values=floatArrayOf( 1.2643979787826538f, 0.0f, 0.0f, 0.0f, 0.0f, 1.2912620306015015f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -6.216331958770752f, -4.000422954559326f, 0.0f, 1.0f) ))}){ // _0_0_12 if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(41.10058f, 35.051105f) cubicTo(41.127632f, 36.682228f, 37.915836f, 38.192577f, 32.681362f, 39.010254f) cubicTo(27.446886f, 39.827927f, 20.989925f, 39.827927f, 15.755449f, 39.010254f) cubicTo(10.520973f, 38.192577f, 7.3091793f, 36.682228f, 7.336233f, 35.051105f) cubicTo(7.3091793f, 33.419983f, 10.520973f, 31.909634f, 15.755449f, 31.091959f) cubicTo(20.989925f, 30.274284f, 27.446886f, 30.274284f, 32.681362f, 31.091959f) cubicTo(37.915836f, 31.909634f, 41.127632f, 33.419983f, 41.10058f, 35.051105f) close() } shape = Outline.Generic(generalPath!!) brush = Brush.radialGradient(0.0f to Color(0, 0, 0, 255), 1.0f to Color(0, 0, 0, 0), center = Offset(24.218403f, 35.051075f), radius = 16.882172f, tileMode = TileMode.Clamp) drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode) } alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver // _0_0_13 if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(6.462184f, 36.81745f) lineTo(37.46459f, 36.81745f) cubicTo(38.58384f, 36.81745f, 38.441944f, 37.08889f, 38.556816f, 37.430298f) lineTo(41.391464f, 45.855106f) cubicTo(41.506336f, 46.196518f, 41.418484f, 46.467953f, 40.299236f, 46.467953f) lineTo(3.6275382f, 46.467953f) cubicTo(2.508289f, 46.467953f, 2.4204388f, 46.196518f, 2.5353107f, 45.855106f) lineTo(5.3699565f, 37.430298f) cubicTo(5.4848285f, 37.08889f, 5.3429346f, 36.81745f, 6.462184f, 36.81745f) close() } shape = Outline.Generic(generalPath!!) brush = Brush.linearGradient(0.0f to Color(221, 225, 217, 255), 1.0f to Color(202, 205, 198, 255), start = Offset(20.6957f, 43.052326f), end = Offset(20.537241f, 46.498077f), tileMode = TileMode.Clamp) drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode) brush = Brush.linearGradient(0.0f to Color(143, 143, 143, 255), 1.0f to Color(73, 73, 73, 255), start = Offset(11.4755f, 4.8730407f), end = Offset(35.93357f, 28.292397f), tileMode = TileMode.Clamp) stroke = Stroke(width=1.0f, cap=StrokeCap.Butt, join=StrokeJoin.Miter, miter=4.0f) if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(6.462184f, 36.81745f) lineTo(37.46459f, 36.81745f) cubicTo(38.58384f, 36.81745f, 38.441944f, 37.08889f, 38.556816f, 37.430298f) lineTo(41.391464f, 45.855106f) cubicTo(41.506336f, 46.196518f, 41.418484f, 46.467953f, 40.299236f, 46.467953f) lineTo(3.6275382f, 46.467953f) cubicTo(2.508289f, 46.467953f, 2.4204388f, 46.196518f, 2.5353107f, 45.855106f) lineTo(5.3699565f, 37.430298f) cubicTo(5.4848285f, 37.08889f, 5.3429346f, 36.81745f, 6.462184f, 36.81745f) close() } shape = Outline.Generic(generalPath!!) drawOutline(outline = shape!!, style = stroke!!, brush=brush!!, alpha = alpha, blendMode = blendMode) alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver // _0_0_14 if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(6.3916893f, 38.829113f) lineTo(4.6239223f, 43.95564f) lineTo(10.104f, 43.95564f) lineTo(10.63433f, 41.922707f) lineTo(25.483572f, 41.922707f) lineTo(26.03325f, 43.99782f) lineTo(32.201084f, 43.99782f) lineTo(30.521708f, 38.829113f) lineTo(6.3916893f, 38.829113f) close() } shape = Outline.Generic(generalPath!!) brush = SolidColor(Color(122, 125, 119, 255)) drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode) alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver // _0_0_15 if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(11.076272f, 42.27626f) lineTo(10.63433f, 43.95564f) lineTo(25.395184f, 43.95564f) lineTo(24.953241f, 42.187874f) lineTo(11.076272f, 42.27626f) close() } shape = Outline.Generic(generalPath!!) brush = SolidColor(Color(119, 120, 116, 255)) drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode) alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver // _0_0_16 if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(37.592777f, 38.829113f) lineTo(39.272156f, 43.86725f) lineTo(33.792076f, 43.778862f) lineTo(32.289474f, 38.917503f) lineTo(37.592777f, 38.829113f) close() } shape = Outline.Generic(generalPath!!) brush = SolidColor(Color(119, 122, 117, 255)) drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode) alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver // _0_0_17 if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(37.592777f, 38.298786f) lineTo(39.272156f, 43.33692f) lineTo(33.792076f, 43.24853f) lineTo(32.289474f, 38.387173f) lineTo(37.592777f, 38.298786f) close() } shape = Outline.Generic(generalPath!!) brush = Brush.linearGradient(0.0f to Color(157, 157, 157, 255), 1.0f to Color(185, 185, 185, 255), start = Offset(18.7408f, 38.318054f), end = Offset(18.740799f, 43.37945f), tileMode = TileMode.Clamp) drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode) alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver // _0_0_18 if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(6.3916893f, 38.210396f) lineTo(4.6239223f, 43.33692f) lineTo(10.104f, 43.33692f) lineTo(10.63433f, 41.30399f) lineTo(25.483572f, 41.30399f) lineTo(26.03325f, 43.379105f) lineTo(32.201084f, 43.379105f) lineTo(30.521708f, 38.210396f) lineTo(6.3916893f, 38.210396f) close() } shape = Outline.Generic(generalPath!!) brush = Brush.linearGradient(0.0f to Color(157, 157, 157, 255), 1.0f to Color(185, 185, 185, 255), start = Offset(18.7408f, 38.318054f), end = Offset(18.740799f, 43.37945f), tileMode = TileMode.Clamp) drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode) alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver // _0_0_19 if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(11.076272f, 41.745934f) lineTo(10.63433f, 43.425312f) lineTo(25.395184f, 43.425312f) lineTo(24.953241f, 41.657543f) lineTo(11.076272f, 41.745934f) close() } shape = Outline.Generic(generalPath!!) brush = Brush.linearGradient(0.0f to Color(157, 157, 157, 255), 1.0f to Color(185, 185, 185, 255), start = Offset(18.7408f, 38.318054f), end = Offset(18.740799f, 43.37945f), tileMode = TileMode.Clamp) drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode) alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver // _0_0_20 brush = Brush.linearGradient(0.0f to Color(249, 255, 245, 255), 1.0f to Color(249, 255, 245, 0), start = Offset(30.214968f, 46.740234f), end = Offset(19.539223f, 34.057743f), tileMode = TileMode.Clamp) stroke = Stroke(width=0.5f, cap=StrokeCap.Butt, join=StrokeJoin.Round, miter=4.0f) if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(6.127819f, 37.578117f) lineTo(37.953632f, 37.578117f) lineTo(40.590813f, 45.670677f) lineTo(3.329743f, 45.670677f) lineTo(6.127819f, 37.578117f) close() } shape = Outline.Generic(generalPath!!) drawOutline(outline = shape!!, style = stroke!!, brush=brush!!, alpha = alpha, blendMode = blendMode) alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver withTransform({ transform( Matrix(values=floatArrayOf( 1.3312369585037231f, 0.0f, 0.0f, 0.0f, 0.0f, 0.6584489941596985f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -10.419329643249512f, 2.8538661003112793f, 0.0f, 1.0f) ))}){ // _0_0_21 if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(35.620502f, 3.9384086f) cubicTo(35.62185f, 4.2392945f, 35.4621f, 4.5179024f, 35.201748f, 4.668735f) cubicTo(34.941395f, 4.8195677f, 34.620235f, 4.8195677f, 34.359882f, 4.668735f) cubicTo(34.09953f, 4.5179024f, 33.93978f, 4.2392945f, 33.941128f, 3.9384086f) cubicTo(33.93978f, 3.6375227f, 34.09953f, 3.358915f, 34.359882f, 3.2080822f) cubicTo(34.620235f, 3.0572495f, 34.941395f, 3.0572495f, 35.201748f, 3.2080822f) cubicTo(35.4621f, 3.358915f, 35.62185f, 3.6375227f, 35.620502f, 3.9384086f) close() } shape = Outline.Generic(generalPath!!) brush = Brush.linearGradient(0.0f to Color(144, 144, 144, 255), 1.0f to Color(190, 190, 190, 0), start = Offset(34.30099f, 3.9384086f), end = Offset(35.520542f, 3.8451097f), tileMode = TileMode.Clamp) drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode) } alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver withTransform({ transform( Matrix(values=floatArrayOf( 1.3312369585037231f, 0.0f, 0.0f, 0.0f, 0.0f, 0.6584489941596985f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -10.305729866027832f, 4.959650993347168f, 0.0f, 1.0f) ))}){ // _0_0_22 if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(35.620502f, 3.9384086f) cubicTo(35.62185f, 4.2392945f, 35.4621f, 4.5179024f, 35.201748f, 4.668735f) cubicTo(34.941395f, 4.8195677f, 34.620235f, 4.8195677f, 34.359882f, 4.668735f) cubicTo(34.09953f, 4.5179024f, 33.93978f, 4.2392945f, 33.941128f, 3.9384086f) cubicTo(33.93978f, 3.6375227f, 34.09953f, 3.358915f, 34.359882f, 3.2080822f) cubicTo(34.620235f, 3.0572495f, 34.941395f, 3.0572495f, 35.201748f, 3.2080822f) cubicTo(35.4621f, 3.358915f, 35.62185f, 3.6375227f, 35.620502f, 3.9384086f) close() } shape = Outline.Generic(generalPath!!) brush = Brush.linearGradient(0.0f to Color(144, 144, 144, 255), 1.0f to Color(190, 190, 190, 0), start = Offset(34.30099f, 3.9384086f), end = Offset(35.520542f, 3.8451097f), tileMode = TileMode.Clamp) drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode) } alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver withTransform({ transform( Matrix(values=floatArrayOf( 1.3312369585037231f, 0.0f, 0.0f, 0.0f, 0.0f, 0.6584489941596985f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -10.192130088806152f, 6.959650993347168f, 0.0f, 1.0f) ))}){ // _0_0_23 if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(35.620502f, 3.9384086f) cubicTo(35.62185f, 4.2392945f, 35.4621f, 4.5179024f, 35.201748f, 4.668735f) cubicTo(34.941395f, 4.8195677f, 34.620235f, 4.8195677f, 34.359882f, 4.668735f) cubicTo(34.09953f, 4.5179024f, 33.93978f, 4.2392945f, 33.941128f, 3.9384086f) cubicTo(33.93978f, 3.6375227f, 34.09953f, 3.358915f, 34.359882f, 3.2080822f) cubicTo(34.620235f, 3.0572495f, 34.941395f, 3.0572495f, 35.201748f, 3.2080822f) cubicTo(35.4621f, 3.358915f, 35.62185f, 3.6375227f, 35.620502f, 3.9384086f) close() } shape = Outline.Generic(generalPath!!) brush = Brush.linearGradient(0.0f to Color(144, 144, 144, 255), 1.0f to Color(190, 190, 190, 0), start = Offset(34.30099f, 3.9384086f), end = Offset(35.520542f, 3.8451097f), tileMode = TileMode.Clamp) drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode) } alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver withTransform({ transform( Matrix(values=floatArrayOf( 1.3312369585037231f, 0.0f, 0.0f, 0.0f, 0.0f, 0.6584489941596985f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -10.078530311584473f, 8.959650993347168f, 0.0f, 1.0f) ))}){ // _0_0_24 if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(35.620502f, 3.9384086f) cubicTo(35.62185f, 4.2392945f, 35.4621f, 4.5179024f, 35.201748f, 4.668735f) cubicTo(34.941395f, 4.8195677f, 34.620235f, 4.8195677f, 34.359882f, 4.668735f) cubicTo(34.09953f, 4.5179024f, 33.93978f, 4.2392945f, 33.941128f, 3.9384086f) cubicTo(33.93978f, 3.6375227f, 34.09953f, 3.358915f, 34.359882f, 3.2080822f) cubicTo(34.620235f, 3.0572495f, 34.941395f, 3.0572495f, 35.201748f, 3.2080822f) cubicTo(35.4621f, 3.358915f, 35.62185f, 3.6375227f, 35.620502f, 3.9384086f) close() } shape = Outline.Generic(generalPath!!) brush = Brush.linearGradient(0.0f to Color(144, 144, 144, 255), 1.0f to Color(190, 190, 190, 0), start = Offset(34.30099f, 3.9384086f), end = Offset(35.520542f, 3.8451097f), tileMode = TileMode.Clamp) drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode) } alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver withTransform({ transform( Matrix(values=floatArrayOf( 1.3312369585037231f, 0.0f, 0.0f, 0.0f, 0.0f, 0.6584489941596985f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -9.964929580688477f, 10.959650039672852f, 0.0f, 1.0f) ))}){ // _0_0_25 if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(35.620502f, 3.9384086f) cubicTo(35.62185f, 4.2392945f, 35.4621f, 4.5179024f, 35.201748f, 4.668735f) cubicTo(34.941395f, 4.8195677f, 34.620235f, 4.8195677f, 34.359882f, 4.668735f) cubicTo(34.09953f, 4.5179024f, 33.93978f, 4.2392945f, 33.941128f, 3.9384086f) cubicTo(33.93978f, 3.6375227f, 34.09953f, 3.358915f, 34.359882f, 3.2080822f) cubicTo(34.620235f, 3.0572495f, 34.941395f, 3.0572495f, 35.201748f, 3.2080822f) cubicTo(35.4621f, 3.358915f, 35.62185f, 3.6375227f, 35.620502f, 3.9384086f) close() } shape = Outline.Generic(generalPath!!) brush = Brush.linearGradient(0.0f to Color(144, 144, 144, 255), 1.0f to Color(190, 190, 190, 0), start = Offset(34.30099f, 3.9384086f), end = Offset(35.520542f, 3.8451097f), tileMode = TileMode.Clamp) drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode) } alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alphaStack.add(0, alpha) alpha *= 1.0f blendModeStack.add(0, BlendMode.SrcOver) blendMode = BlendMode.SrcOver // _0_0_26 if (generalPath == null) { generalPath = Path() } else { generalPath!!.reset() } generalPath?.run { moveTo(20.0f, 27.317665f) lineTo(20.281715f, 27.317665f) cubicTo(20.36548f, 27.317667f, 20.4297f, 27.33633f, 20.474377f, 27.373655f) cubicTo(20.519344f, 27.41069f, 20.541828f, 27.463594f, 20.54183f, 27.53237f) cubicTo(20.541828f, 27.60144f, 20.519344f, 27.654638f, 20.474377f, 27.691965f) cubicTo(20.4297f, 27.728998f, 20.36548f, 27.747515f, 20.281715f, 27.747515f) lineTo(20.169735f, 27.747515f) lineTo(20.169735f, 27.975885f) lineTo(20.0f, 27.975885f) lineTo(20.0f, 27.317665f) moveTo(20.169735f, 27.440668f) lineTo(20.169735f, 27.624512f) lineTo(20.26364f, 27.624512f) cubicTo(20.296558f, 27.624512f, 20.321981f, 27.616575f, 20.33991f, 27.600704f) cubicTo(20.35784f, 27.58454f, 20.366804f, 27.561762f, 20.366804f, 27.53237f) cubicTo(20.366804f, 27.50298f, 20.35784f, 27.480349f, 20.33991f, 27.464476f) cubicTo(20.321981f, 27.448605f, 20.296558f, 27.440668f, 20.26364f, 27.440668f) lineTo(20.169735f, 27.440668f) moveTo(20.961979f, 27.428764f) cubicTo(20.91025f, 27.428766f, 20.87013f, 27.44787f, 20.841621f, 27.486078f) cubicTo(20.813112f, 27.524288f, 20.798857f, 27.578074f, 20.798857f, 27.647436f) cubicTo(20.798857f, 27.716507f, 20.813112f, 27.770145f, 20.841621f, 27.808355f) cubicTo(20.87013f, 27.846563f, 20.91025f, 27.865667f, 20.961979f, 27.865667f) cubicTo(21.014002f, 27.865667f, 21.054268f, 27.846563f, 21.082779f, 27.808355f) cubicTo(21.111286f, 27.770145f, 21.125542f, 27.716507f, 21.125542f, 27.647436f) cubicTo(21.125542f, 27.578074f, 21.111286f, 27.524288f, 21.082779f, 27.486078f) cubicTo(21.054268f, 27.44787f, 21.014002f, 27.428766f, 20.961979f, 27.428764f) moveTo(20.961979f, 27.305761f) cubicTo(21.067787f, 27.305763f, 21.150671f, 27.336037f, 21.21063f, 27.396582f) cubicTo(21.270588f, 27.457129f, 21.300568f, 27.540747f, 21.300568f, 27.647436f) cubicTo(21.300568f, 27.753834f, 21.270588f, 27.837305f, 21.21063f, 27.897852f) cubicTo(21.150671f, 27.958399f, 21.067787f, 27.98867f, 20.961979f, 27.98867f) cubicTo(20.856464f, 27.98867f, 20.77358f, 27.958399f, 20.713327f, 27.897852f) cubicTo(20.65337f, 27.837305f, 20.62339f, 27.753834f, 20.62339f, 27.647436f) cubicTo(20.62339f, 27.540747f, 20.65337f, 27.457129f, 20.713327f, 27.396582f) cubicTo(20.77358f, 27.336037f, 20.856464f, 27.305763f, 20.961979f, 27.305761f) moveTo(21.42842f, 27.317665f) lineTo(21.617994f, 27.317665f) lineTo(21.857388f, 27.769117f) lineTo(21.857388f, 27.317665f) lineTo(22.018305f, 27.317665f) lineTo(22.018305f, 27.975885f) lineTo(21.82873f, 27.975885f) lineTo(21.589338f, 27.524433f) lineTo(21.589338f, 27.975885f) lineTo(21.42842f, 27.975885f) lineTo(21.42842f, 27.317665f) moveTo(22.09149f, 27.317665f) lineTo(22.277096f, 27.317665f) lineTo(22.42699f, 27.55221f) lineTo(22.576887f, 27.317665f) lineTo(22.762936f, 27.317665f) lineTo(22.51208f, 27.698578f) lineTo(22.51208f, 27.975885f) lineTo(22.342344f, 27.975885f) lineTo(22.342344f, 27.698578f) lineTo(22.09149f, 27.317665f) } shape = Outline.Generic(generalPath!!) brush = SolidColor(Color(74, 74, 74, 255)) drawOutline(outline = shape!!, style=Fill, brush=brush!!, alpha=alpha, blendMode = blendMode) alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) alpha = alphaStack.removeAt(0) blendMode = blendModeStack.removeAt(0) } } private fun innerPaint(drawScope: DrawScope) { _paint0(drawScope) shape = null generalPath = null brush = null stroke = null clip = null alpha = 1.0f } companion object { /** * Returns the X of the bounding box of the original SVG image. * * @return The X of the bounding box of the original SVG image. */ fun getOrigX(): Double { return 1.997342824935913 } /** * Returns the Y of the bounding box of the original SVG image. * * @return The Y of the bounding box of the original SVG image. */ fun getOrigY(): Double { return 1.1956220865249634 } /** * Returns the width of the bounding box of the original SVG image. * * @return The width of the bounding box of the original SVG image. */ fun getOrigWidth(): Double { return 45.31852722167969 } /** * Returns the height of the bounding box of the original SVG image. * * @return The height of the bounding box of the original SVG image. */ fun getOrigHeight(): Double { return 46.232242584228516 } } override val intrinsicSize: Size get() = Size.Unspecified override fun DrawScope.onDraw() { clipRect { // Use the original icon bounding box and the current icon dimension to compute // the scaling factor val fullOrigWidth = getOrigX() + getOrigWidth() val fullOrigHeight = getOrigY() + getOrigHeight() val coef1 = size.width / fullOrigWidth val coef2 = size.height / fullOrigHeight val coef = min(coef1, coef2).toFloat() // Use the original icon bounding box and the current icon dimension to compute // the offset pivot for the scaling var translateX = -getOrigX() var translateY = -getOrigY() if (coef1 != coef2) { if (coef1 < coef2) { val extraDy = ((fullOrigWidth - fullOrigHeight) / 2.0f).toFloat() translateY += extraDy } else { val extraDx = ((fullOrigHeight - fullOrigWidth) / 2.0f).toFloat() translateX += extraDx } } val translateXDp = translateX.toFloat().toDp().value val translateYDp = translateY.toFloat().toDp().value // Create a combined scale + translate + clip transform before calling the transcoded painting instructions withTransform({ scale(scaleX = coef, scaleY = coef, pivot = Offset.Zero) translate(translateXDp, translateYDp) clipRect(left = 0.0f, top = 0.0f, right = fullOrigWidth.toFloat(), bottom = fullOrigHeight.toFloat(), clipOp = ClipOp.Intersect) }) { innerPaint(this) } } } }
8
Kotlin
19
570
c9aa4a852fa2843a72473e710f3cf9a4ebd63f6d
42,794
aurora
Apache License 2.0
Realtime/src/commonTest/kotlin/RealtimeTest.kt
supabase-community
495,084,592
false
{"Kotlin": 901718}
import io.github.jan.supabase.realtime.Realtime import io.github.jan.supabase.realtime.RealtimeMessage import io.github.jan.supabase.realtime.realtime import kotlinx.coroutines.test.runTest import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put import kotlin.test.Test import kotlin.test.assertEquals class RealtimeTest { @Test fun testRealtimeStatus() { runTest { createTestClient( wsHandler = { _, _ -> //Does not matter for this test }, supabaseHandler = { assertEquals(Realtime.Status.DISCONNECTED, it.realtime.status.value) it.realtime.connect() assertEquals(Realtime.Status.CONNECTED, it.realtime.status.value) it.realtime.disconnect() assertEquals(Realtime.Status.DISCONNECTED, it.realtime.status.value) } ) } } @Test fun testSendingRealtimeMessages() { val expectedMessage = RealtimeMessage( topic = "realtimeTopic", event = "realtimeEvent", payload = buildJsonObject { put("key", "value") }, ref = "realtimeRef" ) runTest { createTestClient( wsHandler = { i, _ -> val message = i.receive() assertEquals(expectedMessage, message) }, supabaseHandler = { it.realtime.connect() it.realtime.send(expectedMessage) } ) } } }
11
Kotlin
37
395
52abcc3d5744ad2703afc40a9d1e6cae5b74b834
1,687
supabase-kt
MIT License
app/src/main/java/ke/co/tulivuapps/hoteltours/data/model/user/UserInfoResponse.kt
RushiChavan-dev
740,244,295
false
{"Kotlin": 872337}
package ke.co.tulivuapps.hoteltours.data.model.user /** * Created by Rushi on 12.03.2023 */ data class UserInfoResponse( val status : String?, val body:ResultUser?, val message: String?, )
0
Kotlin
0
0
ad74422b1b7930e5665c94cc9368ec69d425ffba
204
HotelApp
Apache License 2.0
compiler/light-classes/src/org/jetbrains/kotlin/asJava/classes/KtLightClassForFacadeImpl.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2016 JetBrains s.r.o. * * 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 org.jetbrains.kotlin.asJava.classes import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.* import com.intellij.psi.impl.PsiSuperMethodImplUtil import com.intellij.psi.impl.java.stubs.PsiJavaFileStub import com.intellij.psi.impl.light.LightEmptyImplementsList import com.intellij.psi.impl.light.LightModifierList import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.CachedValue import com.intellij.psi.util.CachedValuesManager import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.asJava.KotlinAsJavaSupport import org.jetbrains.kotlin.asJava.LightClassGenerationSupport import org.jetbrains.kotlin.asJava.builder.LightClassDataHolder import org.jetbrains.kotlin.asJava.builder.LightClassDataProviderForFileFacade import org.jetbrains.kotlin.asJava.elements.FakeFileForLightClass import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.load.java.structure.LightClassOriginKind import org.jetbrains.kotlin.load.kotlin.PackagePartClassUtils import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtStringTemplateExpression import org.jetbrains.kotlin.psi.psiUtil.siblings import javax.swing.Icon open class KtLightClassForFacadeImpl constructor( manager: PsiManager, override val facadeClassFqName: FqName, myLightClassDataCache: CachedValue<LightClassDataHolder.ForFacade>, override val files: Collection<KtFile> ) : KtLazyLightClass(manager), KtLightClassForFacade { protected open val lightClassDataCache: CachedValue<LightClassDataHolder.ForFacade> = myLightClassDataCache protected open val javaFileStub: PsiJavaFileStub? get() = lightClassDataCache.value.javaFileStub override val lightClassData get() = lightClassDataCache.value.findDataForFacade(facadeClassFqName) private val firstFileInFacade by lazyPub { files.iterator().next() } private val hashCode: Int = computeHashCode() private val packageFqName: FqName = facadeClassFqName.parent() private val modifierList: PsiModifierList = LightModifierList(manager, KotlinLanguage.INSTANCE, PsiModifier.PUBLIC, PsiModifier.FINAL) private val implementsList: LightEmptyImplementsList = LightEmptyImplementsList(manager) private val packageClsFile = FakeFileForLightClass( firstFileInFacade, lightClass = { this }, stub = { javaFileStub }, packageFqName = packageFqName ) override fun getParent(): PsiElement = containingFile override val kotlinOrigin: KtClassOrObject? get() = null val fqName: FqName get() = facadeClassFqName override fun getModifierList() = modifierList override fun hasModifierProperty(@NonNls name: String) = modifierList.hasModifierProperty(name) override fun getExtendsList(): PsiReferenceList? = null override fun isDeprecated() = false override fun isInterface() = false override fun isAnnotationType() = false override fun isEnum() = false override fun getContainingClass(): PsiClass? = null override fun getContainingFile() = packageClsFile override fun hasTypeParameters() = false override fun getTypeParameters(): Array<out PsiTypeParameter> = PsiTypeParameter.EMPTY_ARRAY override fun getTypeParameterList(): PsiTypeParameterList? = null override fun getDocComment(): Nothing? = null override fun getImplementsList() = implementsList override fun getImplementsListTypes(): Array<out PsiClassType> = PsiClassType.EMPTY_ARRAY override fun getInterfaces(): Array<out PsiClass> = PsiClass.EMPTY_ARRAY override fun getInnerClasses(): Array<out PsiClass> = PsiClass.EMPTY_ARRAY override fun getOwnInnerClasses(): List<PsiClass> = listOf() override fun getAllInnerClasses(): Array<out PsiClass> = PsiClass.EMPTY_ARRAY override fun getInitializers(): Array<out PsiClassInitializer> = PsiClassInitializer.EMPTY_ARRAY override fun findInnerClassByName(@NonNls name: String, checkBases: Boolean): PsiClass? = null override fun isInheritorDeep(baseClass: PsiClass?, classToByPass: PsiClass?): Boolean = false override fun getLBrace(): PsiElement? = null override fun getRBrace(): PsiElement? = null override fun getName() = super<KtLightClassForFacade>.getName() override fun setName(name: String): PsiElement? { for (file in files) { val jvmNameEntry = JvmFileClassUtil.findAnnotationEntryOnFileNoResolve(file, JvmFileClassUtil.JVM_NAME_SHORT) if (PackagePartClassUtils.getFilePartShortName(file.name) == name) { jvmNameEntry?.delete() continue } if (jvmNameEntry == null) { val newFileName = PackagePartClassUtils.getFileNameByFacadeName(name) val facadeDir = file.parent if (newFileName != null && facadeDir != null && facadeDir.findFile(newFileName) == null) { file.name = newFileName continue } val psiFactory = KtPsiFactory(this) val annotationText = "${JvmFileClassUtil.JVM_NAME_SHORT}(\"$name\")" val newFileAnnotationList = psiFactory.createFileAnnotationListWithAnnotation(annotationText) val annotationList = file.fileAnnotationList if (annotationList != null) { annotationList.add(newFileAnnotationList.annotationEntries.first()) } else { val anchor = file.firstChild.siblings().firstOrNull { it !is PsiWhiteSpace && it !is PsiComment } file.addBefore(newFileAnnotationList, anchor) } continue } val jvmNameExpression = jvmNameEntry.valueArguments.firstOrNull()?.getArgumentExpression() as? KtStringTemplateExpression ?: continue ElementManipulators.handleContentChange(jvmNameExpression, name) } return this } override fun getQualifiedName() = facadeClassFqName.asString() override fun getNameIdentifier(): PsiIdentifier? = null override fun isValid() = files.all { it.isValid && it.hasTopLevelCallables() && facadeClassFqName == it.javaFileFacadeFqName } override fun copy(): KtLightClassForFacade = KtLightClassForFacadeImpl(manager, facadeClassFqName, lightClassDataCache, files) override fun getNavigationElement() = firstFileInFacade override fun isEquivalentTo(another: PsiElement?): Boolean = equals(another) || (another is KtLightClassForFacade && another.facadeClassFqName == facadeClassFqName) override fun getElementIcon(flags: Int): Icon? = throw UnsupportedOperationException("This should be done by JetIconProvider") override fun isInheritor(baseClass: PsiClass, checkDeep: Boolean): Boolean { return baseClass.qualifiedName == CommonClassNames.JAVA_LANG_OBJECT } override fun getSuperClass(): PsiClass? { return JavaPsiFacade.getInstance(project).findClass(CommonClassNames.JAVA_LANG_OBJECT, resolveScope) } override fun getSupers(): Array<PsiClass> { return superClass?.let { arrayOf(it) } ?: arrayOf() } override fun getSuperTypes(): Array<PsiClassType> { return arrayOf(PsiType.getJavaLangObject(manager, resolveScope)) } override fun hashCode() = hashCode private fun computeHashCode(): Int { var result = manager.hashCode() result = 31 * result + files.hashCode() result = 31 * result + facadeClassFqName.hashCode() return result } override fun equals(other: Any?): Boolean { if (other == null || this::class.java != other::class.java) { return false } val lightClass = other as KtLightClassForFacadeImpl if (this === other) return true if (this.hashCode != lightClass.hashCode) return false if (manager != lightClass.manager) return false if (files != lightClass.files) return false if (facadeClassFqName != lightClass.facadeClassFqName) return false return true } override fun toString() = "${KtLightClassForFacadeImpl::class.java.simpleName}:$facadeClassFqName" override val originKind: LightClassOriginKind get() = LightClassOriginKind.SOURCE override fun getText() = firstFileInFacade.text ?: "" override fun getTextRange(): TextRange = firstFileInFacade.textRange ?: TextRange.EMPTY_RANGE override fun getTextOffset() = firstFileInFacade.textOffset override fun getStartOffsetInParent() = firstFileInFacade.startOffsetInParent override fun isWritable() = files.all { it.isWritable } override fun getVisibleSignatures(): MutableCollection<HierarchicalMethodSignature> = PsiSuperMethodImplUtil.getVisibleSignatures(this) companion object { fun createForFacadeNoCache(fqName: FqName, searchScope: GlobalSearchScope, project: Project): KtLightClassForFacade? { val sources = KotlinAsJavaSupport.getInstance(project).findFilesForFacade(fqName, searchScope) .filterNot { it.isCompiled } if (sources.isEmpty()) return null val stubProvider = LightClassDataProviderForFileFacade.ByProjectSource(project, fqName, searchScope) val stubValue = CachedValuesManager.getManager(project) .createCachedValue(stubProvider, false) val manager = PsiManager.getInstance(project) return LightClassGenerationSupport.getInstance(project).run { if (useUltraLightClasses) createUltraLightClassForFacade(manager, fqName, stubValue, sources) ?: error { "Unable to create UL class for facade" } else KtLightClassForFacadeImpl(manager, fqName, stubValue, sources) } } fun createForFacade( manager: PsiManager, facadeClassFqName: FqName, searchScope: GlobalSearchScope ): KtLightClassForFacade? { return FacadeCache.getInstance(manager.project)[facadeClassFqName, searchScope] } fun createForSyntheticFile( facadeClassFqName: FqName, file: KtFile ): KtLightClassForFacade { val project = file.project // TODO: refactor, using cached value doesn't make sense for this case val cachedValue = CachedValuesManager.getManager(project).createCachedValue( LightClassDataProviderForFileFacade.ByFile(project, facadeClassFqName, file), false ) return KtLightClassForFacadeImpl(PsiManager.getInstance(project), facadeClassFqName, cachedValue, listOf(file)) } } }
132
null
5074
40,992
57fe6721e3afb154571eb36812fd8ef7ec9d2026
11,705
kotlin
Apache License 2.0
mpp-library/domain/src/commonMain/kotlin/com/jaa/library/domain/useCases/ChangeVisitedStateUseCase.kt
Jaime97
300,568,157
false
null
package com.jaa.library.domain.useCases import com.jaa.library.domain.repository.filmDetail.FilmDetailRepositoryInterface import dev.icerock.moko.network.generated.models.FilmData class ChangeVisitedStateUseCase ( private val filmDetailRepository : FilmDetailRepositoryInterface ) { interface ChangeVisitedStateListener { fun onSuccess(filmUpdated: FilmData) fun onError() } suspend fun execute(filmTitle:String, listener:ChangeVisitedStateListener) { val film = filmDetailRepository.getFilm(filmTitle) if(film != null) { val visitedState = film.visited ?: false filmDetailRepository.updateFilm( FilmData(film.title, film.releaseYear, film.locations, film.funFacts, film.productionCompany, film.distributor, film.director, film.writer, film.actor1, film.actor2, film.actor3, !visitedState, film.favourite) ) listener.onSuccess(filmDetailRepository.getFilm(filmTitle)!!) } else { listener.onError() } } }
1
Kotlin
1
2
38611cb56edfafcc5647049a0cf45a695bc97945
1,071
LikeAStarMpp
Apache License 2.0
lib/src/main/kotlin/com/github/hofmmaxi/exaroton/entities/Logs.kt
hofmmaxi
689,362,188
false
{"Kotlin": 42264}
package com.github.hofmmaxi.exaroton.entities import com.github.hofmmaxi.exaroton.data.LogsData /** * @property content Represents the whole server logs as a single string */ class Logs(private val data: LogsData) { val content: String? get() = data.content }
2
Kotlin
0
0
b526dddb3fb915db45fe879203db6d773be405fe
267
exaroton-kt
MIT License
src/main/kotlin/de/pflugradts/passbird/application/boot/main/ApplicationModule.kt
christianpflugradt
522,173,174
false
{"Kotlin": 416483}
package de.pflugradts.passbird.application.boot.main import com.google.inject.AbstractModule import com.google.inject.Inject import com.google.inject.Provider import com.google.inject.Singleton import com.google.inject.assistedinject.FactoryModuleBuilder import com.google.inject.multibindings.Multibinder import de.pflugradts.passbird.adapter.clipboard.ClipboardService import de.pflugradts.passbird.adapter.exchange.FilePasswordExchange import de.pflugradts.passbird.adapter.keystore.KeyStoreService import de.pflugradts.passbird.adapter.passwordstore.PasswordStoreFacade import de.pflugradts.passbird.adapter.userinterface.CommandLineInterfaceService import de.pflugradts.passbird.application.ClipboardAdapterPort import de.pflugradts.passbird.application.ExchangeAdapterPort import de.pflugradts.passbird.application.KeyStoreAdapterPort import de.pflugradts.passbird.application.UserInterfaceAdapterPort import de.pflugradts.passbird.application.boot.Bootable import de.pflugradts.passbird.application.commandhandling.handler.CommandHandler import de.pflugradts.passbird.application.commandhandling.handler.CustomSetCommandHandler import de.pflugradts.passbird.application.commandhandling.handler.DiscardCommandHandler import de.pflugradts.passbird.application.commandhandling.handler.ExportCommandHandler import de.pflugradts.passbird.application.commandhandling.handler.GetCommandHandler import de.pflugradts.passbird.application.commandhandling.handler.HelpCommandHandler import de.pflugradts.passbird.application.commandhandling.handler.ImportCommandHandler import de.pflugradts.passbird.application.commandhandling.handler.ListCommandHandler import de.pflugradts.passbird.application.commandhandling.handler.QuitCommandHandler import de.pflugradts.passbird.application.commandhandling.handler.RenameCommandHandler import de.pflugradts.passbird.application.commandhandling.handler.SetCommandHandler import de.pflugradts.passbird.application.commandhandling.handler.SetInfoCommandHandler import de.pflugradts.passbird.application.commandhandling.handler.ViewCommandHandler import de.pflugradts.passbird.application.commandhandling.handler.nest.AddNestCommandHandler import de.pflugradts.passbird.application.commandhandling.handler.nest.DiscardNestCommandHandler import de.pflugradts.passbird.application.commandhandling.handler.nest.MoveToNestCommandHandler import de.pflugradts.passbird.application.commandhandling.handler.nest.SwitchNestCommandHandler import de.pflugradts.passbird.application.commandhandling.handler.nest.ViewNestCommandHandler import de.pflugradts.passbird.application.configuration.ConfigurationFactory import de.pflugradts.passbird.application.configuration.ReadableConfiguration import de.pflugradts.passbird.application.eventhandling.ApplicationEventHandler import de.pflugradts.passbird.application.eventhandling.PassbirdEventRegistry import de.pflugradts.passbird.application.exchange.ExchangeFactory import de.pflugradts.passbird.application.exchange.ImportExportService import de.pflugradts.passbird.application.exchange.PasswordImportExportService import de.pflugradts.passbird.application.process.Finalizer import de.pflugradts.passbird.application.process.Initializer import de.pflugradts.passbird.application.process.backup.BackupManager import de.pflugradts.passbird.application.process.exchange.ExportFileChecker import de.pflugradts.passbird.application.process.inactivity.InactivityHandlerScheduler import de.pflugradts.passbird.application.security.CryptoProviderFactory import de.pflugradts.passbird.domain.service.eventhandling.DomainEventHandler import de.pflugradts.passbird.domain.service.eventhandling.EventHandler import de.pflugradts.passbird.domain.service.eventhandling.EventRegistry import de.pflugradts.passbird.domain.service.nest.NestService import de.pflugradts.passbird.domain.service.nest.NestingGroundService import de.pflugradts.passbird.domain.service.password.PasswordFacade import de.pflugradts.passbird.domain.service.password.PasswordService import de.pflugradts.passbird.domain.service.password.encryption.CryptoProvider import de.pflugradts.passbird.domain.service.password.provider.PasswordProvider import de.pflugradts.passbird.domain.service.password.provider.RandomPasswordProvider import de.pflugradts.passbird.domain.service.password.storage.EggRepository import de.pflugradts.passbird.domain.service.password.storage.NestingGround import de.pflugradts.passbird.domain.service.password.storage.PasswordStoreAdapterPort class ApplicationModule : AbstractModule() { override fun configure() { configureApplication() configureMultibinders() configureProviders() } private fun configureApplication() { bind(Bootable::class.java).to(PassbirdApplication::class.java) bind(ClipboardAdapterPort::class.java).to(ClipboardService::class.java) bind(EventRegistry::class.java).to(PassbirdEventRegistry::class.java) bind(ImportExportService::class.java).to(PasswordImportExportService::class.java) bind(KeyStoreAdapterPort::class.java).to(KeyStoreService::class.java) bind(EggRepository::class.java).to(NestingGround::class.java) bind(NestService::class.java).to(NestingGroundService::class.java) bind(PasswordProvider::class.java).to(RandomPasswordProvider::class.java) bind(PasswordService::class.java).to(PasswordFacade::class.java) bind(PasswordStoreAdapterPort::class.java).to(PasswordStoreFacade::class.java) bind(UserInterfaceAdapterPort::class.java).to(CommandLineInterfaceService::class.java) } private fun configureMultibinders() { Multibinder.newSetBinder(binder(), CommandHandler::class.java).apply { listOf( AddNestCommandHandler::class.java, MoveToNestCommandHandler::class.java, CustomSetCommandHandler::class.java, DiscardCommandHandler::class.java, DiscardNestCommandHandler::class.java, ExportCommandHandler::class.java, GetCommandHandler::class.java, HelpCommandHandler::class.java, ImportCommandHandler::class.java, ListCommandHandler::class.java, QuitCommandHandler::class.java, RenameCommandHandler::class.java, SetCommandHandler::class.java, SetInfoCommandHandler::class.java, SwitchNestCommandHandler::class.java, ViewCommandHandler::class.java, ViewNestCommandHandler::class.java, ).forEach { this.addBinding().to(it) } } Multibinder.newSetBinder(binder(), EventHandler::class.java).apply { listOf( ApplicationEventHandler::class.java, DomainEventHandler::class.java, ).forEach { this.addBinding().to(it) } } Multibinder.newSetBinder(binder(), Initializer::class.java).apply { listOf( ExportFileChecker::class.java, InactivityHandlerScheduler::class.java, ).forEach { this.addBinding().to(it) } } Multibinder.newSetBinder(binder(), Finalizer::class.java).apply { listOf( BackupManager::class.java, ).forEach { this.addBinding().to(it) } } } private fun configureProviders() { bind(ReadableConfiguration::class.java).toProvider(ConfigurationDependencyProvider::class.java).`in`(Singleton::class.java) bind(CryptoProvider::class.java).toProvider(CryptoProviderDependencyProvider::class.java).`in`(Singleton::class.java) install( FactoryModuleBuilder().implement(ExchangeAdapterPort::class.java, FilePasswordExchange::class.java) .build(ExchangeFactory::class.java), ) } private class ConfigurationDependencyProvider @Inject constructor( @Inject private val configurationFactory: ConfigurationFactory, ) : Provider<ReadableConfiguration> { override fun get(): ReadableConfiguration = configurationFactory.loadConfiguration() } private class CryptoProviderDependencyProvider @Inject constructor( @Inject private val cryptoProviderFactory: CryptoProviderFactory, ) : Provider<CryptoProvider> { override fun get() = cryptoProviderFactory.createCryptoProvider() } }
2
Kotlin
0
0
fb5d933a67d1c5ccb9b0129811b7f5bdad3fd318
8,428
PwMan3
Apache License 2.0
common/src/main/java/io/homeassistant/companion/android/common/data/authentication/impl/AuthenticationService.kt
home-assistant
179,008,173
false
null
package io.homeassistant.companion.android.common.data.authentication.impl import io.homeassistant.companion.android.common.data.authentication.impl.entities.LoginFlowAuthentication import io.homeassistant.companion.android.common.data.authentication.impl.entities.LoginFlowForm import io.homeassistant.companion.android.common.data.authentication.impl.entities.LoginFlowMfaCode import io.homeassistant.companion.android.common.data.authentication.impl.entities.LoginFlowRequest import io.homeassistant.companion.android.common.data.authentication.impl.entities.Token import okhttp3.HttpUrl import okhttp3.ResponseBody import retrofit2.Response import retrofit2.http.Body import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.POST import retrofit2.http.Url interface AuthenticationService { companion object { const val CLIENT_ID = "https://home-assistant.io/android" const val GRANT_TYPE_CODE = "authorization_code" const val GRANT_TYPE_REFRESH = "refresh_token" const val REVOKE_ACTION = "revoke" val HANDLER = listOf("homeassistant", null) const val AUTHENTICATE_BASE_PATH = "auth/login_flow/" const val AUTH_CALLBACK = "homeassistant://auth-callback" } @FormUrlEncoded @POST suspend fun getToken( @Url url: HttpUrl, @Field("grant_type") grandType: String, @Field("code") code: String, @Field("client_id") clientId: String ): Token @FormUrlEncoded @POST suspend fun refreshToken( @Url url: HttpUrl, @Field("grant_type") grandType: String, @Field("refresh_token") refreshToken: String, @Field("client_id") clientId: String ): Response<Token> @FormUrlEncoded @POST suspend fun revokeToken( @Url url: HttpUrl, @Field("token") refreshToken: String, @Field("action") action: String ) @POST suspend fun initializeLogin(@Url url: String, @Body body: LoginFlowRequest): LoginFlowForm @POST suspend fun authenticatePassword(@Url url: HttpUrl, @Body body: LoginFlowAuthentication): Response<ResponseBody> @POST suspend fun authenticateMfa(@Url url: HttpUrl, @Body body: LoginFlowMfaCode): Response<ResponseBody> }
100
Kotlin
371
1,243
f4c4d72518f1e8308df5ae09068a651bb2b2f621
2,273
android
Apache License 2.0
src/test/kotlin/no/nav/helse/flex/testdata/DatabaseReset.kt
navikt
475,306,289
false
null
package no.nav.helse.flex.testdata import no.nav.helse.flex.medlemskap.MedlemskapVurderingRepository import no.nav.helse.flex.repository.KlippMetrikkRepository import no.nav.helse.flex.repository.SykepengesoknadDAO import org.springframework.jdbc.core.namedparam.MapSqlParameterSource import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate import org.springframework.stereotype.Repository import org.springframework.transaction.annotation.Transactional @Transactional @Repository class DatabaseReset( private val namedParameterJdbcTemplate: NamedParameterJdbcTemplate, private val sykepengesoknadDAO: SykepengesoknadDAO, private val klippMetrikkRepository: KlippMetrikkRepository, private val medlemskapVurderingRepository: MedlemskapVurderingRepository ) { fun resetDatabase() { val aktorIder = namedParameterJdbcTemplate.query( "SELECT distinct(FNR) FROM sykepengesoknad", MapSqlParameterSource() ) { resultSet, _ -> resultSet.getString("FNR") } if (aktorIder.size > 10) { throw RuntimeException("Sikker på at det er så mye testdata som ${aktorIder.size} i databasen") } aktorIder.forEach { sykepengesoknadDAO.nullstillSoknader(it) } namedParameterJdbcTemplate.update("DELETE FROM julesoknadkandidat", MapSqlParameterSource()) klippMetrikkRepository.deleteAll() medlemskapVurderingRepository.deleteAll() } }
7
null
0
4
eaae25fde2778af57d40ed807501dafeefa02193
1,499
sykepengesoknad-backend
MIT License
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/elasticloadbalancingv2/ListenerCondition.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.elasticloadbalancingv2 import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import kotlin.Any import kotlin.String import kotlin.collections.List /** * ListenerCondition providers definition. * * Example: * * ``` * ApplicationListener listener; * AutoScalingGroup asg; * listener.addTargets("Example.Com Fleet", AddApplicationTargetsProps.builder() * .priority(10) * .conditions(List.of(ListenerCondition.hostHeaders(List.of("example.com")), * ListenerCondition.pathPatterns(List.of("/ok", "/path")))) * .port(8080) * .targets(List.of(asg)) * .build()); * ``` */ public abstract class ListenerCondition( cdkObject: software.amazon.awscdk.services.elasticloadbalancingv2.ListenerCondition, ) : CdkObject(cdkObject) { /** * Render the raw Cfn listener rule condition object. */ public open fun renderRawCondition(): Any = unwrap(this).renderRawCondition() private class Wrapper( cdkObject: software.amazon.awscdk.services.elasticloadbalancingv2.ListenerCondition, ) : ListenerCondition(cdkObject) public companion object { public fun hostHeaders(values: List<String>): ListenerCondition = software.amazon.awscdk.services.elasticloadbalancingv2.ListenerCondition.hostHeaders(values).let(ListenerCondition::wrap) public fun hostHeaders(vararg values: String): ListenerCondition = hostHeaders(values.toList()) public fun httpHeader(name: String, values: List<String>): ListenerCondition = software.amazon.awscdk.services.elasticloadbalancingv2.ListenerCondition.httpHeader(name, values).let(ListenerCondition::wrap) public fun httpRequestMethods(values: List<String>): ListenerCondition = software.amazon.awscdk.services.elasticloadbalancingv2.ListenerCondition.httpRequestMethods(values).let(ListenerCondition::wrap) public fun httpRequestMethods(vararg values: String): ListenerCondition = httpRequestMethods(values.toList()) public fun pathPatterns(values: List<String>): ListenerCondition = software.amazon.awscdk.services.elasticloadbalancingv2.ListenerCondition.pathPatterns(values).let(ListenerCondition::wrap) public fun pathPatterns(vararg values: String): ListenerCondition = pathPatterns(values.toList()) public fun queryStrings(values: List<QueryStringCondition>): ListenerCondition = software.amazon.awscdk.services.elasticloadbalancingv2.ListenerCondition.queryStrings(values.map(QueryStringCondition.Companion::unwrap)).let(ListenerCondition::wrap) public fun queryStrings(vararg values: QueryStringCondition): ListenerCondition = queryStrings(values.toList()) public fun sourceIps(values: List<String>): ListenerCondition = software.amazon.awscdk.services.elasticloadbalancingv2.ListenerCondition.sourceIps(values).let(ListenerCondition::wrap) public fun sourceIps(vararg values: String): ListenerCondition = sourceIps(values.toList()) internal fun wrap(cdkObject: software.amazon.awscdk.services.elasticloadbalancingv2.ListenerCondition): ListenerCondition = CdkObjectWrappers.wrap(cdkObject) as? ListenerCondition ?: Wrapper(cdkObject) internal fun unwrap(wrapped: ListenerCondition): software.amazon.awscdk.services.elasticloadbalancingv2.ListenerCondition = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.elasticloadbalancingv2.ListenerCondition } }
4
null
0
4
9a242bcc59b2c1cf505be2f9d838f1cd8008fe12
3,691
kotlin-cdk-wrapper
Apache License 2.0
collaboration-suite-phone-ui/src/main/java/com/kaleyra/collaboration_suite_phone_ui/whiteboard/layout/KaleyraWhiteboardLoadingError.kt
Bandyer
337,367,845
false
{"Kotlin": 1272666, "Shell": 7470, "Python": 5656}
/* * Copyright 2022 Kaleyra @ https://www.kaleyra.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kaleyra.collaboration_suite_phone_ui.whiteboard.layout import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.animation.Animation import android.view.animation.AnimationUtils import androidx.constraintlayout.widget.ConstraintLayout import com.kaleyra.collaboration_suite_phone_ui.R import com.kaleyra.collaboration_suite_phone_ui.databinding.KaleyraWhiteboardLoadingErrorBinding import com.google.android.material.button.MaterialButton import com.google.android.material.textview.MaterialTextView /** * A view showing an error occurred while loading the whiteboard web view * @property reloadTitle MaterialTextView? * @property reloadSubtitle MaterialTextView? * @property reloadButton MaterialButton? * @constructor */ class KaleyraWhiteboardLoadingError @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.kaleyra_rootLayoutStyle) : ConstraintLayout(context, attrs, defStyleAttr) { /** * Title of the error layout */ var reloadTitle: MaterialTextView? = null private set /** * Subtitle of the error layout */ var reloadSubtitle: MaterialTextView? = null private set /** * The reload button of the error layout */ var reloadButton: MaterialButton? = null private set private val binding: KaleyraWhiteboardLoadingErrorBinding by lazy { KaleyraWhiteboardLoadingErrorBinding.inflate(LayoutInflater.from(context), this) } /** * Animation applied to reload button */ private val reloadAnimation: Animation = AnimationUtils.loadAnimation(context, R.anim.kaleyra_reload_animation) init { reloadTitle = binding.kaleyraReloadTitle reloadSubtitle = binding.kaleyraReloadSubtitle reloadButton = binding.kaleyraReloadButton } /** * Set a click listener on the reload button and animate it on click * @param callback the callback function to be executed when clicking the button */ fun onReload(callback: () -> Unit) = reloadButton?.setOnClickListener { callback.invoke() reloadButton?.startAnimation(reloadAnimation) } }
1
Kotlin
2
2
f74e81cbd9d8fb06e625ae909f504f56baa15bb5
2,881
Bandyer-Android-Design
Apache License 2.0
bugsnag-android-core/src/main/java/com/bugsnag/android/DefaultDelivery.kt
yeaper
467,615,335
true
{"Kotlin": 609040, "Java": 465805, "C": 418485, "Gherkin": 119579, "C++": 33621, "Ruby": 18463, "Shell": 9519, "CMake": 4538, "Makefile": 1937}
package com.bugsnag.android import android.net.TrafficStats import java.io.ByteArrayOutputStream import java.io.IOException import java.io.PrintWriter import java.net.HttpURLConnection import java.net.HttpURLConnection.HTTP_BAD_REQUEST import java.net.HttpURLConnection.HTTP_CLIENT_TIMEOUT import java.net.HttpURLConnection.HTTP_OK import java.net.URL /** * Converts a [JsonStream.Streamable] into JSON, placing it in a [ByteArray] */ internal fun serializeJsonPayload(streamable: JsonStream.Streamable): ByteArray { return ByteArrayOutputStream().use { baos -> JsonStream(PrintWriter(baos).buffered()).use(streamable::toStream) baos.toByteArray() } } internal class DefaultDelivery( private val connectivity: Connectivity?, val logger: Logger ) : Delivery { override fun deliver(payload: Session, deliveryParams: DeliveryParams): DeliveryStatus { val status = deliver(deliveryParams.endpoint, payload, deliveryParams.headers) logger.i("Session API request finished with status $status") return status } override fun deliver(payload: EventPayload, deliveryParams: DeliveryParams): DeliveryStatus { val status = deliver(deliveryParams.endpoint, payload, deliveryParams.headers) logger.i("Error API request finished with status $status") return status } fun deliver( urlString: String, streamable: JsonStream.Streamable, headers: Map<String, String?> ): DeliveryStatus { TrafficStats.setThreadStatsTag(1) if (connectivity != null && !connectivity.hasNetworkConnection()) { return DeliveryStatus.UNDELIVERED } var conn: HttpURLConnection? = null try { val json = serializeJsonPayload(streamable) conn = makeRequest(URL(urlString), json, headers) // End the request, get the response code val responseCode = conn.responseCode val status = getDeliveryStatus(responseCode) logRequestInfo(responseCode, conn, status) return status } catch (oom: OutOfMemoryError) { // attempt to persist the payload on disk. This approach uses streams to write to a // file, which takes less memory than serializing the payload into a ByteArray, and // therefore has a reasonable chance of retaining the payload for future delivery. logger.w("Encountered OOM delivering payload, falling back to persist on disk", oom) return DeliveryStatus.UNDELIVERED } catch (exception: IOException) { logger.w("IOException encountered in request", exception) return DeliveryStatus.UNDELIVERED } catch (exception: Exception) { logger.w("Unexpected error delivering payload", exception) return DeliveryStatus.FAILURE } finally { conn?.disconnect() } } private fun makeRequest( url: URL, json: ByteArray, headers: Map<String, String?> ): HttpURLConnection { val conn = url.openConnection() as HttpURLConnection conn.doOutput = true // avoids creating a buffer within HttpUrlConnection, see // https://developer.android.com/reference/java/net/HttpURLConnection conn.setFixedLengthStreamingMode(json.size) // calculate the SHA-1 digest and add all other headers computeSha1Digest(json)?.let { digest -> conn.addRequestProperty(HEADER_BUGSNAG_INTEGRITY, digest) } headers.forEach { (key, value) -> if (value != null) { conn.addRequestProperty(key, value) } } // write the JSON payload conn.outputStream.use { it.write(json) } return conn } private fun logRequestInfo(code: Int, conn: HttpURLConnection, status: DeliveryStatus) { logger.i( "Request completed with code $code, " + "message: ${conn.responseMessage}, " + "headers: ${conn.headerFields}" ) conn.inputStream.bufferedReader().use { logger.d("Received request response: ${it.readText()}") } if (status != DeliveryStatus.DELIVERED) { conn.errorStream.bufferedReader().use { logger.w("Request error details: ${it.readText()}") } } } internal fun getDeliveryStatus(responseCode: Int): DeliveryStatus { val unrecoverableCodes = IntRange(HTTP_BAD_REQUEST, 499).filter { it != HTTP_CLIENT_TIMEOUT && it != 429 } return when (responseCode) { in HTTP_OK..299 -> DeliveryStatus.DELIVERED in unrecoverableCodes -> DeliveryStatus.FAILURE else -> DeliveryStatus.UNDELIVERED } } }
2
Kotlin
0
0
3808c4141cf113de9890aa08670fa7317523b6d1
4,883
bugsnag-android
MIT License
src/test/kotlin/TestExtensions.kt
SebastianRiga
399,853,220
false
null
import com.riga.sebastian.propertiesextended.BackingField import java.io.InputStream var InputStream.tag by BackingField { "$it" }
0
Kotlin
0
0
01aabc88da5209e849fd359922a7dc4932e6eda6
131
kotlin_property_extensions
MIT License
privacysandbox/ui/ui-client/src/main/java/androidx/privacysandbox/ui/client/view/SandboxedSdkView.kt
androidx
256,589,781
false
null
/* * Copyright 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.privacysandbox.ui.client.view import android.content.Context import android.content.res.Configuration import android.graphics.Rect import android.os.Binder import android.os.Build import android.os.IBinder import android.util.AttributeSet import android.view.SurfaceControl import android.view.SurfaceHolder import android.view.SurfaceView import android.view.View import android.view.ViewGroup import android.view.ViewParent import android.view.ViewTreeObserver import androidx.annotation.DoNotInline import androidx.annotation.RequiresApi import androidx.annotation.VisibleForTesting import androidx.customview.poolingcontainer.PoolingContainerListener import androidx.customview.poolingcontainer.addPoolingContainerListener import androidx.customview.poolingcontainer.isPoolingContainer import androidx.customview.poolingcontainer.isWithinPoolingContainer import androidx.customview.poolingcontainer.removePoolingContainerListener import androidx.privacysandbox.ui.client.view.SandboxedSdkUiSessionState.Active import androidx.privacysandbox.ui.client.view.SandboxedSdkUiSessionState.Idle import androidx.privacysandbox.ui.client.view.SandboxedSdkUiSessionState.Loading import androidx.privacysandbox.ui.core.SandboxedUiAdapter import java.util.concurrent.CopyOnWriteArrayList import kotlin.math.min /** * A listener for changes to the state of the UI session associated with SandboxedSdkView. */ fun interface SandboxedSdkUiSessionStateChangedListener { /** * Called when the state of the session for SandboxedSdkView is updated. */ fun onStateChanged(state: SandboxedSdkUiSessionState) } /** * Represents the state of a UI session. * * A UI session refers to the session opened with a [SandboxedUiAdapter] to let the host display UI * from the UI provider. If the host has requested to open a session with its [SandboxedUiAdapter], * the state will be [Loading] until the session has been opened and the content has been displayed. * At this point, the state will become [Active]. If there is no active session and no session is * being loaded, the state is [Idle]. */ sealed class SandboxedSdkUiSessionState private constructor() { /** * A UI session is currently attempting to be opened. * * This state occurs when the UI has requested to open a session with its [SandboxedUiAdapter]. * No UI from the [SandboxedUiAdapter] will be shown during this state. When the session has * been successfully opened and the content has been displayed, the state will transition to * [Active]. */ object Loading : SandboxedSdkUiSessionState() /** * There is an open session with the supplied [SandboxedUiAdapter] and its UI is currently * being displayed. This state is set after the first draw event of the [SandboxedSdkView]. */ object Active : SandboxedSdkUiSessionState() /** * There is no currently open UI session and there is no operation in progress to open one. * * The UI provider may close the session at any point, which will result in the state becoming * [Idle] if the session is closed without an error. If there is an error that causes the * session to close, the state will be [Error]. * * If a new [SandboxedUiAdapter] is set on a [SandboxedSdkView], the existing session will close * and the state will become [Idle]. */ object Idle : SandboxedSdkUiSessionState() /** * There was an error in the UI session. * * @param throwable The error that caused the session to end. */ class Error(val throwable: Throwable) : SandboxedSdkUiSessionState() } class SandboxedSdkView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : ViewGroup(context, attrs) { // This will only be invoked when the content view has been set and the window is attached. private val surfaceChangedCallback = object : SurfaceHolder.Callback { override fun surfaceCreated(p0: SurfaceHolder) { updateAndSetClippingBounds(true) viewTreeObserver.addOnGlobalLayoutListener(globalLayoutChangeListener) } override fun surfaceChanged(p0: SurfaceHolder, p1: Int, p2: Int, p3: Int) { } override fun surfaceDestroyed(p0: SurfaceHolder) { } } // This will only be invoked when the content view has been set and the window is attached. private val globalLayoutChangeListener = ViewTreeObserver.OnGlobalLayoutListener { updateAndSetClippingBounds() } private var adapter: SandboxedUiAdapter? = null private var client: Client? = null private var isZOrderOnTop = true private var contentView: View? = null private var requestedWidth = -1 private var requestedHeight = -1 private var isTransitionGroupSet = false private var windowInputToken: IBinder? = null private var previousWidth = -1 private var previousHeight = -1 private var currentClippingBounds = Rect() internal val stateListenerManager: StateListenerManager = StateListenerManager() private var poolingContainerChild: View? = null private var poolingContainerListener = PoolingContainerListener {} /** * Adds a state change listener to the UI session and immediately reports the current * state. */ fun addStateChangedListener(stateChangedListener: SandboxedSdkUiSessionStateChangedListener) { stateListenerManager.addStateChangedListener(stateChangedListener) } /** * Removes the specified state change listener from SandboxedSdkView. */ fun removeStateChangedListener( stateChangedListener: SandboxedSdkUiSessionStateChangedListener ) { stateListenerManager.removeStateChangedListener(stateChangedListener) } fun setAdapter(sandboxedUiAdapter: SandboxedUiAdapter) { if (this.adapter === sandboxedUiAdapter) return client?.close() client = null this.adapter = sandboxedUiAdapter checkClientOpenSession() } /** * Sets the Z-ordering of the [SandboxedSdkView]'s surface, relative to its window. * * When [providerUiOnTop] is true, every [android.view.MotionEvent] on the [SandboxedSdkView] * will be sent to the UI provider. When [providerUiOnTop] is false, every * [android.view.MotionEvent] will be sent to the client. By default, motion events are sent to * the UI provider. * * When [providerUiOnTop] is true, the UI provider's surface will be placed above the client's * window. In this case, none of the contents of the client's window beneath the provider's * surface will be visible. */ fun orderProviderUiAboveClientUi(providerUiOnTop: Boolean) { if (providerUiOnTop == isZOrderOnTop) return client?.notifyZOrderChanged(providerUiOnTop) isZOrderOnTop = providerUiOnTop checkClientOpenSession() } internal fun updateAndSetClippingBounds(forceUpdate: Boolean = false) { if (maybeUpdateClippingBounds(currentClippingBounds) || forceUpdate) { CompatImpl.setClippingBounds(contentView, isAttachedToWindow, currentClippingBounds) } } /** * Computes the window space coordinates for the bounding parent of this view, and stores the * result in [rect]. * * Returns true if the coordinates have changed, false otherwise. */ @VisibleForTesting internal fun maybeUpdateClippingBounds(rect: Rect): Boolean { val prevBounds = Rect(rect) var viewParent: ViewParent? = parent while (viewParent != null && viewParent is View) { val v = viewParent as View if (v.isScrollContainer || v.id == android.R.id.content) { v.getGlobalVisibleRect(rect) return prevBounds != rect } viewParent = viewParent.getParent() } return false } private fun checkClientOpenSession() { val adapter = adapter if (client == null && adapter != null && windowInputToken != null && width > 0 && height > 0) { stateListenerManager.currentUiSessionState = SandboxedSdkUiSessionState.Loading client = Client(this) adapter.openSession( context, windowInputToken!!, width, height, isZOrderOnTop, handler::post, client!! ) } } internal fun requestSize(width: Int, height: Int) { if (width == this.width && height == this.height) return requestedWidth = width requestedHeight = height requestLayout() } private fun removeContentView() { removeCallbacks() if (childCount == 1) { super.removeViewAt(0) } } private fun removeCallbacks() { (contentView as? SurfaceView)?.holder?.removeCallback(surfaceChangedCallback) viewTreeObserver.removeOnGlobalLayoutListener(globalLayoutChangeListener) } internal fun setContentView(contentView: View) { if (childCount > 1) { throw IllegalStateException("Number of children views must not exceed 1") } this.contentView = contentView removeContentView() if (contentView.layoutParams == null) { super.addView(contentView, 0, generateDefaultLayoutParams()) } else { super.addView(contentView, 0, contentView.layoutParams) } // Wait for the next frame commit before sending an ACTIVE state change to listeners. CompatImpl.registerFrameCommitCallback(viewTreeObserver) { stateListenerManager.currentUiSessionState = Active } if (contentView is SurfaceView) { contentView.holder.addCallback(surfaceChangedCallback) } } internal fun onClientClosedSession(error: Throwable? = null) { removeContentView() stateListenerManager.currentUiSessionState = if (error != null) { SandboxedSdkUiSessionState.Error(error) } else { SandboxedSdkUiSessionState.Idle } } private fun calculateMeasuredDimension(requestedSize: Int, measureSpec: Int): Int { val measureSpecSize = MeasureSpec.getSize(measureSpec) when (MeasureSpec.getMode(measureSpec)) { MeasureSpec.EXACTLY -> { return measureSpecSize } MeasureSpec.UNSPECIFIED -> { return if (requestedSize < 0) { measureSpecSize } else { requestedSize } } MeasureSpec.AT_MOST -> { return if (requestedSize >= 0) { min(requestedSize, measureSpecSize) } else { measureSpecSize } } else -> { return measureSpecSize } } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val newWidth = calculateMeasuredDimension(requestedWidth, widthMeasureSpec) val newHeight = calculateMeasuredDimension(requestedHeight, heightMeasureSpec) requestedWidth = -1 requestedHeight = -1 setMeasuredDimension(newWidth, newHeight) } override fun isTransitionGroup(): Boolean = !isTransitionGroupSet || super.isTransitionGroup() override fun setTransitionGroup(isTransitionGroup: Boolean) { super.setTransitionGroup(isTransitionGroup) isTransitionGroupSet = true } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { if (this.isWithinPoolingContainer) { attachPoolingContainerListener() } // We will not call client?.notifyResized for the first onLayout call // and the case in which the width and the height remain unchanged. if ((previousWidth != (right - left) || previousHeight != (bottom - top)) && (previousWidth != -1 && previousHeight != -1)) { client?.notifyResized(right - left, bottom - top) } else { // Child needs to receive coordinates that are relative to the parent. getChildAt(0)?.layout( /* left = */ 0, /* top = */ 0, /* right = */ right - left, /* bottom = */ bottom - top) } previousHeight = height previousWidth = width checkClientOpenSession() } private fun closeClient() { client?.close() client = null windowInputToken = null removeCallbacks() } private fun attachPoolingContainerListener() { val listener = PoolingContainerListener { closeClient() poolingContainerChild ?.removePoolingContainerListener(poolingContainerListener) } var currentView = this as View var parentView = parent while (parentView != null && !(parentView as View).isPoolingContainer) { currentView = parentView parentView = currentView.parent } if (currentView == poolingContainerChild) { return } poolingContainerChild ?.removePoolingContainerListener(poolingContainerListener) currentView.addPoolingContainerListener(listener) poolingContainerChild = currentView poolingContainerListener = listener } override fun onAttachedToWindow() { super.onAttachedToWindow() if (this.isWithinPoolingContainer) { attachPoolingContainerListener() } CompatImpl.deriveInputTokenAndOpenSession(context, this) } override fun onDetachedFromWindow() { if (!this.isWithinPoolingContainer) { closeClient() } super.onDetachedFromWindow() } // TODO(b/298658350): Cache previous config properly to avoid unnecessary binder calls override fun onConfigurationChanged(config: Configuration?) { requireNotNull(config) { "Config cannot be null" } super.onConfigurationChanged(config) client?.notifyConfigurationChanged(config) checkClientOpenSession() } /** * @throws UnsupportedOperationException when called */ override fun addView( view: View?, index: Int, params: LayoutParams? ) { throw UnsupportedOperationException("Cannot add a view to SandboxedSdkView") } /** * @throws UnsupportedOperationException when called */ override fun removeView(view: View?) { throw UnsupportedOperationException("Cannot remove a view from SandboxedSdkView") } /** * @throws UnsupportedOperationException when called */ override fun removeViewInLayout(view: View?) { throw UnsupportedOperationException("Cannot remove a view from SandboxedSdkView") } /** * @throws UnsupportedOperationException when called */ override fun removeViewsInLayout(start: Int, count: Int) { throw UnsupportedOperationException("Cannot remove a view from SandboxedSdkView") } /** * @throws UnsupportedOperationException when called */ override fun removeViewAt(index: Int) { throw UnsupportedOperationException("Cannot remove a view from SandboxedSdkView") } /** * @throws UnsupportedOperationException when called */ override fun removeViews(start: Int, count: Int) { throw UnsupportedOperationException("Cannot remove a view from SandboxedSdkView") } /** * @throws UnsupportedOperationException when called */ override fun removeAllViews() { throw UnsupportedOperationException("Cannot remove a view from SandboxedSdkView") } /** * @throws UnsupportedOperationException when called */ override fun removeAllViewsInLayout() { throw UnsupportedOperationException("Cannot remove a view from SandboxedSdkView") } private fun addTemporarySurfaceView(surfaceView: SurfaceView) { super.addView(surfaceView, 0, generateDefaultLayoutParams()) } private fun removeTemporarySurfaceView(surfaceView: SurfaceView) { super.removeView(surfaceView) } internal class Client(private var sandboxedSdkView: SandboxedSdkView?) : SandboxedUiAdapter.SessionClient { private var session: SandboxedUiAdapter.Session? = null private var pendingWidth: Int? = null private var pendingHeight: Int? = null private var pendingZOrderOnTop: Boolean? = null private var pendingConfiguration: Configuration? = null fun notifyConfigurationChanged(configuration: Configuration) { val session = session if (session != null) { session.notifyConfigurationChanged(configuration) } else { pendingConfiguration = configuration } } fun notifyResized(width: Int, height: Int) { val session = session if (session != null) { session.notifyResized(width, height) } else { pendingWidth = width pendingHeight = height } } fun notifyZOrderChanged(isZOrderOnTop: Boolean) { if (sandboxedSdkView?.isZOrderOnTop == isZOrderOnTop) return val session = session if (session != null) { session.notifyZOrderChanged(isZOrderOnTop) } else { pendingZOrderOnTop = isZOrderOnTop } } fun close() { session?.close() session = null sandboxedSdkView?.onClientClosedSession() sandboxedSdkView = null } override fun onSessionOpened(session: SandboxedUiAdapter.Session) { if (sandboxedSdkView == null) { session.close() return } sandboxedSdkView?.setContentView(session.view) this.session = session val width = pendingWidth val height = pendingHeight if ((width != null) && (height != null) && (width >= 0) && (height >= 0)) { session.notifyResized(width, height) } pendingConfiguration?.let { session.notifyConfigurationChanged(it) } pendingConfiguration = null pendingZOrderOnTop?.let { session.notifyZOrderChanged(it) } pendingZOrderOnTop = null } override fun onSessionError(throwable: Throwable) { if (sandboxedSdkView == null) return sandboxedSdkView?.onClientClosedSession(throwable) } override fun onResizeRequested(width: Int, height: Int) { if (sandboxedSdkView == null) return sandboxedSdkView?.requestSize(width, height) } } internal class StateListenerManager { internal var currentUiSessionState: SandboxedSdkUiSessionState = SandboxedSdkUiSessionState.Idle set(value) { if (field != value) { field = value for (listener in stateChangedListeners) { listener.onStateChanged(currentUiSessionState) } } } private var stateChangedListeners = CopyOnWriteArrayList<SandboxedSdkUiSessionStateChangedListener>() fun addStateChangedListener(listener: SandboxedSdkUiSessionStateChangedListener) { stateChangedListeners.add(listener) listener.onStateChanged(currentUiSessionState) } fun removeStateChangedListener(listener: SandboxedSdkUiSessionStateChangedListener) { stateChangedListeners.remove(listener) } } /** * Provides backward compat support for APIs. * * If the API is available, it's called from a version-specific static inner class gated with * version check, otherwise a fallback action is taken depending on the situation. */ private object CompatImpl { fun deriveInputTokenAndOpenSession( context: Context, sandboxedSdkView: SandboxedSdkView ) { // TODO(b/284147223): Remove this logic in V+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { Api34PlusImpl.attachTemporarySurfaceViewAndOpenSession( context, sandboxedSdkView) } else { // the openSession signature requires a non-null input token, so the session // will not be opened until this is set sandboxedSdkView.windowInputToken = Binder() sandboxedSdkView.checkClientOpenSession() } } fun setClippingBounds( contentView: View?, isAttachedToWindow: Boolean, currentClippingBounds: Rect ) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { Api34PlusImpl.setClippingBounds( contentView, isAttachedToWindow, currentClippingBounds) } } fun registerFrameCommitCallback(observer: ViewTreeObserver, callback: Runnable) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { Api29PlusImpl.registerFrameCommitCallback(observer, callback) } else { callback.run() } } @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE) private object Api34PlusImpl { @JvmStatic @DoNotInline fun setClippingBounds( contentView: View?, isAttachedToWindow: Boolean, currentClippingBounds: Rect ) { checkNotNull(contentView) check(isAttachedToWindow) val surfaceView: SurfaceView = contentView as SurfaceView val attachedSurfaceControl = checkNotNull(surfaceView.rootSurfaceControl) { "attachedSurfaceControl should be non-null if the window is attached" } val name = "clippingBounds-${System.currentTimeMillis()}" val clippingBoundsSurfaceControl = SurfaceControl.Builder().setName(name) .build() val reparentSurfaceControlTransaction = SurfaceControl.Transaction() .reparent(surfaceView.surfaceControl, clippingBoundsSurfaceControl) val reparentClippingBoundsTransaction = checkNotNull( attachedSurfaceControl.buildReparentTransaction(clippingBoundsSurfaceControl)) { "Reparent transaction should be non-null if the window is attached" } reparentClippingBoundsTransaction.setCrop( clippingBoundsSurfaceControl, currentClippingBounds) reparentClippingBoundsTransaction.setVisibility(clippingBoundsSurfaceControl, true) reparentSurfaceControlTransaction.merge(reparentClippingBoundsTransaction) attachedSurfaceControl.applyTransactionOnDraw(reparentSurfaceControlTransaction) } @JvmStatic @DoNotInline fun attachTemporarySurfaceViewAndOpenSession( context: Context, sandboxedSdkView: SandboxedSdkView ) { val surfaceView = SurfaceView(context).apply { visibility = GONE } val onSurfaceViewAttachedListener = object : OnAttachStateChangeListener { override fun onViewAttachedToWindow(view: View) { view.removeOnAttachStateChangeListener(this) sandboxedSdkView.windowInputToken = surfaceView.hostToken sandboxedSdkView.removeTemporarySurfaceView(surfaceView) sandboxedSdkView.checkClientOpenSession() } override fun onViewDetachedFromWindow(view: View) { } } surfaceView.addOnAttachStateChangeListener(onSurfaceViewAttachedListener) sandboxedSdkView.addTemporarySurfaceView(surfaceView) } } @RequiresApi(Build.VERSION_CODES.Q) private object Api29PlusImpl { @JvmStatic @DoNotInline fun registerFrameCommitCallback(observer: ViewTreeObserver, callback: Runnable) { observer.registerFrameCommitCallback(callback) } } } }
30
null
984
5,256
b4f2ba144b1330987d46dda7707499423171642b
25,707
androidx
Apache License 2.0
ok-propertysale-mp-pipelines/src/commonTest/kotlin/ru/otus/otuskotlin/propertysale/mp/pipelines/PipelineTest.kt
otuskotlin
330,109,804
false
null
package ru.otus.otuskotlin.marketplace.pipelines.kmp import runBlockingTest import kotlin.test.Test import kotlin.test.assertEquals class PipelineTest { @Test fun simplePipeline() { val givenOperation = operation<TestContext> { execute { a += "c" } } val givenPipeline = pipeline<TestContext> { execute { a = "a" } execute(givenOperation) operation { startIf { println("Check a: $a") a.isNotEmpty() } execute { a += "b" } } } val givenContext = TestContext() runBlockingTest { println("Starting test") givenPipeline.execute(givenContext) assertEquals("acb", givenContext.a) println("Test Done") println("Finish test") } } @Test fun nestedPipeline() { val givenOperation = operation<TestContext> { execute { a += "c" } } val givenPipeline = pipeline<TestContext> { execute { a = "a" } execute(givenOperation) pipeline { startIf { println("Check a: $a") a.isNotEmpty() } execute { a += "b" } } } val givenContext = TestContext() runBlockingTest { println("Starting test") givenPipeline.execute(givenContext) assertEquals("acb", givenContext.a) println("Test Done") println("Finish test") } } data class TestContext( var a: String = "" ) }
1
null
1
1
ed9a38627e64ed36131280ca7449547ba1d06829
1,710
otuskotlin-202012-propertysale-ks
MIT License
app/src/main/java/volovyk/guerrillamail/data/emails/remote/model/RemoteEmailDatabaseException.kt
oleksandrvolovyk
611,731,548
false
{"Kotlin": 158288, "Java": 767}
package volovyk.guerrillamail.data.emails.remote.model open class RemoteEmailDatabaseException: RuntimeException { constructor(message: String) : super(message) constructor(throwable: Throwable) : super(throwable) constructor() : super() data object EmptyResponseException: RemoteEmailDatabaseException() data object UnsuccessfulRequestException : RemoteEmailDatabaseException() data object NoEmailAddressAssignedException : RemoteEmailDatabaseException() }
0
Kotlin
0
1
0e204bb437a6cfd837cd0bb911a29f0fc43164ce
483
guerrilla-mail-android-client
MIT License
sketch-core/src/main/kotlin/com/github/panpf/sketch/request/internal/RequestExecutor.kt
panpf
14,798,941
false
null
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.request.internal import android.graphics.drawable.Drawable import android.view.View import android.widget.ImageView import androidx.annotation.MainThread import com.github.panpf.sketch.Sketch import com.github.panpf.sketch.decode.internal.logString import com.github.panpf.sketch.drawable.internal.tryToResizeDrawable import com.github.panpf.sketch.request.DepthException import com.github.panpf.sketch.request.DisplayData import com.github.panpf.sketch.request.DisplayRequest import com.github.panpf.sketch.request.DisplayResult import com.github.panpf.sketch.request.DownloadData import com.github.panpf.sketch.request.DownloadRequest import com.github.panpf.sketch.request.DownloadResult import com.github.panpf.sketch.request.ImageRequest import com.github.panpf.sketch.request.ImageResult import com.github.panpf.sketch.request.LoadData import com.github.panpf.sketch.request.LoadRequest import com.github.panpf.sketch.request.LoadResult import com.github.panpf.sketch.request.UriInvalidException import com.github.panpf.sketch.stateimage.internal.toSketchStateDrawable import com.github.panpf.sketch.target.DisplayTarget import com.github.panpf.sketch.target.DownloadTarget import com.github.panpf.sketch.target.LoadTarget import com.github.panpf.sketch.target.Target import com.github.panpf.sketch.target.ViewDisplayTarget import com.github.panpf.sketch.transition.TransitionDisplayTarget import com.github.panpf.sketch.util.Size import com.github.panpf.sketch.util.asOrNull import com.github.panpf.sketch.util.awaitStarted import com.github.panpf.sketch.util.fitScale import com.github.panpf.sketch.util.requiredMainThread import kotlinx.coroutines.CancellationException import kotlinx.coroutines.job import kotlin.coroutines.coroutineContext class RequestExecutor { companion object { const val MODULE = "RequestExecutor" } @MainThread suspend fun execute(sketch: Sketch, request: ImageRequest, enqueue: Boolean): ImageResult { requiredMainThread() // Wrap the request to manage its lifecycle. val requestDelegate = requestDelegate(sketch, request, coroutineContext.job) requestDelegate.assertActive() var requestContext: RequestContext? = null var firstRequestKey: String? = null try { val uriString = request.uriString if (uriString.isEmpty() || uriString.isBlank()) { throw UriInvalidException("Request uri is empty or blank") } // Set up the request's lifecycle observers. Cancel the request when destroy requestDelegate.start() // Enqueued requests suspend until the lifecycle is started. if (enqueue) { request.lifecycle.awaitStarted() } // resolve resize size val resizeSize = request.resizeSizeResolver.size() requestContext = RequestContext(request, resizeSize) firstRequestKey = requestContext.key onStart(sketch, requestContext, firstRequestKey) val result = RequestInterceptorChain( sketch = sketch, initialRequest = requestContext.request, request = requestContext.request, requestContext = requestContext, interceptors = sketch.components.getRequestInterceptorList(requestContext.request), index = 0, ).proceed(requestContext.request) val imageData = result.getOrNull() if (imageData != null) { val lastRequest: ImageRequest = requestContext.request val successResult: ImageResult.Success = when { lastRequest is DisplayRequest && imageData is DisplayData -> DisplayResult.Success( request = lastRequest, requestKey = requestContext.key, requestCacheKey = requestContext.cacheKey, drawable = imageData.drawable .tryToResizeDrawable(lastRequest, requestContext.resizeSize), imageInfo = imageData.imageInfo, dataFrom = imageData.dataFrom, transformedList = imageData.transformedList, extras = imageData.extras, ) lastRequest is LoadRequest && imageData is LoadData -> LoadResult.Success( request = lastRequest, requestKey = requestContext.key, requestCacheKey = requestContext.cacheKey, bitmap = imageData.bitmap, imageInfo = imageData.imageInfo, dataFrom = imageData.dataFrom, transformedList = imageData.transformedList, extras = imageData.extras, ) lastRequest is DownloadRequest && imageData is DownloadData -> DownloadResult.Success( lastRequest, imageData ) else -> throw UnsupportedOperationException("Unsupported ImageData: ${imageData::class.java}") } onSuccess(sketch, requestContext, firstRequestKey, successResult) return successResult } else { throw result.exceptionOrNull()!! } } catch (throwable: Throwable) { val lastRequest = (requestContext?.request ?: request) if (throwable is CancellationException) { onCancel(sketch, requestContext, firstRequestKey, request) throw throwable } else { val errorResult: ImageResult.Error = when (lastRequest) { is DisplayRequest -> { val errorDrawable = getErrorDrawable( sketch = sketch, request = lastRequest, resizeSize = requestContext?.resizeSize, throwable = throwable ) DisplayResult.Error(lastRequest, errorDrawable, throwable) } is LoadRequest -> LoadResult.Error(lastRequest, throwable) is DownloadRequest -> DownloadResult.Error(lastRequest, throwable) else -> throw UnsupportedOperationException("Unsupported ImageRequest: ${lastRequest::class.java}") } onError(sketch, requestContext, firstRequestKey, request, errorResult) return errorResult } } finally { requestContext?.completeCountDrawable("RequestCompleted") requestDelegate.finish() } } @MainThread private fun onStart(sketch: Sketch, requestContext: RequestContext, firstRequestKey: String) { val request = requestContext.request request.listener?.onStart(request) sketch.logger.d(MODULE) { "Request started. '${firstRequestKey}'" } } @MainThread private fun onSuccess( sketch: Sketch, requestContext: RequestContext, firstRequestKey: String, result: ImageResult.Success ) { val request = requestContext.request val target = request.target when { target is DisplayTarget && result is DisplayResult.Success -> { setDrawable(target, result) { target.onSuccess(result.drawable) } } target is LoadTarget && result is LoadResult.Success -> { target.onSuccess(result.bitmap) } target is DownloadTarget && result is DownloadResult.Success -> { target.onSuccess(result.data) } } request.listener?.onSuccess(request, result) sketch.logger.d(MODULE) { val logKey = newLogKey(requestContext, firstRequestKey, request) when (result) { is DisplayResult.Success -> { "Request Successful. ${result.drawable}. $logKey" } is LoadResult.Success -> { "Request Successful. ${result.bitmap.logString}. ${result.imageInfo}. ${result.transformedList}. $logKey" } is DownloadResult.Success -> { "Request Successful. ${result.data}. '${requestContext.key}'. $logKey" } else -> { "Request Successful. $logKey" } } } } @MainThread private fun onError( sketch: Sketch, requestContext: RequestContext?, firstRequestKey: String?, request: ImageRequest, result: ImageResult.Error ) { val request1 = requestContext?.request ?: request val target = request1.target when { target is DisplayTarget && result is DisplayResult.Error -> { setDrawable(target, result) { target.onError(result.drawable) } } target is LoadTarget && result is LoadResult.Error -> { target.onError(result.throwable) } target is DownloadTarget && result is DownloadResult.Error -> { target.onError(result.throwable) } } request1.listener?.onError(request1, result) if (result.throwable is DepthException) { sketch.logger.d(MODULE) { val logKey = newLogKey(requestContext, firstRequestKey, request) "Request failed. ${result.throwable.message}. $logKey" } } else { sketch.logger.e(MODULE, result.throwable) { val logKey = newLogKey(requestContext, firstRequestKey, request) "Request failed. ${result.throwable.message}. $logKey" } } } @MainThread private fun onCancel( sketch: Sketch, requestContext: RequestContext?, firstRequestKey: String?, request: ImageRequest ) { val request1 = requestContext?.request ?: request sketch.logger.d(MODULE) { val logKey = newLogKey(requestContext, firstRequestKey, request) "Request canceled. $logKey" } request1.listener?.onCancel(request1) } @MainThread private fun setDrawable( target: Target?, result: DisplayResult, setDrawable: () -> Unit ) { if (result.drawable == null) { return } if (target !is TransitionDisplayTarget) { setDrawable() return } val fitScale = target.asOrNull<ViewDisplayTarget<View>>()?.view.asOrNull<ImageView>()?.fitScale ?: true val transition = result.request.transitionFactory?.create(target, result, fitScale) if (transition == null) { setDrawable() return } transition.transition() } private fun getErrorDrawable( sketch: Sketch, request: ImageRequest, resizeSize: Size?, throwable: Throwable ): Drawable? = (request.error?.getDrawable(sketch, request, throwable) ?: request.placeholder?.getDrawable(sketch, request, throwable)) ?.tryToResizeDrawable(request, resizeSize) ?.toSketchStateDrawable() private fun newLogKey( requestContext: RequestContext?, firstRequestKey: String?, request: ImageRequest ): String { val request1 = requestContext?.request ?: request val firstRequestKey1 = firstRequestKey ?: request1.uriString val lastRequestKey = requestContext?.key ?: request1.uriString return if (firstRequestKey1 != lastRequestKey) { "'${firstRequestKey1}' --> '$lastRequestKey'" } else { "'${firstRequestKey1}'" } } }
7
null
308
1,978
82ffde1ff148311bb5b36eb70a4c82224d1f3af4
12,771
sketch
Apache License 2.0
network/src/main/java/org/itsman/network/ApiServer.kt
mkitcc
631,505,045
false
null
package org.itsman.network import io.reactivex.Observable import retrofit2.Response import retrofit2.http.GET interface ApiServer { @GET("/quotes") suspend fun getQuotes(): Response<QuoteList> @GET("/quotes") fun getQuotes2(): Observable<QuoteList> }
0
Kotlin
0
0
9e7ac0769f128f069423b183942a13b1aeac82eb
270
BaseAndroid
MIT License
app/src/test/java/com/jbr/asharplibrary/searchartist/ui/SearchArtistViewModelTest.kt
jrmybrault
210,299,381
false
null
package com.jbr.asharplibrary.searchartist.ui import android.app.Application import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.MutableLiveData import com.jbr.asharplibrary.random.RandomArtistGenerator import com.jbr.asharplibrary.random.RandomPreviousArtistSearchGenerator import com.jbr.asharplibrary.random.RandomStringGenerator import com.jbr.asharplibrary.random.createMockResourcesString import com.jbr.asharplibrary.searchartist.navigation.SearchArtistNavigator import com.jbr.coredomain.searchartist.Artist import com.jbr.coredomain.searchartist.ArtistFinder import com.jbr.coredomain.searchartist.PreviousArtistSearch import com.jbr.coredomain.searchartist.PreviousArtistSearchesRepository import com.jbr.sharedfoundation.dateFrom import com.jraska.livedata.test import io.mockk.coVerify import io.mockk.every import io.mockk.mockk import io.mockk.verify import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ObsoleteCoroutinesApi import kotlinx.coroutines.newSingleThreadContext import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TestRule import java.lang.ref.WeakReference import java.util.* import kotlin.random.Random class SearchArtistViewModelTest { @get: Rule var rule: TestRule = InstantTaskExecutorRule() @ObsoleteCoroutinesApi private val mainThreadSurrogate = newSingleThreadContext("Main thread") private val mockApplication = mockk<Application>(relaxed = true) private val fakeResults = MutableLiveData<List<Artist>>(emptyList()) private val mockArtistFinder = mockk<ArtistFinder>(relaxed = true) { every { results } returns fakeResults } private val fakePreviousSearches = MutableLiveData<List<PreviousArtistSearch>>(emptyList()) private val mockPreviousSearchesRepository = mockk<PreviousArtistSearchesRepository>(relaxed = true) { every { searches } returns fakePreviousSearches } private val mockNavigator = mockk<SearchArtistNavigator>(relaxed = true) private val viewModel = SearchArtistViewModel(mockApplication, mockArtistFinder, mockPreviousSearchesRepository) .apply { navigator = WeakReference(mockNavigator) } //region - Setup & Teardown @Before fun setUp() { Dispatchers.setMain(mainThreadSurrogate) } @After fun tearDown() { fakeResults.postValue(emptyList()) fakePreviousSearches.postValue(emptyList()) Dispatchers.resetMain() mainThreadSurrogate.close() } //endregion @Test fun `show previous searches only when search text is set to null`() { // Arrange viewModel.searchText = RandomStringGenerator.generate() // Act viewModel.searchText = null // Assert viewModel.shouldDisplayPreviousSearches .test() .assertValueHistory(true) } @Test fun `show previous searches when search text is set to empty`() { // Arrange viewModel.searchText = RandomStringGenerator.generate() // Act viewModel.searchText = "" // Assert viewModel.shouldDisplayPreviousSearches .test() .assertValueHistory(true) } @Test fun `hide previous searches when a non empty search text is set`() { // Arrange viewModel.searchText = "" // Act viewModel.searchText = RandomStringGenerator.generate() // Assert viewModel.shouldDisplayPreviousSearches .test() .assertValueHistory(false) } @Test fun `refresh search when a search text change`() { // Arrange viewModel.searchText = "" val newSearchText = RandomStringGenerator.generate() // Act viewModel.searchText = newSearchText // Assert coVerify { mockArtistFinder.search(newSearchText) } } @Test fun `show searching while searching`() { // Arrange val observer = viewModel.isSearching .test() // Act viewModel.searchText = RandomStringGenerator.generate() // Assert observer.assertValueHistory(false, true) // TODO: Find a way to test when searching is reset to false } @Test fun `updating displayable results when results change`() { // Arrange val results = (0..10).map { RandomArtistGenerator.generate() } // Act fakeResults.value = results // Assert viewModel.displayableResults .test() .assertHasValue() .assertHistorySize(1) assertEquals(results.size, viewModel.displayableResults.value!!.size) assertEquals(results.map { it.identifier }.sorted(), viewModel.displayableResults.value!!.map { it.identifier }.sorted()) } @Test fun `sorting displayable results`() { // Arrange val results = listOf( RandomArtistGenerator.generate(score = 80), RandomArtistGenerator.generate(score = 90), RandomArtistGenerator.generate(score = 85) ) // Act fakeResults.value = results // Assert viewModel.displayableResults .test() assertNotEquals(results.map { it.identifier }, viewModel.displayableResults.value!!.map { it.identifier }) } @Test fun `search result text is empty if search text is empty`() { // Arrange viewModel.searchText = RandomStringGenerator.generate() val observer = viewModel.searchResultText .test() // Act viewModel.searchText = "" // Assert observer.assertValueHistory("") } @Test fun `search result text is not empty when search text is not empty and results change`() { // Arrange viewModel.searchText = RandomStringGenerator.generate() val fakeResultText = RandomStringGenerator.generate() val mockResources = createMockResourcesString(fakeResultText) every { mockApplication.resources } returns mockResources val results = (0..10).map { RandomArtistGenerator.generate() } // Act fakeResults.value = results // Assert viewModel.searchResultText .test() assertEquals(fakeResultText, viewModel.searchResultText.value!!) } @Test fun `updating displayable previous searches when previous searches change`() { // Arrange val previousSearches = (0..10).map { RandomPreviousArtistSearchGenerator.generate() } // Act fakePreviousSearches.value = previousSearches // Assert viewModel.displayablePreviousSearches .test() .assertHasValue() .assertHistorySize(1) assertEquals(previousSearches.size, viewModel.displayablePreviousSearches.value!!.size) assertEquals(previousSearches.map { it.identifier }.sorted(), viewModel.displayablePreviousSearches.value!!.map { it.identifier }.sorted()) } @Test fun `sorting displayable previous searches`() { // Arrange val previousSearches = listOf( RandomPreviousArtistSearchGenerator.generate(date = GregorianCalendar().dateFrom(2019, 1, 1)), RandomPreviousArtistSearchGenerator.generate(date = GregorianCalendar().dateFrom(2019, 11, 1)), RandomPreviousArtistSearchGenerator.generate(date = GregorianCalendar().dateFrom(2019, 6, 1)) ) // Act fakePreviousSearches.value = previousSearches // Assert viewModel.displayablePreviousSearches .test() assertNotEquals(previousSearches.map { it.identifier }, viewModel.displayablePreviousSearches.value!!.map { it.identifier }) } @Test fun `handle selection of artist delegates to navigator`() { // Arrange val results = listOf( RandomArtistGenerator.generate(score = 90), RandomArtistGenerator.generate(score = 85), RandomArtistGenerator.generate(score = 80) ) fakeResults.value = results viewModel.displayableResults // FIXME: This is not a clean way to wait for the displayables to be ready. .test() val fakeSelectionIndex = Random.nextInt(0, results.size - 1) // Act viewModel.handleSelectionOfArtist(fakeSelectionIndex) // Assert verify { mockNavigator.goToArtistDetails(results[fakeSelectionIndex].identifier) } } @Test fun `load next page when reaching list end`() { // Act viewModel.handleReachingListEnd() // Assert coVerify { mockArtistFinder.loadNextPage() } } @Test fun `handle selection of previous searches delegates to navigator`() { // Arrange val previousSearches = listOf( RandomPreviousArtistSearchGenerator.generate(date = GregorianCalendar().dateFrom(2019, 11, 1)), RandomPreviousArtistSearchGenerator.generate(date = GregorianCalendar().dateFrom(2019, 6, 1)), RandomPreviousArtistSearchGenerator.generate(date = GregorianCalendar().dateFrom(2019, 1, 1)) ) fakePreviousSearches.value = previousSearches viewModel.displayablePreviousSearches // FIXME: This is not a clean way to wait for the displayables to be ready. .test() val fakeSelectionIndex = Random.nextInt(0, previousSearches.size - 1) // Act viewModel.handleSelectionOfPreviousSearch(fakeSelectionIndex) // Assert verify { mockNavigator.goToArtistDetails(previousSearches[fakeSelectionIndex].artist.identifier) } } @Test fun `handle tap on clear previous search delegates to repository`() { // Arrange val previousSearches = listOf( RandomPreviousArtistSearchGenerator.generate(date = GregorianCalendar().dateFrom(2019, 11, 1)), RandomPreviousArtistSearchGenerator.generate(date = GregorianCalendar().dateFrom(2019, 6, 1)), RandomPreviousArtistSearchGenerator.generate(date = GregorianCalendar().dateFrom(2019, 1, 1)) ) fakePreviousSearches.value = previousSearches viewModel.displayablePreviousSearches // FIXME: This is not a clean way to wait for the displayables to be ready. .test() val fakeSelectionIndex = Random.nextInt(0, previousSearches.size - 1) // Act viewModel.handleTapOnClearPreviousSearch(fakeSelectionIndex) // Assert coVerify { mockPreviousSearchesRepository.remove(any()) } // TODO: Find a way to check that the removed seach is the right one. ArgumentCaptor doesn't seem to play nice with coVerify. } }
0
Kotlin
0
0
ad06f792538867a732bd79fae74849f5130addce
10,970
aSharp-library
MIT License
lib_modbus/src/main/kotlin/com/crow/modbus/model/KModbusRtuSlaveResp.kt
crowforkotlin
696,702,450
false
{"Kotlin": 107203, "C": 13860, "Makefile": 1695, "CMake": 208}
package com.crow.modbus.model import com.crow.modbus.tools.BytesOutput import com.crow.modbus.tools.CRC16 import com.crow.modbus.tools.fromInt16 data class KModbusRtuSlaveResp( val mSlaveID: Int, val mFunction: KModbusFunction, val mAddress: Int, val mCount: Int? = null, val mByteCount: Int? = null, val mValues: ByteArray?, val mCrc: Int ) { /** * ⦁ 校验CRC 是否正确, true:正确 false:失败 * * ⦁ 2024-01-22 14:25:03 周一 下午 * @author crowforkotlin */ @OptIn(ExperimentalStdlibApi::class) fun verifyCRC16(): Boolean { val address = fromInt16(mAddress) val count = mCount?.let { fromInt16(it) } val bytes = ByteArray(4 + (count?.size ?: 0) + (mValues?.size ?: 0)) bytes[0] = mSlaveID.toByte() bytes[1] = mFunction.mCode.toByte() bytes[2] = address[0] bytes[3] = address[1] count?.let { bytes[4] = it[0] bytes[5] = it[1] } if (mValues != null) { System.arraycopy(mValues, 0, bytes, 4 + (count?.size ?: 0), mValues.size) } return CRC16.compute(bytes) == mCrc } fun buildResponse(skipValue: Boolean = false, reComputeCrc16: Boolean = false): ByteArray { val output = BytesOutput() output.writeInt8(mSlaveID) output.writeInt8(mFunction.mCode) output.writeInt16(mAddress) if (mCount != null) { output.writeInt16(mCount) } if (mValues != null && !skipValue) { output.write(mValues) } if (reComputeCrc16) { output.writeInt16Reversal(CRC16.compute(output.toByteArray())) } else { output.writeInt16Reversal(mCrc) } return output.toByteArray() } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as KModbusRtuSlaveResp if (mSlaveID != other.mSlaveID) return false if (mFunction != other.mFunction) return false if (mAddress != other.mAddress) return false if (mCount != other.mCount) return false if (mByteCount != other.mByteCount) return false if (mValues != null) { if (other.mValues == null) return false if (!mValues.contentEquals(other.mValues)) return false } else if (other.mValues != null) return false if (mCrc != other.mCrc) return false return true } override fun hashCode(): Int { var result = mSlaveID result = 31 * result + mFunction.hashCode() result = 31 * result + mAddress result = 31 * result + (mCount ?: 0) result = 31 * result + (mByteCount ?: 0) result = 31 * result + (mValues?.contentHashCode() ?: 0) result = 31 * result + mCrc return result } }
1
Kotlin
0
2
9b342a239066ebfe1d60dc1da028ba7b93a85178
2,844
KModbus
Apache License 2.0
idea/src/org/jetbrains/kotlin/idea/inspections/LiftReturnOrAssignmentInspection.kt
tnorbye
189,964,139
true
null
/* * Copyright 2010-2017 JetBrains s.r.o. * * 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 org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.* import com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR_OR_WARNING import com.intellij.codeInspection.ProblemHighlightType.INFORMATION import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.intentions.branchedTransformations.BranchedFoldingUtils import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isElseIf import org.jetbrains.kotlin.idea.intentions.branchedTransformations.lineCount import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.startOffset class LiftReturnOrAssignmentInspection @JvmOverloads constructor(private val skipLongExpressions: Boolean = true) : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) = object : KtVisitorVoid() { private fun visitIfOrWhenOrTry(expression: KtExpression, keyword: PsiElement) { if (skipLongExpressions && expression.lineCount() > LINES_LIMIT) return if (expression.isElseIf()) return val foldableReturns = BranchedFoldingUtils.getFoldableReturns(expression) if (foldableReturns?.isNotEmpty() == true) { val hasOtherReturns = expression.anyDescendantOfType<KtReturnExpression> { it !in foldableReturns } val isSerious = !hasOtherReturns && foldableReturns.size > 1 registerProblem(expression, keyword, isSerious, LiftReturnOutFix(keyword.text)) foldableReturns.forEach { registerProblem(expression, keyword, isSerious, LiftReturnOutFix(keyword.text), it, INFORMATION) } return } val assignmentNumber = BranchedFoldingUtils.getFoldableAssignmentNumber(expression) if (assignmentNumber > 0) { val isSerious = assignmentNumber > 1 registerProblem(expression, keyword, isSerious, LiftAssignmentOutFix(keyword.text)) } } private fun registerProblem( expression: KtExpression, keyword: PsiElement, isSerious: Boolean, fix: LocalQuickFix, highlightElement: PsiElement = keyword, highlightType: ProblemHighlightType = if (isSerious) GENERIC_ERROR_OR_WARNING else INFORMATION ) { val subject = if (fix is LiftReturnOutFix) "Return" else "Assignment" val verb = if (isSerious) "should" else "can" holder.registerProblemWithoutOfflineInformation( expression, "$subject $verb be lifted out of '${keyword.text}'", isOnTheFly, highlightType, highlightElement.textRange?.shiftRight(-expression.startOffset), fix ) } override fun visitIfExpression(expression: KtIfExpression) { super.visitIfExpression(expression) visitIfOrWhenOrTry(expression, expression.ifKeyword) } override fun visitWhenExpression(expression: KtWhenExpression) { super.visitWhenExpression(expression) visitIfOrWhenOrTry(expression, expression.whenKeyword) } override fun visitTryExpression(expression: KtTryExpression) { super.visitTryExpression(expression) expression.tryKeyword?.let { visitIfOrWhenOrTry(expression, it) } } } private class LiftReturnOutFix(private val keyword: String) : LocalQuickFix { override fun getName() = "Lift return out of '$keyword'" override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val replaced = BranchedFoldingUtils.foldToReturn(descriptor.psiElement as KtExpression) replaced.findExistingEditor()?.caretModel?.moveToOffset(replaced.startOffset) } } private class LiftAssignmentOutFix(private val keyword: String) : LocalQuickFix { override fun getName() = "Lift assignment out of '$keyword'" override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { BranchedFoldingUtils.foldToAssignment(descriptor.psiElement as KtExpression) } } companion object { private const val LINES_LIMIT = 15 } }
0
Kotlin
2
2
dca23f871cc22acee9258c3d58b40d71e3693858
5,402
kotlin
Apache License 2.0
step3/backend/src/main/kotlin/br/com/zup/beagle/demo/configuration/JacksonConfiguration.kt
ayala-borba
591,939,225
false
null
package br.com.zup.beagle.demo.configuration import br.com.zup.beagle.serialization.jackson.BeagleActionSerializer import br.com.zup.beagle.serialization.jackson.BeagleComponentSerializer import br.com.zup.beagle.serialization.jackson.BeagleScreenBuilderSerializer import br.com.zup.beagle.serialization.jackson.BeagleScreenSerializer import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.module.SimpleModule import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration class JacksonConfiguration { @Bean fun objectMapper(): ObjectMapper { val module = SimpleModule().apply { this.addSerializer(BeagleActionSerializer()) this.addSerializer(BeagleComponentSerializer()) this.addSerializer(BeagleScreenSerializer()) this.addSerializer(BeagleScreenBuilderSerializer()) } return jacksonObjectMapper().apply { this.registerModule(module) this.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL) } } }
0
Kotlin
0
0
7805ef611cebc5035ea65740ec8c12c7ee0941fd
1,236
beagle-webinar
Apache License 2.0
app/src/main/java/com/example/tokumemo/utility/FirstDialogFragment.kt
tokudai0000
560,016,320
false
null
import android.app.AlertDialog import android.app.Dialog import android.content.DialogInterface import android.os.Bundle import androidx.fragment.app.DialogFragment import com.example.tokumemo.R class FirstDialogFragment: DialogFragment() { // ダイアログ外タップ無効 @Deprecated("Deprecated in Java") override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) this.isCancelable = false } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { return activity?.let { // Use the Builder class for convenient dialog construction val builder = AlertDialog.Builder(it, R.style.FirstDialogStyle) builder.setMessage(R.string.first_dialog) .setPositiveButton("同意する", DialogInterface.OnClickListener { dialog, id -> }) // Create the AlertDialog object and return it builder.create() } ?: throw IllegalStateException("Activity cannot be null") } }
6
null
0
2
e694cd89df251eadd49959861d26299cbc5cdb37
1,063
TokumemoAndroid
MIT License
compiler/testData/diagnostics/tests/functionLiterals/kt7383_starProjectedFunction.kt
BradOselo
367,097,840
false
null
// !WITH_NEW_INFERENCE // KT-7383 Assertion failed when a star-projection of function type is used fun foo() { val f : Function1<*, *> = { x -> x.toString() } <!MEMBER_PROJECTED_OUT{OI}!>f<!>(<!CONSTANT_EXPECTED_TYPE_MISMATCH{NI}!>1<!>) }
1
null
1
3
58c7aa9937334b7f3a70acca84a9ce59c35ab9d1
248
kotlin
Apache License 2.0
app/src/main/java/com/example/belindas_closet/data/network/product/DeleteServiceImpl.kt
SeattleColleges
656,918,420
false
{"Kotlin": 191183}
package com.example.nsc_events.data.network.auth import com.example.nsc_events.data.network.HttpRoutes import com.example.nsc_events.data.network.dto.auth_dto.DeleteRequest import com.example.nsc_events.data.network.dto.auth_dto.DeleteResponse import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.plugins.ClientRequestException import io.ktor.client.plugins.RedirectResponseException import io.ktor.client.plugins.ServerResponseException import io.ktor.client.request.delete import io.ktor.client.request.header import io.ktor.client.request.url import io.ktor.http.ContentType import io.ktor.http.HttpHeaders import io.ktor.util.InternalAPI import kotlinx.serialization.json.Json class DeleteServiceImpl ( private val client: HttpClient, private val getToken: suspend () -> String ) : DeleteService { @OptIn(InternalAPI::class) override suspend fun delete(deleteRequest: DeleteRequest): DeleteResponse? { return try { val token = getToken() val response = client.delete { url("${HttpRoutes.DELETE}/${deleteRequest.id}") header(HttpHeaders.ContentType, ContentType.Application.Json.toString()) header(HttpHeaders.Authorization, "Bearer $token") body = Json.encodeToString(DeleteRequest.serializer(), deleteRequest) } response.body() } catch (e: RedirectResponseException) { println("Error: ${e.response.status.description}") null } catch (e: ClientRequestException) { println("Error: ${e.response.status.description}") null } catch (e: ServerResponseException) { println("Error: ${e.response.status.description}") null } catch (e: Exception) { println("Error: ${e.message}") null } } }
40
Kotlin
6
9
b3522c87e2afe2f73f11807378d18cb0c7ab906c
1,897
belindas-closet-android
MIT License
app/src/main/java/br/com/codeone/minhasreceitas/application/MinhasReceitasApplication.kt
luizgoes10
162,925,102
false
null
package br.com.codeone.minhasreceitas.application import android.app.Application import android.util.Log class MinhasReceitasApplication : Application() { // Chamado quando o Android criar o processo do aplicativo override fun onCreate() { super.onCreate() // Salva a instância para termos acesso como Singleton appInstance = this } companion object { private const val TAG = "MinhasReceitasApp" // Singleton da classe Application lateinit var appInstance: MinhasReceitasApplication private set fun getInstance(): MinhasReceitasApplication { if (appInstance == null) { throw IllegalStateException("Configure a classe de Application no AndroidManifest.xml") } return appInstance } } // Chamado quando o Android finalizar o processo do aplicativo override fun onTerminate() { super.onTerminate() Log.d(TAG, "MinhasReceitasApplication.onTerminate()") } }
0
Kotlin
0
0
7714809c537002f59005bc2619e20d70ae06eb9f
1,028
my-recipes-app
MIT License
composeApp/src/wasmJsMain/kotlin/App.kt
Hamamas
732,402,221
false
{"Kotlin": 8166, "HTML": 332}
import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.layout.* import androidx.compose.material.Button import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import kotlinx.browser.document @Composable fun App() { MaterialTheme { var visibility by remember { mutableStateOf(false) } Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(12.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Button(onClick = { visibility = visibility.not() }) { Text(if (visibility) "Hide video" else "Show video") } AnimatedVisibility(visibility) { HtmlView( modifier = Modifier.fillMaxWidth().height(300.dp), factory = { val video = document.createElement("video") video.setAttribute( "src", "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4" ) video } ) } } } }
0
Kotlin
0
1
4f495d9428eade075d967b1f4e59ae438de157e4
1,414
Kotlin-Wasm-Html-Interop
Apache License 2.0
app/src/main/java/com/perol/asdpl/pixivez/dialog/SearchSectionDialog.kt
hunterx9
222,638,256
false
null
/* * MIT License * * Copyright (c) 2019 Perol_Notsfsssf * * 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.perol.asdpl.pixivez.dialog import android.app.Dialog import android.os.Bundle import androidx.databinding.DataBindingUtil.inflate import androidx.fragment.app.DialogFragment import androidx.fragment.app.FragmentManager import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.tabs.TabLayout import com.perol.asdpl.pixivez.R import com.perol.asdpl.pixivez.databinding.DialogSearchsectionBinding class SearchSectionDialog : DialogFragment() { fun show(fragmentManager: FragmentManager) { show(fragmentManager, "LongHoldDialogFragment") } var callback: Callback? = null override fun onDestroy() { if (dialog != null && dialog!!.isShowing) { dialog!!.dismiss(); } super.onDestroy() callback = null } interface Callback { fun onClick(search_target: Int, sort: Int, duration: Int) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val builder = MaterialAlertDialogBuilder(activity) val inflater = activity!!.layoutInflater val binding = inflate<DialogSearchsectionBinding>(inflater, R.layout.dialog_searchsection, null, false) val view = binding.root val first = view.findViewById<TabLayout>(R.id.tablayout_search_target) val second = view.findViewById<TabLayout>(R.id.tablayout_sort) val third = view.findViewById<TabLayout>(R.id.tablayout_duration) builder.setView(view) builder.setNegativeButton(android.R.string.ok) { p0, p1 -> if (callback != null) { callback!!.onClick(first.selectedTabPosition, second.selectedTabPosition, third.selectedTabPosition) } } builder.setPositiveButton(android.R.string.cancel) { p0, p1 -> } val dialog = builder.create() return dialog } }
0
null
0
3
e0ef6514264a6024f4277d38e2162536cd1d53c1
3,033
Pix-EzViewer
MIT License
zipline-gradle-plugin/src/main/kotlin/app/cash/zipline/gradle/jsProductionTasks.kt
cashapp
41,445,081
false
{"C": 2212200, "Kotlin": 1306939, "C++": 39548, "Shell": 1471, "CMake": 804, "JavaScript": 313}
/* * Copyright (C) 2023 Block, 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 app.cash.zipline.gradle import java.io.File import org.gradle.api.internal.provider.DefaultProvider import org.gradle.api.provider.Provider import org.jetbrains.kotlin.gradle.targets.js.dsl.KotlinJsBinaryMode import org.jetbrains.kotlin.gradle.targets.js.ir.JsIrBinary import org.jetbrains.kotlin.gradle.targets.js.webpack.KotlinWebpack /** * A task that produces `.js` files. * * This is used to create a [ZiplineCompileTask] that uses the produced JS as input. */ internal interface JsProductionTask { /** Like 'compileDevelopmentExecutableKotlinJsZipline'. */ val name: String /** Like "js" or "blue". */ val targetName: String /** Either "Webpack" or null. */ val toolName: String? val mode: KotlinJsBinaryMode val outputFile: Provider<File> } /** Output of the Kotlin compiler. */ internal fun JsIrBinary.asJsProductionTask(): JsProductionTask { return object : JsProductionTask { override val name get() = linkTaskName override val targetName get() = target.name override val toolName = null override val mode get() = [email protected] override val outputFile get() = linkTask.map { it.outputFileProperty.get() } } } /** Output of the Kotlin compiler, post-processed by a Webpack toolchain. */ internal fun KotlinWebpack.asJsProductionTask(): JsProductionTask { return object : JsProductionTask { override val name = [email protected] override val targetName = compilation.target.name override val toolName = "Webpack" override val mode = when { name.endsWith("DevelopmentWebpack") -> KotlinJsBinaryMode.DEVELOPMENT name.endsWith("ProductionWebpack") -> KotlinJsBinaryMode.PRODUCTION else -> error("unexpected KotlinWebpack task name: $name") } override val outputFile get() = DefaultProvider { [email protected] } } }
78
C
147
1,932
55a4412b60fdee701dfdfe89925bbd0be5293f31
2,470
zipline
Apache License 2.0
frontend/src/jsMain/kotlin/com/monkopedia/konstructor/frontend/menu/MenuComponent.kt
Monkopedia
418,215,448
false
{"Kotlin": 507651, "JavaScript": 159882, "HTML": 1015}
/* * Copyright 2022 Jason Monk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.monkopedia.konstructor.frontend.menu import com.monkopedia.konstructor.frontend.WorkManager import com.monkopedia.konstructor.frontend.koin.RootScope import com.monkopedia.konstructor.frontend.model.SettingsModel.CodePaneMode.EDITOR import com.monkopedia.konstructor.frontend.model.SettingsModel.CodePaneMode.GL_SETTINGS import com.monkopedia.konstructor.frontend.model.SettingsModel.CodePaneMode.NAVIGATION import com.monkopedia.konstructor.frontend.model.SettingsModel.CodePaneMode.RULE import com.monkopedia.konstructor.frontend.model.SettingsModel.CodePaneMode.SETTINGS import com.monkopedia.konstructor.frontend.utils.useCollected import emotion.react.css import mui.icons.material.ArrowBack import mui.icons.material.LightMode import mui.icons.material.Rule import mui.icons.material.Settings import mui.material.AppBar import mui.material.IconButton import mui.material.IconButtonColor.Companion.inherit import mui.material.IconButtonEdge.Companion.end import mui.material.IconButtonEdge.Companion.start import mui.material.Size.Companion.large import mui.material.Toolbar import mui.material.Typography import mui.material.styles.TypographyVariant import mui.system.sx import react.FC import react.Props import react.dom.aria.ariaLabel import react.dom.html.ReactHTML.div import web.cssom.Position.Companion.relative import web.cssom.important import web.cssom.number import web.cssom.pct external interface MenuComponentProps : Props { var workManager: WorkManager } val MenuComponent = FC<MenuComponentProps> { props -> val mode = RootScope.settingsModel.codePaneMode.useCollected(EDITOR) val spaceListModel = RootScope.spaceListModel val currentSpace = spaceListModel.selectedSpace.useCollected() val currentKonstruction = RootScope.scopeTracker.currentKonstruction.useCollected() AppBar { css { width = important(100.pct) position = important(relative) } Toolbar { css { width = important(100.pct) } if (mode != EDITOR) { IconButton { this.size = large this.edge = start this.color = inherit this.ariaLabel = "back" this.onClick = { RootScope.settingsModel.setCodePaneMode(EDITOR) } ArrowBack() } } Typography { this.variant = TypographyVariant.h6 this.component = div this.sx { this.flexGrow = number(1.0) } when (mode) { RULE, EDITOR -> { this.onClick = { RootScope.settingsModel.setCodePaneMode(NAVIGATION) } if (currentSpace == null) { +"<No Space Selected>" } else if (currentKonstruction == null) { +"${currentSpace.name} > <No Konstruction Selected>" } else { +"${currentSpace.name} > ${currentKonstruction.name}" } } NAVIGATION -> { if (currentSpace != null && currentKonstruction != null) { this.onClick = { RootScope.settingsModel.setCodePaneMode(EDITOR) } } +"Navigation" } GL_SETTINGS -> { this.onClick = { RootScope.settingsModel.setCodePaneMode(NAVIGATION) } +"Viewport Settings" } SETTINGS -> { this.onClick = { RootScope.settingsModel.setCodePaneMode(NAVIGATION) } +"Settings" } } } IconButton { this.size = large this.edge = end this.color = inherit this.ariaLabel = "selection" this.onClick = { if (mode != RULE) { RootScope.settingsModel.setCodePaneMode(RULE) } else { RootScope.settingsModel.setCodePaneMode(EDITOR) } } Rule() } IconButton { this.size = large this.edge = end this.color = inherit this.ariaLabel = "lighting" this.onClick = { if (mode != GL_SETTINGS) { RootScope.settingsModel.setCodePaneMode(GL_SETTINGS) } else { RootScope.settingsModel.setCodePaneMode(EDITOR) } } LightMode() } IconButton { this.size = large this.edge = end this.color = inherit this.ariaLabel = "settings" this.onClick = { if (mode != SETTINGS) { RootScope.settingsModel.setCodePaneMode(SETTINGS) } else { RootScope.settingsModel.setCodePaneMode(EDITOR) } } Settings() } } } }
0
Kotlin
0
0
553817a530a5e60913cfa76c7e45c8e3a247b0d3
6,323
Konstructor
Apache License 2.0
litho-it/src/test/com/facebook/litho/LithoViewVisibilityProcessingTest.kt
facebook
80,179,724
false
{"Kotlin": 5825848, "Java": 5578851, "C++": 616537, "Starlark": 198527, "JavaScript": 29060, "C": 25074, "Shell": 8243, "CSS": 5558, "CMake": 4783, "Objective-C": 4012}
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho import android.graphics.Rect import com.facebook.litho.config.LithoDebugConfigurations import com.facebook.litho.core.height import com.facebook.litho.core.width import com.facebook.litho.kotlin.widget.Text import com.facebook.litho.testing.LithoTestRule import com.facebook.litho.testing.testrunner.LithoTestRunner import com.facebook.litho.visibility.onVisible import com.facebook.rendercore.px import java.util.concurrent.atomic.AtomicInteger import org.assertj.core.api.Assertions.assertThat import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(LithoTestRunner::class) class LithoViewVisibilityProcessingTest { @get:Rule val mLithoTestRule = LithoTestRule() @Before fun setup() { LithoDebugConfigurations.isIncrementalMountGloballyDisabled = true } @After fun teardown() { LithoDebugConfigurations.isIncrementalMountGloballyDisabled = false } @Test fun `should process visibility outputs with the current visible rect when mount state is dirty and incremental mount disabled`() { val firstComponentOnVisibleCounter = AtomicInteger() val secondComponentOnVisibleCounter = AtomicInteger() val firstComponent = MyTestComponent(firstComponentOnVisibleCounter) val secondComponent = MyTestComponent(secondComponentOnVisibleCounter) /* We start out by rendering two different components in two different litho views */ val firstLithoView = mLithoTestRule.render { firstComponent }.lithoView val secondLithoView = mLithoTestRule.render { secondComponent }.lithoView /* we verify that both components on visible callback was triggered */ assertThat(firstComponentOnVisibleCounter.get()).isEqualTo(1) assertThat(secondComponentOnVisibleCounter.get()).isEqualTo(1) /* we re-use the second litho view component tree, and set it in the first litho view. */ firstLithoView.componentTree = secondLithoView.componentTree /* immediately after, we "fake" translate down the component out of the viewport, so that it is not visible; calling translate * is not possible in this test because it requires a wrapping view of the LithoView */ firstLithoView.notifyVisibleBoundsChanged(Rect(0, 200, 200, 600), true) /* during the translation, the used rect should be the visible rect (and not the last stored one in the visibility extensions), and therefore no extra visible callback should be called. */ assertThat(firstComponentOnVisibleCounter.get()).isEqualTo(1) assertThat(secondComponentOnVisibleCounter.get()).isEqualTo(1) } class MyTestComponent(private val atomicCounter: AtomicInteger) : KComponent() { override fun ComponentScope.render(): Component { return Row { child( Text( "Hello", style = Style.height(200.px).width(200.px).onVisible { atomicCounter.incrementAndGet() })) } } } }
88
Kotlin
769
7,703
8bde23649ae0b1c594b9bdfcb4668feb7d8a80c0
3,661
litho
Apache License 2.0