path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
756M
is_fork
bool
2 classes
languages_distribution
stringlengths
12
2.44k
content
stringlengths
6
6.29M
issues
float64
0
10k
main_language
stringclasses
128 values
forks
int64
0
54.2k
stars
int64
0
157k
commit_sha
stringlengths
40
40
size
int64
6
6.29M
name
stringlengths
1
100
license
stringclasses
104 values
liveness/src/main/java/com/amplifyframework/ui/liveness/camera/LivenessMuxer.kt
aws-amplify
490,439,616
false
{"Kotlin": 503031, "Java": 41586, "C++": 26045, "CMake": 1057}
/* * Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amplifyframework.ui.liveness.camera import android.media.MediaCodec import android.media.MediaFormat import android.media.MediaMuxer import androidx.annotation.WorkerThread import java.io.File import java.io.RandomAccessFile import java.nio.ByteBuffer @WorkerThread internal class LivenessMuxer( private val tempOutputFile: File, outputFormat: MediaFormat, private val onMuxedSegment: OnMuxedSegment ) { private val muxerRandomAccessFile = RandomAccessFile( tempOutputFile.apply { createNewFile() }, "r" ) private val videoTrack: Int private var currentVideoStartTime: Long private var currentBytePosition = 0L private var lastChunkNotificationTimestamp = 0L // start ready to notify private val muxer = MediaMuxer( tempOutputFile.toString(), MediaMuxer.OutputFormat.MUXER_OUTPUT_WEBM ).apply { videoTrack = addTrack(outputFormat) start() currentVideoStartTime = System.currentTimeMillis() } /* Attempt to notify listener that chunked data is available if minimum chunk interval has exceeded Write new frame to muxer */ @WorkerThread fun write(byteBuf: ByteBuffer, bufferInfo: MediaCodec.BufferInfo) { if (System.currentTimeMillis() - lastChunkNotificationTimestamp >= MIN_CHUNK_DELAY_MILLIS) { if (notifyChunk()) { lastChunkNotificationTimestamp = System.currentTimeMillis() currentVideoStartTime = System.currentTimeMillis() } } muxer.writeSampleData(videoTrack, byteBuf, bufferInfo) } @WorkerThread fun stop() { try { muxer.stop() muxer.release() } catch (e: Exception) { // don't crash if muxer encounters internal error } // send partial chunk notifyChunk() muxerRandomAccessFile.close() tempOutputFile.delete() } /** * We are sending the muxed output file in chunks. Each time this method is called, * we attempt to get the new bytes of the file we have not yet provided to the callback. * Once we provide the new bytes, we update the current byte position so the next update * only sends new byte data. * @return true if chunk notified */ private fun notifyChunk(): Boolean { try { muxerRandomAccessFile.apply { try { val sizeToRead = length() - currentBytePosition // don't attempt to send chunk if no update available, // or if the first chunk hasn't accumulated enough data if (sizeToRead <= 0 || (currentBytePosition == 0L && sizeToRead < 10_000)) { return false } val chunkByteArray = ByteArray(sizeToRead.toInt()) seek(currentBytePosition) read(chunkByteArray) currentBytePosition += sizeToRead onMuxedSegment(chunkByteArray, currentVideoStartTime) return true } catch (e: Exception) { // failed to access muxer file return false } } } catch (e: Exception) { // process possibly stopped return false } } companion object { const val MIN_CHUNK_DELAY_MILLIS = 100L // Minimum time between chunk notifications } }
5
Kotlin
4
8
27c702ca16b29acbb249f91ff2744afbe63f9feb
4,109
amplify-ui-android
Apache License 2.0
app/src/main/java/com/halil/ozel/retrofitapp/PlayListData.kt
halilozel1903
141,455,772
false
{"Kotlin": 7254}
package com.halil.ozel.retrofitapp import com.google.gson.annotations.SerializedName class PlayListData { @SerializedName("kind") var kind: String? = null @SerializedName("etag") var etag: String? = null @SerializedName("nextPageToken") var nextPageToken: String? = null @SerializedName("pageInfo") var pageInfo: PageInfo? = null @SerializedName("items") var items: List<Items>? = null class PageInfo { @SerializedName("totalResults") var totalResults: Int = 0 @SerializedName("resultsPerPage") var resultsPerPage: Int = 0 } class MyDefault { @SerializedName("url") var url: String? = null @SerializedName("width") var width: Int = 0 @SerializedName("height") var height: Int = 0 } class Medium { @SerializedName("url") var url: String? = null @SerializedName("width") var width: Int = 0 @SerializedName("height") var height: Int = 0 } class High { @SerializedName("url") var url: String? = null @SerializedName("width") var width: Int = 0 @SerializedName("height") var height: Int = 0 } class Standard { @SerializedName("url") var url: String? = null @SerializedName("width") var width: Int = 0 @SerializedName("height") var height: Int = 0 } class Thumbnails { @SerializedName("default") var mdefault: MyDefault? = null @SerializedName("medium") var medium: Medium? = null @SerializedName("high") var high: High? = null @SerializedName("standard") var standard: Standard? = null } class Localized { @SerializedName("title") var title: String? = null @SerializedName("description") var description: String? = null } class Snippet { @SerializedName("publishedAt") var publishedAt: String? = null @SerializedName("channelId") var channelId: String? = null @SerializedName("title") var title: String? = null @SerializedName("description") var description: String? = null @SerializedName("thumbnails") var thumbnails: Thumbnails? = null @SerializedName("channelTitle") var channelTitle: String? = null @SerializedName("localized") var localized: Localized? = null } class Items { @SerializedName("kind") var kind: String? = null @SerializedName("etag") var etag: String? = null @SerializedName("id") var id: String? = null @SerializedName("snippet") var snippet: Snippet? = null } }
0
Kotlin
2
4
2ec5c901f39396e1ba05303985bc9102ef230e15
2,825
RetrofitApp
The Unlicense
base/build-system/gradle-core/src/test/java/com/android/build/gradle/internal/tasks/VerifyLibraryResourcesTaskTest.kt
qiangxu1996
255,410,085
false
{"Java": 38854631, "Kotlin": 10438678, "C++": 1701601, "HTML": 795500, "FreeMarker": 695102, "Starlark": 542991, "C": 148853, "RenderScript": 58853, "Shell": 51803, "CSS": 36591, "Python": 32879, "XSLT": 23593, "Batchfile": 8747, "Dockerfile": 7341, "Emacs Lisp": 4737, "Makefile": 4067, "JavaScript": 3488, "CMake": 3295, "PureBasic": 2359, "GLSL": 1628, "Objective-C": 308, "Prolog": 214, "D": 121}
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.build.gradle.internal.tasks import com.android.build.gradle.internal.res.Aapt2CompileRunnable import com.android.build.gradle.internal.res.namespaced.Aapt2ServiceKey import com.android.build.gradle.options.SyncOptions import com.android.build.gradle.tasks.VerifyLibraryResourcesTask import com.android.builder.files.SerializableChange import com.android.builder.files.SerializableInputChanges import com.android.ide.common.resources.CompileResourceRequest import com.android.ide.common.resources.FileStatus import com.android.ide.common.workers.WorkerExecutorFacade import com.android.utils.FileUtils import com.google.common.io.Files import com.google.common.truth.Truth.assertThat import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import org.mockito.Mockito.mock import java.io.File import java.io.Serializable import java.util.HashMap /* * Unit tests for {@link VerifyLibraryResourcesTask}. */ class VerifyLibraryResourcesTaskTest { @get: Rule val temporaryFolder = TemporaryFolder() object Facade : WorkerExecutorFacade { override fun submit(actionClass: Class<out Runnable>, parameter: Serializable) { assertThat(actionClass).isEqualTo(Aapt2CompileRunnable::class.java) parameter as Aapt2CompileRunnable.Params for (request in parameter.requests) { Files.copy(request.inputFile, compileOutputFor(request)) } } override fun await() {} override fun close() {} fun compileOutputFor(request: CompileResourceRequest): File { return File(request.outputDirectory, request.inputFile.name + "-c") } } @Test fun otherFilesShouldBeIgnored() { val inputs = mutableListOf<SerializableChange>() val mergedDir = File(temporaryFolder.newFolder("merged"), "release") FileUtils.mkdirs(mergedDir) val relativeFilePath = "values/file.xml" val file = File(mergedDir, relativeFilePath) FileUtils.createFile(file, "content") assertTrue(file.exists()) inputs.add(SerializableChange(file, FileStatus.NEW, relativeFilePath)) val invalidFilePath = "values/invalid/invalid.xml" val invalidFile = File(mergedDir, invalidFilePath) FileUtils.createFile(invalidFile, "content") assertTrue(invalidFile.exists()) inputs.add(SerializableChange(invalidFile, FileStatus.NEW, invalidFilePath)) val invalidFilePath2 = "invalid.xml" val invalidFile2 = File(mergedDir, invalidFilePath2) FileUtils.createFile(invalidFile2, "content") assertTrue(invalidFile2.exists()) inputs.add(SerializableChange(invalidFile2, FileStatus.NEW, invalidFilePath2)) val outputDir = temporaryFolder.newFolder("output") VerifyLibraryResourcesTask.compileResources( SerializableInputChanges(listOf(mergedDir), inputs), outputDir, Facade, mock(Aapt2ServiceKey::class.java), SyncOptions.ErrorFormatMode.HUMAN_READABLE, temporaryFolder.newFolder() ) val fileOut = Facade.compileOutputFor(CompileResourceRequest(file, outputDir, "values")) assertTrue(fileOut.exists()) val dirOut = Facade.compileOutputFor( CompileResourceRequest(invalidFile, outputDir, mergedDir.name)) assertFalse(dirOut.exists()) } }
0
Java
1
1
3411c5436d0d34e6e2b84cbf0e9395ac8c55c9d4
4,144
vmtrace
Apache License 2.0
app/src/main/java/com/rikkeisoft/rmvvmsample/data/model/db/User.kt
nguyenthoai248
243,664,537
false
null
package com.rikkeisoft.rmvvmsample.data.model.db import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey /** * Created by ThoaiNguyen on 2/28/2020. */ @Entity(tableName = "users") class User { @ColumnInfo(name = "created_at") var createdAt: String? = null @PrimaryKey var id: Long? = null var name: String? = null @ColumnInfo(name = "updated_at") var updatedAt: String? = null }
0
Kotlin
0
0
bde45e6836155dc389aa30e16beaf0da7dcedf84
450
rmvvmsample
Apache License 2.0
sdk-api/src/main/kotlin/com/pexip/sdk/api/infinity/internal/RequestRegistrationTokenResponseSerializer.kt
pexip
493,156,648
false
{"Kotlin": 664232, "CSS": 387}
/* * Copyright 2022-2023 Pexip AS * * 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.pexip.sdk.api.infinity.internal import com.pexip.sdk.api.infinity.RequestRegistrationTokenResponse internal object RequestRegistrationTokenResponseSerializer : UnboxingSerializer<RequestRegistrationTokenResponse>(RequestRegistrationTokenResponse.serializer())
6
Kotlin
3
7
5731d13a229dbc3a639e3f1f6da193b56bb45455
875
pexip-android-sdk
Apache License 2.0
increase-kotlin-core/src/main/kotlin/com/increase/api/models/RealTimeDecision.kt
Increase
614,596,742
false
{"Kotlin": 12881439, "Shell": 1257, "Dockerfile": 305}
// File generated from our OpenAPI spec by Stainless. package com.increase.api.models import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.increase.api.core.ExcludeMissing import com.increase.api.core.JsonField import com.increase.api.core.JsonMissing import com.increase.api.core.JsonValue import com.increase.api.core.NoAutoDetect import com.increase.api.core.toUnmodifiable import com.increase.api.errors.IncreaseInvalidDataException import java.time.OffsetDateTime import java.util.Objects /** * Real Time Decisions are created when your application needs to take action in real-time to some * event such as a card authorization. For more information, see our * [Real-Time Decisions guide](https://increase.com/documentation/real-time-decisions). */ @JsonDeserialize(builder = RealTimeDecision.Builder::class) @NoAutoDetect class RealTimeDecision private constructor( private val id: JsonField<String>, private val createdAt: JsonField<OffsetDateTime>, private val timeoutAt: JsonField<OffsetDateTime>, private val status: JsonField<Status>, private val category: JsonField<Category>, private val cardAuthorization: JsonField<CardAuthorization>, private val digitalWalletToken: JsonField<DigitalWalletToken>, private val digitalWalletAuthentication: JsonField<DigitalWalletAuthentication>, private val type: JsonField<Type>, private val additionalProperties: Map<String, JsonValue>, ) { private var validated: Boolean = false private var hashCode: Int = 0 /** The Real-Time Decision identifier. */ fun id(): String = id.getRequired("id") /** * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time at which the Real-Time * Decision was created. */ fun createdAt(): OffsetDateTime = createdAt.getRequired("created_at") /** * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time at which your * application can no longer respond to the Real-Time Decision. */ fun timeoutAt(): OffsetDateTime = timeoutAt.getRequired("timeout_at") /** The status of the Real-Time Decision. */ fun status(): Status = status.getRequired("status") /** The category of the Real-Time Decision. */ fun category(): Category = category.getRequired("category") /** Fields related to a card authorization. */ fun cardAuthorization(): CardAuthorization? = cardAuthorization.getNullable("card_authorization") /** Fields related to a digital wallet token provisioning attempt. */ fun digitalWalletToken(): DigitalWalletToken? = digitalWalletToken.getNullable("digital_wallet_token") /** Fields related to a digital wallet authentication attempt. */ fun digitalWalletAuthentication(): DigitalWalletAuthentication? = digitalWalletAuthentication.getNullable("digital_wallet_authentication") /** * A constant representing the object's type. For this resource it will always be * `real_time_decision`. */ fun type(): Type = type.getRequired("type") /** The Real-Time Decision identifier. */ @JsonProperty("id") @ExcludeMissing fun _id() = id /** * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time at which the Real-Time * Decision was created. */ @JsonProperty("created_at") @ExcludeMissing fun _createdAt() = createdAt /** * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time at which your * application can no longer respond to the Real-Time Decision. */ @JsonProperty("timeout_at") @ExcludeMissing fun _timeoutAt() = timeoutAt /** The status of the Real-Time Decision. */ @JsonProperty("status") @ExcludeMissing fun _status() = status /** The category of the Real-Time Decision. */ @JsonProperty("category") @ExcludeMissing fun _category() = category /** Fields related to a card authorization. */ @JsonProperty("card_authorization") @ExcludeMissing fun _cardAuthorization() = cardAuthorization /** Fields related to a digital wallet token provisioning attempt. */ @JsonProperty("digital_wallet_token") @ExcludeMissing fun _digitalWalletToken() = digitalWalletToken /** Fields related to a digital wallet authentication attempt. */ @JsonProperty("digital_wallet_authentication") @ExcludeMissing fun _digitalWalletAuthentication() = digitalWalletAuthentication /** * A constant representing the object's type. For this resource it will always be * `real_time_decision`. */ @JsonProperty("type") @ExcludeMissing fun _type() = type @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun validate(): RealTimeDecision = apply { if (!validated) { id() createdAt() timeoutAt() status() category() cardAuthorization()?.validate() digitalWalletToken()?.validate() digitalWalletAuthentication()?.validate() type() validated = true } } fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is RealTimeDecision && this.id == other.id && this.createdAt == other.createdAt && this.timeoutAt == other.timeoutAt && this.status == other.status && this.category == other.category && this.cardAuthorization == other.cardAuthorization && this.digitalWalletToken == other.digitalWalletToken && this.digitalWalletAuthentication == other.digitalWalletAuthentication && this.type == other.type && this.additionalProperties == other.additionalProperties } override fun hashCode(): Int { if (hashCode == 0) { hashCode = Objects.hash( id, createdAt, timeoutAt, status, category, cardAuthorization, digitalWalletToken, digitalWalletAuthentication, type, additionalProperties, ) } return hashCode } override fun toString() = "RealTimeDecision{id=$id, createdAt=$createdAt, timeoutAt=$timeoutAt, status=$status, category=$category, cardAuthorization=$cardAuthorization, digitalWalletToken=$digitalWalletToken, digitalWalletAuthentication=$digitalWalletAuthentication, type=$type, additionalProperties=$additionalProperties}" companion object { fun builder() = Builder() } class Builder { private var id: JsonField<String> = JsonMissing.of() private var createdAt: JsonField<OffsetDateTime> = JsonMissing.of() private var timeoutAt: JsonField<OffsetDateTime> = JsonMissing.of() private var status: JsonField<Status> = JsonMissing.of() private var category: JsonField<Category> = JsonMissing.of() private var cardAuthorization: JsonField<CardAuthorization> = JsonMissing.of() private var digitalWalletToken: JsonField<DigitalWalletToken> = JsonMissing.of() private var digitalWalletAuthentication: JsonField<DigitalWalletAuthentication> = JsonMissing.of() private var type: JsonField<Type> = JsonMissing.of() private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from(realTimeDecision: RealTimeDecision) = apply { this.id = realTimeDecision.id this.createdAt = realTimeDecision.createdAt this.timeoutAt = realTimeDecision.timeoutAt this.status = realTimeDecision.status this.category = realTimeDecision.category this.cardAuthorization = realTimeDecision.cardAuthorization this.digitalWalletToken = realTimeDecision.digitalWalletToken this.digitalWalletAuthentication = realTimeDecision.digitalWalletAuthentication this.type = realTimeDecision.type additionalProperties(realTimeDecision.additionalProperties) } /** The Real-Time Decision identifier. */ fun id(id: String) = id(JsonField.of(id)) /** The Real-Time Decision identifier. */ @JsonProperty("id") @ExcludeMissing fun id(id: JsonField<String>) = apply { this.id = id } /** * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time at which the * Real-Time Decision was created. */ fun createdAt(createdAt: OffsetDateTime) = createdAt(JsonField.of(createdAt)) /** * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time at which the * Real-Time Decision was created. */ @JsonProperty("created_at") @ExcludeMissing fun createdAt(createdAt: JsonField<OffsetDateTime>) = apply { this.createdAt = createdAt } /** * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time at which your * application can no longer respond to the Real-Time Decision. */ fun timeoutAt(timeoutAt: OffsetDateTime) = timeoutAt(JsonField.of(timeoutAt)) /** * The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time at which your * application can no longer respond to the Real-Time Decision. */ @JsonProperty("timeout_at") @ExcludeMissing fun timeoutAt(timeoutAt: JsonField<OffsetDateTime>) = apply { this.timeoutAt = timeoutAt } /** The status of the Real-Time Decision. */ fun status(status: Status) = status(JsonField.of(status)) /** The status of the Real-Time Decision. */ @JsonProperty("status") @ExcludeMissing fun status(status: JsonField<Status>) = apply { this.status = status } /** The category of the Real-Time Decision. */ fun category(category: Category) = category(JsonField.of(category)) /** The category of the Real-Time Decision. */ @JsonProperty("category") @ExcludeMissing fun category(category: JsonField<Category>) = apply { this.category = category } /** Fields related to a card authorization. */ fun cardAuthorization(cardAuthorization: CardAuthorization) = cardAuthorization(JsonField.of(cardAuthorization)) /** Fields related to a card authorization. */ @JsonProperty("card_authorization") @ExcludeMissing fun cardAuthorization(cardAuthorization: JsonField<CardAuthorization>) = apply { this.cardAuthorization = cardAuthorization } /** Fields related to a digital wallet token provisioning attempt. */ fun digitalWalletToken(digitalWalletToken: DigitalWalletToken) = digitalWalletToken(JsonField.of(digitalWalletToken)) /** Fields related to a digital wallet token provisioning attempt. */ @JsonProperty("digital_wallet_token") @ExcludeMissing fun digitalWalletToken(digitalWalletToken: JsonField<DigitalWalletToken>) = apply { this.digitalWalletToken = digitalWalletToken } /** Fields related to a digital wallet authentication attempt. */ fun digitalWalletAuthentication(digitalWalletAuthentication: DigitalWalletAuthentication) = digitalWalletAuthentication(JsonField.of(digitalWalletAuthentication)) /** Fields related to a digital wallet authentication attempt. */ @JsonProperty("digital_wallet_authentication") @ExcludeMissing fun digitalWalletAuthentication( digitalWalletAuthentication: JsonField<DigitalWalletAuthentication> ) = apply { this.digitalWalletAuthentication = digitalWalletAuthentication } /** * A constant representing the object's type. For this resource it will always be * `real_time_decision`. */ fun type(type: Type) = type(JsonField.of(type)) /** * A constant representing the object's type. For this resource it will always be * `real_time_decision`. */ @JsonProperty("type") @ExcludeMissing fun type(type: JsonField<Type>) = apply { this.type = type } fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.putAll(additionalProperties) } fun build(): RealTimeDecision = RealTimeDecision( id, createdAt, timeoutAt, status, category, cardAuthorization, digitalWalletToken, digitalWalletAuthentication, type, additionalProperties.toUnmodifiable(), ) } /** Fields related to a card authorization. */ @JsonDeserialize(builder = CardAuthorization.Builder::class) @NoAutoDetect class CardAuthorization private constructor( private val merchantAcceptorId: JsonField<String>, private val merchantDescriptor: JsonField<String>, private val merchantCategoryCode: JsonField<String>, private val merchantCity: JsonField<String>, private val merchantCountry: JsonField<String>, private val digitalWalletTokenId: JsonField<String>, private val physicalCardId: JsonField<String>, private val verification: JsonField<Verification>, private val networkIdentifiers: JsonField<NetworkIdentifiers>, private val networkDetails: JsonField<NetworkDetails>, private val decision: JsonField<Decision>, private val cardId: JsonField<String>, private val accountId: JsonField<String>, private val presentmentAmount: JsonField<Long>, private val presentmentCurrency: JsonField<String>, private val settlementAmount: JsonField<Long>, private val settlementCurrency: JsonField<String>, private val processingCategory: JsonField<ProcessingCategory>, private val requestDetails: JsonField<RequestDetails>, private val additionalProperties: Map<String, JsonValue>, ) { private var validated: Boolean = false private var hashCode: Int = 0 /** * The merchant identifier (commonly abbreviated as MID) of the merchant the card is * transacting with. */ fun merchantAcceptorId(): String = merchantAcceptorId.getRequired("merchant_acceptor_id") /** The merchant descriptor of the merchant the card is transacting with. */ fun merchantDescriptor(): String = merchantDescriptor.getRequired("merchant_descriptor") /** * The Merchant Category Code (commonly abbreviated as MCC) of the merchant the card is * transacting with. */ fun merchantCategoryCode(): String? = merchantCategoryCode.getNullable("merchant_category_code") /** The city the merchant resides in. */ fun merchantCity(): String? = merchantCity.getNullable("merchant_city") /** The country the merchant resides in. */ fun merchantCountry(): String? = merchantCountry.getNullable("merchant_country") /** * If the authorization was made via a Digital Wallet Token (such as an Apple Pay purchase), * the identifier of the token that was used. */ fun digitalWalletTokenId(): String? = digitalWalletTokenId.getNullable("digital_wallet_token_id") /** * If the authorization was made in-person with a physical card, the Physical Card that was * used. */ fun physicalCardId(): String? = physicalCardId.getNullable("physical_card_id") /** Fields related to verification of cardholder-provided values. */ fun verification(): Verification = verification.getRequired("verification") /** Network-specific identifiers for a specific request or transaction. */ fun networkIdentifiers(): NetworkIdentifiers = networkIdentifiers.getRequired("network_identifiers") /** Fields specific to the `network`. */ fun networkDetails(): NetworkDetails = networkDetails.getRequired("network_details") /** Whether or not the authorization was approved. */ fun decision(): Decision? = decision.getNullable("decision") /** The identifier of the Card that is being authorized. */ fun cardId(): String = cardId.getRequired("card_id") /** The identifier of the Account the authorization will debit. */ fun accountId(): String = accountId.getRequired("account_id") /** * The amount of the attempted authorization in the currency the card user sees at the time * of purchase, in the minor unit of that currency. For dollars, for example, this is cents. */ fun presentmentAmount(): Long = presentmentAmount.getRequired("presentment_amount") /** * The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) code for the currency the user * sees at the time of purchase. */ fun presentmentCurrency(): String = presentmentCurrency.getRequired("presentment_currency") /** * The amount of the attempted authorization in the currency it will be settled in. This * currency is the same as that of the Account the card belongs to. */ fun settlementAmount(): Long = settlementAmount.getRequired("settlement_amount") /** * The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) code for the currency the * transaction will be settled in. */ fun settlementCurrency(): String = settlementCurrency.getRequired("settlement_currency") /** * The processing category describes the intent behind the authorization, such as whether it * was used for bill payments or an automatic fuel dispenser. */ fun processingCategory(): ProcessingCategory = processingCategory.getRequired("processing_category") /** Fields specific to the type of request, such as an incremental authorization. */ fun requestDetails(): RequestDetails = requestDetails.getRequired("request_details") /** * The merchant identifier (commonly abbreviated as MID) of the merchant the card is * transacting with. */ @JsonProperty("merchant_acceptor_id") @ExcludeMissing fun _merchantAcceptorId() = merchantAcceptorId /** The merchant descriptor of the merchant the card is transacting with. */ @JsonProperty("merchant_descriptor") @ExcludeMissing fun _merchantDescriptor() = merchantDescriptor /** * The Merchant Category Code (commonly abbreviated as MCC) of the merchant the card is * transacting with. */ @JsonProperty("merchant_category_code") @ExcludeMissing fun _merchantCategoryCode() = merchantCategoryCode /** The city the merchant resides in. */ @JsonProperty("merchant_city") @ExcludeMissing fun _merchantCity() = merchantCity /** The country the merchant resides in. */ @JsonProperty("merchant_country") @ExcludeMissing fun _merchantCountry() = merchantCountry /** * If the authorization was made via a Digital Wallet Token (such as an Apple Pay purchase), * the identifier of the token that was used. */ @JsonProperty("digital_wallet_token_id") @ExcludeMissing fun _digitalWalletTokenId() = digitalWalletTokenId /** * If the authorization was made in-person with a physical card, the Physical Card that was * used. */ @JsonProperty("physical_card_id") @ExcludeMissing fun _physicalCardId() = physicalCardId /** Fields related to verification of cardholder-provided values. */ @JsonProperty("verification") @ExcludeMissing fun _verification() = verification /** Network-specific identifiers for a specific request or transaction. */ @JsonProperty("network_identifiers") @ExcludeMissing fun _networkIdentifiers() = networkIdentifiers /** Fields specific to the `network`. */ @JsonProperty("network_details") @ExcludeMissing fun _networkDetails() = networkDetails /** Whether or not the authorization was approved. */ @JsonProperty("decision") @ExcludeMissing fun _decision() = decision /** The identifier of the Card that is being authorized. */ @JsonProperty("card_id") @ExcludeMissing fun _cardId() = cardId /** The identifier of the Account the authorization will debit. */ @JsonProperty("account_id") @ExcludeMissing fun _accountId() = accountId /** * The amount of the attempted authorization in the currency the card user sees at the time * of purchase, in the minor unit of that currency. For dollars, for example, this is cents. */ @JsonProperty("presentment_amount") @ExcludeMissing fun _presentmentAmount() = presentmentAmount /** * The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) code for the currency the user * sees at the time of purchase. */ @JsonProperty("presentment_currency") @ExcludeMissing fun _presentmentCurrency() = presentmentCurrency /** * The amount of the attempted authorization in the currency it will be settled in. This * currency is the same as that of the Account the card belongs to. */ @JsonProperty("settlement_amount") @ExcludeMissing fun _settlementAmount() = settlementAmount /** * The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) code for the currency the * transaction will be settled in. */ @JsonProperty("settlement_currency") @ExcludeMissing fun _settlementCurrency() = settlementCurrency /** * The processing category describes the intent behind the authorization, such as whether it * was used for bill payments or an automatic fuel dispenser. */ @JsonProperty("processing_category") @ExcludeMissing fun _processingCategory() = processingCategory /** Fields specific to the type of request, such as an incremental authorization. */ @JsonProperty("request_details") @ExcludeMissing fun _requestDetails() = requestDetails @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun validate(): CardAuthorization = apply { if (!validated) { merchantAcceptorId() merchantDescriptor() merchantCategoryCode() merchantCity() merchantCountry() digitalWalletTokenId() physicalCardId() verification().validate() networkIdentifiers().validate() networkDetails().validate() decision() cardId() accountId() presentmentAmount() presentmentCurrency() settlementAmount() settlementCurrency() processingCategory() requestDetails().validate() validated = true } } fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is CardAuthorization && this.merchantAcceptorId == other.merchantAcceptorId && this.merchantDescriptor == other.merchantDescriptor && this.merchantCategoryCode == other.merchantCategoryCode && this.merchantCity == other.merchantCity && this.merchantCountry == other.merchantCountry && this.digitalWalletTokenId == other.digitalWalletTokenId && this.physicalCardId == other.physicalCardId && this.verification == other.verification && this.networkIdentifiers == other.networkIdentifiers && this.networkDetails == other.networkDetails && this.decision == other.decision && this.cardId == other.cardId && this.accountId == other.accountId && this.presentmentAmount == other.presentmentAmount && this.presentmentCurrency == other.presentmentCurrency && this.settlementAmount == other.settlementAmount && this.settlementCurrency == other.settlementCurrency && this.processingCategory == other.processingCategory && this.requestDetails == other.requestDetails && this.additionalProperties == other.additionalProperties } override fun hashCode(): Int { if (hashCode == 0) { hashCode = Objects.hash( merchantAcceptorId, merchantDescriptor, merchantCategoryCode, merchantCity, merchantCountry, digitalWalletTokenId, physicalCardId, verification, networkIdentifiers, networkDetails, decision, cardId, accountId, presentmentAmount, presentmentCurrency, settlementAmount, settlementCurrency, processingCategory, requestDetails, additionalProperties, ) } return hashCode } override fun toString() = "CardAuthorization{merchantAcceptorId=$merchantAcceptorId, merchantDescriptor=$merchantDescriptor, merchantCategoryCode=$merchantCategoryCode, merchantCity=$merchantCity, merchantCountry=$merchantCountry, digitalWalletTokenId=$digitalWalletTokenId, physicalCardId=$physicalCardId, verification=$verification, networkIdentifiers=$networkIdentifiers, networkDetails=$networkDetails, decision=$decision, cardId=$cardId, accountId=$accountId, presentmentAmount=$presentmentAmount, presentmentCurrency=$presentmentCurrency, settlementAmount=$settlementAmount, settlementCurrency=$settlementCurrency, processingCategory=$processingCategory, requestDetails=$requestDetails, additionalProperties=$additionalProperties}" companion object { fun builder() = Builder() } class Builder { private var merchantAcceptorId: JsonField<String> = JsonMissing.of() private var merchantDescriptor: JsonField<String> = JsonMissing.of() private var merchantCategoryCode: JsonField<String> = JsonMissing.of() private var merchantCity: JsonField<String> = JsonMissing.of() private var merchantCountry: JsonField<String> = JsonMissing.of() private var digitalWalletTokenId: JsonField<String> = JsonMissing.of() private var physicalCardId: JsonField<String> = JsonMissing.of() private var verification: JsonField<Verification> = JsonMissing.of() private var networkIdentifiers: JsonField<NetworkIdentifiers> = JsonMissing.of() private var networkDetails: JsonField<NetworkDetails> = JsonMissing.of() private var decision: JsonField<Decision> = JsonMissing.of() private var cardId: JsonField<String> = JsonMissing.of() private var accountId: JsonField<String> = JsonMissing.of() private var presentmentAmount: JsonField<Long> = JsonMissing.of() private var presentmentCurrency: JsonField<String> = JsonMissing.of() private var settlementAmount: JsonField<Long> = JsonMissing.of() private var settlementCurrency: JsonField<String> = JsonMissing.of() private var processingCategory: JsonField<ProcessingCategory> = JsonMissing.of() private var requestDetails: JsonField<RequestDetails> = JsonMissing.of() private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from(cardAuthorization: CardAuthorization) = apply { this.merchantAcceptorId = cardAuthorization.merchantAcceptorId this.merchantDescriptor = cardAuthorization.merchantDescriptor this.merchantCategoryCode = cardAuthorization.merchantCategoryCode this.merchantCity = cardAuthorization.merchantCity this.merchantCountry = cardAuthorization.merchantCountry this.digitalWalletTokenId = cardAuthorization.digitalWalletTokenId this.physicalCardId = cardAuthorization.physicalCardId this.verification = cardAuthorization.verification this.networkIdentifiers = cardAuthorization.networkIdentifiers this.networkDetails = cardAuthorization.networkDetails this.decision = cardAuthorization.decision this.cardId = cardAuthorization.cardId this.accountId = cardAuthorization.accountId this.presentmentAmount = cardAuthorization.presentmentAmount this.presentmentCurrency = cardAuthorization.presentmentCurrency this.settlementAmount = cardAuthorization.settlementAmount this.settlementCurrency = cardAuthorization.settlementCurrency this.processingCategory = cardAuthorization.processingCategory this.requestDetails = cardAuthorization.requestDetails additionalProperties(cardAuthorization.additionalProperties) } /** * The merchant identifier (commonly abbreviated as MID) of the merchant the card is * transacting with. */ fun merchantAcceptorId(merchantAcceptorId: String) = merchantAcceptorId(JsonField.of(merchantAcceptorId)) /** * The merchant identifier (commonly abbreviated as MID) of the merchant the card is * transacting with. */ @JsonProperty("merchant_acceptor_id") @ExcludeMissing fun merchantAcceptorId(merchantAcceptorId: JsonField<String>) = apply { this.merchantAcceptorId = merchantAcceptorId } /** The merchant descriptor of the merchant the card is transacting with. */ fun merchantDescriptor(merchantDescriptor: String) = merchantDescriptor(JsonField.of(merchantDescriptor)) /** The merchant descriptor of the merchant the card is transacting with. */ @JsonProperty("merchant_descriptor") @ExcludeMissing fun merchantDescriptor(merchantDescriptor: JsonField<String>) = apply { this.merchantDescriptor = merchantDescriptor } /** * The Merchant Category Code (commonly abbreviated as MCC) of the merchant the card is * transacting with. */ fun merchantCategoryCode(merchantCategoryCode: String) = merchantCategoryCode(JsonField.of(merchantCategoryCode)) /** * The Merchant Category Code (commonly abbreviated as MCC) of the merchant the card is * transacting with. */ @JsonProperty("merchant_category_code") @ExcludeMissing fun merchantCategoryCode(merchantCategoryCode: JsonField<String>) = apply { this.merchantCategoryCode = merchantCategoryCode } /** The city the merchant resides in. */ fun merchantCity(merchantCity: String) = merchantCity(JsonField.of(merchantCity)) /** The city the merchant resides in. */ @JsonProperty("merchant_city") @ExcludeMissing fun merchantCity(merchantCity: JsonField<String>) = apply { this.merchantCity = merchantCity } /** The country the merchant resides in. */ fun merchantCountry(merchantCountry: String) = merchantCountry(JsonField.of(merchantCountry)) /** The country the merchant resides in. */ @JsonProperty("merchant_country") @ExcludeMissing fun merchantCountry(merchantCountry: JsonField<String>) = apply { this.merchantCountry = merchantCountry } /** * If the authorization was made via a Digital Wallet Token (such as an Apple Pay * purchase), the identifier of the token that was used. */ fun digitalWalletTokenId(digitalWalletTokenId: String) = digitalWalletTokenId(JsonField.of(digitalWalletTokenId)) /** * If the authorization was made via a Digital Wallet Token (such as an Apple Pay * purchase), the identifier of the token that was used. */ @JsonProperty("digital_wallet_token_id") @ExcludeMissing fun digitalWalletTokenId(digitalWalletTokenId: JsonField<String>) = apply { this.digitalWalletTokenId = digitalWalletTokenId } /** * If the authorization was made in-person with a physical card, the Physical Card that * was used. */ fun physicalCardId(physicalCardId: String) = physicalCardId(JsonField.of(physicalCardId)) /** * If the authorization was made in-person with a physical card, the Physical Card that * was used. */ @JsonProperty("physical_card_id") @ExcludeMissing fun physicalCardId(physicalCardId: JsonField<String>) = apply { this.physicalCardId = physicalCardId } /** Fields related to verification of cardholder-provided values. */ fun verification(verification: Verification) = verification(JsonField.of(verification)) /** Fields related to verification of cardholder-provided values. */ @JsonProperty("verification") @ExcludeMissing fun verification(verification: JsonField<Verification>) = apply { this.verification = verification } /** Network-specific identifiers for a specific request or transaction. */ fun networkIdentifiers(networkIdentifiers: NetworkIdentifiers) = networkIdentifiers(JsonField.of(networkIdentifiers)) /** Network-specific identifiers for a specific request or transaction. */ @JsonProperty("network_identifiers") @ExcludeMissing fun networkIdentifiers(networkIdentifiers: JsonField<NetworkIdentifiers>) = apply { this.networkIdentifiers = networkIdentifiers } /** Fields specific to the `network`. */ fun networkDetails(networkDetails: NetworkDetails) = networkDetails(JsonField.of(networkDetails)) /** Fields specific to the `network`. */ @JsonProperty("network_details") @ExcludeMissing fun networkDetails(networkDetails: JsonField<NetworkDetails>) = apply { this.networkDetails = networkDetails } /** Whether or not the authorization was approved. */ fun decision(decision: Decision) = decision(JsonField.of(decision)) /** Whether or not the authorization was approved. */ @JsonProperty("decision") @ExcludeMissing fun decision(decision: JsonField<Decision>) = apply { this.decision = decision } /** The identifier of the Card that is being authorized. */ fun cardId(cardId: String) = cardId(JsonField.of(cardId)) /** The identifier of the Card that is being authorized. */ @JsonProperty("card_id") @ExcludeMissing fun cardId(cardId: JsonField<String>) = apply { this.cardId = cardId } /** The identifier of the Account the authorization will debit. */ fun accountId(accountId: String) = accountId(JsonField.of(accountId)) /** The identifier of the Account the authorization will debit. */ @JsonProperty("account_id") @ExcludeMissing fun accountId(accountId: JsonField<String>) = apply { this.accountId = accountId } /** * The amount of the attempted authorization in the currency the card user sees at the * time of purchase, in the minor unit of that currency. For dollars, for example, this * is cents. */ fun presentmentAmount(presentmentAmount: Long) = presentmentAmount(JsonField.of(presentmentAmount)) /** * The amount of the attempted authorization in the currency the card user sees at the * time of purchase, in the minor unit of that currency. For dollars, for example, this * is cents. */ @JsonProperty("presentment_amount") @ExcludeMissing fun presentmentAmount(presentmentAmount: JsonField<Long>) = apply { this.presentmentAmount = presentmentAmount } /** * The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) code for the currency the user * sees at the time of purchase. */ fun presentmentCurrency(presentmentCurrency: String) = presentmentCurrency(JsonField.of(presentmentCurrency)) /** * The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) code for the currency the user * sees at the time of purchase. */ @JsonProperty("presentment_currency") @ExcludeMissing fun presentmentCurrency(presentmentCurrency: JsonField<String>) = apply { this.presentmentCurrency = presentmentCurrency } /** * The amount of the attempted authorization in the currency it will be settled in. This * currency is the same as that of the Account the card belongs to. */ fun settlementAmount(settlementAmount: Long) = settlementAmount(JsonField.of(settlementAmount)) /** * The amount of the attempted authorization in the currency it will be settled in. This * currency is the same as that of the Account the card belongs to. */ @JsonProperty("settlement_amount") @ExcludeMissing fun settlementAmount(settlementAmount: JsonField<Long>) = apply { this.settlementAmount = settlementAmount } /** * The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) code for the currency the * transaction will be settled in. */ fun settlementCurrency(settlementCurrency: String) = settlementCurrency(JsonField.of(settlementCurrency)) /** * The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) code for the currency the * transaction will be settled in. */ @JsonProperty("settlement_currency") @ExcludeMissing fun settlementCurrency(settlementCurrency: JsonField<String>) = apply { this.settlementCurrency = settlementCurrency } /** * The processing category describes the intent behind the authorization, such as * whether it was used for bill payments or an automatic fuel dispenser. */ fun processingCategory(processingCategory: ProcessingCategory) = processingCategory(JsonField.of(processingCategory)) /** * The processing category describes the intent behind the authorization, such as * whether it was used for bill payments or an automatic fuel dispenser. */ @JsonProperty("processing_category") @ExcludeMissing fun processingCategory(processingCategory: JsonField<ProcessingCategory>) = apply { this.processingCategory = processingCategory } /** Fields specific to the type of request, such as an incremental authorization. */ fun requestDetails(requestDetails: RequestDetails) = requestDetails(JsonField.of(requestDetails)) /** Fields specific to the type of request, such as an incremental authorization. */ @JsonProperty("request_details") @ExcludeMissing fun requestDetails(requestDetails: JsonField<RequestDetails>) = apply { this.requestDetails = requestDetails } fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.putAll(additionalProperties) } fun build(): CardAuthorization = CardAuthorization( merchantAcceptorId, merchantDescriptor, merchantCategoryCode, merchantCity, merchantCountry, digitalWalletTokenId, physicalCardId, verification, networkIdentifiers, networkDetails, decision, cardId, accountId, presentmentAmount, presentmentCurrency, settlementAmount, settlementCurrency, processingCategory, requestDetails, additionalProperties.toUnmodifiable(), ) } class Decision @JsonCreator private constructor( private val value: JsonField<String>, ) { @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is Decision && this.value == other.value } override fun hashCode() = value.hashCode() override fun toString() = value.toString() companion object { val APPROVE = Decision(JsonField.of("approve")) val DECLINE = Decision(JsonField.of("decline")) fun of(value: String) = Decision(JsonField.of(value)) } enum class Known { APPROVE, DECLINE, } enum class Value { APPROVE, DECLINE, _UNKNOWN, } fun value(): Value = when (this) { APPROVE -> Value.APPROVE DECLINE -> Value.DECLINE else -> Value._UNKNOWN } fun known(): Known = when (this) { APPROVE -> Known.APPROVE DECLINE -> Known.DECLINE else -> throw IncreaseInvalidDataException("Unknown Decision: $value") } fun asString(): String = _value().asStringOrThrow() } /** Fields specific to the `network`. */ @JsonDeserialize(builder = NetworkDetails.Builder::class) @NoAutoDetect class NetworkDetails private constructor( private val category: JsonField<Category>, private val visa: JsonField<Visa>, private val additionalProperties: Map<String, JsonValue>, ) { private var validated: Boolean = false private var hashCode: Int = 0 /** The payment network used to process this card authorization. */ fun category(): Category = category.getRequired("category") /** Fields specific to the `visa` network. */ fun visa(): Visa? = visa.getNullable("visa") /** The payment network used to process this card authorization. */ @JsonProperty("category") @ExcludeMissing fun _category() = category /** Fields specific to the `visa` network. */ @JsonProperty("visa") @ExcludeMissing fun _visa() = visa @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun validate(): NetworkDetails = apply { if (!validated) { category() visa()?.validate() validated = true } } fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is NetworkDetails && this.category == other.category && this.visa == other.visa && this.additionalProperties == other.additionalProperties } override fun hashCode(): Int { if (hashCode == 0) { hashCode = Objects.hash( category, visa, additionalProperties, ) } return hashCode } override fun toString() = "NetworkDetails{category=$category, visa=$visa, additionalProperties=$additionalProperties}" companion object { fun builder() = Builder() } class Builder { private var category: JsonField<Category> = JsonMissing.of() private var visa: JsonField<Visa> = JsonMissing.of() private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from(networkDetails: NetworkDetails) = apply { this.category = networkDetails.category this.visa = networkDetails.visa additionalProperties(networkDetails.additionalProperties) } /** The payment network used to process this card authorization. */ fun category(category: Category) = category(JsonField.of(category)) /** The payment network used to process this card authorization. */ @JsonProperty("category") @ExcludeMissing fun category(category: JsonField<Category>) = apply { this.category = category } /** Fields specific to the `visa` network. */ fun visa(visa: Visa) = visa(JsonField.of(visa)) /** Fields specific to the `visa` network. */ @JsonProperty("visa") @ExcludeMissing fun visa(visa: JsonField<Visa>) = apply { this.visa = visa } fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.putAll(additionalProperties) } fun build(): NetworkDetails = NetworkDetails( category, visa, additionalProperties.toUnmodifiable(), ) } class Category @JsonCreator private constructor( private val value: JsonField<String>, ) { @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is Category && this.value == other.value } override fun hashCode() = value.hashCode() override fun toString() = value.toString() companion object { val VISA = Category(JsonField.of("visa")) fun of(value: String) = Category(JsonField.of(value)) } enum class Known { VISA, } enum class Value { VISA, _UNKNOWN, } fun value(): Value = when (this) { VISA -> Value.VISA else -> Value._UNKNOWN } fun known(): Known = when (this) { VISA -> Known.VISA else -> throw IncreaseInvalidDataException("Unknown Category: $value") } fun asString(): String = _value().asStringOrThrow() } /** Fields specific to the `visa` network. */ @JsonDeserialize(builder = Visa.Builder::class) @NoAutoDetect class Visa private constructor( private val electronicCommerceIndicator: JsonField<ElectronicCommerceIndicator>, private val pointOfServiceEntryMode: JsonField<PointOfServiceEntryMode>, private val additionalProperties: Map<String, JsonValue>, ) { private var validated: Boolean = false private var hashCode: Int = 0 /** * For electronic commerce transactions, this identifies the level of security used * in obtaining the customer's payment credential. For mail or telephone order * transactions, identifies the type of mail or telephone order. */ fun electronicCommerceIndicator(): ElectronicCommerceIndicator? = electronicCommerceIndicator.getNullable("electronic_commerce_indicator") /** * The method used to enter the cardholder's primary account number and card * expiration date. */ fun pointOfServiceEntryMode(): PointOfServiceEntryMode? = pointOfServiceEntryMode.getNullable("point_of_service_entry_mode") /** * For electronic commerce transactions, this identifies the level of security used * in obtaining the customer's payment credential. For mail or telephone order * transactions, identifies the type of mail or telephone order. */ @JsonProperty("electronic_commerce_indicator") @ExcludeMissing fun _electronicCommerceIndicator() = electronicCommerceIndicator /** * The method used to enter the cardholder's primary account number and card * expiration date. */ @JsonProperty("point_of_service_entry_mode") @ExcludeMissing fun _pointOfServiceEntryMode() = pointOfServiceEntryMode @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun validate(): Visa = apply { if (!validated) { electronicCommerceIndicator() pointOfServiceEntryMode() validated = true } } fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is Visa && this.electronicCommerceIndicator == other.electronicCommerceIndicator && this.pointOfServiceEntryMode == other.pointOfServiceEntryMode && this.additionalProperties == other.additionalProperties } override fun hashCode(): Int { if (hashCode == 0) { hashCode = Objects.hash( electronicCommerceIndicator, pointOfServiceEntryMode, additionalProperties, ) } return hashCode } override fun toString() = "Visa{electronicCommerceIndicator=$electronicCommerceIndicator, pointOfServiceEntryMode=$pointOfServiceEntryMode, additionalProperties=$additionalProperties}" companion object { fun builder() = Builder() } class Builder { private var electronicCommerceIndicator: JsonField<ElectronicCommerceIndicator> = JsonMissing.of() private var pointOfServiceEntryMode: JsonField<PointOfServiceEntryMode> = JsonMissing.of() private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from(visa: Visa) = apply { this.electronicCommerceIndicator = visa.electronicCommerceIndicator this.pointOfServiceEntryMode = visa.pointOfServiceEntryMode additionalProperties(visa.additionalProperties) } /** * For electronic commerce transactions, this identifies the level of security * used in obtaining the customer's payment credential. For mail or telephone * order transactions, identifies the type of mail or telephone order. */ fun electronicCommerceIndicator( electronicCommerceIndicator: ElectronicCommerceIndicator ) = electronicCommerceIndicator(JsonField.of(electronicCommerceIndicator)) /** * For electronic commerce transactions, this identifies the level of security * used in obtaining the customer's payment credential. For mail or telephone * order transactions, identifies the type of mail or telephone order. */ @JsonProperty("electronic_commerce_indicator") @ExcludeMissing fun electronicCommerceIndicator( electronicCommerceIndicator: JsonField<ElectronicCommerceIndicator> ) = apply { this.electronicCommerceIndicator = electronicCommerceIndicator } /** * The method used to enter the cardholder's primary account number and card * expiration date. */ fun pointOfServiceEntryMode(pointOfServiceEntryMode: PointOfServiceEntryMode) = pointOfServiceEntryMode(JsonField.of(pointOfServiceEntryMode)) /** * The method used to enter the cardholder's primary account number and card * expiration date. */ @JsonProperty("point_of_service_entry_mode") @ExcludeMissing fun pointOfServiceEntryMode( pointOfServiceEntryMode: JsonField<PointOfServiceEntryMode> ) = apply { this.pointOfServiceEntryMode = pointOfServiceEntryMode } fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.putAll(additionalProperties) } fun build(): Visa = Visa( electronicCommerceIndicator, pointOfServiceEntryMode, additionalProperties.toUnmodifiable(), ) } class ElectronicCommerceIndicator @JsonCreator private constructor( private val value: JsonField<String>, ) { @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is ElectronicCommerceIndicator && this.value == other.value } override fun hashCode() = value.hashCode() override fun toString() = value.toString() companion object { val MAIL_PHONE_ORDER = ElectronicCommerceIndicator(JsonField.of("mail_phone_order")) val RECURRING = ElectronicCommerceIndicator(JsonField.of("recurring")) val INSTALLMENT = ElectronicCommerceIndicator(JsonField.of("installment")) val UNKNOWN_MAIL_PHONE_ORDER = ElectronicCommerceIndicator(JsonField.of("unknown_mail_phone_order")) val SECURE_ELECTRONIC_COMMERCE = ElectronicCommerceIndicator(JsonField.of("secure_electronic_commerce")) val NON_AUTHENTICATED_SECURITY_TRANSACTION_AT_3DS_CAPABLE_MERCHANT = ElectronicCommerceIndicator( JsonField.of( "non_authenticated_security_transaction_at_3ds_capable_merchant" ) ) val NON_AUTHENTICATED_SECURITY_TRANSACTION = ElectronicCommerceIndicator( JsonField.of("non_authenticated_security_transaction") ) val NON_SECURE_TRANSACTION = ElectronicCommerceIndicator(JsonField.of("non_secure_transaction")) fun of(value: String) = ElectronicCommerceIndicator(JsonField.of(value)) } enum class Known { MAIL_PHONE_ORDER, RECURRING, INSTALLMENT, UNKNOWN_MAIL_PHONE_ORDER, SECURE_ELECTRONIC_COMMERCE, NON_AUTHENTICATED_SECURITY_TRANSACTION_AT_3DS_CAPABLE_MERCHANT, NON_AUTHENTICATED_SECURITY_TRANSACTION, NON_SECURE_TRANSACTION, } enum class Value { MAIL_PHONE_ORDER, RECURRING, INSTALLMENT, UNKNOWN_MAIL_PHONE_ORDER, SECURE_ELECTRONIC_COMMERCE, NON_AUTHENTICATED_SECURITY_TRANSACTION_AT_3DS_CAPABLE_MERCHANT, NON_AUTHENTICATED_SECURITY_TRANSACTION, NON_SECURE_TRANSACTION, _UNKNOWN, } fun value(): Value = when (this) { MAIL_PHONE_ORDER -> Value.MAIL_PHONE_ORDER RECURRING -> Value.RECURRING INSTALLMENT -> Value.INSTALLMENT UNKNOWN_MAIL_PHONE_ORDER -> Value.UNKNOWN_MAIL_PHONE_ORDER SECURE_ELECTRONIC_COMMERCE -> Value.SECURE_ELECTRONIC_COMMERCE NON_AUTHENTICATED_SECURITY_TRANSACTION_AT_3DS_CAPABLE_MERCHANT -> Value.NON_AUTHENTICATED_SECURITY_TRANSACTION_AT_3DS_CAPABLE_MERCHANT NON_AUTHENTICATED_SECURITY_TRANSACTION -> Value.NON_AUTHENTICATED_SECURITY_TRANSACTION NON_SECURE_TRANSACTION -> Value.NON_SECURE_TRANSACTION else -> Value._UNKNOWN } fun known(): Known = when (this) { MAIL_PHONE_ORDER -> Known.MAIL_PHONE_ORDER RECURRING -> Known.RECURRING INSTALLMENT -> Known.INSTALLMENT UNKNOWN_MAIL_PHONE_ORDER -> Known.UNKNOWN_MAIL_PHONE_ORDER SECURE_ELECTRONIC_COMMERCE -> Known.SECURE_ELECTRONIC_COMMERCE NON_AUTHENTICATED_SECURITY_TRANSACTION_AT_3DS_CAPABLE_MERCHANT -> Known.NON_AUTHENTICATED_SECURITY_TRANSACTION_AT_3DS_CAPABLE_MERCHANT NON_AUTHENTICATED_SECURITY_TRANSACTION -> Known.NON_AUTHENTICATED_SECURITY_TRANSACTION NON_SECURE_TRANSACTION -> Known.NON_SECURE_TRANSACTION else -> throw IncreaseInvalidDataException( "Unknown ElectronicCommerceIndicator: $value" ) } fun asString(): String = _value().asStringOrThrow() } class PointOfServiceEntryMode @JsonCreator private constructor( private val value: JsonField<String>, ) { @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is PointOfServiceEntryMode && this.value == other.value } override fun hashCode() = value.hashCode() override fun toString() = value.toString() companion object { val UNKNOWN = PointOfServiceEntryMode(JsonField.of("unknown")) val MANUAL = PointOfServiceEntryMode(JsonField.of("manual")) val MAGNETIC_STRIPE_NO_CVV = PointOfServiceEntryMode(JsonField.of("magnetic_stripe_no_cvv")) val OPTICAL_CODE = PointOfServiceEntryMode(JsonField.of("optical_code")) val INTEGRATED_CIRCUIT_CARD = PointOfServiceEntryMode(JsonField.of("integrated_circuit_card")) val CONTACTLESS = PointOfServiceEntryMode(JsonField.of("contactless")) val CREDENTIAL_ON_FILE = PointOfServiceEntryMode(JsonField.of("credential_on_file")) val MAGNETIC_STRIPE = PointOfServiceEntryMode(JsonField.of("magnetic_stripe")) val CONTACTLESS_MAGNETIC_STRIPE = PointOfServiceEntryMode(JsonField.of("contactless_magnetic_stripe")) val INTEGRATED_CIRCUIT_CARD_NO_CVV = PointOfServiceEntryMode(JsonField.of("integrated_circuit_card_no_cvv")) fun of(value: String) = PointOfServiceEntryMode(JsonField.of(value)) } enum class Known { UNKNOWN, MANUAL, MAGNETIC_STRIPE_NO_CVV, OPTICAL_CODE, INTEGRATED_CIRCUIT_CARD, CONTACTLESS, CREDENTIAL_ON_FILE, MAGNETIC_STRIPE, CONTACTLESS_MAGNETIC_STRIPE, INTEGRATED_CIRCUIT_CARD_NO_CVV, } enum class Value { UNKNOWN, MANUAL, MAGNETIC_STRIPE_NO_CVV, OPTICAL_CODE, INTEGRATED_CIRCUIT_CARD, CONTACTLESS, CREDENTIAL_ON_FILE, MAGNETIC_STRIPE, CONTACTLESS_MAGNETIC_STRIPE, INTEGRATED_CIRCUIT_CARD_NO_CVV, _UNKNOWN, } fun value(): Value = when (this) { UNKNOWN -> Value.UNKNOWN MANUAL -> Value.MANUAL MAGNETIC_STRIPE_NO_CVV -> Value.MAGNETIC_STRIPE_NO_CVV OPTICAL_CODE -> Value.OPTICAL_CODE INTEGRATED_CIRCUIT_CARD -> Value.INTEGRATED_CIRCUIT_CARD CONTACTLESS -> Value.CONTACTLESS CREDENTIAL_ON_FILE -> Value.CREDENTIAL_ON_FILE MAGNETIC_STRIPE -> Value.MAGNETIC_STRIPE CONTACTLESS_MAGNETIC_STRIPE -> Value.CONTACTLESS_MAGNETIC_STRIPE INTEGRATED_CIRCUIT_CARD_NO_CVV -> Value.INTEGRATED_CIRCUIT_CARD_NO_CVV else -> Value._UNKNOWN } fun known(): Known = when (this) { UNKNOWN -> Known.UNKNOWN MANUAL -> Known.MANUAL MAGNETIC_STRIPE_NO_CVV -> Known.MAGNETIC_STRIPE_NO_CVV OPTICAL_CODE -> Known.OPTICAL_CODE INTEGRATED_CIRCUIT_CARD -> Known.INTEGRATED_CIRCUIT_CARD CONTACTLESS -> Known.CONTACTLESS CREDENTIAL_ON_FILE -> Known.CREDENTIAL_ON_FILE MAGNETIC_STRIPE -> Known.MAGNETIC_STRIPE CONTACTLESS_MAGNETIC_STRIPE -> Known.CONTACTLESS_MAGNETIC_STRIPE INTEGRATED_CIRCUIT_CARD_NO_CVV -> Known.INTEGRATED_CIRCUIT_CARD_NO_CVV else -> throw IncreaseInvalidDataException( "Unknown PointOfServiceEntryMode: $value" ) } fun asString(): String = _value().asStringOrThrow() } } } /** Network-specific identifiers for a specific request or transaction. */ @JsonDeserialize(builder = NetworkIdentifiers.Builder::class) @NoAutoDetect class NetworkIdentifiers private constructor( private val transactionId: JsonField<String>, private val traceNumber: JsonField<String>, private val retrievalReferenceNumber: JsonField<String>, private val additionalProperties: Map<String, JsonValue>, ) { private var validated: Boolean = false private var hashCode: Int = 0 /** * A globally unique transaction identifier provided by the card network, used across * multiple life-cycle requests. */ fun transactionId(): String? = transactionId.getNullable("transaction_id") /** * A counter used to verify an individual authorization. Expected to be unique per * acquirer within a window of time. */ fun traceNumber(): String? = traceNumber.getNullable("trace_number") /** * A life-cycle identifier used across e.g., an authorization and a reversal. Expected * to be unique per acquirer within a window of time. For some card networks the * retrieval reference number includes the trace counter. */ fun retrievalReferenceNumber(): String? = retrievalReferenceNumber.getNullable("retrieval_reference_number") /** * A globally unique transaction identifier provided by the card network, used across * multiple life-cycle requests. */ @JsonProperty("transaction_id") @ExcludeMissing fun _transactionId() = transactionId /** * A counter used to verify an individual authorization. Expected to be unique per * acquirer within a window of time. */ @JsonProperty("trace_number") @ExcludeMissing fun _traceNumber() = traceNumber /** * A life-cycle identifier used across e.g., an authorization and a reversal. Expected * to be unique per acquirer within a window of time. For some card networks the * retrieval reference number includes the trace counter. */ @JsonProperty("retrieval_reference_number") @ExcludeMissing fun _retrievalReferenceNumber() = retrievalReferenceNumber @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun validate(): NetworkIdentifiers = apply { if (!validated) { transactionId() traceNumber() retrievalReferenceNumber() validated = true } } fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is NetworkIdentifiers && this.transactionId == other.transactionId && this.traceNumber == other.traceNumber && this.retrievalReferenceNumber == other.retrievalReferenceNumber && this.additionalProperties == other.additionalProperties } override fun hashCode(): Int { if (hashCode == 0) { hashCode = Objects.hash( transactionId, traceNumber, retrievalReferenceNumber, additionalProperties, ) } return hashCode } override fun toString() = "NetworkIdentifiers{transactionId=$transactionId, traceNumber=$traceNumber, retrievalReferenceNumber=$retrievalReferenceNumber, additionalProperties=$additionalProperties}" companion object { fun builder() = Builder() } class Builder { private var transactionId: JsonField<String> = JsonMissing.of() private var traceNumber: JsonField<String> = JsonMissing.of() private var retrievalReferenceNumber: JsonField<String> = JsonMissing.of() private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from(networkIdentifiers: NetworkIdentifiers) = apply { this.transactionId = networkIdentifiers.transactionId this.traceNumber = networkIdentifiers.traceNumber this.retrievalReferenceNumber = networkIdentifiers.retrievalReferenceNumber additionalProperties(networkIdentifiers.additionalProperties) } /** * A globally unique transaction identifier provided by the card network, used * across multiple life-cycle requests. */ fun transactionId(transactionId: String) = transactionId(JsonField.of(transactionId)) /** * A globally unique transaction identifier provided by the card network, used * across multiple life-cycle requests. */ @JsonProperty("transaction_id") @ExcludeMissing fun transactionId(transactionId: JsonField<String>) = apply { this.transactionId = transactionId } /** * A counter used to verify an individual authorization. Expected to be unique per * acquirer within a window of time. */ fun traceNumber(traceNumber: String) = traceNumber(JsonField.of(traceNumber)) /** * A counter used to verify an individual authorization. Expected to be unique per * acquirer within a window of time. */ @JsonProperty("trace_number") @ExcludeMissing fun traceNumber(traceNumber: JsonField<String>) = apply { this.traceNumber = traceNumber } /** * A life-cycle identifier used across e.g., an authorization and a reversal. * Expected to be unique per acquirer within a window of time. For some card * networks the retrieval reference number includes the trace counter. */ fun retrievalReferenceNumber(retrievalReferenceNumber: String) = retrievalReferenceNumber(JsonField.of(retrievalReferenceNumber)) /** * A life-cycle identifier used across e.g., an authorization and a reversal. * Expected to be unique per acquirer within a window of time. For some card * networks the retrieval reference number includes the trace counter. */ @JsonProperty("retrieval_reference_number") @ExcludeMissing fun retrievalReferenceNumber(retrievalReferenceNumber: JsonField<String>) = apply { this.retrievalReferenceNumber = retrievalReferenceNumber } fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.putAll(additionalProperties) } fun build(): NetworkIdentifiers = NetworkIdentifiers( transactionId, traceNumber, retrievalReferenceNumber, additionalProperties.toUnmodifiable(), ) } } class ProcessingCategory @JsonCreator private constructor( private val value: JsonField<String>, ) { @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is ProcessingCategory && this.value == other.value } override fun hashCode() = value.hashCode() override fun toString() = value.toString() companion object { val ACCOUNT_FUNDING = ProcessingCategory(JsonField.of("account_funding")) val AUTOMATIC_FUEL_DISPENSER = ProcessingCategory(JsonField.of("automatic_fuel_dispenser")) val BILL_PAYMENT = ProcessingCategory(JsonField.of("bill_payment")) val PURCHASE = ProcessingCategory(JsonField.of("purchase")) val QUASI_CASH = ProcessingCategory(JsonField.of("quasi_cash")) val REFUND = ProcessingCategory(JsonField.of("refund")) fun of(value: String) = ProcessingCategory(JsonField.of(value)) } enum class Known { ACCOUNT_FUNDING, AUTOMATIC_FUEL_DISPENSER, BILL_PAYMENT, PURCHASE, QUASI_CASH, REFUND, } enum class Value { ACCOUNT_FUNDING, AUTOMATIC_FUEL_DISPENSER, BILL_PAYMENT, PURCHASE, QUASI_CASH, REFUND, _UNKNOWN, } fun value(): Value = when (this) { ACCOUNT_FUNDING -> Value.ACCOUNT_FUNDING AUTOMATIC_FUEL_DISPENSER -> Value.AUTOMATIC_FUEL_DISPENSER BILL_PAYMENT -> Value.BILL_PAYMENT PURCHASE -> Value.PURCHASE QUASI_CASH -> Value.QUASI_CASH REFUND -> Value.REFUND else -> Value._UNKNOWN } fun known(): Known = when (this) { ACCOUNT_FUNDING -> Known.ACCOUNT_FUNDING AUTOMATIC_FUEL_DISPENSER -> Known.AUTOMATIC_FUEL_DISPENSER BILL_PAYMENT -> Known.BILL_PAYMENT PURCHASE -> Known.PURCHASE QUASI_CASH -> Known.QUASI_CASH REFUND -> Known.REFUND else -> throw IncreaseInvalidDataException("Unknown ProcessingCategory: $value") } fun asString(): String = _value().asStringOrThrow() } /** Fields specific to the type of request, such as an incremental authorization. */ @JsonDeserialize(builder = RequestDetails.Builder::class) @NoAutoDetect class RequestDetails private constructor( private val category: JsonField<Category>, private val initialAuthorization: JsonValue, private val incrementalAuthorization: JsonField<IncrementalAuthorization>, private val additionalProperties: Map<String, JsonValue>, ) { private var validated: Boolean = false private var hashCode: Int = 0 /** * The type of this request (e.g., an initial authorization or an incremental * authorization). */ fun category(): Category = category.getRequired("category") /** Fields specific to the category `incremental_authorization`. */ fun incrementalAuthorization(): IncrementalAuthorization? = incrementalAuthorization.getNullable("incremental_authorization") /** * The type of this request (e.g., an initial authorization or an incremental * authorization). */ @JsonProperty("category") @ExcludeMissing fun _category() = category /** Fields specific to the category `initial_authorization`. */ @JsonProperty("initial_authorization") @ExcludeMissing fun _initialAuthorization() = initialAuthorization /** Fields specific to the category `incremental_authorization`. */ @JsonProperty("incremental_authorization") @ExcludeMissing fun _incrementalAuthorization() = incrementalAuthorization @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun validate(): RequestDetails = apply { if (!validated) { category() incrementalAuthorization()?.validate() validated = true } } fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is RequestDetails && this.category == other.category && this.initialAuthorization == other.initialAuthorization && this.incrementalAuthorization == other.incrementalAuthorization && this.additionalProperties == other.additionalProperties } override fun hashCode(): Int { if (hashCode == 0) { hashCode = Objects.hash( category, initialAuthorization, incrementalAuthorization, additionalProperties, ) } return hashCode } override fun toString() = "RequestDetails{category=$category, initialAuthorization=$initialAuthorization, incrementalAuthorization=$incrementalAuthorization, additionalProperties=$additionalProperties}" companion object { fun builder() = Builder() } class Builder { private var category: JsonField<Category> = JsonMissing.of() private var initialAuthorization: JsonValue = JsonMissing.of() private var incrementalAuthorization: JsonField<IncrementalAuthorization> = JsonMissing.of() private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from(requestDetails: RequestDetails) = apply { this.category = requestDetails.category this.initialAuthorization = requestDetails.initialAuthorization this.incrementalAuthorization = requestDetails.incrementalAuthorization additionalProperties(requestDetails.additionalProperties) } /** * The type of this request (e.g., an initial authorization or an incremental * authorization). */ fun category(category: Category) = category(JsonField.of(category)) /** * The type of this request (e.g., an initial authorization or an incremental * authorization). */ @JsonProperty("category") @ExcludeMissing fun category(category: JsonField<Category>) = apply { this.category = category } /** Fields specific to the category `initial_authorization`. */ @JsonProperty("initial_authorization") @ExcludeMissing fun initialAuthorization(initialAuthorization: JsonValue) = apply { this.initialAuthorization = initialAuthorization } /** Fields specific to the category `incremental_authorization`. */ fun incrementalAuthorization(incrementalAuthorization: IncrementalAuthorization) = incrementalAuthorization(JsonField.of(incrementalAuthorization)) /** Fields specific to the category `incremental_authorization`. */ @JsonProperty("incremental_authorization") @ExcludeMissing fun incrementalAuthorization( incrementalAuthorization: JsonField<IncrementalAuthorization> ) = apply { this.incrementalAuthorization = incrementalAuthorization } fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.putAll(additionalProperties) } fun build(): RequestDetails = RequestDetails( category, initialAuthorization, incrementalAuthorization, additionalProperties.toUnmodifiable(), ) } class Category @JsonCreator private constructor( private val value: JsonField<String>, ) { @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is Category && this.value == other.value } override fun hashCode() = value.hashCode() override fun toString() = value.toString() companion object { val INITIAL_AUTHORIZATION = Category(JsonField.of("initial_authorization")) val INCREMENTAL_AUTHORIZATION = Category(JsonField.of("incremental_authorization")) fun of(value: String) = Category(JsonField.of(value)) } enum class Known { INITIAL_AUTHORIZATION, INCREMENTAL_AUTHORIZATION, } enum class Value { INITIAL_AUTHORIZATION, INCREMENTAL_AUTHORIZATION, _UNKNOWN, } fun value(): Value = when (this) { INITIAL_AUTHORIZATION -> Value.INITIAL_AUTHORIZATION INCREMENTAL_AUTHORIZATION -> Value.INCREMENTAL_AUTHORIZATION else -> Value._UNKNOWN } fun known(): Known = when (this) { INITIAL_AUTHORIZATION -> Known.INITIAL_AUTHORIZATION INCREMENTAL_AUTHORIZATION -> Known.INCREMENTAL_AUTHORIZATION else -> throw IncreaseInvalidDataException("Unknown Category: $value") } fun asString(): String = _value().asStringOrThrow() } /** Fields specific to the category `incremental_authorization`. */ @JsonDeserialize(builder = IncrementalAuthorization.Builder::class) @NoAutoDetect class IncrementalAuthorization private constructor( private val cardPaymentId: JsonField<String>, private val originalCardAuthorizationId: JsonField<String>, private val additionalProperties: Map<String, JsonValue>, ) { private var validated: Boolean = false private var hashCode: Int = 0 /** The card payment for this authorization and increment. */ fun cardPaymentId(): String = cardPaymentId.getRequired("card_payment_id") /** * The identifier of the card authorization this request is attempting to increment. */ fun originalCardAuthorizationId(): String = originalCardAuthorizationId.getRequired("original_card_authorization_id") /** The card payment for this authorization and increment. */ @JsonProperty("card_payment_id") @ExcludeMissing fun _cardPaymentId() = cardPaymentId /** * The identifier of the card authorization this request is attempting to increment. */ @JsonProperty("original_card_authorization_id") @ExcludeMissing fun _originalCardAuthorizationId() = originalCardAuthorizationId @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun validate(): IncrementalAuthorization = apply { if (!validated) { cardPaymentId() originalCardAuthorizationId() validated = true } } fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is IncrementalAuthorization && this.cardPaymentId == other.cardPaymentId && this.originalCardAuthorizationId == other.originalCardAuthorizationId && this.additionalProperties == other.additionalProperties } override fun hashCode(): Int { if (hashCode == 0) { hashCode = Objects.hash( cardPaymentId, originalCardAuthorizationId, additionalProperties, ) } return hashCode } override fun toString() = "IncrementalAuthorization{cardPaymentId=$cardPaymentId, originalCardAuthorizationId=$originalCardAuthorizationId, additionalProperties=$additionalProperties}" companion object { fun builder() = Builder() } class Builder { private var cardPaymentId: JsonField<String> = JsonMissing.of() private var originalCardAuthorizationId: JsonField<String> = JsonMissing.of() private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from(incrementalAuthorization: IncrementalAuthorization) = apply { this.cardPaymentId = incrementalAuthorization.cardPaymentId this.originalCardAuthorizationId = incrementalAuthorization.originalCardAuthorizationId additionalProperties(incrementalAuthorization.additionalProperties) } /** The card payment for this authorization and increment. */ fun cardPaymentId(cardPaymentId: String) = cardPaymentId(JsonField.of(cardPaymentId)) /** The card payment for this authorization and increment. */ @JsonProperty("card_payment_id") @ExcludeMissing fun cardPaymentId(cardPaymentId: JsonField<String>) = apply { this.cardPaymentId = cardPaymentId } /** * The identifier of the card authorization this request is attempting to * increment. */ fun originalCardAuthorizationId(originalCardAuthorizationId: String) = originalCardAuthorizationId(JsonField.of(originalCardAuthorizationId)) /** * The identifier of the card authorization this request is attempting to * increment. */ @JsonProperty("original_card_authorization_id") @ExcludeMissing fun originalCardAuthorizationId( originalCardAuthorizationId: JsonField<String> ) = apply { this.originalCardAuthorizationId = originalCardAuthorizationId } fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.putAll(additionalProperties) } fun build(): IncrementalAuthorization = IncrementalAuthorization( cardPaymentId, originalCardAuthorizationId, additionalProperties.toUnmodifiable(), ) } } } /** Fields related to verification of cardholder-provided values. */ @JsonDeserialize(builder = Verification.Builder::class) @NoAutoDetect class Verification private constructor( private val cardholderAddress: JsonField<CardholderAddress>, private val cardVerificationCode: JsonField<CardVerificationCode>, private val additionalProperties: Map<String, JsonValue>, ) { private var validated: Boolean = false private var hashCode: Int = 0 /** * Cardholder address provided in the authorization request and the address on file we * verified it against. */ fun cardholderAddress(): CardholderAddress = cardholderAddress.getRequired("cardholder_address") /** * Fields related to verification of the Card Verification Code, a 3-digit code on the * back of the card. */ fun cardVerificationCode(): CardVerificationCode = cardVerificationCode.getRequired("card_verification_code") /** * Cardholder address provided in the authorization request and the address on file we * verified it against. */ @JsonProperty("cardholder_address") @ExcludeMissing fun _cardholderAddress() = cardholderAddress /** * Fields related to verification of the Card Verification Code, a 3-digit code on the * back of the card. */ @JsonProperty("card_verification_code") @ExcludeMissing fun _cardVerificationCode() = cardVerificationCode @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun validate(): Verification = apply { if (!validated) { cardholderAddress().validate() cardVerificationCode().validate() validated = true } } fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is Verification && this.cardholderAddress == other.cardholderAddress && this.cardVerificationCode == other.cardVerificationCode && this.additionalProperties == other.additionalProperties } override fun hashCode(): Int { if (hashCode == 0) { hashCode = Objects.hash( cardholderAddress, cardVerificationCode, additionalProperties, ) } return hashCode } override fun toString() = "Verification{cardholderAddress=$cardholderAddress, cardVerificationCode=$cardVerificationCode, additionalProperties=$additionalProperties}" companion object { fun builder() = Builder() } class Builder { private var cardholderAddress: JsonField<CardholderAddress> = JsonMissing.of() private var cardVerificationCode: JsonField<CardVerificationCode> = JsonMissing.of() private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from(verification: Verification) = apply { this.cardholderAddress = verification.cardholderAddress this.cardVerificationCode = verification.cardVerificationCode additionalProperties(verification.additionalProperties) } /** * Cardholder address provided in the authorization request and the address on file * we verified it against. */ fun cardholderAddress(cardholderAddress: CardholderAddress) = cardholderAddress(JsonField.of(cardholderAddress)) /** * Cardholder address provided in the authorization request and the address on file * we verified it against. */ @JsonProperty("cardholder_address") @ExcludeMissing fun cardholderAddress(cardholderAddress: JsonField<CardholderAddress>) = apply { this.cardholderAddress = cardholderAddress } /** * Fields related to verification of the Card Verification Code, a 3-digit code on * the back of the card. */ fun cardVerificationCode(cardVerificationCode: CardVerificationCode) = cardVerificationCode(JsonField.of(cardVerificationCode)) /** * Fields related to verification of the Card Verification Code, a 3-digit code on * the back of the card. */ @JsonProperty("card_verification_code") @ExcludeMissing fun cardVerificationCode(cardVerificationCode: JsonField<CardVerificationCode>) = apply { this.cardVerificationCode = cardVerificationCode } fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.putAll(additionalProperties) } fun build(): Verification = Verification( cardholderAddress, cardVerificationCode, additionalProperties.toUnmodifiable(), ) } /** * Fields related to verification of the Card Verification Code, a 3-digit code on the * back of the card. */ @JsonDeserialize(builder = CardVerificationCode.Builder::class) @NoAutoDetect class CardVerificationCode private constructor( private val result: JsonField<Result>, private val additionalProperties: Map<String, JsonValue>, ) { private var validated: Boolean = false private var hashCode: Int = 0 /** The result of verifying the Card Verification Code. */ fun result(): Result = result.getRequired("result") /** The result of verifying the Card Verification Code. */ @JsonProperty("result") @ExcludeMissing fun _result() = result @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun validate(): CardVerificationCode = apply { if (!validated) { result() validated = true } } fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is CardVerificationCode && this.result == other.result && this.additionalProperties == other.additionalProperties } override fun hashCode(): Int { if (hashCode == 0) { hashCode = Objects.hash(result, additionalProperties) } return hashCode } override fun toString() = "CardVerificationCode{result=$result, additionalProperties=$additionalProperties}" companion object { fun builder() = Builder() } class Builder { private var result: JsonField<Result> = JsonMissing.of() private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from(cardVerificationCode: CardVerificationCode) = apply { this.result = cardVerificationCode.result additionalProperties(cardVerificationCode.additionalProperties) } /** The result of verifying the Card Verification Code. */ fun result(result: Result) = result(JsonField.of(result)) /** The result of verifying the Card Verification Code. */ @JsonProperty("result") @ExcludeMissing fun result(result: JsonField<Result>) = apply { this.result = result } fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.putAll(additionalProperties) } fun build(): CardVerificationCode = CardVerificationCode(result, additionalProperties.toUnmodifiable()) } class Result @JsonCreator private constructor( private val value: JsonField<String>, ) { @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is Result && this.value == other.value } override fun hashCode() = value.hashCode() override fun toString() = value.toString() companion object { val NOT_CHECKED = Result(JsonField.of("not_checked")) val MATCH = Result(JsonField.of("match")) val NO_MATCH = Result(JsonField.of("no_match")) fun of(value: String) = Result(JsonField.of(value)) } enum class Known { NOT_CHECKED, MATCH, NO_MATCH, } enum class Value { NOT_CHECKED, MATCH, NO_MATCH, _UNKNOWN, } fun value(): Value = when (this) { NOT_CHECKED -> Value.NOT_CHECKED MATCH -> Value.MATCH NO_MATCH -> Value.NO_MATCH else -> Value._UNKNOWN } fun known(): Known = when (this) { NOT_CHECKED -> Known.NOT_CHECKED MATCH -> Known.MATCH NO_MATCH -> Known.NO_MATCH else -> throw IncreaseInvalidDataException("Unknown Result: $value") } fun asString(): String = _value().asStringOrThrow() } } /** * Cardholder address provided in the authorization request and the address on file we * verified it against. */ @JsonDeserialize(builder = CardholderAddress.Builder::class) @NoAutoDetect class CardholderAddress private constructor( private val providedPostalCode: JsonField<String>, private val providedLine1: JsonField<String>, private val actualPostalCode: JsonField<String>, private val actualLine1: JsonField<String>, private val result: JsonField<Result>, private val additionalProperties: Map<String, JsonValue>, ) { private var validated: Boolean = false private var hashCode: Int = 0 /** The postal code provided for verification in the authorization request. */ fun providedPostalCode(): String? = providedPostalCode.getNullable("provided_postal_code") /** * The cardholder address line 1 provided for verification in the authorization * request. */ fun providedLine1(): String? = providedLine1.getNullable("provided_line1") /** The postal code of the address on file for the cardholder. */ fun actualPostalCode(): String? = actualPostalCode.getNullable("actual_postal_code") /** Line 1 of the address on file for the cardholder. */ fun actualLine1(): String? = actualLine1.getNullable("actual_line1") /** The address verification result returned to the card network. */ fun result(): Result = result.getRequired("result") /** The postal code provided for verification in the authorization request. */ @JsonProperty("provided_postal_code") @ExcludeMissing fun _providedPostalCode() = providedPostalCode /** * The cardholder address line 1 provided for verification in the authorization * request. */ @JsonProperty("provided_line1") @ExcludeMissing fun _providedLine1() = providedLine1 /** The postal code of the address on file for the cardholder. */ @JsonProperty("actual_postal_code") @ExcludeMissing fun _actualPostalCode() = actualPostalCode /** Line 1 of the address on file for the cardholder. */ @JsonProperty("actual_line1") @ExcludeMissing fun _actualLine1() = actualLine1 /** The address verification result returned to the card network. */ @JsonProperty("result") @ExcludeMissing fun _result() = result @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun validate(): CardholderAddress = apply { if (!validated) { providedPostalCode() providedLine1() actualPostalCode() actualLine1() result() validated = true } } fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is CardholderAddress && this.providedPostalCode == other.providedPostalCode && this.providedLine1 == other.providedLine1 && this.actualPostalCode == other.actualPostalCode && this.actualLine1 == other.actualLine1 && this.result == other.result && this.additionalProperties == other.additionalProperties } override fun hashCode(): Int { if (hashCode == 0) { hashCode = Objects.hash( providedPostalCode, providedLine1, actualPostalCode, actualLine1, result, additionalProperties, ) } return hashCode } override fun toString() = "CardholderAddress{providedPostalCode=$providedPostalCode, providedLine1=$providedLine1, actualPostalCode=$actualPostalCode, actualLine1=$actualLine1, result=$result, additionalProperties=$additionalProperties}" companion object { fun builder() = Builder() } class Builder { private var providedPostalCode: JsonField<String> = JsonMissing.of() private var providedLine1: JsonField<String> = JsonMissing.of() private var actualPostalCode: JsonField<String> = JsonMissing.of() private var actualLine1: JsonField<String> = JsonMissing.of() private var result: JsonField<Result> = JsonMissing.of() private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from(cardholderAddress: CardholderAddress) = apply { this.providedPostalCode = cardholderAddress.providedPostalCode this.providedLine1 = cardholderAddress.providedLine1 this.actualPostalCode = cardholderAddress.actualPostalCode this.actualLine1 = cardholderAddress.actualLine1 this.result = cardholderAddress.result additionalProperties(cardholderAddress.additionalProperties) } /** The postal code provided for verification in the authorization request. */ fun providedPostalCode(providedPostalCode: String) = providedPostalCode(JsonField.of(providedPostalCode)) /** The postal code provided for verification in the authorization request. */ @JsonProperty("provided_postal_code") @ExcludeMissing fun providedPostalCode(providedPostalCode: JsonField<String>) = apply { this.providedPostalCode = providedPostalCode } /** * The cardholder address line 1 provided for verification in the authorization * request. */ fun providedLine1(providedLine1: String) = providedLine1(JsonField.of(providedLine1)) /** * The cardholder address line 1 provided for verification in the authorization * request. */ @JsonProperty("provided_line1") @ExcludeMissing fun providedLine1(providedLine1: JsonField<String>) = apply { this.providedLine1 = providedLine1 } /** The postal code of the address on file for the cardholder. */ fun actualPostalCode(actualPostalCode: String) = actualPostalCode(JsonField.of(actualPostalCode)) /** The postal code of the address on file for the cardholder. */ @JsonProperty("actual_postal_code") @ExcludeMissing fun actualPostalCode(actualPostalCode: JsonField<String>) = apply { this.actualPostalCode = actualPostalCode } /** Line 1 of the address on file for the cardholder. */ fun actualLine1(actualLine1: String) = actualLine1(JsonField.of(actualLine1)) /** Line 1 of the address on file for the cardholder. */ @JsonProperty("actual_line1") @ExcludeMissing fun actualLine1(actualLine1: JsonField<String>) = apply { this.actualLine1 = actualLine1 } /** The address verification result returned to the card network. */ fun result(result: Result) = result(JsonField.of(result)) /** The address verification result returned to the card network. */ @JsonProperty("result") @ExcludeMissing fun result(result: JsonField<Result>) = apply { this.result = result } fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.putAll(additionalProperties) } fun build(): CardholderAddress = CardholderAddress( providedPostalCode, providedLine1, actualPostalCode, actualLine1, result, additionalProperties.toUnmodifiable(), ) } class Result @JsonCreator private constructor( private val value: JsonField<String>, ) { @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is Result && this.value == other.value } override fun hashCode() = value.hashCode() override fun toString() = value.toString() companion object { val NOT_CHECKED = Result(JsonField.of("not_checked")) val POSTAL_CODE_MATCH_ADDRESS_NOT_CHECKED = Result(JsonField.of("postal_code_match_address_not_checked")) val POSTAL_CODE_MATCH_ADDRESS_NO_MATCH = Result(JsonField.of("postal_code_match_address_no_match")) val POSTAL_CODE_NO_MATCH_ADDRESS_MATCH = Result(JsonField.of("postal_code_no_match_address_match")) val MATCH = Result(JsonField.of("match")) val NO_MATCH = Result(JsonField.of("no_match")) fun of(value: String) = Result(JsonField.of(value)) } enum class Known { NOT_CHECKED, POSTAL_CODE_MATCH_ADDRESS_NOT_CHECKED, POSTAL_CODE_MATCH_ADDRESS_NO_MATCH, POSTAL_CODE_NO_MATCH_ADDRESS_MATCH, MATCH, NO_MATCH, } enum class Value { NOT_CHECKED, POSTAL_CODE_MATCH_ADDRESS_NOT_CHECKED, POSTAL_CODE_MATCH_ADDRESS_NO_MATCH, POSTAL_CODE_NO_MATCH_ADDRESS_MATCH, MATCH, NO_MATCH, _UNKNOWN, } fun value(): Value = when (this) { NOT_CHECKED -> Value.NOT_CHECKED POSTAL_CODE_MATCH_ADDRESS_NOT_CHECKED -> Value.POSTAL_CODE_MATCH_ADDRESS_NOT_CHECKED POSTAL_CODE_MATCH_ADDRESS_NO_MATCH -> Value.POSTAL_CODE_MATCH_ADDRESS_NO_MATCH POSTAL_CODE_NO_MATCH_ADDRESS_MATCH -> Value.POSTAL_CODE_NO_MATCH_ADDRESS_MATCH MATCH -> Value.MATCH NO_MATCH -> Value.NO_MATCH else -> Value._UNKNOWN } fun known(): Known = when (this) { NOT_CHECKED -> Known.NOT_CHECKED POSTAL_CODE_MATCH_ADDRESS_NOT_CHECKED -> Known.POSTAL_CODE_MATCH_ADDRESS_NOT_CHECKED POSTAL_CODE_MATCH_ADDRESS_NO_MATCH -> Known.POSTAL_CODE_MATCH_ADDRESS_NO_MATCH POSTAL_CODE_NO_MATCH_ADDRESS_MATCH -> Known.POSTAL_CODE_NO_MATCH_ADDRESS_MATCH MATCH -> Known.MATCH NO_MATCH -> Known.NO_MATCH else -> throw IncreaseInvalidDataException("Unknown Result: $value") } fun asString(): String = _value().asStringOrThrow() } } } } class Category @JsonCreator private constructor( private val value: JsonField<String>, ) { @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is Category && this.value == other.value } override fun hashCode() = value.hashCode() override fun toString() = value.toString() companion object { val CARD_AUTHORIZATION_REQUESTED = Category(JsonField.of("card_authorization_requested")) val DIGITAL_WALLET_TOKEN_REQUESTED = Category(JsonField.of("digital_wallet_token_requested")) val DIGITAL_WALLET_AUTHENTICATION_REQUESTED = Category(JsonField.of("digital_wallet_authentication_requested")) fun of(value: String) = Category(JsonField.of(value)) } enum class Known { CARD_AUTHORIZATION_REQUESTED, DIGITAL_WALLET_TOKEN_REQUESTED, DIGITAL_WALLET_AUTHENTICATION_REQUESTED, } enum class Value { CARD_AUTHORIZATION_REQUESTED, DIGITAL_WALLET_TOKEN_REQUESTED, DIGITAL_WALLET_AUTHENTICATION_REQUESTED, _UNKNOWN, } fun value(): Value = when (this) { CARD_AUTHORIZATION_REQUESTED -> Value.CARD_AUTHORIZATION_REQUESTED DIGITAL_WALLET_TOKEN_REQUESTED -> Value.DIGITAL_WALLET_TOKEN_REQUESTED DIGITAL_WALLET_AUTHENTICATION_REQUESTED -> Value.DIGITAL_WALLET_AUTHENTICATION_REQUESTED else -> Value._UNKNOWN } fun known(): Known = when (this) { CARD_AUTHORIZATION_REQUESTED -> Known.CARD_AUTHORIZATION_REQUESTED DIGITAL_WALLET_TOKEN_REQUESTED -> Known.DIGITAL_WALLET_TOKEN_REQUESTED DIGITAL_WALLET_AUTHENTICATION_REQUESTED -> Known.DIGITAL_WALLET_AUTHENTICATION_REQUESTED else -> throw IncreaseInvalidDataException("Unknown Category: $value") } fun asString(): String = _value().asStringOrThrow() } /** Fields related to a digital wallet authentication attempt. */ @JsonDeserialize(builder = DigitalWalletAuthentication.Builder::class) @NoAutoDetect class DigitalWalletAuthentication private constructor( private val result: JsonField<Result>, private val cardId: JsonField<String>, private val digitalWallet: JsonField<DigitalWallet>, private val channel: JsonField<Channel>, private val oneTimePasscode: JsonField<String>, private val phone: JsonField<String>, private val email: JsonField<String>, private val additionalProperties: Map<String, JsonValue>, ) { private var validated: Boolean = false private var hashCode: Int = 0 /** Whether your application successfully delivered the one-time passcode. */ fun result(): Result? = result.getNullable("result") /** The identifier of the Card that is being tokenized. */ fun cardId(): String = cardId.getRequired("card_id") /** The digital wallet app being used. */ fun digitalWallet(): DigitalWallet = digitalWallet.getRequired("digital_wallet") /** The channel to send the card user their one-time passcode. */ fun channel(): Channel = channel.getRequired("channel") /** The one-time passcode to send the card user. */ fun oneTimePasscode(): String = oneTimePasscode.getRequired("one_time_passcode") /** The phone number to send the one-time passcode to if `channel` is equal to `sms`. */ fun phone(): String? = phone.getNullable("phone") /** The email to send the one-time passcode to if `channel` is equal to `email`. */ fun email(): String? = email.getNullable("email") /** Whether your application successfully delivered the one-time passcode. */ @JsonProperty("result") @ExcludeMissing fun _result() = result /** The identifier of the Card that is being tokenized. */ @JsonProperty("card_id") @ExcludeMissing fun _cardId() = cardId /** The digital wallet app being used. */ @JsonProperty("digital_wallet") @ExcludeMissing fun _digitalWallet() = digitalWallet /** The channel to send the card user their one-time passcode. */ @JsonProperty("channel") @ExcludeMissing fun _channel() = channel /** The one-time passcode to send the card user. */ @JsonProperty("one_time_passcode") @ExcludeMissing fun _oneTimePasscode() = oneTimePasscode /** The phone number to send the one-time passcode to if `channel` is equal to `sms`. */ @JsonProperty("phone") @ExcludeMissing fun _phone() = phone /** The email to send the one-time passcode to if `channel` is equal to `email`. */ @JsonProperty("email") @ExcludeMissing fun _email() = email @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun validate(): DigitalWalletAuthentication = apply { if (!validated) { result() cardId() digitalWallet() channel() oneTimePasscode() phone() email() validated = true } } fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is DigitalWalletAuthentication && this.result == other.result && this.cardId == other.cardId && this.digitalWallet == other.digitalWallet && this.channel == other.channel && this.oneTimePasscode == other.oneTimePasscode && this.phone == other.phone && this.email == other.email && this.additionalProperties == other.additionalProperties } override fun hashCode(): Int { if (hashCode == 0) { hashCode = Objects.hash( result, cardId, digitalWallet, channel, oneTimePasscode, phone, email, additionalProperties, ) } return hashCode } override fun toString() = "DigitalWalletAuthentication{result=$result, cardId=$cardId, digitalWallet=$digitalWallet, channel=$channel, oneTimePasscode=$oneTimePasscode, phone=$phone, email=$email, additionalProperties=$additionalProperties}" companion object { fun builder() = Builder() } class Builder { private var result: JsonField<Result> = JsonMissing.of() private var cardId: JsonField<String> = JsonMissing.of() private var digitalWallet: JsonField<DigitalWallet> = JsonMissing.of() private var channel: JsonField<Channel> = JsonMissing.of() private var oneTimePasscode: JsonField<String> = JsonMissing.of() private var phone: JsonField<String> = JsonMissing.of() private var email: JsonField<String> = JsonMissing.of() private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from(digitalWalletAuthentication: DigitalWalletAuthentication) = apply { this.result = digitalWalletAuthentication.result this.cardId = digitalWalletAuthentication.cardId this.digitalWallet = digitalWalletAuthentication.digitalWallet this.channel = digitalWalletAuthentication.channel this.oneTimePasscode = digitalWalletAuthentication.oneTimePasscode this.phone = digitalWalletAuthentication.phone this.email = digitalWalletAuthentication.email additionalProperties(digitalWalletAuthentication.additionalProperties) } /** Whether your application successfully delivered the one-time passcode. */ fun result(result: Result) = result(JsonField.of(result)) /** Whether your application successfully delivered the one-time passcode. */ @JsonProperty("result") @ExcludeMissing fun result(result: JsonField<Result>) = apply { this.result = result } /** The identifier of the Card that is being tokenized. */ fun cardId(cardId: String) = cardId(JsonField.of(cardId)) /** The identifier of the Card that is being tokenized. */ @JsonProperty("card_id") @ExcludeMissing fun cardId(cardId: JsonField<String>) = apply { this.cardId = cardId } /** The digital wallet app being used. */ fun digitalWallet(digitalWallet: DigitalWallet) = digitalWallet(JsonField.of(digitalWallet)) /** The digital wallet app being used. */ @JsonProperty("digital_wallet") @ExcludeMissing fun digitalWallet(digitalWallet: JsonField<DigitalWallet>) = apply { this.digitalWallet = digitalWallet } /** The channel to send the card user their one-time passcode. */ fun channel(channel: Channel) = channel(JsonField.of(channel)) /** The channel to send the card user their one-time passcode. */ @JsonProperty("channel") @ExcludeMissing fun channel(channel: JsonField<Channel>) = apply { this.channel = channel } /** The one-time passcode to send the card user. */ fun oneTimePasscode(oneTimePasscode: String) = oneTimePasscode(JsonField.of(oneTimePasscode)) /** The one-time passcode to send the card user. */ @JsonProperty("one_time_passcode") @ExcludeMissing fun oneTimePasscode(oneTimePasscode: JsonField<String>) = apply { this.oneTimePasscode = oneTimePasscode } /** The phone number to send the one-time passcode to if `channel` is equal to `sms`. */ fun phone(phone: String) = phone(JsonField.of(phone)) /** The phone number to send the one-time passcode to if `channel` is equal to `sms`. */ @JsonProperty("phone") @ExcludeMissing fun phone(phone: JsonField<String>) = apply { this.phone = phone } /** The email to send the one-time passcode to if `channel` is equal to `email`. */ fun email(email: String) = email(JsonField.of(email)) /** The email to send the one-time passcode to if `channel` is equal to `email`. */ @JsonProperty("email") @ExcludeMissing fun email(email: JsonField<String>) = apply { this.email = email } fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.putAll(additionalProperties) } fun build(): DigitalWalletAuthentication = DigitalWalletAuthentication( result, cardId, digitalWallet, channel, oneTimePasscode, phone, email, additionalProperties.toUnmodifiable(), ) } class Channel @JsonCreator private constructor( private val value: JsonField<String>, ) { @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is Channel && this.value == other.value } override fun hashCode() = value.hashCode() override fun toString() = value.toString() companion object { val SMS = Channel(JsonField.of("sms")) val EMAIL = Channel(JsonField.of("email")) fun of(value: String) = Channel(JsonField.of(value)) } enum class Known { SMS, EMAIL, } enum class Value { SMS, EMAIL, _UNKNOWN, } fun value(): Value = when (this) { SMS -> Value.SMS EMAIL -> Value.EMAIL else -> Value._UNKNOWN } fun known(): Known = when (this) { SMS -> Known.SMS EMAIL -> Known.EMAIL else -> throw IncreaseInvalidDataException("Unknown Channel: $value") } fun asString(): String = _value().asStringOrThrow() } class DigitalWallet @JsonCreator private constructor( private val value: JsonField<String>, ) { @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is DigitalWallet && this.value == other.value } override fun hashCode() = value.hashCode() override fun toString() = value.toString() companion object { val APPLE_PAY = DigitalWallet(JsonField.of("apple_pay")) val GOOGLE_PAY = DigitalWallet(JsonField.of("google_pay")) val UNKNOWN = DigitalWallet(JsonField.of("unknown")) fun of(value: String) = DigitalWallet(JsonField.of(value)) } enum class Known { APPLE_PAY, GOOGLE_PAY, UNKNOWN, } enum class Value { APPLE_PAY, GOOGLE_PAY, UNKNOWN, _UNKNOWN, } fun value(): Value = when (this) { APPLE_PAY -> Value.APPLE_PAY GOOGLE_PAY -> Value.GOOGLE_PAY UNKNOWN -> Value.UNKNOWN else -> Value._UNKNOWN } fun known(): Known = when (this) { APPLE_PAY -> Known.APPLE_PAY GOOGLE_PAY -> Known.GOOGLE_PAY UNKNOWN -> Known.UNKNOWN else -> throw IncreaseInvalidDataException("Unknown DigitalWallet: $value") } fun asString(): String = _value().asStringOrThrow() } class Result @JsonCreator private constructor( private val value: JsonField<String>, ) { @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is Result && this.value == other.value } override fun hashCode() = value.hashCode() override fun toString() = value.toString() companion object { val SUCCESS = Result(JsonField.of("success")) val FAILURE = Result(JsonField.of("failure")) fun of(value: String) = Result(JsonField.of(value)) } enum class Known { SUCCESS, FAILURE, } enum class Value { SUCCESS, FAILURE, _UNKNOWN, } fun value(): Value = when (this) { SUCCESS -> Value.SUCCESS FAILURE -> Value.FAILURE else -> Value._UNKNOWN } fun known(): Known = when (this) { SUCCESS -> Known.SUCCESS FAILURE -> Known.FAILURE else -> throw IncreaseInvalidDataException("Unknown Result: $value") } fun asString(): String = _value().asStringOrThrow() } } /** Fields related to a digital wallet token provisioning attempt. */ @JsonDeserialize(builder = DigitalWalletToken.Builder::class) @NoAutoDetect class DigitalWalletToken private constructor( private val decision: JsonField<Decision>, private val cardId: JsonField<String>, private val digitalWallet: JsonField<DigitalWallet>, private val cardProfileId: JsonField<String>, private val additionalProperties: Map<String, JsonValue>, ) { private var validated: Boolean = false private var hashCode: Int = 0 /** * Whether or not the provisioning request was approved. This will be null until the real * time decision is responded to. */ fun decision(): Decision? = decision.getNullable("decision") /** The identifier of the Card that is being tokenized. */ fun cardId(): String = cardId.getRequired("card_id") /** The digital wallet app being used. */ fun digitalWallet(): DigitalWallet = digitalWallet.getRequired("digital_wallet") /** * The identifier of the Card Profile that was set via the real time decision. This will be * null until the real time decision is responded to or if the real time decision did not * set a card profile. */ fun cardProfileId(): String? = cardProfileId.getNullable("card_profile_id") /** * Whether or not the provisioning request was approved. This will be null until the real * time decision is responded to. */ @JsonProperty("decision") @ExcludeMissing fun _decision() = decision /** The identifier of the Card that is being tokenized. */ @JsonProperty("card_id") @ExcludeMissing fun _cardId() = cardId /** The digital wallet app being used. */ @JsonProperty("digital_wallet") @ExcludeMissing fun _digitalWallet() = digitalWallet /** * The identifier of the Card Profile that was set via the real time decision. This will be * null until the real time decision is responded to or if the real time decision did not * set a card profile. */ @JsonProperty("card_profile_id") @ExcludeMissing fun _cardProfileId() = cardProfileId @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun validate(): DigitalWalletToken = apply { if (!validated) { decision() cardId() digitalWallet() cardProfileId() validated = true } } fun toBuilder() = Builder().from(this) override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is DigitalWalletToken && this.decision == other.decision && this.cardId == other.cardId && this.digitalWallet == other.digitalWallet && this.cardProfileId == other.cardProfileId && this.additionalProperties == other.additionalProperties } override fun hashCode(): Int { if (hashCode == 0) { hashCode = Objects.hash( decision, cardId, digitalWallet, cardProfileId, additionalProperties, ) } return hashCode } override fun toString() = "DigitalWalletToken{decision=$decision, cardId=$cardId, digitalWallet=$digitalWallet, cardProfileId=$cardProfileId, additionalProperties=$additionalProperties}" companion object { fun builder() = Builder() } class Builder { private var decision: JsonField<Decision> = JsonMissing.of() private var cardId: JsonField<String> = JsonMissing.of() private var digitalWallet: JsonField<DigitalWallet> = JsonMissing.of() private var cardProfileId: JsonField<String> = JsonMissing.of() private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from(digitalWalletToken: DigitalWalletToken) = apply { this.decision = digitalWalletToken.decision this.cardId = digitalWalletToken.cardId this.digitalWallet = digitalWalletToken.digitalWallet this.cardProfileId = digitalWalletToken.cardProfileId additionalProperties(digitalWalletToken.additionalProperties) } /** * Whether or not the provisioning request was approved. This will be null until the * real time decision is responded to. */ fun decision(decision: Decision) = decision(JsonField.of(decision)) /** * Whether or not the provisioning request was approved. This will be null until the * real time decision is responded to. */ @JsonProperty("decision") @ExcludeMissing fun decision(decision: JsonField<Decision>) = apply { this.decision = decision } /** The identifier of the Card that is being tokenized. */ fun cardId(cardId: String) = cardId(JsonField.of(cardId)) /** The identifier of the Card that is being tokenized. */ @JsonProperty("card_id") @ExcludeMissing fun cardId(cardId: JsonField<String>) = apply { this.cardId = cardId } /** The digital wallet app being used. */ fun digitalWallet(digitalWallet: DigitalWallet) = digitalWallet(JsonField.of(digitalWallet)) /** The digital wallet app being used. */ @JsonProperty("digital_wallet") @ExcludeMissing fun digitalWallet(digitalWallet: JsonField<DigitalWallet>) = apply { this.digitalWallet = digitalWallet } /** * The identifier of the Card Profile that was set via the real time decision. This will * be null until the real time decision is responded to or if the real time decision did * not set a card profile. */ fun cardProfileId(cardProfileId: String) = cardProfileId(JsonField.of(cardProfileId)) /** * The identifier of the Card Profile that was set via the real time decision. This will * be null until the real time decision is responded to or if the real time decision did * not set a card profile. */ @JsonProperty("card_profile_id") @ExcludeMissing fun cardProfileId(cardProfileId: JsonField<String>) = apply { this.cardProfileId = cardProfileId } fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.putAll(additionalProperties) } fun build(): DigitalWalletToken = DigitalWalletToken( decision, cardId, digitalWallet, cardProfileId, additionalProperties.toUnmodifiable(), ) } class Decision @JsonCreator private constructor( private val value: JsonField<String>, ) { @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is Decision && this.value == other.value } override fun hashCode() = value.hashCode() override fun toString() = value.toString() companion object { val APPROVE = Decision(JsonField.of("approve")) val DECLINE = Decision(JsonField.of("decline")) fun of(value: String) = Decision(JsonField.of(value)) } enum class Known { APPROVE, DECLINE, } enum class Value { APPROVE, DECLINE, _UNKNOWN, } fun value(): Value = when (this) { APPROVE -> Value.APPROVE DECLINE -> Value.DECLINE else -> Value._UNKNOWN } fun known(): Known = when (this) { APPROVE -> Known.APPROVE DECLINE -> Known.DECLINE else -> throw IncreaseInvalidDataException("Unknown Decision: $value") } fun asString(): String = _value().asStringOrThrow() } class DigitalWallet @JsonCreator private constructor( private val value: JsonField<String>, ) { @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is DigitalWallet && this.value == other.value } override fun hashCode() = value.hashCode() override fun toString() = value.toString() companion object { val APPLE_PAY = DigitalWallet(JsonField.of("apple_pay")) val GOOGLE_PAY = DigitalWallet(JsonField.of("google_pay")) val UNKNOWN = DigitalWallet(JsonField.of("unknown")) fun of(value: String) = DigitalWallet(JsonField.of(value)) } enum class Known { APPLE_PAY, GOOGLE_PAY, UNKNOWN, } enum class Value { APPLE_PAY, GOOGLE_PAY, UNKNOWN, _UNKNOWN, } fun value(): Value = when (this) { APPLE_PAY -> Value.APPLE_PAY GOOGLE_PAY -> Value.GOOGLE_PAY UNKNOWN -> Value.UNKNOWN else -> Value._UNKNOWN } fun known(): Known = when (this) { APPLE_PAY -> Known.APPLE_PAY GOOGLE_PAY -> Known.GOOGLE_PAY UNKNOWN -> Known.UNKNOWN else -> throw IncreaseInvalidDataException("Unknown DigitalWallet: $value") } fun asString(): String = _value().asStringOrThrow() } } class Status @JsonCreator private constructor( private val value: JsonField<String>, ) { @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is Status && this.value == other.value } override fun hashCode() = value.hashCode() override fun toString() = value.toString() companion object { val PENDING = Status(JsonField.of("pending")) val RESPONDED = Status(JsonField.of("responded")) val TIMED_OUT = Status(JsonField.of("timed_out")) fun of(value: String) = Status(JsonField.of(value)) } enum class Known { PENDING, RESPONDED, TIMED_OUT, } enum class Value { PENDING, RESPONDED, TIMED_OUT, _UNKNOWN, } fun value(): Value = when (this) { PENDING -> Value.PENDING RESPONDED -> Value.RESPONDED TIMED_OUT -> Value.TIMED_OUT else -> Value._UNKNOWN } fun known(): Known = when (this) { PENDING -> Known.PENDING RESPONDED -> Known.RESPONDED TIMED_OUT -> Known.TIMED_OUT else -> throw IncreaseInvalidDataException("Unknown Status: $value") } fun asString(): String = _value().asStringOrThrow() } class Type @JsonCreator private constructor( private val value: JsonField<String>, ) { @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is Type && this.value == other.value } override fun hashCode() = value.hashCode() override fun toString() = value.toString() companion object { val REAL_TIME_DECISION = Type(JsonField.of("real_time_decision")) fun of(value: String) = Type(JsonField.of(value)) } enum class Known { REAL_TIME_DECISION, } enum class Value { REAL_TIME_DECISION, _UNKNOWN, } fun value(): Value = when (this) { REAL_TIME_DECISION -> Value.REAL_TIME_DECISION else -> Value._UNKNOWN } fun known(): Known = when (this) { REAL_TIME_DECISION -> Known.REAL_TIME_DECISION else -> throw IncreaseInvalidDataException("Unknown Type: $value") } fun asString(): String = _value().asStringOrThrow() } }
0
Kotlin
0
2
496494b0adf5480bab91f61b7a6decbfe3a129fa
155,508
increase-kotlin
Apache License 2.0
app/src/main/java/com/irateam/vkplayer/player/PlaylistPlayNextEvent.kt
IRA-Team
42,990,339
false
null
package com.irateam.vkplayer.player import com.irateam.vkplayer.event.Event class PlaylistPlayNextEvent : Event { val playNextPosition: Int val playNextSize: Int val playlistPosition: Int constructor(playNextPosition: Int, playNextSize: Int, playlistPosition: Int) { this.playNextPosition = playNextPosition this.playNextSize = playNextSize this.playlistPosition = playlistPosition } }
3
Kotlin
12
39
9d57e78a5ba29375d453aa0b117b74d1d22c0b5d
434
VKPlayer
Apache License 2.0
application/src/main/kotlin/com/coach/flame/api/coach/response/CoachResponse.kt
FlameNutrition
333,186,829
false
null
package com.coach.flame.api.coach.response import java.util.* data class CoachResponse( val identifier: UUID, val clientsCoach: Set<ClientCoach> = setOf() )
20
Kotlin
0
0
7c1c498be8afbb39848a2f6eb27e97099ebda58f
166
flame-coach-service
MIT License
application/src/main/kotlin/com/coach/flame/api/client/request/EnrollmentRequest.kt
FlameNutrition
333,186,829
false
null
package com.coach.flame.api.client.request import java.util.* data class EnrollmentRequest( val client: UUID?, val coach: UUID?, val accept: Boolean?, )
20
Kotlin
0
0
7c1c498be8afbb39848a2f6eb27e97099ebda58f
166
flame-coach-service
MIT License
src/test/kotlin/ca/wheatstalk/resticagent/restic/WrappedCommandTest.kt
misterjoshua
185,891,996
false
null
package ca.wheatstalk.resticagent.restic import ca.wheatstalk.resticagent.command.NoOpCommand import ca.wheatstalk.resticagent.command.SequenceCommand import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test internal class WrappedCommandTest { @Test fun myTest() { val context = ResticConfig() val parser = CommandStringParser(resticConfig = context) val backupCommand = parser.parse("backup") as SequenceCommand assertTrue(backupCommand.sequence[0] is NoOpCommand) assertTrue(backupCommand.sequence[1].toString().contains("restic backup")) assertTrue(backupCommand.sequence[2] is NoOpCommand) val restorecommand = parser.parse("restore latest") as SequenceCommand assertTrue(restorecommand.sequence[0] is NoOpCommand) assertTrue(restorecommand.sequence[1].toString().contains("restic restore")) assertTrue(restorecommand.sequence[2] is NoOpCommand) assertFalse(parser.parse("snapshots") is SequenceCommand) } }
0
Kotlin
0
0
94974ba5e54db7057e4d80685753505577881bcc
1,096
restic-backup-agent
Apache License 2.0
api/coroutines/v1.5.4/src/commonMain/kotlin/dev/whyoleg/ktd/api/message/GetChatHistory.kt
whyoleg
202,767,670
false
null
@file:Suppress( "unused" ) @file:UseExperimental( BotsOnly::class, TestingOnly::class ) package dev.whyoleg.ktd.api.message import dev.whyoleg.ktd.* import dev.whyoleg.ktd.api.* import dev.whyoleg.ktd.api.TdApi.* /** * Returns messages in a chat * The messages are returned in a reverse chronological order (i.e., in order of decreasing message_id) * For optimal performance the number of returned messages is chosen by the library * This is an offline request if only_local is true * * @chatId - Chat identifier * @fromMessageId - Identifier of the message starting from which history must be fetched * Use 0 to get results from the last message * @offset - Specify 0 to get results from exactly the from_message_id or a negative offset up to 99 to get additionally some newer messages * @limit - The maximum number of messages to be returned * Must be positive and can't be greater than 100 * If the offset is negative, the limit must be greater or equal to -offset * Fewer messages may be returned than specified by the limit, even if the end of the message history has not been reached * @onlyLocal - If true, returns only messages that are available locally without sending network requests */ suspend fun TelegramClient.getChatHistory( chatId: Long = 0L, fromMessageId: Long = 0L, offset: Int = 0, limit: Int = 0, onlyLocal: Boolean = false ): Messages = message( GetChatHistory( chatId, fromMessageId, offset, limit, onlyLocal ) ) /** * Returns messages in a chat * The messages are returned in a reverse chronological order (i.e., in order of decreasing message_id) * For optimal performance the number of returned messages is chosen by the library * This is an offline request if only_local is true */ suspend fun TelegramClient.message( f: GetChatHistory ): Messages = exec(f) as Messages
7
Kotlin
10
45
7284eeabef0bd002dc72634351ab751b048900e9
1,951
ktd
Apache License 2.0
service/src/test/kotlin/io/provenance/api/util/TestHelper.kt
provenance-io
480,452,118
false
{"Kotlin": 210541, "Shell": 13707}
package io.provenance.api.util import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.google.protobuf.AbstractMessage.Builder import com.google.protobuf.Message import com.google.protobuf.util.JsonFormat import java.io.File import java.nio.file.Paths const val TEST_DATA_FOLDER = "TestData/" object TestHelper { fun getDataFromFile(fileName: String): String = File( Paths.get( this.javaClass.classLoader.getResource("$TEST_DATA_FOLDER$fileName").toURI() ).toString() ).readText(Charsets.UTF_8) inline fun <reified T : Message> getTestDataToProtobuf(fileName: String, clazz: Class<T>): List<T> = jacksonObjectMapper().readTree( getDataFromFile(fileName) ).map { jsonNode -> (clazz.getMethod("newBuilder").invoke(null) as Builder<*>) .also { builder -> JsonFormat.parser().merge( jacksonObjectMapper().writeValueAsString(jsonNode), builder ) }.build() as T } }
5
Kotlin
6
1
5ffb3f5760cbff388eafd3e969311adaded9de74
1,115
p8e-cee-api
Apache License 2.0
api/coroutines/v1.5.4/src/commonMain/kotlin/dev/whyoleg/ktd/api/animation/AddSavedAnimation.kt
whyoleg
202,767,670
false
null
@file:Suppress( "unused" ) @file:UseExperimental( BotsOnly::class, TestingOnly::class ) package dev.whyoleg.ktd.api.animation import dev.whyoleg.ktd.* import dev.whyoleg.ktd.api.* import dev.whyoleg.ktd.api.TdApi.* /** * Manually adds a new animation to the list of saved animations * The new animation is added to the beginning of the list * If the animation was already in the list, it is removed first * Only non-secret video animations with MIME type "video/mp4" can be added to the list * * @animation - The animation file to be added * Only animations known to the server (i.e * Successfully sent via a message) can be added to the list */ suspend fun TelegramClient.addSavedAnimation( animation: InputFile? = null ): Ok = animation( AddSavedAnimation( animation ) ) /** * Manually adds a new animation to the list of saved animations * The new animation is added to the beginning of the list * If the animation was already in the list, it is removed first * Only non-secret video animations with MIME type "video/mp4" can be added to the list */ suspend fun TelegramClient.animation( f: AddSavedAnimation ): Ok = exec(f) as Ok
7
Kotlin
10
45
7284eeabef0bd002dc72634351ab751b048900e9
1,214
ktd
Apache License 2.0
data/persistence/src/main/kotlin/com/melih/persistence/converters/BaseListConverter.kt
melihaksoy
194,683,166
false
null
package com.melih.persistence.converters import androidx.room.TypeConverter import com.squareup.moshi.JsonAdapter import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory /** * Base converter for reduced boilerplate code */ abstract class BaseListConverter<T> { //region Abstractions abstract fun getAdapter(moshi: Moshi): JsonAdapter<List<T>> //endregion //region Properties private val moshi = Moshi.Builder() .add(KotlinJsonAdapterFactory()) .build() //endregion //region Functions @TypeConverter fun convertFrom(items: List<T>) = getAdapter(moshi).toJson(items) @TypeConverter fun convertTo(string: String): List<T>? = getAdapter(moshi).fromJson(string) //endregion }
8
Kotlin
38
356
1bcde286ddff6d81862687cd55893042065c68cd
804
Android-Kotlin-Modulerized-CleanArchitecture
Apache License 2.0
mobile_app1/module1248/src/main/java/module1248packageKt0/Foo574.kt
uber-common
294,831,672
false
null
package module1248packageKt0; annotation class Foo574Fancy @Foo574Fancy class Foo574 { fun foo0(){ module1248packageKt0.Foo573().foo6() } fun foo1(){ foo0() } fun foo2(){ foo1() } fun foo3(){ foo2() } fun foo4(){ foo3() } fun foo5(){ foo4() } fun foo6(){ foo5() } }
6
Java
6
72
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
329
android-build-eval
Apache License 2.0
app/src/main/java/org/asghari/guardiannews/domain/usecases/SaveSelectedSectionsUseCase.kt
asgrdev
568,400,588
false
{"Kotlin": 119697}
package org.asghari.guardiannews.domain.usecases import org.asghari.guardiannews.domain.repositories.SettingsRepository import javax.inject.Inject class SaveSelectedSectionsUseCase @Inject constructor(private val settingsRepository: SettingsRepository) { operator suspend fun invoke(section:String) { settingsRepository.getSelectedSections().collect{ currentSections -> var newSections:MutableList<String> = currentSections.split(",").toMutableList() if(section !in newSections) { newSections.add(section) } val section_ids = newSections.joinToString(",") settingsRepository.addSection(section_ids); } } }
0
Kotlin
1
4
e165facdbdba899b78edf0e4cfc7ca1a849e8d8a
701
GuardianNews
MIT License
game/src/main/kotlin/com/runt9/heroDynasty/character/attribute/Attributes.kt
runt9
130,910,358
false
null
package com.runt9.heroDynasty.character.attribute import com.runt9.heroDynasty.character.Modifier class Attributes(physical: Int, mental: Int, social: Int, luck: Int) { private val physical = Physical(physical) private val mental = Mental(mental) private val social = Social(social) private val luck = Luck(luck) fun copy() = Attributes(physical.value, mental.value, social.value, luck.value) fun getModifiers(): List<Modifier> { val modifiers = mutableListOf<Modifier>() modifiers.addAll(physical.getModifiers()) modifiers.addAll(mental.getModifiers()) modifiers.addAll(social.getModifiers()) modifiers.addAll(luck.getModifiers()) return modifiers } fun forEach(loop: (Attribute) -> Unit) { loop(physical) loop(mental) loop(social) loop(luck) } }
0
Kotlin
0
0
87be0aa7394a2980145768ee315797a3e1655ff0
869
hero-dynasty
MIT License
app/src/main/java/com/tiagohs/hqr/ui/contracts/SourcesContract.kt
tiagohs
135,235,006
false
null
package com.tiagohs.hqr.ui.contracts import com.tiagohs.hqr.models.database.CatalogueSource import com.tiagohs.hqr.ui.presenter.config.IPresenter import com.tiagohs.hqr.ui.views.config.IView class SourcesContract { interface ISourcesView: IView { fun onBindSources(sources: List<CatalogueSource>) } interface ISourcesPresenter: IPresenter<ISourcesView> { fun getAllSources() } }
1
Kotlin
2
11
8a86fa1c66a9ba52afcf02bea4acbb674d8a473a
416
hqr-comics-reader
Apache License 2.0
src/main/kotlin/com/skillw/itemsystem/internal/core/meta/bukkit/MetaFlags.kt
Skillw
522,072,132
false
{"Kotlin": 183714, "JavaScript": 14111}
package com.skillw.itemsystem.internal.core.meta.bukkit import com.skillw.itemsystem.api.builder.ItemData import com.skillw.itemsystem.api.meta.BaseMeta import com.skillw.itemsystem.api.meta.data.Memory import com.skillw.pouvoir.api.plugin.annotation.AutoRegister import org.bukkit.inventory.ItemFlag import taboolib.common5.Coerce @AutoRegister object MetaFlags : BaseMeta("flags") { override val priority = 8 override val default = emptyList<String>() override fun invoke(memory: Memory) { with(memory) { builder.flags.addAll(getList("flags").map { Coerce.toEnum(it, ItemFlag::class.java) }) } } override fun loadData(data: ItemData): Any { data.itemTag.remove("HideFlags") return data.builder.flags.map { it.name } } }
2
Kotlin
2
5
1e913b805a9e5416c9afb653b011c90cd1e0522a
825
ItemSystem
Creative Commons Zero v1.0 Universal
foundation/src/test/kotlin/com/walletconnect/foundation/adapters/TtlAdapterTest.kt
WalletConnect
435,951,419
false
{"Kotlin": 2031812, "Java": 4358, "Shell": 1892}
package com.walletconnect.foundation.adapters import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import com.walletconnect.foundation.common.adapters.TtlAdapter import com.walletconnect.foundation.common.model.Ttl import junit.framework.TestCase.assertEquals import org.junit.Test class TtlAdapterTest { private val moshi = Moshi.Builder() .add { _, _, _ -> TtlAdapter } .add(KotlinJsonAdapterFactory()) .build() @Test fun toJson() { val ttl = Ttl(100L) val expected = """"${ttl.seconds}"""" val ttlJson = moshi.adapter(Ttl::class.java).toJson(ttl) assertEquals(expected, """"$ttlJson"""") } }
157
Kotlin
76
172
e86a4194a5bb37e9f66feec4192d108dadfa4e81
736
WalletConnectKotlinV2
Apache License 2.0
login/UserListViewHolder.kt
theethawat
265,786,697
false
{"Kotlin": 185651}
package com.cnr.phr_android.dashboard.monitor.login import android.support.v7.widget.RecyclerView import android.view.View class UserListViewHolder (userListView: View): RecyclerView.ViewHolder(userListView){ }
2
Kotlin
1
0
c1232e8877e50cefe83b3b59f648ea16ea4fd69b
213
cnrphr-open
Apache License 2.0
src/main/kotlin/io/github/guttenbase/mapping/ColumnTypeMapping.kt
guttenbase
644,774,036
false
{"Kotlin": 532982, "PLpgSQL": 271}
package io.github.guttenbase.mapping import io.github.guttenbase.meta.ColumnType /** * Container for column type mapping information. * * &copy; 2012-2034 akquinet tech@spree * * @author <NAME> */ data class ColumnTypeMapping( val sourceColumnType: ColumnType, val targetColumnType: ColumnType, val columnDataMapper: ColumnDataMapper )
0
Kotlin
0
0
2c9dc459e2d85fc541066dbe6d193d7dae6b46da
352
guttenbase
Apache License 2.0
plotlykt-core/src/jsMain/kotlin/scientifik/plotly/Plotly.kt
jfftonsic
232,934,146
true
{"Kotlin": 43324, "JavaScript": 2633}
package scientifik.plotly import org.w3c.dom.Element @JsName("Plotly") external object PlotlyJs { fun newPlot( graphDiv: Element, data: dynamic = definedExternally, layout: dynamic = definedExternally, config: dynamic = definedExternally ) fun restyle(graphDiv: Element, update: dynamic, traceIndices: dynamic = definedExternally) fun relayout(graphDiv: Element, update: dynamic) }
0
Kotlin
0
0
e2ffdea55d9149b0b07e764f67206619f0374c4b
433
plotly.kt
Apache License 2.0
app/src/test/kotlin/compiler/regex/RegexTest.kt
brzeczyk-compiler
545,707,939
false
{"Kotlin": 1167879, "C": 4004, "Shell": 3242, "Vim Script": 2238}
/* * This Kotlin source file was generated by the Gradle 'init' task. */ package compiler.regex import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotEquals import kotlin.test.assertTrue private val ATOMIC_AB = Regex.Atomic(setOf('a', 'b')) private val ATOMIC_AC = Regex.Atomic(setOf('a', 'c')) private val EMPTY = Regex.Empty<Char>() private val EPSILON = Regex.Epsilon<Char>() private val CONCAT_EP_EM = Regex.Concat(EPSILON, EMPTY) private val CONCAT_EM_EP = Regex.Concat(EMPTY, EPSILON) private val STAR_AB = Regex.Star(ATOMIC_AB) private val UNION_EP_EM = Regex.Union(EPSILON, EMPTY) private val UNION_EM_EP = Regex.Union(EMPTY, EPSILON) class RegexTest { @Test fun `test empty does not contain epsilon`() { val reg = Regex.Empty<Char>() assertFalse(reg.containsEpsilon()) } @Test fun `test epsilon contains epsilon`() { val reg = Regex.Epsilon<Char>() assertTrue(reg.containsEpsilon()) } @Test fun `test atomic does not contain epsilon`() { val reg = Regex.Atomic(setOf('a', 'b', 'c')) assertFalse(reg.containsEpsilon()) } @Test fun `test star contains epsilon`() { val reg = Regex.Star(Regex.Empty<Char>()) assertTrue(reg.containsEpsilon()) } @Test fun `test unions with epsilon`() { val reg1 = Regex.Union( Regex.Epsilon(), Regex.Atomic(setOf('d', 'e', 'f')), ) val reg2 = Regex.Union( Regex.Atomic(setOf('d', 'e', 'f')), Regex.Star(Regex.Empty()), ) assertTrue(reg1.containsEpsilon()) assertTrue(reg2.containsEpsilon()) } @Test fun `test unions with no epsilon`() { val reg1 = Regex.Union( Regex.Atomic(setOf('a', 'b', 'c')), Regex.Atomic(setOf('d', 'e', 'f')), ) val reg2 = Regex.Union( Regex.Concat(Regex.Epsilon(), Regex.Atomic(setOf('x'))), Regex.Concat(Regex.Atomic(setOf('y')), Regex.Star(Regex.Empty())), ) assertFalse(reg1.containsEpsilon()) assertFalse(reg2.containsEpsilon()) } @Test fun `test concats with epsilon`() { val reg1 = Regex.Concat<Char>( Regex.Epsilon(), Regex.Epsilon(), ) val reg2 = Regex.Concat( Regex.Star(Regex.Atomic(setOf('q'))), Regex.Union(Regex.Epsilon(), Regex.Atomic(setOf('w'))) ) assertTrue(reg1.containsEpsilon()) assertTrue(reg2.containsEpsilon()) } @Test fun `test concats with no epsilon`() { val reg1 = Regex.Concat( Regex.Epsilon(), Regex.Atomic(setOf('d', 'e', 'f')), ) val reg2 = Regex.Concat<Char>( Regex.Empty(), Regex.Star(Regex.Empty()), ) assertFalse(reg1.containsEpsilon()) assertFalse(reg2.containsEpsilon()) } @Test fun `test derivative of empty is empty`() { val reg = RegexFactory.createEmpty<Char>() assertTrue(reg.derivative('a') is Regex.Empty) } @Test fun `test derivative of epsilon is empty`() { val reg = RegexFactory.createEpsilon<Char>() assertTrue(reg.derivative('a') is Regex.Empty) } @Test fun `test derivative of atomic with proper atom is epsilon`() { val reg = RegexFactory.createAtomic(setOf('a')) assertTrue(reg.derivative('a') is Regex.Epsilon) } @Test fun `test derivative of atomic with no proper atom is empty`() { val reg = RegexFactory.createAtomic(setOf('a')) assertTrue(reg.derivative('b') is Regex.Empty) } @Test fun `test derivatives of star`() { // (ab)* --a--> b(ab)* val reg = RegexFactory.createStar( RegexFactory.createConcat( RegexFactory.createAtomic(setOf('a')), RegexFactory.createAtomic(setOf('b')), ) ) val expectedDerivative = RegexFactory.createConcat( RegexFactory.createAtomic(setOf('b')), reg ) assertEquals(reg.derivative('a'), expectedDerivative) assertEquals(reg.derivative('b'), EMPTY) } @Test fun `test derivatives of union`() { // (bc)+(bd) --b--> (c)+(d) val reg = RegexFactory.createUnion( RegexFactory.createConcat( RegexFactory.createAtomic(setOf('b')), RegexFactory.createAtomic(setOf('c')), ), RegexFactory.createConcat( RegexFactory.createAtomic(setOf('b')), RegexFactory.createAtomic(setOf('d')), ) ) val expectedDerivative = RegexFactory.createUnion( RegexFactory.createAtomic(setOf('c')), RegexFactory.createAtomic(setOf('d')), ) assertEquals(reg.derivative('b'), expectedDerivative) assertEquals(reg.derivative('a'), EMPTY) } @Test fun `test derivatives of concat`() { // (epsilon+x+y)((y)(z+q)) --x--> (y)(z+q) // (epsilon+x+y)((y)(z+q)) --y--> ((y)(z+q))+(z+q) == (y+epsi)(z+q) val reg = RegexFactory.createConcat( RegexFactory.createUnion( EPSILON, RegexFactory.createAtomic(setOf('x', 'y')) ), RegexFactory.createConcat( RegexFactory.createAtomic(setOf('y')), RegexFactory.createAtomic(setOf('z', 'q')) ) ) val expectedDerivativeX = RegexFactory.createConcat( RegexFactory.createAtomic(setOf('y')), RegexFactory.createAtomic(setOf('z', 'q')) ) val expectedDerivativeY = RegexFactory.createConcat( RegexFactory.createUnion( RegexFactory.createAtomic(setOf('y')), EPSILON ), RegexFactory.createAtomic(setOf('z', 'q')) ) assertEquals(expectedDerivativeX, reg.derivative('x')) assertEquals(expectedDerivativeY, reg.derivative('y')) assertEquals(EMPTY, reg.derivative('z')) } private fun <T : Comparable<T>> assertOrdered(desiredOrder: List<T>) { for (i in desiredOrder.indices) { for (j in desiredOrder.indices) { if (i > j) assertTrue(desiredOrder[i] > desiredOrder[j]) else if (i < j) assertTrue(desiredOrder[i] < desiredOrder[j]) } } } private fun <T> assertAllNotEqual(elements: List<T>) { for (i in elements.indices) { for (j in elements.indices) { if (i != j) assertNotEquals(elements[i], elements[j]) } } } private fun <T> assertEqualsWellDefined(controlElement: T, equalElement: T, notEqualElement: T) { assertEquals(controlElement, equalElement) assertEquals(controlElement.hashCode(), equalElement.hashCode()) assertNotEquals(controlElement, notEqualElement) } @Test fun `test regexes of different kind are not equal`() { assertAllNotEqual(listOf(ATOMIC_AB, CONCAT_EP_EM, EMPTY, EPSILON, UNION_EP_EM, STAR_AB)) } @Test fun `test equals operator is well defined for regexes of same kind`() { assertEquals<Regex<Char>>(EMPTY, Regex.Empty()) assertEquals(EMPTY.hashCode(), Regex.Empty<Char>().hashCode()) assertEquals<Regex<Char>>(EPSILON, Regex.Epsilon()) assertEquals(EPSILON.hashCode(), Regex.Epsilon<Char>().hashCode()) assertEqualsWellDefined(ATOMIC_AB, Regex.Atomic(setOf('a', 'b')), ATOMIC_AC) assertEqualsWellDefined(STAR_AB, Regex.Star(ATOMIC_AB), Regex.Star(EMPTY)) assertEqualsWellDefined(UNION_EP_EM, Regex.Union(EPSILON, EMPTY), UNION_EM_EP) assertEqualsWellDefined(CONCAT_EP_EM, Regex.Concat(EPSILON, EMPTY), CONCAT_EM_EP) } @Test fun `test regexes are sorted lexicographically by type`() { // also ensures atomic is the smallest, which is important for us assertOrdered(listOf(ATOMIC_AB, CONCAT_EP_EM, EMPTY, EPSILON, STAR_AB, UNION_EP_EM)) } @Test fun `test atomics are sorted lexicographically by chars`() { assertOrdered(listOf(Regex.Atomic(setOf('a')), ATOMIC_AB, ATOMIC_AC)) } @Test fun `test concats are sorted lexicographically by children`() { assertOrdered(listOf(CONCAT_EM_EP, Regex.Concat(EPSILON, ATOMIC_AB), Regex.Concat(EPSILON, ATOMIC_AC), CONCAT_EP_EM)) } @Test fun `test stars are sorted by children`() { assertOrdered(listOf(STAR_AB, Regex.Star(ATOMIC_AC), Regex.Star(EPSILON))) } @Test fun `test unions are sorted lexicographically by children`() { assertOrdered(listOf(UNION_EM_EP, Regex.Union(EPSILON, ATOMIC_AB), Regex.Union(EPSILON, ATOMIC_AC), UNION_EP_EM)) } @Test fun `test atomics comparisons work for strings`() { val a: Regex<String> = Regex.Atomic(setOf("ab", "c")) val b: Regex<String> = Regex.Atomic(setOf("a", "bc")) assertTrue(a > b) } @Test fun `test first method`() { val unionAbAc = Regex.Union(ATOMIC_AB, ATOMIC_AC) val concatEpsAb = Regex.Concat(EPSILON, ATOMIC_AB) val concatAbEps = Regex.Concat(ATOMIC_AB, EPSILON) val unionAbEps = Regex.Union(ATOMIC_AB, EPSILON) val concatEmptyAb = Regex.Concat(EMPTY, ATOMIC_AB) assertEquals(ATOMIC_AB.first(), setOf('a', 'b')) assertEquals(ATOMIC_AC.first(), setOf('a', 'c')) assertEquals(EMPTY.first(), emptySet()) assertEquals(EPSILON.first(), emptySet()) assertEquals(CONCAT_EP_EM.first(), emptySet()) assertEquals(CONCAT_EM_EP.first(), emptySet()) assertEquals(STAR_AB.first(), setOf('a', 'b')) assertEquals(UNION_EP_EM.first(), emptySet()) assertEquals(UNION_EM_EP.first(), emptySet()) assertEquals(unionAbAc.first(), setOf('a', 'b', 'c')) assertEquals(concatEpsAb.first(), setOf('a', 'b')) assertEquals(concatAbEps.first(), setOf('a', 'b')) assertEquals(unionAbEps.first(), setOf('a', 'b')) assertEquals(concatEmptyAb.first(), emptySet()) } }
7
Kotlin
0
2
5917f4f9d0c13c2c87d02246da8ef8394499d33c
10,178
brzeczyk
MIT License
app/src/main/java/com/example/hotplenavigation/view/bottom_menu/search/search_result/SearchResultActivityViewModel.kt
HanBI24
469,585,277
false
{"Kotlin": 103866}
package com.example.hotplenavigation.view.bottom_menu.search.search_result import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.hotplenavigation.data.geo.Addresse import com.example.hotplenavigation.data.geo_reverse.Result1 import com.example.hotplenavigation.data.get_result_path.Traavoidtoll import com.example.hotplenavigation.data.search_result.Item import com.example.hotplenavigation.database.BookmarkFragmentEntity import com.example.hotplenavigation.repository.GetGeoCodeRepository import com.example.hotplenavigation.repository.GetResultPathRepository import com.example.hotplenavigation.repository.GetReverseGeoCodeRepository import com.example.hotplenavigation.repository.GetSearchResultRepository import com.naver.maps.map.overlay.Marker import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject // 20165304 김성곤 // API와 통신하여 필요한 데이터를 필터링하는 ViewModel @HiltViewModel class SearchResultActivityViewModel @Inject constructor( // Repository 패턴을 사용하여 API 응답 값을 받아옴 private val getResultPathRepository: GetResultPathRepository, private val getReverseGeoCodeRepository: GetReverseGeoCodeRepository, private val getSearchResultRepository: GetSearchResultRepository, private val getGeoCodeRepository: GetGeoCodeRepository ) : ViewModel() { private val _getResultPath = MutableLiveData<List<Traavoidtoll>>() val getResultPath: LiveData<List<Traavoidtoll>> get() = _getResultPath private val _getResultPathGuide = MutableLiveData<List<Traavoidtoll>>() val getResultPathGuide: LiveData<List<Traavoidtoll>> get() = _getResultPathGuide private val _geoCode = MutableLiveData<Result1>() val geoCode: LiveData<Result1> get() = _geoCode private val _searchResult = MutableLiveData<List<Item>>() val searchResult: LiveData<List<Item>> get() = _searchResult private val _regionMutableLiveList = MutableLiveData<Set<String>>() val regionMutableLiveList: MutableLiveData<Set<String>> get() = _regionMutableLiveList private val _geoCodeLatLng = MutableLiveData<Addresse>() val getCodeLatLng: LiveData<Addresse> get() = _geoCodeLatLng private val data = arrayListOf<BookmarkFragmentEntity>() private val _bookmarkData = MutableLiveData<BookmarkFragmentEntity>() val bookmarkData: LiveData<BookmarkFragmentEntity> get() = _bookmarkData private val _getInitialGeoCode = MutableLiveData<Addresse>() val getInitialGeoCode: LiveData<Addresse> get() = _getInitialGeoCode val bottomTitle = MutableLiveData<String>() val bottomAddress = MutableLiveData<String>() val bottomMarker = MutableLiveData<Marker>() // Naver Direction 5 API를 사용하여 경로 데이터 받아옴 fun getResultPath( apiKeyId: String, apiKey: String, start: String, goal: String, option: String ) { getResultPathRepository.makeGetResultPathApiCall(apiKeyId, apiKey, start, goal, option, _getResultPath) } // Naver Reverse Geo API를 사용하여 위도, 경도 값을 위치 정보로 변환 fun getReverseGeoApi( apiKeyId: String, apiKey: String, coords: String, ) { getReverseGeoCodeRepository.makeReverseGeoApiCall(apiKeyId, apiKey, coords, _geoCode) Log.d("SearchResultViewModel", _geoCode.value.toString()) } // Naver Search API를 사용하여 검색 결과를 받아옴 fun getSearchResult( apiKeyId: String, apiKey: String, display: Int, start: Int, sort: String, query: String, ) { getSearchResultRepository.makeSearchResultApiCall(apiKeyId, apiKey, display, start, sort, query, _searchResult) } // 지역 정보를 추가함 fun addRegionMutableLiveList(region: Set<String>) { _regionMutableLiveList.postValue(region) } // 실제 위치를 위도와 경도로 바꿈 fun getGeoApi( apiKeyId: String, apiKey: String, query: String ) { getGeoCodeRepository.makeGetGeoCodeApiCall(apiKeyId, apiKey, query, _geoCodeLatLng) } // 실제 위치를 위도와 경도로 바꿈 (LiveData 분리를 위함) fun getInitialGeoApi( apiKeyId: String, apiKey: String, query: String ) { getGeoCodeRepository.makeGetGeoCodeApiCall(apiKeyId, apiKey, query, _getInitialGeoCode) } // API 응답을 통한 지역 추가 fun addPlace(resultData: BookmarkFragmentEntity) { _bookmarkData.value = resultData } }
19
Kotlin
0
0
228a87112472ebf81bac1def95a44c7424c3e106
4,755
2022_1_Capston_Edge-Map
MIT License
tl/src/main/kotlin/com/github/badoualy/telegram/tl/api/request/TLRequestMessagesSetInlineGameScore.kt
Miha-x64
436,587,061
true
{"Kotlin": 3919807, "Java": 75352}
package com.github.badoualy.telegram.tl.api.request import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT32 import com.github.badoualy.telegram.tl.api.TLAbsInputBotInlineMessageID import com.github.badoualy.telegram.tl.api.TLAbsInputUser import com.github.badoualy.telegram.tl.api.TLInputBotInlineMessageID import com.github.badoualy.telegram.tl.api.TLInputUserEmpty import com.github.badoualy.telegram.tl.core.TLBool import com.github.badoualy.telegram.tl.core.TLMethod import com.github.badoualy.telegram.tl.serialization.TLDeserializer import com.github.badoualy.telegram.tl.serialization.TLSerializer import java.io.IOException /** * @author <NAME> <EMAIL> * @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a> */ class TLRequestMessagesSetInlineGameScore() : TLMethod<TLBool>() { @Transient var editMessage: Boolean = false @Transient var force: Boolean = false var id: TLAbsInputBotInlineMessageID = TLInputBotInlineMessageID() var userId: TLAbsInputUser = TLInputUserEmpty() var score: Int = 0 private val _constructor: String = "messages.setInlineGameScore#15ad9f64" override val constructorId: Int = CONSTRUCTOR_ID constructor( editMessage: Boolean, force: Boolean, id: TLAbsInputBotInlineMessageID, userId: TLAbsInputUser, score: Int ) : this() { this.editMessage = editMessage this.force = force this.id = id this.userId = userId this.score = score } override fun computeFlags() { _flags = 0 updateFlags(editMessage, 1) updateFlags(force, 2) } @Throws(IOException::class) override fun serializeBody(tlSerializer: TLSerializer) = with (tlSerializer) { computeFlags() writeInt(_flags) writeTLObject(id) writeTLObject(userId) writeInt(score) } @Throws(IOException::class) override fun deserializeBody(tlDeserializer: TLDeserializer) = with (tlDeserializer) { _flags = readInt() editMessage = isMask(1) force = isMask(2) id = readTLObject<TLAbsInputBotInlineMessageID>() userId = readTLObject<TLAbsInputUser>() score = readInt() } override fun computeSerializedSize(): Int { computeFlags() var size = SIZE_CONSTRUCTOR_ID size += SIZE_INT32 size += id.computeSerializedSize() size += userId.computeSerializedSize() size += SIZE_INT32 return size } override fun toString() = _constructor override fun equals(other: Any?): Boolean { if (other !is TLRequestMessagesSetInlineGameScore) return false if (other === this) return true return _flags == other._flags && editMessage == other.editMessage && force == other.force && id == other.id && userId == other.userId && score == other.score } companion object { const val CONSTRUCTOR_ID: Int = 0x15ad9f64 } }
1
Kotlin
2
3
1a8963dce921c1e9ef05b9d1e56d8fbcb1ea1c4b
3,217
kotlogram-resurrected
MIT License
chargebee/src/main/java/com/chargebee/android/repository/AddonRepository.kt
chargebee
279,238,499
false
{"Kotlin": 237717, "Java": 23373, "Shell": 1817}
package com.chargebee.android.repository import com.chargebee.android.Chargebee import com.chargebee.android.models.AddonWrapper import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Header import retrofit2.http.Path internal interface AddonRepository { @GET("v2/addons/{addonId}") suspend fun retrieveAddon( @Header("Authorization") token: String = Chargebee.encodedApiKey, @Path("addonId") addonId: String ): Response<AddonWrapper?> }
7
Kotlin
7
6
aa2276f9fe3a14e4f1f6fc8f71803962b32ab7ad
488
chargebee-android
MIT License
src/main/kotlin/com/pivotstir/gogradle/tasks/GoGrpc.kt
innobead
146,837,567
false
null
package com.pivotstir.gogradle.tasks import com.pivotstir.gogradle.GoPlugin import com.pivotstir.gogradle.GradleSupport import com.pivotstir.gogradle.taskName import com.pivotstir.gogradle.tokens import org.gradle.api.Project import org.gradle.api.tasks.Input import org.gradle.api.tasks.Optional import java.io.File class GoGrpcConfig( val project: Project, @Input @Optional var protoDir: File = File("proto"), @Input @Optional var referencePackages: List<String> = emptyList() ) @GradleSupport class GoGrpc : AbstractGoTask<GoGrpcConfig>(GoGrpcConfig::class) { init { group = GoPlugin.NAME description = "Generate gRPC and Protobuf code" dependsOn( taskName(GoDep::class) ) } override fun run() { super.run() val pkgFilePaths = mutableMapOf<String, MutableList<String>>() config.protoDir.walkTopDown().forEach { if (it.isFile) { val result = """package (\S+);""".toRegex().find(it.readText()) if (result != null) { val (pkgName) = result.destructured if (pkgName !in pkgFilePaths) { pkgFilePaths[pkgName] = mutableListOf() } pkgFilePaths[pkgName]!!.add(it.path) } } } logger.lifecycle("Generating go gRPC protobuf stub files") val protocFile = (project.tasks.findByName(taskName(GoDep::class)) as GoDep).protocFile val generatedDir = project.projectDir val gopathDir = task<GoEnv>()!!.goPathDir pkgFilePaths.forEach { _, filePaths -> val cmd = """$protocFile -I${config.protoDir} -I$gopathDir/src -I$gopathDir/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --go_out=plugins=grpc:$generatedDir --grpc-gateway_out=logtostderr=true:$generatedDir --swagger_out=logtostderr=true:$generatedDir ${filePaths.joinToString(" ")}""".trimIndent() logger.lifecycle("Generating gRPC stub files. Cmd: $cmd") exec(cmd.tokens()) { spec -> spec.environment.putAll(this.goEnvs(spec.environment)) } } if (config.referencePackages.isNotEmpty()) { logger.lifecycle("Correcting referenced proto go packagePaths used in other proto go packagePaths by adding module path as prefix path") val pbGoDirs = mutableListOf<File>() pbGoDirs += config.project.projectDir pbGoDirs += config.protoDir.listFiles { it -> return@listFiles it.isDirectory }.map { File(project.projectDir, it.name) } val pbGoFiles = pbGoDirs.flatMap { it.listFiles { f -> return@listFiles f.name.endsWith(".pb.go") }.toList() } logger.lifecycle("$pbGoFiles") config.referencePackages.forEach { pkg -> pbGoFiles.forEach { logger.lifecycle("Updating $it") it.writeText(it.readText().replace("""$pkg "$pkg"""", """$pkg "${pluginExtension.pluginConfig.modulePath}/$pkg"""")) } } } } }
2
Kotlin
4
5
8b877e3d8a288dbf8be75f970ebabc7f74d1fa8b
3,392
gogradle
Apache License 2.0
examples/purchase-tester/src/main/java/com/revenuecat/purchasetester/TesterLogHandler.kt
RevenueCat
127,346,826
false
{"Kotlin": 2835167, "Java": 75428, "Ruby": 27742, "Shell": 443}
package com.revenuecat.purchasetester import android.content.Context import android.os.Handler import android.os.Looper import android.util.Log import android.widget.Toast import com.revenuecat.purchases.LogHandler import com.revenuecat.purchases.LogLevel class TesterLogHandler( private val applicationContext: Context, private val mainHandler: Handler = Handler(Looper.getMainLooper()), ) : LogHandler { val storedLogs: List<LogMessage> get() = mutableStoredLogs private val mutableStoredLogs: MutableList<LogMessage> = mutableListOf() @Synchronized override fun v(tag: String, msg: String) { Log.v(tag, msg) mutableStoredLogs.add(LogMessage(LogLevel.VERBOSE, "$tag: $msg")) } @Synchronized override fun d(tag: String, msg: String) { Log.d(tag, msg) mutableStoredLogs.add(LogMessage(LogLevel.DEBUG, "$tag: $msg")) } @Synchronized override fun i(tag: String, msg: String) { Log.i(tag, msg) mutableStoredLogs.add(LogMessage(LogLevel.INFO, "$tag: $msg")) } @Synchronized override fun w(tag: String, msg: String) { Log.w(tag, msg) mutableStoredLogs.add(LogMessage(LogLevel.WARN, "$tag: $msg")) } @Synchronized override fun e(tag: String, msg: String, throwable: Throwable?) { if (throwable != null) { Log.e(tag, msg, throwable) } else { Log.e(tag, msg) } mutableStoredLogs.add(LogMessage(LogLevel.ERROR, "$tag: $msg, ${throwable?.localizedMessage}")) mainHandler.post { Toast.makeText(applicationContext, "ERROR: $msg", Toast.LENGTH_LONG).show() } } }
23
Kotlin
44
215
aa9f9b89ef4fc2d3429bddc857de31f6c1d68a73
1,691
purchases-android
MIT License
ratpack-kotlin-dsl/src/test/kotlin/ratpack/kotlin/handling/ExtensionsTest.kt
drmaas
60,143,818
false
null
package ratpack.kotlin.handling import com.google.inject.AbstractModule import com.google.inject.Provider import io.kotest.core.spec.style.BehaviorSpec import io.kotest.matchers.shouldBe import ratpack.func.Action import ratpack.guice.BindingsSpec import ratpack.guice.ConfigurableModule import ratpack.guice.Guice import ratpack.registry.Registry import ratpack.server.ServerConfig class ExtensionsTest : BehaviorSpec() { init { given("Module test") { val registry = initialRegistry() `when`("module 1") { val result = registry(registry) { it.module<MyModule>() } then("it works") { result.get<String>() shouldBe "test" } } `when`("module 2") { val result = registry(registry) { it.module<MyConfigurableModule, MyConfig>( Action { it.x = "x" }) } then("it works") { result.get<String>() shouldBe "test" result.get<MyConfig>().x shouldBe "x" } } `when`("moduleConfig 1") { val result = registry(registry) { it.moduleConfig<MyConfigurableModule, MyConfig>(MyConfig("x"), Action { it.x = "y" }) } then("it works") { result.get<String>() shouldBe "test" result.get<MyConfig>().x shouldBe "y" } } `when`("moduleConfig 2") { val result = registry(registry) { it.moduleConfig<MyConfigurableModule, MyConfig>(MyConfig("x")) } then("it works") { result.get<String>() shouldBe "test" result.get<MyConfig>().x shouldBe "x" } } `when`("multiBinder") { val result = registry(registry) { it.multiBinder<String>(Action { it.addBinding().toInstance("x") it.addBinding().toInstance("y") }) } then("it works") { result.get<Set<String>>() shouldBe setOf("x","y") } } `when`("bind") { val result = registry(registry) { it.bind<String>() } then("it works") { result.get<String>() shouldBe "" } } `when`("bindType") { val result = registry(registry) { it.bindType<Test, Test2>() } then("it works") { result.get<Test>().x shouldBe "" } } `when`("multiBind") { val result = registry(registry) { it.multiBind<Test>() } then("it works") { result.get<Test>().x shouldBe "" } } `when`("bindInstance") { val result = registry(registry) { it.bindInstance<Test>(Test("1")) } then("it works") { result.get<Test>().x shouldBe "1" } } `when`("multiBindInstance") { val result = registry(registry) { it.multiBindInstance<Test3>(Test3("1")).multiBindInstance<Test3>(Test3("2")) } then("it works") { result.get<Set<Test>>() shouldBe setOf(Test3("1"), Test3("2")) } } `when`("provider") { val result = registry(registry) { it.provider(Test3Provider()) } then("it works") { result.get<Test3>() shouldBe Test3("1") } } `when`("multiBindProvider") { val result = registry(registry) { it.multiBindProvider(Test3Provider2("1")).multiBindProvider(Test3Provider2("2")) } then("it works") { result.get<Set<Test>>() shouldBe setOf(Test3("1"), Test3("2")) } } } } } fun initialRegistry(): Registry { return Registry.of { it.add(ServerConfig.builder().build()) } } fun registry(registry: Registry, spec: (BindingsSpec) -> Unit): Registry { return Guice.registry(spec).apply(registry) } class MyModule: AbstractModule() { override fun configure() { bind(String::class.java).toInstance("test") } } data class MyConfig(var x: String? = null) class MyConfigurableModule: ConfigurableModule<MyConfig>() { override fun configure() { bind(String::class.java).toInstance("test") } } open class Test(var x: String? = "") class Test2: Test() data class Test3(var x: String? = "") class Test3Provider: Provider<Test3> { override fun get(): Test3 { return Test3("1") } } class Test3Provider2(val x: String): Provider<Test3> { override fun get(): Test3 { return Test3(x) } }
0
Kotlin
11
25
4dd89ae5a967cfec2fee06c83a6f098b3c6c3b44
4,462
ratpack-kotlin
Apache License 2.0
src/main/kotlin/ru/andreyTw/delivery/DeliveryController.kt
AndreyTW
693,493,672
false
{"Kotlin": 19061, "HTML": 1340, "Gherkin": 1288}
package ru.andreyTw.delivery import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RestController import ru.andreyTw.delivery.service.CostCalculationService import ru.andreyTw.delivery.service.clientType.UnknownClientTypeException @RestController class DeliveryController( private val costCalculationService: CostCalculationService ) { @GetMapping("/delivery/{clientType}/{cartAmount}/") @Throws(UnknownClientTypeException::class) fun calculate( @PathVariable("clientType") clientType: String, @PathVariable("cartAmount") cartAmount: Int ): Int = costCalculationService.calculate(clientType, cartAmount) }
0
Kotlin
0
0
8a3ad8cdcd1c12f923a0690d62850d52b873150c
756
delivery-service-kotlin
MIT License
src/main/java/com/example/android/dagger/di/component/UserComponent.kt
ersiver
274,222,129
false
null
package com.example.android.dagger.di.component import com.example.android.dagger.di.scope.LoggedUserScope import com.example.android.dagger.main.MainActivity import com.example.android.dagger.settings.SettingsActivity import dagger.Subcomponent // Scope annotation that the UserComponent uses // Classes annotated with @LoggedUserScope will have a unique instance in this Component @LoggedUserScope @Subcomponent interface UserComponent { @Subcomponent.Factory interface Factory{ fun create() : UserComponent } fun inject(activity: SettingsActivity) fun inject(activity: MainActivity) }
0
Kotlin
0
1
250cb7ec77e7e1793ba9d8819bb72ac99067388d
621
sample-dagger
Apache License 2.0
src/main/kotlin/io/github/hnosmium0001/glfwdemo/minecraft/DemoMod.kt
hnOsmium0001
233,987,874
false
null
package io.github.hnosmium0001.glfwdemo.minecraft import net.alexwells.kottle.FMLKotlinModLoadingContext import net.minecraft.client.Minecraft import net.minecraftforge.fml.common.Mod import org.ice1000.jimgui.JImGui import org.ice1000.jimgui.util.JniLoader @Mod(DemoMod.MODID) object DemoMod { const val MODID = "glfwdemo" // val gui: JImGui init { FMLKotlinModLoadingContext.get().modEventBus.register(RegistryHandler) JniLoader.load() // gui = JImGui.fromExistingPointer(Minecraft.getInstance().mainWindow.handle); // gui.initBeforeMainLoop() } }
0
Kotlin
0
0
a9151967cca8c9a79cf7f87f18e0047fde3b1b85
599
DEMO-MinecraftMod-GLFW-Window
MIT License
app/src/main/java/com/wisnu/kurniawan/composetodolist/features/host/ui/HostScreen.kt
wisnukurniawan
409,054,048
false
{"Kotlin": 701343}
package com.wisnu.kurniawan.composetodolist.features.host.ui import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.wisnu.kurniawan.composetodolist.foundation.theme.Theme @Composable fun Host(content: @Composable () -> Unit) { val viewModel = hiltViewModel<HostViewModel>() val state by viewModel.state.collectAsStateWithLifecycle() Theme(theme = state.theme, content = content) }
12
Kotlin
30
304
bfe3110d9be3283dad70ddad7340419595852b6f
552
Compose-ToDo
Apache License 2.0
library/src/main/java/com/zackratos/ultimatebarx/library/operator/Operator.kt
zhangxu616181
336,448,748
true
{"Kotlin": 51483}
package com.zackratos.ultimatebarx.library.operator import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import com.zackratos.ultimatebarx.library.bean.BarConfig /** * @Author : Zackratos * @Date : 2020/11/27 1:41 * @email : <EMAIL> * @Describe : */ interface Operator { fun applyStatusBar() fun applyNavigationBar() fun config(config: BarConfig): Operator fun transparent(): Operator fun light(light: Boolean): Operator fun fitWindow(fitWindow: Boolean): Operator fun drawableRes(@DrawableRes drawableRes: Int): Operator fun colorRes(@ColorRes colorRes: Int): Operator fun color(@ColorInt color: Int): Operator }
0
null
0
1
f745b50ed93f84dc8efbc74c33eca148fabbc2cc
742
UltimateBarX
Apache License 2.0
tl/src/main/kotlin/com/github/badoualy/telegram/tl/api/TLChannelAdminLogEventActionParticipantVolume.kt
Miha-x64
436,587,061
true
{"Kotlin": 3919807, "Java": 75352}
package com.github.badoualy.telegram.tl.api import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID import com.github.badoualy.telegram.tl.serialization.TLDeserializer import com.github.badoualy.telegram.tl.serialization.TLSerializer import java.io.IOException /** * channelAdminLogEventActionParticipantMute#f92424d2 * * @author <NAME> <EMAIL> * @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a> */ class TLChannelAdminLogEventActionParticipantMute() : TLAbsChannelAdminLogEventAction() { var participant: TLGroupCallParticipant = TLGroupCallParticipant() private val _constructor: String = "channelAdminLogEventActionParticipantMute#f92424d2" override val constructorId: Int = CONSTRUCTOR_ID constructor(participant: TLGroupCallParticipant) : this() { this.participant = participant } @Throws(IOException::class) override fun serializeBody(tlSerializer: TLSerializer) = with (tlSerializer) { writeTLObject(participant) } @Throws(IOException::class) override fun deserializeBody(tlDeserializer: TLDeserializer) = with (tlDeserializer) { participant = readTLObject<TLGroupCallParticipant>(TLGroupCallParticipant::class, TLGroupCallParticipant.CONSTRUCTOR_ID) } override fun computeSerializedSize(): Int { var size = SIZE_CONSTRUCTOR_ID size += participant.computeSerializedSize() return size } override fun toString() = _constructor override fun equals(other: Any?): Boolean { if (other !is TLChannelAdminLogEventActionParticipantMute) return false if (other === this) return true return participant == other.participant } companion object { const val CONSTRUCTOR_ID: Int = 0xf92424d2.toInt() } }
1
Kotlin
2
3
1a8963dce921c1e9ef05b9d1e56d8fbcb1ea1c4b
1,852
kotlogram-resurrected
MIT License
lib-moshi/src/main/java/net/codefeet/lemmyandroidclient/gen/types/BlockPerson.kt
Flex4Reddit
648,927,752
false
null
package net.codefeet.lemmyandroidclient.gen.types import android.os.Parcelable import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import kotlin.Boolean import kotlin.String import kotlinx.parcelize.Parcelize @Parcelize @JsonClass(generateAdapter = true) public data class BlockPerson( @Json(name = "person_id") public val personId: PersonId, public val block: Boolean, public val auth: String, ) : Parcelable
0
Kotlin
0
0
8028bbf4fc50d7c945d20c7034d6da2de4b7c0ac
435
lemmy-android-client
MIT License
app/src/main/java/com/example/yxm/photogenic/ui/fragment/HotWordsFragment.kt
yxmFromTheMoon
230,591,386
false
null
package com.example.yxm.photogenic.ui.fragment import android.view.View import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.yxm.photogenic.R import com.example.yxm.photogenic.base.BaseFragment import com.example.yxm.photogenic.module.hotwords.HotWordsAdapter import com.example.yxm.photogenic.module.hotwords.HotWordsContract import com.example.yxm.photogenic.module.hotwords.HotWordsEvent import com.example.yxm.photogenic.module.hotwords.HotWordsPresenter import com.example.yxm.photogenic.utils.KeyBoardHelper import kotlinx.android.synthetic.main.fragment_hot_words.view.* import org.greenrobot.eventbus.EventBus /** * Created by yxm on 2020-1-16 * @function: 热搜词汇fragment */ class HotWordsFragment : BaseFragment(), HotWordsContract.IHotWordsView { private lateinit var hotWordsRv: RecyclerView private val mAdapter: HotWordsAdapter by lazy { HotWordsAdapter() } private val mHotWordsPresenter: HotWordsPresenter by lazy { HotWordsPresenter() } init { mHotWordsPresenter.attachView(this) } override fun setHotWords(data: ArrayList<String>) { mAdapter.setNewData(data) } override fun showError(msg: String) { showErrorToast("获取热搜失败") } override fun showLoading() { } override fun showSuccess() { } override fun dismissLoading() { } override fun getLayoutId(): Int { return R.layout.fragment_hot_words } override fun initView(view: View) { hotWordsRv = view.hot_words_rv hotWordsRv.run { layoutManager = LinearLayoutManager(mContext) adapter = mAdapter } } override fun initListener() { mAdapter.setOnItemClickListener { adapter, _, position -> val item = adapter.getItem(position) as String KeyBoardHelper.hideKeyBoard(hotWordsRv) EventBus.getDefault().post(HotWordsEvent(item)) } } override fun lazyLoad() { mHotWordsPresenter.getHotWords() } companion object { fun newInstance(): HotWordsFragment = HotWordsFragment() } override fun onDestroyView() { super.onDestroyView() mHotWordsPresenter.detachView() } }
0
Kotlin
2
5
324dd4ed32ae0591082f44ed239d5ea6ff84645e
2,324
Photogenic
The Unlicense
plugin-mute/src/main/kotlin/kr/summitsystems/mute/infrastructure/async/AsyncConfiguration.kt
summit-systems
728,844,161
false
{"Kotlin": 17716}
package kr.summitsystems.mute.infrastructure.async import org.springframework.context.annotation.Configuration import org.springframework.scheduling.annotation.EnableAsync @Configuration @EnableAsync class AsyncConfiguration
0
Kotlin
0
2
dfa44ba7eb59fd7f72b46d7e03dcc57427505b20
226
spring-bukkit-examples
Apache License 2.0
samples/kotlin-dsl/xjc-plugin/build.gradle.kts
unbroken-dome
72,039,967
false
null
plugins { java id("org.unbroken-dome.xjc") version "2.0.0" } repositories { jcenter() } sourceSets.named("main") { xjcExtraArgs.addAll("-Xequals", "-XhashCode", "-XtoString") } dependencies { implementation("javax.xml.bind:jaxb-api:2.3.0") "xjcClasspath"("org.jvnet.jaxb2_commons:jaxb2-basics:0.12.0") // The JAXB2 commons plugins require an additional compile/runtime dependency implementation("org.jvnet.jaxb2_commons:jaxb2-basics-runtime:0.12.0") }
21
Kotlin
17
52
82c1d69e0de91d11a61ae6153f89491adafa3a84
492
gradle-xjc-plugin
MIT License
e2e/pokemon-api/src/main/kotlin/com/redbee/pokemonapi/adapter/rest/model/MoveDamageVO.kt
redbeestudios
295,908,626
false
null
package com.redbee.pokemonapi.adapter.rest.model import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.databind.PropertyNamingStrategy import com.fasterxml.jackson.databind.annotation.JsonNaming @JsonIgnoreProperties(ignoreUnknown = true) @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy::class) data class MoveDamageVO( val name: String )
1
Kotlin
0
1
8d93ca6d06485e38d857531159cb6172c377b2d3
390
sting-kt
Apache License 2.0
tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Expression.kt
mParticle
42,615,957
false
{"Java": 1371144, "Kotlin": 1028720, "Groovy": 7805, "Shell": 4130, "JavaScript": 2582}
package com.mparticle.lints.dtos import org.jetbrains.uast.UExpression interface Expression { val node: UExpression val parent: Expression fun resolve(): Any? fun forEachExpression(predicate: (Expression) -> Unit) } interface ParameterizedExpression : Expression { var arguments: List<Value> } class RootParent(override val node: UExpression) : Expression { override val parent: Expression = this override fun resolve() = null override fun forEachExpression(predicate: (Expression) -> Unit) {} }
19
Java
58
52
180e505f4b603d293530e0c5d29579e471693490
534
mparticle-android-sdk
Apache License 2.0
androidenhancedvideoplayer/src/main/java/com/profusion/androidenhancedvideoplayer/utils/VolumeController.kt
profusion
644,051,440
false
{"Kotlin": 109077, "JavaScript": 1494, "Shell": 250}
package com.profusion.androidenhancedvideoplayer.utils import android.content.Context import android.media.AudioManager private const val HIDE_VISUAL_FEEDBACK = 0 class VolumeController(context: Context) { private val audioManager: AudioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager val deviceHasVolumeFixedPolicy = audioManager.isVolumeFixed fun setDeviceVolume(volume: Int) { audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, HIDE_VISUAL_FEEDBACK) } fun getDeviceVolume(): Int { return audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) } fun getMaxVolumeValue(): Int { return audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC) } }
6
Kotlin
0
4
f7ad2d0a9b3ae04543c56ce11976ff18b4aee4c5
759
android-enhanced-video-player
MIT License
app/src/main/java/com/example/administrator/piechartview/AllStuAnswerStatisticalGraphDialog.kt
pcyfox
262,931,149
true
{"Java": 18581, "Kotlin": 1734}
package com.example.administrator.piechartview import android.app.DialogFragment import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.lwb.piechart.PieChartView.ItemType import kotlinx.android.synthetic.main.activity_main.* /** * 提问答题->全员答题报表 */ class AllStuAnswerStatisticalGraphDialog() : DialogFragment() { var listener: DialogClickListener? = null override fun onStart() { super.onStart() val lp = dialog?.window?.attributes lp?.width = 1200 lp?.height = 900 dialog?.window?.attributes = lp dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) } private val colors = arrayOf("#4CAF50", "#FFC107", "#E91E63", "#00BCD4", "#FF9800") override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.activity_main, null) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initView() } private fun initView() { pie_chart_view.setCell(5); //设置环形图的间距 pie_chart_view.setInnerRadius(0.4f); //设置环形图内环半径比例 0 - 1.0f pie_chart_view.addItemType(ItemType("苹果", 1, -0xdf4d56)) // pie_chart_view.addItemType(ItemType("华为", 17, -0x97dd75)) } abstract class DialogClickListener { open fun onCancelClick() {} open fun onConfirmClick(channelId: String?, deskNumber: Int) {} } }
0
Java
1
0
cf14d5aa3fd9d7f5894a9ad505b978aa26a4798a
1,734
PieChartView
Apache License 2.0
coroutines/src/jvmMain/kotlin/ClientSession-jvm.kt
cufyorg
502,485,629
false
{"Kotlin": 730586}
/* * Copyright 2022-2023 cufy.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.cufy.mongodb /* ============= ------------------ ============= */ typealias JavaClientSession = com.mongodb.reactivestreams.client.ClientSession actual interface ClientSession { val java: JavaClientSession } /* ============= ------------------ ============= */ /** * Create a new [ClientSession] instance wrapping * this session instance. * * @since 2.0.0 */ val JavaClientSession.kt: ClientSession get() = object : ClientSession { override val java = this@kt } /* ============= ------------------ ============= */
3
Kotlin
1
4
00305e65ff712d9a7a38078486c5ae14a388cee6
1,163
moonkit
Apache License 2.0
Controls/src/commonMain/kotlin/io/nacular/doodle/controls/theme/CommonTextButtonBehavior.kt
nacular
108,631,782
false
{"Kotlin": 2979553}
package io.nacular.doodle.controls.theme import io.nacular.doodle.controls.buttons.Button import io.nacular.doodle.core.Behavior import io.nacular.doodle.core.Icon import io.nacular.doodle.drawing.Canvas import io.nacular.doodle.drawing.Font import io.nacular.doodle.drawing.TextMetrics import io.nacular.doodle.focus.FocusManager import io.nacular.doodle.geometry.Point import io.nacular.doodle.geometry.Rectangle import io.nacular.doodle.layout.Insets import io.nacular.doodle.layout.Insets.Companion.None import io.nacular.doodle.text.TextSpacing import io.nacular.doodle.text.TextSpacing.Companion.default import io.nacular.doodle.utils.Anchor import io.nacular.doodle.utils.HorizontalAlignment.Center import io.nacular.doodle.utils.HorizontalAlignment.Left import io.nacular.doodle.utils.HorizontalAlignment.Right import io.nacular.doodle.utils.VerticalAlignment.Bottom import io.nacular.doodle.utils.VerticalAlignment.Middle import io.nacular.doodle.utils.VerticalAlignment.Top import kotlin.math.max import kotlin.math.min /** * Created by <NAME> on 10/3/18. */ public abstract class CommonTextButtonBehavior<in T: Button>( private val textMetrics : TextMetrics, private val defaultFont : Font? = null, private val insets : Insets = None, focusManager: FocusManager? = null): CommonButtonBehavior<T>(focusManager) { protected open val textChanged: (Button, String, String) -> Unit = { button,_,_ -> button.rerender() } override fun install(view: T) { super.install(view) view.textChanged += textChanged } override fun uninstall(view: T) { super.uninstall(view) view.textChanged -= textChanged } public fun textPosition(button: Button, text: String = button.text, icon: Icon<Button>? = button.icon, bounds: Rectangle = button.bounds.atOrigin, textSpacing: TextSpacing = default): Point { var minX = insets.left val stringSize = textMetrics.size(text, font(button), textSpacing) var iconWidth = 0.0 var maxX = bounds.width - stringSize.width - insets.right icon?.let { iconWidth = it.size(button).width + button.iconTextSpacing when (button.iconAnchor) { Anchor.Left, Anchor.Leading -> minX += iconWidth Anchor.Right, Anchor.Trailing -> maxX -= iconWidth } } val x = when (button.horizontalAlignment) { Right -> max(maxX, minX) Center -> { val iconOffset = when (button.iconAnchor) { Anchor.Leading -> iconWidth else -> 0.0 } max(minX, min(maxX, (bounds.width - (stringSize.width + iconWidth)) / 2 + iconOffset)) } Left -> minX } val y = when (button.verticalAlignment) { Bottom -> bounds.height - insets.bottom Middle -> max(insets.top, min(bounds.height - insets.bottom, (bounds.height - stringSize.height) / 2)) Top -> insets.top } return Point(x, y) + bounds.position } public fun iconPosition( button: Button, text: String = button.text, icon: Icon<Button>, stringPosition: Point = textPosition(button, text, icon), bounds: Rectangle = button.bounds.atOrigin ): Point { val size = icon.size(button) val y = when (button.verticalAlignment) { Bottom -> bounds.height - insets.bottom Middle -> max(insets.top, min(bounds.height - insets.bottom, (bounds.height - size.height) / 2)) Top -> insets.top } val minX = insets.left val maxX = bounds.width - size.width - insets.right val stringWidth = textMetrics.width(text, font(button)) val x = when (button.iconAnchor) { Anchor.Leading -> when { stringWidth > 0 -> max(minX, stringPosition.x - size.width - button.iconTextSpacing) else -> max(minX, min(maxX, (bounds.width - size.width) / 2)) } Anchor.Right -> when { stringWidth > 0 -> max(maxX, stringPosition.x + stringWidth + button.iconTextSpacing) else -> max(maxX, minX) } Anchor.Trailing -> when { stringWidth > 0 -> stringPosition.x + stringWidth + button.iconTextSpacing else -> max(minX, min(maxX, (bounds.width - size.width) / 2)) } else -> minX } return Point(x, y) + bounds.position } public fun iconPosition( button: Button, text: String = button.text, icon: Icon<Button>, textSpacing: TextSpacing = default, stringPosition: Point = textPosition(button, text, icon, textSpacing = textSpacing), bounds: Rectangle = button.bounds.atOrigin ): Point = iconPosition(button = button, text = text, icon = icon, stringPosition = stringPosition, bounds = bounds) public fun font(button: Button): Font? = button.font ?: defaultFont } public inline fun <T: Button> simpleTextButtonRenderer( textMetrics : TextMetrics, crossinline render: CommonTextButtonBehavior<T>.(button: T, canvas: Canvas) -> Unit): Behavior<T> = object: CommonTextButtonBehavior<T>(textMetrics, focusManager = null) { override fun render(view: T, canvas: Canvas) = render(this, view, canvas) } public inline fun <T: Button> simpleTextButtonRenderer( textMetrics : TextMetrics, focusManager: FocusManager?, crossinline render: CommonTextButtonBehavior<T>.(button: T, canvas: Canvas) -> Unit): Behavior<T> = object: CommonTextButtonBehavior<T>(textMetrics, focusManager = focusManager) { override fun render(view: T, canvas: Canvas) = render(this, view, canvas) } public inline fun <T: Button> simpleTextButtonRenderer( textMetrics : TextMetrics, focusManager: FocusManager? = null, insets : Insets = None, crossinline render: CommonTextButtonBehavior<T>.(button: T, canvas: Canvas) -> Unit): Behavior<T> = object: CommonTextButtonBehavior<T>(textMetrics, focusManager = focusManager, insets = insets) { override fun render(view: T, canvas: Canvas) = render(this, view, canvas) }
5
Kotlin
19
523
d48ba7fc8c0a8cd0c5bfb24b22286676bc26319e
6,397
doodle
MIT License
domain/src/main/java/app/tivi/domain/observers/ObservePagedTrendingShows.kt
ysawa0
292,612,967
true
{"Kotlin": 962168, "Shell": 2825, "Dockerfile": 1796}
/* * Copyright 2019 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.domain.observers import androidx.paging.PagedList import app.tivi.data.FlowPagedListBuilder import app.tivi.data.daos.TrendingDao import app.tivi.data.resultentities.TrendingEntryWithShow import app.tivi.domain.PagingInteractor import kotlinx.coroutines.flow.Flow import javax.inject.Inject class ObservePagedTrendingShows @Inject constructor( private val trendingShowsDao: TrendingDao ) : PagingInteractor<ObservePagedTrendingShows.Params, TrendingEntryWithShow>() { override fun createObservable(params: Params): Flow<PagedList<TrendingEntryWithShow>> { return FlowPagedListBuilder( trendingShowsDao.entriesDataSource(), params.pagingConfig, boundaryCallback = params.boundaryCallback ).buildFlow() } data class Params( override val pagingConfig: PagedList.Config, override val boundaryCallback: PagedList.BoundaryCallback<TrendingEntryWithShow>? ) : Parameters<TrendingEntryWithShow> }
0
Kotlin
0
0
b4a7a308992f70f9aba1bc05c950b23de1f83d36
1,593
tivi
Apache License 2.0
feature-core/src/main/java/com/maximapps/feature/core/domain/GetLastUnreadMessageUseCase.kt
merklol
535,542,138
false
{"Kotlin": 22995}
package com.maximapps.feature.core.domain import javax.inject.Inject interface GetLastUnreadMessageUseCase { operator fun invoke(): String } internal class GetLastUnreadMessageUseCaseImpl @Inject constructor( private val messageRepository: MessageRepository ) : GetLastUnreadMessageUseCase { override fun invoke() = messageRepository.getLastUnreadMessage() }
0
Kotlin
0
1
4064a9195b1126299ff01eb918665a9c961619c6
374
DaggerExampleApp
The Unlicense
app/src/main/java/dev/vaibhav/musicx/di/ServiceModule.kt
Vaibhav2002
446,123,333
false
{"Kotlin": 147753}
package dev.vaibhav.musicx.di import android.content.Context import com.google.android.exoplayer2.C import com.google.android.exoplayer2.ExoPlayer import com.google.android.exoplayer2.audio.AudioAttributes import com.google.android.exoplayer2.upstream.DefaultDataSource import dagger.Binds import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ServiceComponent import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.android.scopes.ServiceScoped import dev.vaibhav.musicx.exoplayer.datasource.LocalMusicPlayerDataSource import dev.vaibhav.musicx.exoplayer.datasource.MusicPlayerDataSource @Module @InstallIn(ServiceComponent::class) object ServiceModule { @ServiceScoped @Provides fun providesAudioAttributes() = AudioAttributes.Builder() .setContentType(C.CONTENT_TYPE_MUSIC) .setUsage(C.USAGE_MEDIA) .build() @ServiceScoped @Provides fun providesExoPlayer( @ApplicationContext context: Context, audioAttributes: AudioAttributes ): ExoPlayer = ExoPlayer.Builder(context) .setAudioAttributes(audioAttributes, true) .setHandleAudioBecomingNoisy(true) .build().apply { setThrowsWhenUsingWrongThread(false) } @ServiceScoped @Provides fun providesDataSourceFactor( @ApplicationContext context: Context ): DefaultDataSource.Factory = DefaultDataSource.Factory(context) // @ServiceScoped // @Provides // fun providesMusicPlayerDataSource( // dataSource: MusicDataSource, // musicMapper: MusicMapper, // musicDao: MusicDao // ): MusicPlayerDataSource = FirebaseMusicPlayerDataSource(dataSource, musicMapper, musicDao) // @ServiceScoped // @Provides // fun providesMusicDb( // @ApplicationContext context: Context // ): MusicXDatabase = Room.databaseBuilder(context, MusicXDatabase::class.java, "MusicXDatabase") // .fallbackToDestructiveMigration() // .build() // // @ServiceScoped // @Provides // fun providesMusicDao(database: MusicXDatabase): MusicDao = database.getMusicDao() } @Module @InstallIn(ServiceComponent::class) abstract class ServiceInterfaces { @ServiceScoped @Binds abstract fun bindsMusicDataSource( localMusicPlayerDataSource: LocalMusicPlayerDataSource ): MusicPlayerDataSource }
2
Kotlin
23
133
e8a8b8d1ecc5a20c1f61fcce0c5760003865ba9a
2,414
MusicX
MIT License
acrarium/src/main/kotlin/com/faendir/acra/ui/component/grid/GridFilterMenu.kt
otbutz
372,937,897
true
{"Kotlin": 364855, "JavaScript": 10305, "Dockerfile": 539, "CSS": 131, "TypeScript": 29}
package com.faendir.acra.ui.component.grid import com.faendir.acra.i18n.Messages import com.faendir.acra.ui.component.PopupButton import com.faendir.acra.ui.component.Translatable import com.vaadin.flow.component.icon.VaadinIcon import com.vaadin.flow.component.orderedlayout.VerticalLayout class GridFilterMenu(grid: AcrariumGrid<*>) : PopupButton(VaadinIcon.FILTER) { init { val content = VerticalLayout() content.add(Translatable.createLabel(Messages.FILTER).with { style.set("font-weight", "bold") }) content.add(*grid.acrariumColumns.mapNotNull { it.filterComponent }.toTypedArray()) add(content) } }
1
null
0
0
e15439f7402787ee8e06c1a0e73bd5c84cc6513a
668
Acrarium
Apache License 2.0
base/build-system/gradle-core/src/main/java/com/android/build/gradle/internal/dsl/ViewBindingOptionsImpl.kt
qiangxu1996
255,410,085
false
{"Java": 38854631, "Kotlin": 10438678, "C++": 1701601, "HTML": 795500, "FreeMarker": 695102, "Starlark": 542991, "C": 148853, "RenderScript": 58853, "Shell": 51803, "CSS": 36591, "Python": 32879, "XSLT": 23593, "Batchfile": 8747, "Dockerfile": 7341, "Emacs Lisp": 4737, "Makefile": 4067, "JavaScript": 3488, "CMake": 3295, "PureBasic": 2359, "GLSL": 1628, "Objective-C": 308, "Prolog": 214, "D": 121}
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.build.gradle.internal.dsl import com.android.build.gradle.api.ViewBindingOptions /** DSL object for configuring view binding options. */ open class ViewBindingOptionsImpl : ViewBindingOptions { /** Whether to enable data binding. */ override var isEnabled = false }
0
Java
1
1
3411c5436d0d34e6e2b84cbf0e9395ac8c55c9d4
919
vmtrace
Apache License 2.0
app/src/main/java/com/example/fooddelivery/domain/model/Category.kt
spencer2k19
720,201,452
false
{"Kotlin": 305089}
package com.example.fooddelivery.domain.model import com.google.gson.annotations.SerializedName data class Category( @SerializedName("date_created") val dateCreated: String?, @SerializedName("id") val id: Int?, @SerializedName("image") val image: String?, @SerializedName("name") val name: String? )
0
Kotlin
0
2
7be246eba97aa90740952a8bd85dbeb3229c826b
334
Food-Delivery-Android
MIT License
src/main/kotlin/org/strykeforce/thirdcoast/talon/SelectSlotCommand.kt
strykeforce
121,652,525
false
null
package org.strykeforce.thirdcoast.talon import net.consensys.cava.toml.TomlTable import org.koin.standalone.inject import org.strykeforce.thirdcoast.command.AbstractSelectCommand import org.strykeforce.thirdcoast.command.Command import org.strykeforce.thirdcoast.device.TalonFxService import org.strykeforce.thirdcoast.device.TalonService private val SLOTS = listOf(0, 1, 2, 3) class SelectSlotCommand( parent: Command?, key: String, toml: TomlTable ) : AbstractSelectCommand<Int>(parent, key, toml, SLOTS, SLOTS.map(Int::toString)) { val type = toml.getString(Command.DEVICE_KEY) ?: throw Exception("$key: ${Command.DEVICE_KEY} missing") private val talonService: TalonService by inject() private val talonFxService: TalonFxService by inject() override val activeIndex: Int get() { if(type == "srx") return talonService.activeSlotIndex else if(type == "fx") return talonFxService.activeSlotIndex else throw IllegalArgumentException() } override fun setActive(index: Int) { if(type == "srx") talonService.activeSlotIndex = index else if(type == "fx") talonFxService.activeSlotIndex = index } }
0
Kotlin
1
3
d9c64243e8b837f039a436013a960d895ffbd51b
1,221
thirdcoast-tct
MIT License
thirdparty/controlsfx-commons/src/test/kotlin/ktfx/controlsfx/controls/DecoratorTest.kt
hendraanggrian
102,934,147
false
{"Kotlin": 1082781}
package ktfx.controlsfx.controls import com.hendraanggrian.ktfx.test.initToolkit import javafx.scene.Node import javafx.scene.control.Button import javafx.scene.control.Hyperlink import javafx.scene.control.Label import org.controlsfx.control.decoration.Decorator import org.controlsfx.control.decoration.GraphicDecoration import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNull class DecoratorTest { private lateinit var node: Node @BeforeTest fun start() { initToolkit() node = Label("Hello world") } @Test fun addDecoration() { val decoration = GraphicDecoration(Button()) node.addDecoration(decoration) assertEquals(1, node.decorations.size) } @Test fun removeDecoration() { val decoration1 = GraphicDecoration(Button()) val decoration2 = GraphicDecoration(Hyperlink()) node.addDecoration(decoration1) node.addDecoration(decoration2) node.removeDecoration(decoration1) assertEquals(decoration2, node.decorations.single()) } @Test fun clearDecorations() { node.addDecoration(GraphicDecoration(Button())) node.addDecoration(GraphicDecoration(Hyperlink())) node.clearDecorations() assertNull(Decorator.getDecorations(node)) } @Test fun decorations() { node.addDecoration(GraphicDecoration(Button())) node.addDecoration(GraphicDecoration(Hyperlink())) assertEquals(Decorator.getDecorations(node), node.decorations) } }
1
Kotlin
2
17
59470dbff0368a301850b278da7c5f194500d640
1,594
ktfx
Apache License 2.0
app/src/main/java/com/github/bgrebennikov/devbuff/data/remote/models/explore/OwnerIdea.kt
DevBuffProject
467,099,240
false
null
package com.github.bgrebennikov.devbuff.data.remote.models.explore import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.parcelize.Parcelize @Parcelize data class OwnerIdea( @SerializedName("id") val id: String, @SerializedName("userName") val username: String, @SerializedName("firstName") val firstName: String?, @SerializedName("lastName") val lastName: String? ) : Parcelable
0
Kotlin
1
0
f7a7bbb301c8b572bdb323db47c1c973aadfabd3
459
DevBuff-Android
MIT License
java/java-impl/src/com/intellij/codeInsight/hints/MethodChainHintsPassFactory.kt
lots0logs
177,212,454
true
null
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.hints import com.intellij.codeHighlighting.TextEditorHighlightingPass import com.intellij.codeHighlighting.TextEditorHighlightingPassFactory import com.intellij.codeHighlighting.TextEditorHighlightingPassRegistrar import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.Key import com.intellij.psi.PsiFile import com.intellij.psi.PsiJavaFile class MethodChainHintsPassFactory(registrar: TextEditorHighlightingPassRegistrar) : TextEditorHighlightingPassFactory { init { registrar.registerTextEditorHighlightingPass(this, null, null, false, -1) } override fun createHighlightingPass(file: PsiFile, editor: Editor): TextEditorHighlightingPass? { if (editor.isOneLineMode || file !is PsiJavaFile || modificationStampHolder.isNotChanged(editor, file)) return null return MethodChainHintsPass(modificationStampHolder, file, editor) } companion object { val modificationStampHolder: ModificationStampHolder = ModificationStampHolder(Key.create("METHOD_CHAIN_PASS_LAST_MODIFICATION_TIMESTAMP")) } }
1
null
1
1
3dd717a44039d5592619331857621c17baae490a
1,231
intellij-community
Apache License 2.0
kmm/service/content/model/all/src/commonMain/kotlin/movie/dto/MovieDTO.kt
barabasizsolt
524,965,150
false
null
package movie.dto import movie.model.Movie import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class MovieDTO( @SerialName(value = "id") val id: Long?, @SerialName(value = "adult") val adult: Boolean?, @SerialName(value = "backdrop_path") val backdropPath: String?, @SerialName(value = "genre_ids") val genreIds: List<Int>?, @SerialName(value = "original_language") val originalLanguage: String?, @SerialName(value = "original_title") val originalTitle: String?, @SerialName(value = "title") val title: String?, @SerialName(value = "overview") val overview: String?, @SerialName(value = "popularity") val popularity: Double?, @SerialName(value = "poster_path") val posterPath: String?, @SerialName(value = "release_date") val releaseDate: String?, @SerialName(value = "vote_average") val voteAverage: Double? ) fun MovieDTO.toModel() : Movie? { if ( id == null || adult == null || genreIds == null || originalLanguage == null || originalTitle == null || title == null || overview == null || popularity == null || voteAverage == null ) { return null } return Movie( id = id.toString(), adult = adult, backdropPath = backdropPath.orEmpty(), genreIds = genreIds, originalLanguage = originalLanguage, originalTitle = originalTitle, title = title, overview = overview, popularity = popularity.toString(), posterPath = posterPath, releaseDate = releaseDate.orEmpty(), voteAverage = voteAverage.toString().take(n = 3) /*TODO: Fix this*/ // String.format("%.1f", voteAverage) ) }
0
Kotlin
0
0
acf4e021200c670dbc7bc2a38240d019f2a4a3a2
1,774
Mova
GNU General Public License v3.0 or later
app/src/test/java/com/ms/catlife/feature_note_detail/presentation/NoteDetailViewModelTest.kt
morganesoula
446,932,843
false
{"Kotlin": 415897}
package com.ms.catlife.feature_note_detail.presentation import androidx.lifecycle.SavedStateHandle import app.cash.turbine.test import com.ms.catlife.core.domain.use_case.crud.* import com.ms.catlife.feature_inventory.presentation.util.CoroutineTestRule import com.ms.catlife.feature_note.data.entity.NoteEntity import com.ms.catlife.feature_note.data.repository.FakeNoteDataSource import com.ms.catlife.feature_note.domain.use_case.crud.* import com.ms.catlife.feature_note_detail.data.NoteDetailUiState import junit.framework.TestCase import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext import org.junit.Assert.* import org.junit.Before import org.junit.Rule import org.junit.Test @OptIn(ExperimentalCoroutinesApi::class) class NoteDetailViewModelTest { @JvmField @Rule var mainCoroutineDispatcher = CoroutineTestRule() private lateinit var viewModel: NoteDetailViewModel private lateinit var noteUseCases: CrudNoteUseCase private val fakeNoteDataSource = FakeNoteDataSource() private val savedStateHandle = SavedStateHandle() private lateinit var stateTest: StateFlow<NoteDetailUiState> @Before fun setUp() { savedStateHandle["noteId"] = 2 noteUseCases = CrudNoteUseCase( InsertNoteUseCase(fakeNoteDataSource), DeleteNoteUseCase(fakeNoteDataSource), GetNoteByIdUseCase(fakeNoteDataSource), GetAllNotesUseCase(fakeNoteDataSource), GetAllCatNotesUseCase(fakeNoteDataSource), DeleteNoteByIdUseCase(fakeNoteDataSource), DeleteNoteByCatIdUseCase(fakeNoteDataSource) ) viewModel = NoteDetailViewModel( savedStateHandle = savedStateHandle, noteUseCase = noteUseCases, Dispatchers.IO ) stateTest = viewModel.state } @Test fun onUiDeleteEvent() = runTest { noteUseCases.insertNoteUseCase.invoke( NoteEntity( 2, 1, "Empty path", "Felix", 1234L, "Random title for test", "Random content for test" ) ) val data = noteUseCases.getNoteByIdUseCase.invoke(2) this.advanceUntilIdle() TestCase.assertNotNull(data) viewModel.onUiEvent( NoteDetailEvent.OnDeleteCustomDialogOpen( openDialog = true, deleteData = false, 2 ) ) TestCase.assertNotNull(noteUseCases.getNoteByIdUseCase(2)) stateTest.test { TestCase.assertFalse(expectMostRecentItem().noteDeleted) } viewModel.onUiEvent( NoteDetailEvent.OnDeleteCustomDialogOpen( openDialog = true, deleteData = true, 2 ) ) this.advanceUntilIdle() withContext(Dispatchers.IO) { Thread.sleep(1000) } stateTest.test { TestCase.assertTrue(expectMostRecentItem().noteDeleted) } } }
0
Kotlin
0
2
80eb98072fd3326ae13503b2dc150a20f6574742
3,299
catlife
Apache License 2.0
app/src/main/java/com/appacoustic/rt/domain/RecordAudioPermissionChecker.kt
soygabimoreno
294,311,955
false
{"Kotlin": 191442, "CMake": 1598}
package com.appacoustic.rt.domain import android.Manifest import arrow.core.Either class RecordAudioPermissionChecker( private val permissionRequester: PermissionRequester ) { suspend operator fun invoke(): Either<Throwable, PermissionRequester.PermissionState> = permissionRequester(Manifest.permission.RECORD_AUDIO) }
0
Kotlin
1
4
144b2bc430b115de4ba1849b2b4a5c181ffcd4f1
339
RT
Apache License 2.0
app/src/main/java/com/example/codev/presentation/screens/AddprojectScreen.kt
YadavYashvant
697,651,024
false
{"Kotlin": 89127, "Java": 218}
package com.example.codev.presentation.screens import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Check import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedCard import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import com.example.codev.R import com.example.codev.firestore_feature.addToFirebase import com.example.codev.presentation.sign_in.UserData @OptIn(ExperimentalMaterial3Api::class) @Composable fun AddprojectScreen( navController: NavController, userData: UserData? ) { val context = LocalContext.current Box( modifier = Modifier .fillMaxWidth() .fillMaxHeight() ) { val name = remember { mutableStateOf("") } val branch = remember { mutableStateOf("") } val skill = remember { mutableStateOf("") } Column( modifier = Modifier .fillMaxSize() .padding(vertical = 40.dp, horizontal = 16.dp) .fillMaxWidth() .background(MaterialTheme.colorScheme.background) ) { /*Text(text = "Add Project", fontFamily = com.example.codev.com.example.codev.presentation.getSpacefamily, fontSize = 30.sp, fontWeight = FontWeight.Bold, modifier = Modifier.fillMaxSize().padding(bottom = 10.dp), textAlign = TextAlign.Center)*/ TextField( value = name.value, shape = MaterialTheme.shapes.large, onValueChange = { name.value = it }, modifier = Modifier .fillMaxWidth() .padding(top = 32.dp) .height(70.dp), colors = TextFieldDefaults.textFieldColors( unfocusedIndicatorColor = Color.Transparent, focusedIndicatorColor = Color.Transparent ), label = { Text("Enter your project name ", fontFamily = spacefamily) } ) Spacer(modifier = Modifier.height(16.dp)) TextField( value = branch.value, onValueChange = { branch.value = it }, shape = MaterialTheme.shapes.large, modifier = Modifier .fillMaxWidth() .height(70.dp), colors = TextFieldDefaults.textFieldColors( unfocusedIndicatorColor = Color.Transparent, focusedIndicatorColor = Color.Transparent ), label = { Text("Enter description of your project ", fontFamily = spacefamily) } ) Spacer(modifier = Modifier.height(16.dp)) TextField( value = skill.value, onValueChange = { skill.value = it }, shape = MaterialTheme.shapes.large, modifier = Modifier .fillMaxWidth() .height(210.dp), colors = TextFieldDefaults.textFieldColors( unfocusedIndicatorColor = Color.Transparent, focusedIndicatorColor = Color.Transparent ), label = { Text("Enter skills required for your project ", fontFamily = spacefamily) } ) OutlinedCard( onClick = { /*TODO*/ }, shape = MaterialTheme.shapes.large, modifier = Modifier .fillMaxWidth() .padding(vertical = 20.dp, horizontal = 8.dp) .background(color = Color.Transparent), ) { Text(text = "Add relevant project images", fontFamily = spacefamily, fontSize = 20.sp, modifier = Modifier .padding(16.dp) .align(Alignment.CenterHorizontally), textAlign = TextAlign.Center ) Image( painter = painterResource(id = R.drawable.concept), contentDescription = null, modifier = Modifier .align(Alignment.CenterHorizontally) ) } } FloatingActionButton( onClick = { addToFirebase( name.value, branch.value, skill.value, userData?.username, context ) navController.popBackStack() }, modifier = Modifier .align(Alignment.BottomEnd) .padding(bottom = 100.dp, end = 20.dp) ) { Icon(imageVector = Icons.Filled.Check, contentDescription =null) } } }
0
Kotlin
0
2
a3eab94168f43900c6dcd2a67cae9271f99ce21c
6,246
Codev
MIT License
settings.gradle.kts
lzj960515
506,676,326
false
{"Kotlin": 6903}
rootProject.name = "kq-universal-generator"
0
Kotlin
0
0
e7d7bb6e5433f3dba7d252c901f2bbb9917f90b3
44
kq-universal-generator
Apache License 2.0
app/src/main/java/com/example/myapplication/adapter/SearchListAdapter.kt
jakobfridesjo
636,587,336
false
null
package com.example.myapplication.adapter import android.content.Context import android.content.res.ColorStateList import android.graphics.drawable.RippleDrawable import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.example.myapplication.R import com.example.myapplication.databinding.SearchListItemBinding import com.example.myapplication.model.Station class SearchListAdapter( private val context: Context, private val searchListClickListener: SearchListClickListener, private val searchListLongClickListener: SearchListLongClickListener) : ListAdapter<Station, SearchListAdapter.ViewHolder>(SearchListDiffCallback()) { class ViewHolder(private var binding: SearchListItemBinding) : RecyclerView.ViewHolder(binding.root) { fun bind( station: Station, searchListClickListener: SearchListClickListener, searchListLongClickListener: SearchListLongClickListener) { binding.station = station binding.clickListener = searchListClickListener binding.longClickListener = searchListLongClickListener binding.executePendingBindings() } companion object { fun from(parent: ViewGroup) : ViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val binding = SearchListItemBinding.inflate(layoutInflater, parent, false) return ViewHolder(binding) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder.from(parent) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { return holder.bind(getItem(position), searchListClickListener, searchListLongClickListener) } } class SearchListDiffCallback : DiffUtil.ItemCallback<Station>() { override fun areItemsTheSame(oldItem: Station, newItem: Station): Boolean { return oldItem.stationUUID == newItem.stationUUID } override fun areContentsTheSame(oldItem: Station, newItem: Station): Boolean { return oldItem == newItem } } class SearchListClickListener(val clickListener: (station: Station) -> Unit) { fun onClick(station: Station) = clickListener(station) } class SearchListLongClickListener(val longClickListener: (station: Station) -> Boolean) { fun onLongClick(station: Station): Boolean = longClickListener(station) }
0
Kotlin
0
0
a1506821f82fed566598724feab0937cdb67f920
2,592
Waves
MIT License
app/src/main/java/au/edu/utas/zhe4/babytracker/presentation/record/feed/FeedRecordActivity.kt
ShanQincheng
622,925,577
false
null
package au.edu.utas.zhe4.babytracker.presentation.record.feed import android.os.Bundle import android.text.Editable import android.text.TextWatcher import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import au.edu.utas.zhe4.babytracker.databinding.ActivityFeedBinding import au.edu.utas.zhe4.babytracker.domain.FeedingSide import au.edu.utas.zhe4.babytracker.domain.FeedingType import au.edu.utas.zhe4.babytracker.framework.BabyTrackerViewModelFactory import au.edu.utas.zhe4.babytracker.presentation.record.DatePickerFragment import au.edu.utas.zhe4.babytracker.presentation.record.TimePickerFragment class FeedRecordActivity : AppCompatActivity() { private lateinit var ui : ActivityFeedBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ui = ActivityFeedBinding.inflate(layoutInflater) setContentView(ui.root) val viewModel = ViewModelProvider( this, BabyTrackerViewModelFactory )[FeedRecordViewModel::class.java] updateViewModelByIntent(viewModel) showPage(viewModel) viewModel.feedingTime.observe(this, Observer { showFeedingTime(viewModel) }) viewModel.feedingDuration.observe(this, Observer { showFeedingDuration(viewModel) }) ui.rgFeedType.setOnCheckedChangeListener { _, checkedId -> when (checkedId) { ui.rbBreastfeeding.id -> viewModel.updateFeedingType(FeedingType.BREASTFEEDING.toString()) else -> viewModel.updateFeedingType(FeedingType.BOTTLE.toString()) } } ui.btTimePickerPopUp.setOnClickListener { val timePicker = TimePickerFragment(viewModel::setTime) timePicker.show(supportFragmentManager, "timePicker") val datePicker = DatePickerFragment(viewModel::setDate) datePicker.show(supportFragmentManager, "datePicker") } ui.rgFeedSide.setOnCheckedChangeListener { _, checkedId -> when (checkedId) { ui.rbFeedSideLeft.id -> viewModel.updateFeedingSide(FeedingSide.LEFT.toString()) else -> viewModel.updateFeedingSide(FeedingSide.RIGHT.toString()) } } ui.btDurationPickerPopUp.setOnClickListener { val numberPicker = FeedRecordNumberPickerFragment(this, viewModel) numberPicker.showNumberPickerDialog() } ui.tietNote.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } override fun afterTextChanged(s: Editable?) { viewModel.updateFeedingNote(s.toString()) } }) ui.btSave.setOnClickListener{ viewModel.saveOrUpdateToDatabase() finish() } } private fun updateViewModelByIntent(viewModel: FeedRecordViewModel) { if (intent.hasExtra("id")) { val id = intent.getStringExtra("id") viewModel.updateID(id!!) } if (intent.hasExtra("feedingType")) { val fType = intent.getStringExtra("feedingType").toString() viewModel.updateFeedingType(fType) } if (intent.hasExtra("feedingTime")) { val fTime = intent.getStringExtra("feedingTime").toString() viewModel.updateFeedingTime(fTime) } if (intent.hasExtra("feedingSide")) { val fSide = intent.getStringExtra("feedingSide").toString() viewModel.updateFeedingSide(fSide) } if (intent.hasExtra("feedingDuration")) { val fDuration = intent.getStringExtra("feedingDuration").toString() viewModel.updateFeedingDuration(fDuration) } if (intent.hasExtra("feedingNote")) { val fNote = intent.getStringExtra("feedingNote").toString() viewModel.updateFeedingNote(fNote) } } private fun showPage(viewModel : FeedRecordViewModel) { showFeedingType(viewModel) showFeedingTime(viewModel) showFeedingSide(viewModel) showFeedingDuration(viewModel) showFeedingNote(viewModel) } private fun showFeedingType(viewModel : FeedRecordViewModel) { when(viewModel.feedingType.value) { FeedingType.BREASTFEEDING.toString() -> { ui.rbBreastfeeding.isChecked = true ui.rbBottleFeed.isChecked = false } else -> { ui.rbBreastfeeding.isChecked = false ui.rbBottleFeed.isChecked = true } } } private fun showFeedingTime(viewModel : FeedRecordViewModel) { ui.tvTimePickerCurrentTime.text = viewModel.feedingTime.value!! } private fun showFeedingSide(viewModel : FeedRecordViewModel) { when(viewModel.feedingSide.value) { FeedingSide.LEFT.toString() -> { ui.rbFeedSideLeft.isChecked = true ui.rbFeedSideRight.isChecked = false } else -> { ui.rbFeedSideLeft.isChecked = false ui.rbFeedSideRight.isChecked = true } } } private fun showFeedingDuration(viewModel : FeedRecordViewModel) { ui.tvDuration.text = viewModel.feedingDuration.value!! } private fun showFeedingNote(viewModel : FeedRecordViewModel) { ui.tietNote.setText(viewModel.feedingNote.value!!) ui.tietNote.setSelection(viewModel.feedingNote.value!!.length) } }
0
Kotlin
0
0
44ce04d21b6a65f89d4f61910f1bf1fe17f6a21f
5,898
BabyTracker
Apache License 2.0
orchestrator-service/src/main/kotlin/com/dekinci/gdeploy/orchestrator/apiobserver/ApiUriGenerator.kt
DeKinci
380,109,331
false
{"Kotlin": 64234}
package com.dekinci.gdeploy.orchestrator.apiobserver import com.dekinci.gdeploy.orchestrator.CloudService import org.springframework.context.annotation.Profile import org.springframework.stereotype.Service interface ApiUriGenerator { fun apiUri(service: CloudService, namespace: String): String } @Service @Profile("dev") class GatewayApiUriGenerator : ApiUriGenerator { override fun apiUri(service: CloudService, namespace: String) = "http://gd-shop.i.dknc.io/${service.service.split("-").last()}/meta/api" } @Service @Profile(value = ["default", "kubernetes"]) class KubernetesApiUriGenerator : ApiUriGenerator { override fun apiUri(service: CloudService, namespace: String) = "http://${service.service}.$namespace/meta/api" }
0
Kotlin
1
0
77b7e80242f2e30a6e001f0c0d469b49a44cfa35
761
granular-deployment
MIT License
feature-account-impl/src/main/java/io/novafoundation/nova/feature_account_impl/domain/common/AdvancedEncryptionSelectionStore.kt
novasamatech
415,834,480
false
{"Kotlin": 8656332, "Java": 14723, "JavaScript": 425}
package io.novafoundation.nova.feature_account_impl.domain.common import io.novafoundation.nova.common.utils.selectionStore.MutableSelectionStore import io.novafoundation.nova.feature_account_api.domain.account.advancedEncryption.AdvancedEncryption class AdvancedEncryptionSelectionStore : MutableSelectionStore<AdvancedEncryption>()
18
Kotlin
6
15
547f9966ee3aec864b864d6689dc83b6193f5c15
336
nova-wallet-android
Apache License 2.0
wifi-signal-strength-view/src/main/java/at/robhor/wifisignalstrength/WifiSignalStrengthView.kt
robhor
126,234,132
false
null
package at.robhor.wifisignalstrength import android.content.Context import android.graphics.Canvas import android.graphics.drawable.Drawable import android.net.wifi.WifiManager import android.util.AttributeSet import android.view.View private const val UPDATE_INTERVAL_MILLIS = 1000L /** * Displays an icon representing wifi signal strength. * * @author <NAME> */ class WifiSignalStrengthView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : View(context, attrs) { private val wifiDrawable = WifiSignalStrengthDrawable() private val levels = 5 private var disconnected = false private var visible = false private var started = false private var running = false private val updateRunnable = object : Runnable { override fun run() { if (running) { update() postDelayed(this, UPDATE_INTERVAL_MILLIS) } } } init { wifiDrawable.callback = this if (!isInEditMode) { setLayerType(View.LAYER_TYPE_HARDWARE, null) } if (attrs != null) { val ta = context.obtainStyledAttributes(attrs, R.styleable.WifiSignalStrengthView) wifiDrawable.fillColor = ta.getColor(R.styleable.WifiSignalStrengthView_fillColor, wifiDrawable.fillColor) wifiDrawable.backgroundColor = ta.getColor(R.styleable.WifiSignalStrengthView_backgroundColor, wifiDrawable.backgroundColor) wifiDrawable.filled = ta.getFraction(R.styleable.WifiSignalStrengthView_fill, 1, 1, 0.8f) val strikeThrough = ta.getBoolean(R.styleable.WifiSignalStrengthView_wifiOff, false) wifiDrawable.strikeThrough = strikeThrough && !isInEditMode if (ta.getBoolean(R.styleable.WifiSignalStrengthView_autoUpdating, true) && !isInEditMode) start() ta.recycle() } else if (!isInEditMode) { start() } wifiDrawable.jumpToCurrentState() } private fun update() { val level = signalLevel val isDisconnected = level == null wifiDrawable.filled = when (level) { null -> 0f else -> level.toFloat() / (levels - 1) } invalidate() if (disconnected != isDisconnected && !isInEditMode) { disconnected = isDisconnected wifiDrawable.strikeThrough = isDisconnected } } private val signalLevel: Int? get() { if (isInEditMode) return 3 val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager if (!wifiManager.isWifiEnabled) return null val connectionInfo = wifiManager.connectionInfo val rssi = connectionInfo.rssi return WifiManager.calculateSignalLevel(rssi, levels) } fun start() { started = true updateRunning() } fun stop() { started = false updateRunning() } fun setNotConnected() { stop() wifiDrawable.filled = 0f wifiDrawable.strikeThrough = true } fun setLevel(level: Float) { stop() wifiDrawable.filled = level wifiDrawable.strikeThrough = false } override fun onDetachedFromWindow() { super.onDetachedFromWindow() visible = false updateRunning() } override fun onWindowVisibilityChanged(visibility: Int) { super.onWindowVisibilityChanged(visibility) visible = visibility == View.VISIBLE updateRunning() } override fun onVisibilityChanged(changedView: View, visibility: Int) { super.onVisibilityChanged(changedView, visibility) updateRunning() } private fun updateRunning() { val running = visible && started && isShown if (running != this.running) { if (running) { update() postDelayed(updateRunnable, UPDATE_INTERVAL_MILLIS) } else { removeCallbacks(updateRunnable) } this.running = running } } override fun draw(canvas: Canvas) { super.draw(canvas) wifiDrawable.draw(canvas) } override fun verifyDrawable(who: Drawable): Boolean { return super.verifyDrawable(who) || who == wifiDrawable } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) wifiDrawable.setBounds(0, 0, w, h) } override fun getSuggestedMinimumWidth() = (24 * resources.displayMetrics.density).toInt() override fun getSuggestedMinimumHeight() = (24 * resources.displayMetrics.density).toInt() override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val measuredWidth = when (MeasureSpec.getMode(widthMeasureSpec)) { MeasureSpec.EXACTLY -> MeasureSpec.getSize(widthMeasureSpec) MeasureSpec.AT_MOST -> minOf(suggestedMinimumWidth, MeasureSpec.getSize(widthMeasureSpec)) MeasureSpec.UNSPECIFIED -> suggestedMinimumWidth else -> suggestedMinimumWidth } val measuredHeight = when (MeasureSpec.getMode(heightMeasureSpec)) { MeasureSpec.EXACTLY -> MeasureSpec.getSize(heightMeasureSpec) MeasureSpec.AT_MOST -> minOf(suggestedMinimumHeight, MeasureSpec.getSize(heightMeasureSpec)) MeasureSpec.UNSPECIFIED -> suggestedMinimumHeight else -> suggestedMinimumHeight } setMeasuredDimension(measuredWidth, measuredHeight) } }
0
Kotlin
1
9
c66b261b8dc362c5e6cb4bd5dc831081bbbe4367
5,624
WifiSignalStrengthView
MIT License
src/main/kotlin/pl/allegro/tech/spunit/util/Tuple.kt
allegro
562,882,340
false
{"Kotlin": 32422}
package pl.allegro.tech.spunit.util data class Quadruple<out A, out B, out C, out D>( val first: A, val second: B, val third: C, val fourth: D ) { override fun toString(): String = "($first, $second, $third, $fourth)" } data class Quintuple<out A, out B, out C, out D, out E>( val first: A, val second: B, val third: C, val fourth: D, val fifth: E, ) { override fun toString(): String = "($first, $second, $third, $fourth, $fifth)" } data class Sextuple<out A, out B, out C, out D, out E, out F>( val first: A, val second: B, val third: C, val fourth: D, val fifth: E, val sixth: F, ) { override fun toString(): String = "($first, $second, $third, $fourth, $fifth, $sixth)" } fun <P1, P2, P3> List<Pair<Pair<P1, P2>, P3>>.flattenTriple(): List<Triple<P1, P2, P3>> = map { Triple(it.first.first, it.first.second, it.second) } fun <P1, P2, P3, P4> List<Pair<Pair<Pair<P1, P2>, P3>, P4>>.flattenQuadruple(): List<Quadruple<P1, P2, P3, P4>> = map { Quadruple(it.first.first.first, it.first.first.second, it.first.second, it.second) } fun <P1, P2, P3, P4, P5> List<Pair<Pair<Pair<Pair<P1, P2>, P3>, P4>, P5>>.flattenQuintuple(): List<Quintuple<P1, P2, P3, P4, P5>> = map { Quintuple(it.first.first.first.first, it.first.first.first.second, it.first.first.second, it.first.second, it.second) } fun <P1, P2, P3, P4, P5, P6> List<Pair<Pair<Pair<Pair<Pair<P1, P2>, P3>, P4>, P5>, P6>>.flattenSextuple(): List<Sextuple<P1, P2, P3, P4, P5, P6>> = map { Sextuple(it.first.first.first.first.first, it.first.first.first.first.second, it.first.first.first.second, it.first.first.second, it.first.second, it.second) }
0
Kotlin
5
14
2d77708dc432cc4f8708742210bb71c609b31e3c
1,682
spunit
Apache License 2.0
src/main/kotlin/com/kotcrab/xgbc/gdx/GdxJoypad.kt
kotcrab
52,388,562
false
null
package com.kotcrab.xgbc.gdx import com.badlogic.gdx.Input import com.badlogic.gdx.InputAdapter import com.kotcrab.xgbc.io.Joypad /** @author Kotcrab */ class GdxJoypad(private val joypad: Joypad) : InputAdapter() { val mapping = mapOf( Input.Keys.X to Joypad.JoypadKey.A, Input.Keys.Z to Joypad.JoypadKey.B, Input.Keys.UP to Joypad.JoypadKey.UP, Input.Keys.LEFT to Joypad.JoypadKey.LEFT, Input.Keys.DOWN to Joypad.JoypadKey.DOWN, Input.Keys.RIGHT to Joypad.JoypadKey.RIGHT, Input.Keys.ENTER to Joypad.JoypadKey.START, Input.Keys.BACKSPACE to Joypad.JoypadKey.SELECT ) override fun keyDown(keycode: Int): Boolean { val key = mapping[keycode] if (key != null) { joypad.keyPressed(key) return true } return false } override fun keyUp(keycode: Int): Boolean { val key = mapping[keycode] if (key != null) { joypad.keyReleased(key) return true } return false } }
0
Kotlin
4
49
25d2623acf0f1e87cb7a2db61c26af4d2d74f735
1,094
xgbc
Apache License 2.0
ocpi-toolkit-2.2.1/src/main/kotlin/com/izivia/ocpi/toolkit/modules/locations/domain/EnergySource.kt
IZIVIA
497,830,391
false
{"Kotlin": 623325}
package com.izivia.ocpi.toolkit.modules.locations.domain import com.izivia.ocpi.toolkit.annotations.Partial import java.math.BigDecimal /** * Key-value pairs (enum + percentage) of energy sources. All given values should add up to 100 percent per category. * * @property source The type of energy source. * @property percentage Percentage of this source (0-100) in the mix. */ @Partial data class EnergySource( val source: EnergySourceCategory, val percentage: BigDecimal )
14
Kotlin
7
18
4642efb20e733eb9c1b133be4fd4399271453d8c
489
ocpi-toolkit
MIT License
collection-kotlin/src/main/java/com/youngmanster/collection_kotlin/base/dialog/DialogWrapper.kt
usernameyangyan
243,885,240
false
null
package com.youngmanster.collection_kotlin.base.dialog /** * Created by yangy *2020/12/14 *Describe: */ class DialogWrapper { private var dialog //统一管理dialog的弹出顺序 : YYDialog.Builder? = null constructor(dialog: YYDialog.Builder){ this.dialog = dialog } fun getDialog(): YYDialog.Builder? { return dialog } fun setDialog(dialog: YYDialog.Builder?) { this.dialog = dialog } }
0
Java
3
20
bc7ed916e676075b35f719ec2d41e63f4ae6d9dd
466
Collection-Android-kotlin
MIT License
app/src/main/java/com/example/takeaway/search/model/SearchEvent.kt
OkieLe
432,074,775
false
{"Kotlin": 117343, "Shell": 645}
package com.example.takeaway.search.model import com.example.takeaway.common.UiEvent import com.example.takeaway.domain.base.Category sealed interface SearchEvent: UiEvent { data class ShowError(val error: Category) : SearchEvent }
0
Kotlin
0
2
94a58df99ec348277ea441890a76a6c5c923c84d
238
ComposeTakeAway
MIT License
src/main/kotlin/org/jetbrains/jps/build/snapshot/dumper/MyMenuGroup.kt
CherepanovAleksei
301,130,505
false
null
package org.jetbrains.jps.build.snapshot.dumper import com.intellij.openapi.actionSystem.DefaultActionGroup class MyMenuGroup : DefaultActionGroup()
0
Kotlin
0
0
af16f3a401e0c3e1b6d89b067b578e4bdc7b0f3b
151
jps-build-snapshot-dumper
Apache License 2.0
src/main/kotlin/cn/therouter/idea/transfer/arouter/NodeRoute.kt
kymjs
700,777,348
false
{"Kotlin": 74273}
package cn.therouter.idea.transfer.arouter import java.util.* class NodeRoute(var path: String, var returnType: String) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is NodeRoute) return false return path == other.path && returnType == other.returnType } override fun hashCode(): Int { return Objects.hash(path, returnType) } }
0
Kotlin
0
9
0c407ff2d6a4a95ad5a551dc89e751ed0968c47c
421
TheRouterIdeaPlugin
Apache License 2.0
src/main/kotlin/com/nftco/flow/sdk/crypto/Crypto.kt
the-nft-company
355,268,322
false
{"Kotlin": 227854, "Cadence": 5040}
package com.nftco.flow.sdk.crypto import com.nftco.flow.sdk.* import com.nftco.flow.sdk.Signer import org.bouncycastle.jce.ECNamedCurveTable import org.bouncycastle.jce.ECPointUtil import org.bouncycastle.jce.interfaces.ECPrivateKey import org.bouncycastle.jce.interfaces.ECPublicKey import org.bouncycastle.jce.provider.BouncyCastleProvider import org.bouncycastle.jce.spec.ECNamedCurveSpec import org.bouncycastle.jce.spec.ECPrivateKeySpec import java.math.BigInteger import java.security.* import java.security.spec.ECGenParameterSpec import java.security.spec.ECPublicKeySpec import kotlin.experimental.and import kotlin.math.max data class KeyPair( val private: PrivateKey, val public: PublicKey ) data class PrivateKey( val key: java.security.PrivateKey, val ecCoupleComponentSize: Int, val hex: String ) data class PublicKey( val key: java.security.PublicKey, val hex: String ) object Crypto { init { Security.addProvider(BouncyCastleProvider()) } @JvmStatic @JvmOverloads fun generateKeyPair(algo: SignatureAlgorithm = SignatureAlgorithm.ECDSA_P256): KeyPair { val generator = KeyPairGenerator.getInstance("EC", "BC") generator.initialize(ECGenParameterSpec(algo.curve), SecureRandom()) val keyPair = generator.generateKeyPair() val privateKey = keyPair.private val publicKey = keyPair.public return KeyPair( private = PrivateKey( key = keyPair.private, ecCoupleComponentSize = if (privateKey is ECPrivateKey) { privateKey.parameters.n.bitLength() / 8 } else { 0 }, hex = if (privateKey is ECPrivateKey) { privateKey.d.toByteArray().bytesToHex() } else { throw IllegalArgumentException("PrivateKey must be an ECPublicKey") } ), public = PublicKey( key = publicKey, hex = if (publicKey is ECPublicKey) { (publicKey.q.xCoord.encoded + publicKey.q.yCoord.encoded).bytesToHex() } else { throw IllegalArgumentException("PublicKey must be an ECPublicKey") } ) ) } @JvmStatic @JvmOverloads fun decodePrivateKey(key: String, algo: SignatureAlgorithm = SignatureAlgorithm.ECDSA_P256): PrivateKey { val ecParameterSpec = ECNamedCurveTable.getParameterSpec(algo.curve) val keyFactory = KeyFactory.getInstance(algo.algorithm, "BC") val ecPrivateKeySpec = ECPrivateKeySpec(BigInteger(key, 16), ecParameterSpec) val pk = keyFactory.generatePrivate(ecPrivateKeySpec) return PrivateKey( key = pk, ecCoupleComponentSize = if (pk is ECPrivateKey) { pk.parameters.n.bitLength() / 8 } else { 0 }, hex = if (pk is ECPrivateKey) { pk.d.toByteArray().bytesToHex() } else { throw IllegalArgumentException("PrivateKey must be an ECPublicKey") } ) } @JvmStatic @JvmOverloads fun decodePublicKey(key: String, algo: SignatureAlgorithm = SignatureAlgorithm.ECDSA_P256): PublicKey { val ecParameterSpec = ECNamedCurveTable.getParameterSpec(algo.curve) val keyFactory = KeyFactory.getInstance("EC", "BC") val params = ECNamedCurveSpec( algo.curve, ecParameterSpec.curve, ecParameterSpec.g, ecParameterSpec.n ) val point = ECPointUtil.decodePoint(params.curve, byteArrayOf(0x04) + key.hexToBytes()) val pubKeySpec = ECPublicKeySpec(point, params) val publicKey = keyFactory.generatePublic(pubKeySpec) return PublicKey( key = publicKey, hex = if (publicKey is ECPublicKey) { (publicKey.q.xCoord.encoded + publicKey.q.yCoord.encoded).bytesToHex() } else { throw IllegalArgumentException("PublicKey must be an ECPublicKey") } ) } @JvmStatic @JvmOverloads fun getSigner(privateKey: PrivateKey, hashAlgo: HashAlgorithm = HashAlgorithm.SHA3_256): Signer { return SignerImpl(privateKey, hashAlgo) } @JvmStatic @JvmOverloads fun getHasher(hashAlgo: HashAlgorithm = HashAlgorithm.SHA3_256): Hasher { return HasherImpl(hashAlgo) } @JvmStatic fun normalizeSignature(signature: ByteArray, ecCoupleComponentSize: Int): ByteArray { val (r, s) = extractRS(signature) val nLen = ecCoupleComponentSize val paddedSignature = ByteArray(2 * nLen) val rBytes = r.toByteArray() val sBytes = s.toByteArray() // occasionally R/S bytes representation has leading zeroes, so make sure we trim them appropriately rBytes.copyInto(paddedSignature, max(nLen - rBytes.size, 0), max(0, rBytes.size - nLen)) sBytes.copyInto(paddedSignature, max(2 * nLen - sBytes.size, nLen), max(0, sBytes.size - nLen)) return paddedSignature } @JvmStatic fun extractRS(signature: ByteArray): Pair<BigInteger, BigInteger> { val startR = if ((signature[1] and 0x80.toByte()) != 0.toByte()) 3 else 2 val lengthR = signature[startR + 1].toInt() val startS = startR + 2 + lengthR val lengthS = signature[startS + 1].toInt() return Pair( BigInteger(signature.copyOfRange(startR + 2, startR + 2 + lengthR)), BigInteger(signature.copyOfRange(startS + 2, startS + 2 + lengthS)) ) } } internal class HasherImpl( private val hashAlgo: HashAlgorithm ) : Hasher { override fun hash(bytes: ByteArray): ByteArray { val digest = MessageDigest.getInstance(hashAlgo.algorithm) return digest.digest(bytes) } } internal class SignerImpl( private val privateKey: PrivateKey, private val hashAlgo: HashAlgorithm, override val hasher: Hasher = HasherImpl(hashAlgo) ) : Signer { override fun sign(bytes: ByteArray): ByteArray { val ecdsaSign = Signature.getInstance(hashAlgo.id) ecdsaSign.initSign(privateKey.key) ecdsaSign.update(bytes) val signature = ecdsaSign.sign() if (privateKey.ecCoupleComponentSize <= 0) { return signature } return Crypto.normalizeSignature(signature, privateKey.ecCoupleComponentSize) } }
15
Kotlin
24
13
c55e05456f22d3d0751ea0f97258221c4b3b677e
6,541
flow-jvm-sdk
Apache License 2.0
src/test/kotlin/org/strykeforce/thirdcoast/talon/HardLimitCommandsTest.kt
strykeforce
121,652,525
false
null
package org.strykeforce.thirdcoast.talon import com.ctre.phoenix.motorcontrol.LimitSwitchNormal.NormallyOpen import com.ctre.phoenix.motorcontrol.LimitSwitchSource.FeedbackConnector import com.ctre.phoenix.motorcontrol.can.TalonSRX import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.verify import net.consensys.cava.toml.Toml import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.koin.log.Logger.SLF4JLogger import org.koin.standalone.StandAloneContext import org.koin.standalone.inject import org.koin.test.KoinTest import org.koin.test.declare import org.strykeforce.thirdcoast.command.Command import org.strykeforce.thirdcoast.device.TalonService internal class HardLimitCommandsTest : KoinTest { private val toml = Toml.parse( """ type = "menu" [limit] type = "menu" device = "srx" order = 1 menu = "configure soft and hard limits" [limit.forward_hard_source] type = "talon.hard.source" device = "srx" order = 1 forward = true menu = "forward hard limit switch source" [limit.forward_hard_normal] type = "talon.hard.normal" device = "srx" order = 2 forward = true menu = "forward hard limit switch normal" """ ) private val talon: TalonSRX = mock() @BeforeEach fun setUp() { StandAloneContext.startKoin(listOf(), logger = SLF4JLogger()) declare { single { TalonService(mock()) { talon } } } } @Test fun `hard limit source configs talon`() { val root = Command.createFromToml(toml) val talonService: TalonService by inject() talonService.activate(listOf(1)) val source = root.children.first().children.first() as SelectHardLimitSourceCommand root.children.first().children.last() as SelectHardLimitNormalCommand source.setActive(1) // FeedbackConnector verify(talon).configForwardLimitSwitchSource(FeedbackConnector, NormallyOpen) } @AfterEach fun tearDown() { StandAloneContext.stopKoin() } }
0
Kotlin
1
3
d9c64243e8b837f039a436013a960d895ffbd51b
2,295
thirdcoast-tct
MIT License
src/main/java/com/dzen/campfire/server/executors/activities/EActivitiesRelayRaceCreate.kt
timas130
443,572,543
true
{"Kotlin": 1072092}
package com.dzen.campfire.server.executors.activities import com.dzen.campfire.api.API import com.dzen.campfire.api.models.activities.UserActivity import com.dzen.campfire.api.models.fandoms.Fandom import com.dzen.campfire.api.models.publications.moderations.activities.ModerationActivitiesCreate import com.dzen.campfire.api.requests.activities.RActivitiesRelayRaceCreate import com.dzen.campfire.server.controllers.* import com.dzen.campfire.api.tools.ApiException class EActivitiesRelayRaceCreate() : RActivitiesRelayRaceCreate(0,0,0,"","", "") { var fandom = Fandom() override fun check() { name = ControllerCensor.cens(name) description = ControllerCensor.cens(description) ControllerModeration.parseComment(comment) ControllerFandom.checkCan(apiAccount, fandomId, languageId, API.LVL_MODERATOR_RELAY_RACE) if(name.length < API.ACTIVITIES_NAME_MIN || name.length > API.ACTIVITIES_NAME_MAX) throw ApiException(API.ERROR_ACCESS) if(description.length < API.ACTIVITIES_DESC_MIN || description.length > API.ACTIVITIES_DESC_MAX) throw ApiException(API.ERROR_ACCESS) val fandom = ControllerFandom.getFandom(fandomId) if(fandom == null || fandom.status != API.STATUS_PUBLIC) throw ApiException(API.ERROR_ACCESS) this.fandom = fandom val account = ControllerAccounts.getAccount(accountId) if(account == null) throw ApiException(API.ERROR_ACCESS) } override fun execute(): Response { val activity = UserActivity() activity.type = API.ACTIVITIES_TYPE_RELAY_RACE activity.fandom.id = fandomId activity.fandom.languageId = languageId activity.dateCreate = System.currentTimeMillis() activity.name = name activity.creatorId = apiAccount.id activity.description = description activity.fandom.id = fandomId activity.fandom.imageId = fandom.imageId activity.fandom.name = fandom.name ControllerActivities.put(activity) ControllerPublications.moderation(ModerationActivitiesCreate(comment, activity.name, activity.id), apiAccount.id, fandomId, languageId, activity.id) ControllerActivities.makeCurrentMember(apiAccount, accountId, activity) ControllerOptimizer.putCollisionWithCheck(apiAccount.id, API.COLLISION_ACHIEVEMENT_RELAY_RACE_FIRST_CREATE) ControllerAchievements.addAchievementWithCheck(apiAccount.id, API.ACHI_RELAY_RACE_FIRST_CREATE) val accountSettings = ControllerAccounts.getSettings(apiAccount.id) if(accountSettings.userActivitiesAutoSubscribe)ControllerActivities.setSubscribe(apiAccount.id, activity.id) return Response(activity) } }
1
Kotlin
2
0
40a2fbdbbdbe6706ed852f7218cb10fd57e50445
2,720
CampfireServer
Apache License 2.0
app/src/main/java/com/example/bitfit/HealthApplication.kt
dexternguyen56
554,612,321
false
{"Kotlin": 14562}
package com.example.bitfit import android.app.Application class HealthApplication : Application() { val db by lazy { HealthDatabase.getInstance(this) } }
1
Kotlin
0
0
65cae2f8168bc9e385194f81bde9e9f0f86db935
159
BitFit
Apache License 2.0
src/main/kotlin/de/tobiasblaschke/midipi/lib/midi/devices/roland/integra7/RolandIntegra7.kt
milnet2
309,163,438
false
null
package de.tobiasblaschke.midipi.lib.midi.devices.roland.integra7 import de.tobiasblaschke.midipi.lib.midi.bearable.UByteSerializable import de.tobiasblaschke.midipi.lib.midi.bearable.driver.javamidi.MBJavaMidiEndpoint import de.tobiasblaschke.midipi.lib.midi.bearable.lifted.* import de.tobiasblaschke.midipi.lib.midi.devices.roland.integra7.domain.Setup import de.tobiasblaschke.midipi.lib.midi.devices.roland.integra7.domain.StudioSet import de.tobiasblaschke.midipi.lib.midi.devices.roland.integra7.domain.SystemCommon import java.util.concurrent.CompletableFuture import java.util.concurrent.Future class RolandIntegra7( midiDevice: MBJavaMidiEndpoint.MBJavaMidiConnection.MBJavaMidiReadWriteConnection, private val midiMapper: MidiMapper<UByteSerializable, RolandIntegra7MidiMessage> = RolandIntegra7MidiMapper()) { private val device = RequestResponseConnection(midiDevice, midiMapper) private val addressRequestBuilder: MonadicFuture<AddressRequestBuilder> = device.send(RolandIntegra7MidiMessage.IdentityRequest()) .map { it as RolandIntegra7MidiMessage.IdentityReply } .map { AddressRequestBuilder(it.deviceId) } val setup: Setup get() = request({ it.setup }).get() val system: SystemCommon get() = request({ it.system }).get() val studioSet: StudioSet get() = request({ it.studioSet }).get() fun part(p: IntegraPart) = Integra7PartFacade(p, this) init { device.subscribe { val message = midiMapper.lift(it) // println("Received $message") } } fun <M> send(unidirectional: M, timestamp: Long = -1) where M: MBUnidirectionalMidiMessage, M: RolandIntegra7MidiMessage { device.send(unidirectional, timestamp) } fun send(rpn: RolandIntegra7RpnMessage) { rpn.messages.forEach { device.send(it, -1) } } fun <T> request(req: (AddressRequestBuilder) -> Integra7MemoryIO<T>): MonadicFuture<T> { val addressRange = req(addressRequestBuilder.get()) val sysEx: RolandIntegra7MidiMessage = addressRange.asDataRequest1() return device.send(sysEx as MBRequestResponseMidiMessage, -1) .map { it as RolandIntegra7MidiMessage.IntegraSysExDataSet1Response } .map { addressRange.deserialize(it.payload) } } fun identity(): Future<RolandIntegra7MidiMessage.IdentityReply> { return device.send(RolandIntegra7MidiMessage.IdentityRequest()) .map { it as RolandIntegra7MidiMessage.IdentityReply } } fun <T, R> CompletableFuture<T>.map(mapper: (T) -> R): CompletableFuture<R> = this.thenApply(mapper) class Integra7PartFacade(private val part: IntegraPart, private val integra: RolandIntegra7) { val sound: Integra7ToneFacade get() = Integra7ToneFacade(integra.request({ it.tones[part]!! }).get()) class Integra7ToneFacade(val tone: ToneAddressRequestBuilder.TemporaryTone) { // Temporary Tone // val pcm: IntegraToneBuilder.PcmSynthToneBuilder.PcmSynthTone // get() = tone.tone as IntegraToneBuilder.PcmSynthToneBuilder.PcmSynthTone } } } enum class IntegraPart(val zeroBased: Int) { P1(0), P2(1), P3(2), P4(3), P5(4), P6(5), P7(6), P8(7), P9(8), P10(9), P11(10), P12(11), P13(12), P14(13), P15(14), P16(15) }
0
null
0
4
486f5ef85d80baf1e80786109824326be8a1f1e3
3,372
integra7-lib
MIT License
ktx-datetime/src/commonMain/kotlin/tech/antibytes/kfixture/ktx/datetime/generator/LocalTimeGenerator.kt
bitPogo
471,069,650
false
{"Kotlin": 1157506}
/* * Copyright (c) 2022 <NAME> (bitPogo) / All rights reserved. * * Use of this source code is governed by Apache v2.0 */ package tech.antibytes.kfixture.ktx.datetime.generator import kotlin.random.Random import kotlinx.datetime.Instant import kotlinx.datetime.LocalDateTime import kotlinx.datetime.LocalTime import kotlinx.datetime.TimeZone import tech.antibytes.kfixture.PublicApi import tech.antibytes.kfixture.ktx.datetime.KtxDateTimeContract.LocalizedDateTimeGenerator import tech.antibytes.kfixture.qualifier.resolveGeneratorId internal class LocalTimeGenerator( private val dateTimeGenerator: LocalizedDateTimeGenerator<LocalDateTime>, ) : LocalizedDateTimeGenerator<LocalTime> { override fun generate(): LocalTime = generate(null, null) override fun generate( instantGenerator: Function0<Instant>?, timeZoneGenerator: Function0<TimeZone>?, ): LocalTime { return dateTimeGenerator.generate( instantGenerator = instantGenerator, timeZoneGenerator = timeZoneGenerator, ).time } companion object : PublicApi.DependentGeneratorFactory<LocalTime> { @Suppress("UNCHECKED_CAST") override fun getInstance( random: Random, generators: Map<String, PublicApi.Generator<out Any>>, ): PublicApi.Generator<LocalTime> { val localDateTimeId = resolveGeneratorId(LocalDateTime::class) return LocalTimeGenerator( dateTimeGenerator = generators[localDateTimeId] as LocalizedDateTimeGenerator<LocalDateTime>, ) } } }
0
Kotlin
1
10
b4f5c732365c4cd887ccce7c21794729a3769142
1,616
kfixture
Apache License 2.0
Estrutura_de_Repetição/exercicio_027.kt
AlvesTSA
627,567,518
false
{"Kotlin": 65446}
/*27. Faça um programa que calcule o número médio de alunos por turma. Para isto, peça a quantidade de turmas e a quantidade de alunos para cada turma. As turmas não podem ter mais de 40 alunos. */ fun main(){ var turmas: Int var soma: Float var media: Float var alunos: Float soma = 0f print("Informe a quantidade de turmas: ") turmas = readLine()!!.toInt() for(i in 1..turmas){ do{ print("Informe a quantidade de alunos da turma $i: ") alunos = readLine()!!.toFloat() if(alunos > 40){ println("erro: a turma não pode ter mais de 40 allunos.") } }while(alunos > 40) soma += alunos } media = soma/turmas.toFloat() println("Media: $media") return }
0
Kotlin
0
0
5403fa0b398da93cf0cebd027c6883bdb550bc86
811
Exercicios_Kotlin
MIT License
src/commonMain/kotlin/com/drjcoding/plow/issues/PlowIssue.kt
PlowLang
377,725,033
false
null
package com.drjcoding.plow.issues /** * A [PlowIssue] indicates any problem that was encountered while attempting to compile plow code. * * @property errorName Tells the user what the error is. It does not provide information about the specific instance of * the error. It is generic to the error message type. * @property mainInfo Provides the main body of information to the user. * @property notes Provides additional information to the user. */ interface PlowIssue { val errorName: String val mainInfo: PlowIssueInfo val notes: Collection<PlowIssueInfo> }
0
Kotlin
0
2
d308cf06d1fa6a9c78022e96a1937fded78ec58f
579
Plow
MIT License
app/src/main/java/com/segunfrancis/cardinfofinder/presentation/ui/keyboard/EnterCardNumberViewModel.kt
segunfrancis
336,113,626
false
null
package com.segunfrancis.cardinfofinder.presentation.ui.keyboard import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.segunfrancis.cardinfofinder.domain.CardInfoEntity import com.segunfrancis.cardinfofinder.presentation.util.Result import com.segunfrancis.cardinfofinder.presentation.util.toLiveData import com.segunfrancis.cardinfofinder.usecase.GetCardInfoUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class EnterCardNumberViewModel @Inject constructor(private val useCase: GetCardInfoUseCase) : ViewModel() { private val _cardResponse: MutableLiveData<Result<CardInfoEntity>> = MutableLiveData() val cardResponse = _cardResponse.toLiveData() fun getCardInfo(number: String) { viewModelScope.launch { useCase(number) .onStart { _cardResponse.postValue(Result.Loading) } .catch { _cardResponse.postValue(Result.Error(it)) } .collect { _cardResponse.postValue(Result.Success(it)) } } } }
0
Kotlin
0
1
f6ba6fdd060014f9c979a04e3269fc0a623c4c8f
1,263
Card-Info-Finder
The Unlicense
transaction-analyzer/kotlin/src/test/kotlin/TransactionRepositoryFakeLoaderTest.kt
hantsy
322,500,356
false
{"Java": 40275, "Scala": 16848, "PHP": 13139, "C#": 12707, "Kotlin": 12224, "TypeScript": 12122, "JavaScript": 8367, "Go": 4787}
import io.kotest.matchers.shouldBe import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource import java.util.stream.Stream internal class TransactionRepositoryFakeLoaderTest { @ParameterizedTest @MethodSource("provideQueryCriteria") fun `test queryByMerchantAndDateRange against fakeloader loader`( fromDate: String, toDate: String, merchant: String, n: Int ) { val loader: TransactionLoader = object : TransactionLoader { override fun load(): List<Transaction> = fakeTransactionData } val transactions = TransactionRepository(loader) .queryByMerchantAndDateRange( merchant, fromDate.toLocalDateTime(), toDate.toLocalDateTime() ) transactions.size shouldBe n } fun provideQueryCriteria(): Stream<Arguments> { return Stream.of( Arguments.of("20/08/2020 12:00:00", "20/08/2020 13:00:00", "Kwik-E-Mart", 1), Arguments.of("20/08/2020 12:00:00", "20/08/2020 15:00:00", "MacLaren", 2) ) } private val fakeTransactionData = Fixtures.transactionData }
30
Java
0
8
d266c1d7d074e88dace3dd2ce2c7ea20f42d5a79
1,265
code-challenges
Apache License 2.0
app/src/main/java/chenmc/sms/ui/preference/DefaultEditTextPreference.kt
zhidao8
105,611,156
false
null
package chenmc.sms.ui.preference import android.annotation.TargetApi import android.app.AlertDialog import android.content.Context import android.content.res.TypedArray import android.os.Build import android.preference.EditTextPreference import android.util.AttributeSet import chenmc.sms.code.helper.R /** * 这个类跟它的父类 [EditTextPreference] 不同的地方一是 Summary 只显示一行,末尾超出部分以...代替; * 二是弹出的对话框显示 NeutralButton,文本为“默认”,用于恢复当前 Preference 默认的值 * * @author 明 明 * Created on 2017-4-20. */ class DefaultEditTextPreference : EditTextPreference { private var defValue: String? = null @TargetApi(Build.VERSION_CODES.LOLLIPOP) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context) : super(context) override fun onGetDefaultValue(a: TypedArray, index: Int): Any? { defValue = super.onGetDefaultValue(a, index) as String return defValue } /* override fun onBindView(view: View) { super.onBindView(view) val summaryView = view.findViewById<View>( android.R.id.summary) as TextView summaryView.setSingleLine(true) summaryView.ellipsize = TextUtils.TruncateAt.END } */ override fun onPrepareDialogBuilder(builder: AlertDialog.Builder) { builder.setPositiveButton(R.string.ok, this) builder.setNegativeButton(R.string.cancel, this) builder.setNeutralButton(R.string.dialog_default) { _, _ -> if (defValue != null) { this.text = defValue this.summary = defValue } } } }
3
Kotlin
10
69
8c83419e2574c464be5cdd7d2e7a50e4beb08ee9
2,100
SmsCodeHelper
Apache License 2.0
apps/app-chat/src/main/java/vip/qsos/app_chat/receiver/IMPushManagerReceiver.kt
hslooooooool
213,874,367
false
null
package vip.qsos.app_chat.receiver import android.annotation.SuppressLint import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import androidx.core.app.NotificationCompat import com.alibaba.android.arouter.launcher.ARouter import com.google.gson.Gson import qsos.base.chat.api.MessageViewHelper import qsos.base.chat.data.entity.ChatMessage import qsos.lib.base.utils.rx.RxBus import vip.qsos.app_chat.R import vip.qsos.app_chat.config.Constants import vip.qsos.app_chat.data.entity.ChatMessageBo import vip.qsos.app_chat.data.entity.ChatSessionBo import vip.qsos.app_chat.data.entity.MessageExtra import vip.qsos.app_chat.data.entity.Session import vip.qsos.app_chat.view.activity.ChatSessionActivity import vip.qsos.im.lib.AbsIMEventBroadcastReceiver import vip.qsos.im.lib.IMListenerManager import vip.qsos.im.lib.model.Message import vip.qsos.im.lib.model.ReplyBody /** * @author : 华清松 * 消息接收广播服务 */ class IMPushManagerReceiver : AbsIMEventBroadcastReceiver() { override fun onMessageReceived(message: Message, intent: Intent) { IMListenerManager.notifyOnMessageReceived(message) /**强行下线消息*/ if (Constants.MessageAction.ACTION_999 == message.action) { ARouter.getInstance().build("/CHAT/LOGIN").navigation() return } val msg = ChatMessageBo.decode(message) val extra = MessageExtra.json(message.extra!!) showNotify(context, message, msg, extra) notifyView(msg, extra) } /**消息广播*/ @SuppressLint("TimberArgCount") private fun showNotify(context: Context, message: Message, msg: ChatMessage, extra: MessageExtra) { val action = message.action ?: "0" val title = message.title ?: "新消息" val content = ChatMessage.getRealContentDesc(msg.content) val time = message.timestamp val timeline = msg.timeline val avatar = extra.sender?.avatar val sessionId = extra.sessionId val sessionType = extra.sessionType val notificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { val channel = NotificationChannel(action, action, NotificationManager.IMPORTANCE_DEFAULT) channel.enableLights(true) notificationManager.createNotificationChannel(channel) } val sessionIntent = Intent(context, ChatSessionActivity::class.java) val mSessionBo = ChatSessionBo( id = sessionId, type = sessionType, title = title, timeline = timeline, avatar = avatar, content = content ) sessionIntent.putExtra("/CHAT/SESSION_JSON", Gson().toJson(mSessionBo)) val contentIntent = PendingIntent.getActivity( context, 1, sessionIntent, PendingIntent.FLAG_UPDATE_CURRENT ) val builder = NotificationCompat.Builder(context, action) builder.setAutoCancel(true) builder.setDefaults(Notification.DEFAULT_ALL) builder.setWhen(time) builder.setSmallIcon(R.drawable.ic_launcher) builder.setTicker(title) builder.setContentTitle(title) builder.setContentText(content) builder.setDefaults(Notification.DEFAULT_LIGHTS) builder.setContentIntent(contentIntent) notificationManager.notify(R.drawable.ic_launcher, builder.build()) } /**更新消息界面*/ private fun notifyView(msg: ChatMessage, extra: MessageExtra) { RxBus.send(MessageViewHelper.MessageEvent( session = Session( id = msg.sessionId, type = extra.sessionType.key ), message = arrayListOf(msg), eventType = MessageViewHelper.EventType.SHOW_NEW) ) } override fun onConnectionSuccess(hasAutoBind: Boolean) { IMListenerManager.notifyOnConnectionSuccess(hasAutoBind) } override fun onConnectionClosed() { IMListenerManager.notifyOnConnectionClosed() } override fun onReplyReceived(body: ReplyBody) { IMListenerManager.notifyOnReplyReceived(body) } override fun onConnectionFailed() { IMListenerManager.notifyOnConnectionFailed() } }
0
Kotlin
0
1
c437a05814a1deb5865790db36f3cc065c2a4e61
4,616
abcl-b
Apache License 2.0
app/src/main/java/com/hritikbhat/spotify_mvvm_app/ui/activities/AddToCustomPlaylistActivity.kt
HritikBhat
714,975,797
false
{"Kotlin": 222613}
package com.hritikbhat.spotify_mvvm_app.ui.Activities import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.databinding.DataBindingUtil import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import androidx.recyclerview.widget.LinearLayoutManager import com.hritikbhat.spotify_mvvm_app.R import com.hritikbhat.spotify_mvvm_app.adapters.AddToPlaylistAdapter import com.hritikbhat.spotify_mvvm_app.databinding.ActivityAddToCustomPlaylistBinding import com.hritikbhat.spotify_mvvm_app.models.AddSongPlaylistQuery import com.hritikbhat.spotify_mvvm_app.models.FavPlaylistQuery import com.hritikbhat.spotify_mvvm_app.models.FavTransactionResp import com.hritikbhat.spotify_mvvm_app.models.OperationResult import com.hritikbhat.spotify_mvvm_app.models.favPlaylists import com.hritikbhat.spotify_mvvm_app.ui.activities.PlayActivity import com.hritikbhat.spotify_mvvm_app.viewModels.FavouritesViewModel import kotlinx.coroutines.launch class AddToCustomPlaylistActivity : AppCompatActivity(),AddToPlaylistAdapter.OnItemClickListener { private lateinit var binding: ActivityAddToCustomPlaylistBinding private val addToPlaylistAdapter = AddToPlaylistAdapter() private lateinit var sid:String private lateinit var viewModel: FavouritesViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_add_to_custom_playlist) addToPlaylistAdapter.setOnItemClickListener(this) val bundle :Bundle ?=intent.extras sid = bundle?.getString("sid").toString() viewModel = ViewModelProvider(this)[FavouritesViewModel::class.java] viewModel.viewModelScope.launch { setInitForAddToPlay(sid) } } private suspend fun setInitForAddToPlay(sid: String) { //binding.songOptionImg.setImageResource(R.drawable.ic_fav_unselected_white) val operationResult: OperationResult<favPlaylists> = viewModel.getUserCustomFavPlaylist(FavPlaylistQuery(PlayActivity.currPassHash,"-1")) when (operationResult) { is OperationResult.Success -> { // Operation was successful, handle the result val favTransactionResp : favPlaylists = operationResult.data addToPlaylistAdapter.setPlaylistItems(favTransactionResp.favPlaylists,sid) binding.addToPlaylistRC.layoutManager = LinearLayoutManager(this) binding.addToPlaylistRC.adapter = addToPlaylistAdapter } is OperationResult.Error -> { // An error occurred, handle the error val errorMessage = operationResult.message Log.e("ERROR", errorMessage) // Handle the error, for example, display an error message to the user } } } override fun onSelectingAddToPlaylistItemClick(plid: String, sid: String) { //AddFavSong viewModel.viewModelScope.launch { addSongToCustomPlaylist(PlayActivity.currPassHash,plid,sid) } } override fun onSelectingBackButton() { //Nothing here } private suspend fun addSongToCustomPlaylist(currPassHash: String, plid: String, sid: String) { val operationResult: OperationResult<FavTransactionResp> = viewModel.addSongToPlaylist( AddSongPlaylistQuery(currPassHash,plid,sid) ) when (operationResult) { is OperationResult.Success -> { // Operation was successful, handle the result val favTransactionResp : FavTransactionResp = operationResult.data if (favTransactionResp.success){ Toast.makeText(this,favTransactionResp.message, Toast.LENGTH_LONG).show() } else{ Toast.makeText(this,favTransactionResp.message, Toast.LENGTH_LONG).show() } finish() // Process searchList here } is OperationResult.Error -> { // An error occurred, handle the error val errorMessage = operationResult.message Log.e("ERROR", errorMessage) // Handle the error, for example, display an error message to the user } } } }
0
Kotlin
0
0
d73ca6a4405848550b9fdd384c216e41cf324d76
4,491
Spotify_Clone_MVVM_App
MIT License
backend/src/main/kotlin/uk/co/threebugs/darwinexclient/tradingstance/TradingStanceDtoOut.kt
willhumphreys
707,276,309
false
{"Kotlin": 179484, "TypeScript": 78046, "MQL5": 45825, "JavaScript": 8872, "Dockerfile": 2660, "Python": 2634, "CSS": 606, "Shell": 595}
package uk.co.threebugs.darwinexclient.tradingstance import uk.co.threebugs.darwinexclient.accountsetupgroups.* import uk.co.threebugs.darwinexclient.setupgroup.* import uk.co.threebugs.darwinexclient.trade.* data class TradingStanceDtoOut( val id: Int? = null, val symbol: String, val direction: Direction, val accountSetupGroups: AccountSetupGroupsDto, val trades: List<TradeDto> )
4
Kotlin
0
0
dca4d0f38f7ed7daa6a7ba3c20b18c282aec1b81
405
darwinex-client
Apache License 2.0
app/src/main/java/ar/com/wolox/android/cookbook/mpchart/MpChartRecipeView.kt
Wolox
151,121,373
false
{"Kotlin": 366039, "Python": 14314, "Shell": 1335, "Ruby": 171}
package ar.com.wolox.android.cookbook.mpchart import com.github.mikephil.charting.data.BarData import com.github.mikephil.charting.data.BubbleData import com.github.mikephil.charting.data.CandleData import com.github.mikephil.charting.data.CombinedData import com.github.mikephil.charting.data.LineData import com.github.mikephil.charting.data.PieData import com.github.mikephil.charting.data.RadarData import com.github.mikephil.charting.data.ScatterData interface MpChartRecipeView { fun hideGraphs() fun showBarChart(barData: BarData) fun showBubbleChart(bubbleData: BubbleData) fun showCombinedChart(combinedData: CombinedData) fun showHorizontalBarChart(hBarData: BarData) fun showLineChart(lineData: LineData) fun showPieChart(pieData: PieData) fun showRadarChart(radarData: RadarData) fun showCandleStickChart(candleData: CandleData) fun showScatterChart(scatterData: ScatterData) fun showProgressBar() fun hideProgressBar() }
3
Kotlin
11
9
2954e7cf59a22a2e987a61c9722273ee13cf821d
995
wolmo-cookbook-android
MIT License
app/src/main/java/com/ibrajix/nftapp/global/MyApplication.kt
ibrajix
470,727,913
false
{"Kotlin": 23585}
/* * Created by <NAME> on 17/03/2022, 7:43 PM * https://linktr.ee/Ibrajix * Copyright (c) 2022. * All rights reserved. */ package com.ibrajix.nftapp.global import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class MyApplication : Application() { }
0
Kotlin
11
80
94eb98747ccda23b3c333efc6fc24961be769516
316
NftApp
Apache License 2.0
app/src/main/java/sgtmelon/adventofcode/app/presentation/model/exception/WrongInputCharException.kt
SerjantArbuz
559,224,296
false
{"Kotlin": 152755}
package sgtmelon.adventofcode.app.presentation.model.exception class WrongInputCharException( text: String ) : IllegalArgumentException("Something wrong with input, illegal: $text") { constructor(char: Char) : this(char.toString()) }
0
Kotlin
0
0
26a57b8431c03e2d09071f7302d6360ba91bfd2f
244
AdventOfCode
Apache License 2.0
app/src/main/java/com/kodmap/app/kmquickadapter/pagedlistAdapterSample/PagedlistAdapterSampleViewModel.kt
smhdk
161,624,978
false
null
package com.kodmap.app.kmquickadapter.pagedlistAdapterSample import android.app.Application import android.arch.lifecycle.AndroidViewModel import android.arch.lifecycle.LiveData import android.arch.paging.DataSource import android.arch.paging.LivePagedListBuilder import android.arch.paging.PagedList import com.kodmap.app.kmquickadapter.model.TestModel import com.kodmap.app.kmquickadapter.pagedlistAdapterSample.pagedList.SamplePagedDataSource class PagedlistAdapterSampleViewModel(app: Application) : AndroidViewModel(app) { fun getList(): LiveData<PagedList<TestModel>> { val dataSourceFactory = object : android.arch.paging.DataSource.Factory<Int, TestModel>() { override fun create(): DataSource<Int, TestModel>? = SamplePagedDataSource() } val pagedListBuilder = LivePagedListBuilder( dataSourceFactory, PagedList.Config.Builder() .setPageSize(20) .setEnablePlaceholders(false) .build() ) return pagedListBuilder.build() } }
0
Kotlin
2
16
00d1e0d6486ad8b8601530658f47396ade29a720
1,070
KM-Quick-Adapter
The Unlicense
src/main/kotlin/kmtt/constants/Content.kt
DareFox
475,636,361
false
{"Kotlin": 311127}
package kmtt.constants import io.ktor.http.* internal object Content { val JSON = ContentType.parse("application/json") }
0
Kotlin
1
1
b21f24b0153e0856c1f37562bfb7b69be26a5e0a
127
kmttAPI
MIT License
transformerkt/src/main/java/dev/transformerkt/ktx/effects/FadeAudioOut.kt
jordond
644,045,485
false
{"Kotlin": 88962}
package dev.transformerkt.ktx.effects import dev.transformerkt.dsl.effects.EffectsBuilder import dev.transformerkt.effects.VolumeChangeProcessor import dev.transformerkt.effects.VolumeChangeProvider import java.util.concurrent.TimeUnit /** * Creates an [VolumeChangeProvider] that you can use to fade the audio out at the end of the video. * * @param[totalDurationUs] The total duration of the video in microseconds. * @param[inputChannels] The number of input channels. * @param[outputChannels] The number of output channels (defaults to stereo - 2). * @param[initialVolume] The initial volume of the audio stream. * @param[finalVolume] The final volume of the audio stream. * @param[fadeDurationUs] The duration of the fade out in microseconds. */ public fun fadeAudioOutEffect( totalDurationUs: Long, inputChannels: Int, outputChannels: Int = 2, initialVolume: Float = 1f, finalVolume: Float = 0f, fadeDurationUs: Long = TimeUnit.SECONDS.toMicros(1), ): VolumeChangeProcessor { val provider = fadeAudioOutProvider( totalDurationUs = totalDurationUs, initialVolume = initialVolume, finalVolume = finalVolume, fadeDurationUs = fadeDurationUs, ) return volumeChangeEffect( inputChannels = inputChannels, outputChannels = outputChannels, volumeChangeProvider = provider, ) } /** * Add an [VolumeChangeProcessor] to the [EffectsBuilder] that you can use to fade the audio out at * the end of the video. * * @param[totalDurationUs] The total duration of the video in microseconds. * @param[inputChannels] The number of input channels. * @param[outputChannels] The number of output channels (defaults to stereo - 2). * @param[initialVolume] The initial volume of the audio stream. * @param[finalVolume] The final volume of the audio stream. * @param[fadeDurationUs] The duration of the fade out in microseconds. */ public fun EffectsBuilder.fadeAudioOut( totalDurationUs: Long, inputChannels: Int, outputChannels: Int = 2, initialVolume: Float = 1f, finalVolume: Float = 0f, fadeDurationUs: Long = TimeUnit.SECONDS.toMicros(1), ): EffectsBuilder = apply { audio( fadeAudioOutEffect( totalDurationUs = totalDurationUs, inputChannels = inputChannels, outputChannels = outputChannels, initialVolume = initialVolume, finalVolume = finalVolume, fadeDurationUs = fadeDurationUs, ) ) } /** * Creates an [VolumeChangeProvider] that you can use to fade the audio out at the end of the video. * * @param[totalDurationUs] The total duration of the video in microseconds. * @param[initialVolume] The initial volume of the audio stream. * @param[finalVolume] The final volume of the audio stream. * @param[fadeDurationUs] The duration of the fade out in microseconds. */ private fun fadeAudioOutProvider( totalDurationUs: Long, initialVolume: Float, finalVolume: Float, fadeDurationUs: Long, ): VolumeChangeProvider = object : VolumeChangeProvider { override val initial: Float = initialVolume override fun getVolume(timeUs: Long): Float = fadeAudioOut( totalDurationUs = totalDurationUs, fadeDurationUs = fadeDurationUs, currentTimeUs = timeUs, finalVolume = finalVolume, ) } /** * A convenience function that calculates the volume value in order to fade the audio out at the * end of the video. * * @param[totalDurationUs] The total duration of the video in microseconds. * @param[fadeDurationUs] The duration of the fade out in microseconds. * @param[currentTimeUs] The current time of the video in microseconds. * @param[finalVolume] The final volume of the audio stream. */ private fun VolumeChangeProvider.fadeAudioOut( totalDurationUs: Long, fadeDurationUs: Long, currentTimeUs: Long, finalVolume: Float, ): Float { val fadeOutStart = totalDurationUs - fadeDurationUs return if (currentTimeUs < fadeOutStart) initial else { val fadeoutElapsedTime = currentTimeUs - fadeOutStart val fadeOutProgress = fadeoutElapsedTime.toFloat() / fadeDurationUs.toFloat() initial - (initial - finalVolume) * fadeOutProgress } }
3
Kotlin
0
7
e286468c1c24c13533a81956beee8ba9b90668df
4,274
transformerKt
MIT License
app/src/main/java/com/digitalinclined/edugate/adapter/ClassroomDiscussionRecyclerAdapter.kt
thisisvd
447,564,444
false
{"Kotlin": 360695}
package com.digitalinclined.edugate.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.AsyncListDiffer import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.request.RequestOptions import com.digitalinclined.edugate.databinding.ClassroomItemLayoutBinding import com.digitalinclined.edugate.models.ClassroomObjectsDataClass import com.digitalinclined.edugate.utils.DateTimeFormatFetcher import com.google.android.material.snackbar.Snackbar class ClassroomDiscussionRecyclerAdapter : RecyclerView.Adapter<ClassroomDiscussionRecyclerAdapter.ClassroomViewHolder>() { // Diff Util Call Back private val differCallback = object : DiffUtil.ItemCallback<ClassroomObjectsDataClass>() { override fun areItemsTheSame( oldItem: ClassroomObjectsDataClass, newItem: ClassroomObjectsDataClass ): Boolean { return oldItem.timestamp == newItem.timestamp } override fun areContentsTheSame( oldItem: ClassroomObjectsDataClass, newItem: ClassroomObjectsDataClass ): Boolean { return oldItem == newItem } } // Differ Value Setup val differ = AsyncListDiffer(this, differCallback) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ClassroomViewHolder { val binding = ClassroomItemLayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ClassroomViewHolder(binding) } override fun onBindViewHolder(holder: ClassroomViewHolder, position: Int) { // data from dataclasses val data = differ.currentList[position] holder.binding.apply { // Image View val requestOptions = RequestOptions() requestOptions.diskCacheStrategy(DiskCacheStrategy.ALL) requestOptions.centerCrop() if (!data.userImage.isNullOrEmpty()) { Glide.with(root) .load(data.userImage) .apply(requestOptions) .into(classroomUserImageView) } // name classroomUsernameTv.text = data.userName // timestamp postTime.text = DateTimeFormatFetcher().getDateWithIncludedTime(data.timestamp!!.toLong()) // pdf if (!data.pdfNameStored.isNullOrEmpty()) { classroomPdfView.visibility = View.VISIBLE pdfName.text = data.pdfNameStored classroomPdfView.setOnClickListener { onClassroomItemClickListener?.let { it(data.pdfId!!) } } } // image if (!data.imageLink.isNullOrEmpty()) { classroomImageView.visibility = View.VISIBLE Glide.with(root) .load(data.imageLink) .apply(requestOptions) .into(classroomImage) } // discussion classroomDiscussionTv.text = data.description // click listener likeIcon1.setOnClickListener { Snackbar.make(it, "Post appreciated", Snackbar.LENGTH_SHORT).show() } } } override fun getItemCount() = differ.currentList.size // Inner Class ViewHolder inner class ClassroomViewHolder(val binding: ClassroomItemLayoutBinding) : RecyclerView.ViewHolder(binding.root) // On click listener private var onClassroomItemClickListener: ((String) -> Unit)? = null fun setClassroomOnItemClickListener(listener: (String) -> Unit) { onClassroomItemClickListener = listener } }
0
Kotlin
0
0
5dc3146cadc4b6831cee6847390a2902a2348ef0
3,949
Eduvae-plus
Apache License 2.0
newcall_library/src/main/java/com/cmcc/newcalllib/manage/support/ExceptionHandler.kt
NewCallTeam
602,468,716
false
{"Kotlin": 398751, "Java": 195473, "Shell": 2136}
package com.cmcc.newcalllib.manage.support /** * Handler of exceptions */ class ExceptionHandler { }
0
Kotlin
7
7
94959797e2d57f22a1f409a1a852d93f66377399
104
NewCalling
Apache License 2.0
spring-web/src/test/kotlin/org/springframework/web/service/invoker/HttpServiceProxyFactoryExtensionsTests.kt
spring-projects
1,148,753
false
{"Java": 45940326, "Kotlin": 763223, "AspectJ": 31773, "FreeMarker": 30820, "Groovy": 6902, "Shell": 6514, "XSLT": 2945, "HTML": 1140, "Ruby": 1060, "CSS": 1019, "Smarty": 700, "PLpgSQL": 305, "JavaScript": 280, "Dockerfile": 257, "Python": 254}
/* * Copyright 2002-2023 the original author or authors. * * 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 org.springframework.web.service.invoker import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.junit.jupiter.api.Test /** * Tests for [HttpServiceProxyFactory] Kotlin extensions. * * @author <NAME> */ class HttpServiceProxyFactoryExtensionsTests { private val proxyFactory = mockk<HttpServiceProxyFactory>() @Test fun `createClient extension`() { every { proxyFactory.createClient(String::class.java) } returns "" proxyFactory.createClient<String>() verify { proxyFactory.createClient(String::class.java) } } }
352
Java
37,405
54,185
1a52c56bd42c1a9ba8cc8f8849d5f5cb742a97e5
1,195
spring-framework
Apache License 2.0
app/src/main/java/im/status/keycard/connect/data/Constants.kt
status-im
218,495,731
false
null
package im.status.keycard.connect.data const val PAIRING_ACTIVITY_PASSWORD = "<PASSWORD>" const val PIN_ACTIVITY_ATTEMPTS = "remainingAttempts" const val PIN_ACTIVITY_CARD_UID = "cardUID" const val PUK_ACTIVITY_ATTEMPTS = PIN_ACTIVITY_ATTEMPTS const val INIT_ACTIVITY_PIN = "initPIN" const val INIT_ACTIVITY_PUK = "initPUK" const val INIT_ACTIVITY_PAIRING = "initPairing" const val SIGN_TEXT_MESSAGE = "signMessage" const val SIGN_TX_AMOUNT = "signTxAmount" const val SIGN_TX_CURRENCY = "signTxCurrency" const val SIGN_TX_DATA = "signTxData" const val SIGN_TX_TO = "signTxTo" const val LOAD_TYPE = "loadKeyType" const val LOAD_NONE = -1 const val LOAD_IMPORT_BIP39 = 0 const val LOAD_GENERATE_BIP39 = 1 const val LOAD_GENERATE = 2 const val LOAD_MNEMONIC = "loadKeyMnemonic" const val MNEMONIC_PHRASE = "mnemonicPhrase" const val REQ_INTERACTIVE_SCRIPT = 0x01 const val REQ_WALLETCONNECT = 0x02 const val REQ_LOADKEY = 0x03 const val REQ_APPLET_FILE = 0x04 const val CACHE_VALIDITY = 15 * 60 * 1000 const val SETTINGS_CHAIN_ID = "chainID" const val SETTINGS_BIP32_PATH = "bip32Path" const val INFURA_API_KEY = "<KEY>" const val RPC_ENDPOINT_TEMPLATE = "https://%s.infura.io/v3/${INFURA_API_KEY}" const val XDAI_ENDPOINT = "https://rpc.xdaichain.com" const val CHAIN_ID_MAINNET = 1L const val CHAIN_ID_ROPSTEN = 3L const val CHAIN_ID_RINKEBY = 4L const val CHAIN_ID_GOERLI = 5L const val CHAIN_ID_KOVAN = 42L const val CHAIN_ID_XDAI = 100L val CHAIN_ID_TO_SHORTNAME = mapOf(CHAIN_ID_MAINNET to "mainnet", CHAIN_ID_ROPSTEN to "ropsten", CHAIN_ID_RINKEBY to "rinkeby", CHAIN_ID_GOERLI to "goerli", CHAIN_ID_KOVAN to "kovan") val CHAIN_IDS = listOf(CHAIN_ID_MAINNET, CHAIN_ID_XDAI, CHAIN_ID_ROPSTEN, CHAIN_ID_RINKEBY, CHAIN_ID_GOERLI, CHAIN_ID_KOVAN) const val DEFAULT_CHAIN_ID = CHAIN_ID_MAINNET const val DEFAULT_BIP32_PATH = "m/44'/60'/0'/0/0"
5
Kotlin
11
21
5650f448ece63135b6e385e7146ee91430473911
1,888
keycard-connect
Apache License 2.0
bluetooth/bluetooth/src/main/java/androidx/bluetooth/ScanResult.kt
yigit
349,503,567
true
{"Kotlin": 84000427, "Java": 65810421, "C++": 9097978, "AIDL": 565428, "Python": 303418, "Shell": 176746, "HTML": 22691, "ANTLR": 19860, "C": 16935, "TypeScript": 15713, "CMake": 14329, "Svelte": 8127, "GLSL": 3842, "Swift": 3153, "JavaScript": 1571}
/* * 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.bluetooth import android.bluetooth.le.ScanResult as FwkScanResult import android.os.ParcelUuid import java.util.UUID /** * ScanResult for Bluetooth LE scan. * * The ScanResult class is used by Bluetooth LE applications to scan for and discover Bluetooth LE * devices. When a Bluetooth LE application scans for devices, it will receive a list of ScanResult * objects that contain information about the scanned devices. The application can then use this * information to determine which devices it wants to connect to. * * @property device Remote device found * @property deviceAddress Bluetooth address for the remote device found * @property timestampNanos Device timestamp when the result was last seen * @property serviceUuids A list of service UUIDs within advertisement that are used to identify the * bluetooth GATT services. * */ class ScanResult internal constructor(private val fwkScanResult: FwkScanResult) { /** Remote Bluetooth device found. */ val device: BluetoothDevice get() = BluetoothDevice(fwkScanResult.device) // TODO(kihongs) Find a way to get address type from framework scan result /** Bluetooth address for the remote device found. */ val deviceAddress: BluetoothAddress get() = BluetoothAddress(fwkScanResult.device.address, AddressType.ADDRESS_TYPE_RANDOM_STATIC) /** Device timestamp when the advertisement was last seen. */ val timestampNanos: Long get() = fwkScanResult.timestampNanos /** * Returns the manufacturer specific data associated with the manufacturer id. * * @param manufacturerId The manufacturer id of the scanned device * @return the manufacturer specific data associated with the manufacturer id, or null if the * manufacturer specific data is not present */ fun getManufacturerSpecificData(manufacturerId: Int): ByteArray? { return fwkScanResult.scanRecord?.getManufacturerSpecificData(manufacturerId) } /** * A list of service UUIDs within advertisement that are used to identify the bluetooth GATT * services. */ val serviceUuids: List<UUID> get() = fwkScanResult.scanRecord?.serviceUuids?.map { it.uuid }.orEmpty() /** * Returns the service data associated with the service UUID. * * @param serviceUuid The service UUID of the service data * @return the service data associated with the specified service UUID, or null if the service * UUID is not found */ fun getServiceData(serviceUuid: UUID): ByteArray? { return fwkScanResult.scanRecord?.getServiceData(ParcelUuid(serviceUuid)) } /** * Checks if this object represents connectable scan result. * * @return true if the scanned device is connectable; false otherwise */ fun isConnectable(): Boolean { return fwkScanResult.isConnectable } }
1
Kotlin
2
2
ee02274ddff8d63df7435f944214d86fe5a60341
3,531
androidx
Apache License 2.0
src/commonMain/kotlin/com/drjcoding/plow/parser/ast_nodes/PlowFileASTNode.kt
PlowLang
377,725,033
false
null
package com.drjcoding.plow.parser.ast_nodes import com.drjcoding.plow.parser.ast_nodes.declaration_AST_nodes.ImportASTNode import com.drjcoding.plow.parser.cst_nodes.CSTNode import com.drjcoding.plow.project.ast.managers.ASTManagers import com.drjcoding.plow.project.ast.managers.Scope import com.drjcoding.plow.source_abstractions.SourceString data class PlowFileASTNode( val name: SourceString, val imports: List<ImportASTNode>, val children: List<FileChildASTNode>, override val underlyingCSTNode: CSTNode, ) : ASTNode(), ScopeChildASTNode { override fun findScopesAndNames( parentScope: Scope, astManagers: ASTManagers ) { val myScope = parentScope.childWithName(name) astManagers.scopes.insertNewScope(myScope) astManagers.imports.addAll(myScope, imports.map { it.scope }) astManagers.imports.add(myScope, myScope) // TODO this should really be ahead of the imports children.forEach { it.findScopesAndNames(myScope, astManagers) } } } interface FileChildASTNode : ScopeChildASTNode
0
Kotlin
0
2
d308cf06d1fa6a9c78022e96a1937fded78ec58f
1,095
Plow
MIT License
core/src/commonMain/kotlin/com/aitorgf/threekt/core/CameraView.kt
tokkenno
276,641,018
false
null
package com.aitorgf.threekt.core @ExperimentalJsExport @JsExport data class CameraView( var enabled: Boolean = false, var fullWidth: Int = 1, var fullHeight: Int = 1, var offsetX:Int = 0, var offsetY: Int = 0, var width: Int = 1, var height: Int = 1 )
0
Kotlin
0
0
ae7731892ca6784f382c858bf623d68f73819fe9
282
threekt
MIT License