path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/br/com/pix/errors/handlers/ChaveInexistenteHandler.kt
|
cbbathaglini
| 382,929,665 | true |
{"Kotlin": 81129, "Dockerfile": 146}
|
package br.com.pix.errors.handlers
import br.com.pix.errors.exceptions.ChaveInexistenteException
import br.com.pix.errors.exceptions.ClienteInexistenteException
import io.grpc.Status
import javax.inject.Singleton
@Singleton
class ChaveInexistenteHandler : ExceptionHandler<ChaveInexistenteException> {
override fun handle(e: ChaveInexistenteException): ExceptionHandler.StatusWithDetails {
return ExceptionHandler.StatusWithDetails(
Status.NOT_FOUND
.withDescription(e.message)
.withCause(e)
)
}
override fun supports(e: Exception): Boolean {
return e is ChaveInexistenteException
}
}
| 0 |
Kotlin
|
0
| 0 |
4b1ed0cf7b8b387bda9b62e8b9037fdca5743f88
| 671 |
orange-talents-05-template-pix-keymanager-grpc
|
Apache License 2.0
|
orb-kotlin-core/src/main/kotlin/com/withorb/api/models/CustomerCreditTopUpCreateParams.kt
|
orbcorp
| 797,931,036 | false |
{"Kotlin": 18029630, "Shell": 3618, "Dockerfile": 399}
|
// File generated from our OpenAPI spec by Stainless.
package com.withorb.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.withorb.api.core.Enum
import com.withorb.api.core.ExcludeMissing
import com.withorb.api.core.JsonField
import com.withorb.api.core.JsonValue
import com.withorb.api.core.NoAutoDetect
import com.withorb.api.core.toUnmodifiable
import com.withorb.api.errors.OrbInvalidDataException
import com.withorb.api.models.*
import java.util.Objects
import java.util.Optional
class CustomerCreditTopUpCreateParams
constructor(
private val customerId: String,
private val amount: String,
private val currency: String,
private val invoiceSettings: InvoiceSettings,
private val perUnitCostBasis: String,
private val threshold: String,
private val expiresAfter: Long?,
private val expiresAfterUnit: ExpiresAfterUnit?,
private val additionalQueryParams: Map<String, List<String>>,
private val additionalHeaders: Map<String, List<String>>,
private val additionalBodyProperties: Map<String, JsonValue>,
) {
fun customerId(): String = customerId
fun amount(): String = amount
fun currency(): String = currency
fun invoiceSettings(): InvoiceSettings = invoiceSettings
fun perUnitCostBasis(): String = perUnitCostBasis
fun threshold(): String = threshold
fun expiresAfter(): Optional<Long> = Optional.ofNullable(expiresAfter)
fun expiresAfterUnit(): Optional<ExpiresAfterUnit> = Optional.ofNullable(expiresAfterUnit)
@JvmSynthetic
internal fun getBody(): CustomerCreditTopUpCreateBody {
return CustomerCreditTopUpCreateBody(
amount,
currency,
invoiceSettings,
perUnitCostBasis,
threshold,
expiresAfter,
expiresAfterUnit,
additionalBodyProperties,
)
}
@JvmSynthetic internal fun getQueryParams(): Map<String, List<String>> = additionalQueryParams
@JvmSynthetic internal fun getHeaders(): Map<String, List<String>> = additionalHeaders
fun getPathParam(index: Int): String {
return when (index) {
0 -> customerId
else -> ""
}
}
@JsonDeserialize(builder = CustomerCreditTopUpCreateBody.Builder::class)
@NoAutoDetect
class CustomerCreditTopUpCreateBody
internal constructor(
private val amount: String?,
private val currency: String?,
private val invoiceSettings: InvoiceSettings?,
private val perUnitCostBasis: String?,
private val threshold: String?,
private val expiresAfter: Long?,
private val expiresAfterUnit: ExpiresAfterUnit?,
private val additionalProperties: Map<String, JsonValue>,
) {
private var hashCode: Int = 0
/** The amount to increment when the threshold is reached. */
@JsonProperty("amount") fun amount(): String? = amount
/**
* The currency or custom pricing unit to use for this top-up. If this is a real-world
* currency, it must match the customer's invoicing currency.
*/
@JsonProperty("currency") fun currency(): String? = currency
/** Settings for invoices generated by triggered top-ups. */
@JsonProperty("invoice_settings") fun invoiceSettings(): InvoiceSettings? = invoiceSettings
/** How much, in the customer's currency, to charge for each unit. */
@JsonProperty("per_unit_cost_basis") fun perUnitCostBasis(): String? = perUnitCostBasis
/**
* The threshold at which to trigger the top-up. If the balance is at or below this
* threshold, the top-up will be triggered.
*/
@JsonProperty("threshold") fun threshold(): String? = threshold
/**
* The number of days or months after which the top-up expires. If unspecified, it does not
* expire.
*/
@JsonProperty("expires_after") fun expiresAfter(): Long? = expiresAfter
/** The unit of expires_after. */
@JsonProperty("expires_after_unit")
fun expiresAfterUnit(): ExpiresAfterUnit? = expiresAfterUnit
@JsonAnyGetter
@ExcludeMissing
fun _additionalProperties(): Map<String, JsonValue> = additionalProperties
fun toBuilder() = Builder().from(this)
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return other is CustomerCreditTopUpCreateBody &&
this.amount == other.amount &&
this.currency == other.currency &&
this.invoiceSettings == other.invoiceSettings &&
this.perUnitCostBasis == other.perUnitCostBasis &&
this.threshold == other.threshold &&
this.expiresAfter == other.expiresAfter &&
this.expiresAfterUnit == other.expiresAfterUnit &&
this.additionalProperties == other.additionalProperties
}
override fun hashCode(): Int {
if (hashCode == 0) {
hashCode =
Objects.hash(
amount,
currency,
invoiceSettings,
perUnitCostBasis,
threshold,
expiresAfter,
expiresAfterUnit,
additionalProperties,
)
}
return hashCode
}
override fun toString() =
"CustomerCreditTopUpCreateBody{amount=$amount, currency=$currency, invoiceSettings=$invoiceSettings, perUnitCostBasis=$perUnitCostBasis, threshold=$threshold, expiresAfter=$expiresAfter, expiresAfterUnit=$expiresAfterUnit, additionalProperties=$additionalProperties}"
companion object {
@JvmStatic fun builder() = Builder()
}
class Builder {
private var amount: String? = null
private var currency: String? = null
private var invoiceSettings: InvoiceSettings? = null
private var perUnitCostBasis: String? = null
private var threshold: String? = null
private var expiresAfter: Long? = null
private var expiresAfterUnit: ExpiresAfterUnit? = null
private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()
@JvmSynthetic
internal fun from(customerCreditTopUpCreateBody: CustomerCreditTopUpCreateBody) =
apply {
this.amount = customerCreditTopUpCreateBody.amount
this.currency = customerCreditTopUpCreateBody.currency
this.invoiceSettings = customerCreditTopUpCreateBody.invoiceSettings
this.perUnitCostBasis = customerCreditTopUpCreateBody.perUnitCostBasis
this.threshold = customerCreditTopUpCreateBody.threshold
this.expiresAfter = customerCreditTopUpCreateBody.expiresAfter
this.expiresAfterUnit = customerCreditTopUpCreateBody.expiresAfterUnit
additionalProperties(customerCreditTopUpCreateBody.additionalProperties)
}
/** The amount to increment when the threshold is reached. */
@JsonProperty("amount") fun amount(amount: String) = apply { this.amount = amount }
/**
* The currency or custom pricing unit to use for this top-up. If this is a real-world
* currency, it must match the customer's invoicing currency.
*/
@JsonProperty("currency")
fun currency(currency: String) = apply { this.currency = currency }
/** Settings for invoices generated by triggered top-ups. */
@JsonProperty("invoice_settings")
fun invoiceSettings(invoiceSettings: InvoiceSettings) = apply {
this.invoiceSettings = invoiceSettings
}
/** How much, in the customer's currency, to charge for each unit. */
@JsonProperty("per_unit_cost_basis")
fun perUnitCostBasis(perUnitCostBasis: String) = apply {
this.perUnitCostBasis = perUnitCostBasis
}
/**
* The threshold at which to trigger the top-up. If the balance is at or below this
* threshold, the top-up will be triggered.
*/
@JsonProperty("threshold")
fun threshold(threshold: String) = apply { this.threshold = threshold }
/**
* The number of days or months after which the top-up expires. If unspecified, it does
* not expire.
*/
@JsonProperty("expires_after")
fun expiresAfter(expiresAfter: Long) = apply { this.expiresAfter = expiresAfter }
/** The unit of expires_after. */
@JsonProperty("expires_after_unit")
fun expiresAfterUnit(expiresAfterUnit: ExpiresAfterUnit) = apply {
this.expiresAfterUnit = expiresAfterUnit
}
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(): CustomerCreditTopUpCreateBody =
CustomerCreditTopUpCreateBody(
checkNotNull(amount) { "`amount` is required but was not set" },
checkNotNull(currency) { "`currency` is required but was not set" },
checkNotNull(invoiceSettings) {
"`invoiceSettings` is required but was not set"
},
checkNotNull(perUnitCostBasis) {
"`perUnitCostBasis` is required but was not set"
},
checkNotNull(threshold) { "`threshold` is required but was not set" },
expiresAfter,
expiresAfterUnit,
additionalProperties.toUnmodifiable(),
)
}
}
fun _additionalQueryParams(): Map<String, List<String>> = additionalQueryParams
fun _additionalHeaders(): Map<String, List<String>> = additionalHeaders
fun _additionalBodyProperties(): Map<String, JsonValue> = additionalBodyProperties
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return other is CustomerCreditTopUpCreateParams &&
this.customerId == other.customerId &&
this.amount == other.amount &&
this.currency == other.currency &&
this.invoiceSettings == other.invoiceSettings &&
this.perUnitCostBasis == other.perUnitCostBasis &&
this.threshold == other.threshold &&
this.expiresAfter == other.expiresAfter &&
this.expiresAfterUnit == other.expiresAfterUnit &&
this.additionalQueryParams == other.additionalQueryParams &&
this.additionalHeaders == other.additionalHeaders &&
this.additionalBodyProperties == other.additionalBodyProperties
}
override fun hashCode(): Int {
return Objects.hash(
customerId,
amount,
currency,
invoiceSettings,
perUnitCostBasis,
threshold,
expiresAfter,
expiresAfterUnit,
additionalQueryParams,
additionalHeaders,
additionalBodyProperties,
)
}
override fun toString() =
"CustomerCreditTopUpCreateParams{customerId=$customerId, amount=$amount, currency=$currency, invoiceSettings=$invoiceSettings, perUnitCostBasis=$perUnitCostBasis, threshold=$threshold, expiresAfter=$expiresAfter, expiresAfterUnit=$expiresAfterUnit, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}"
fun toBuilder() = Builder().from(this)
companion object {
@JvmStatic fun builder() = Builder()
}
@NoAutoDetect
class Builder {
private var customerId: String? = null
private var amount: String? = null
private var currency: String? = null
private var invoiceSettings: InvoiceSettings? = null
private var perUnitCostBasis: String? = null
private var threshold: String? = null
private var expiresAfter: Long? = null
private var expiresAfterUnit: ExpiresAfterUnit? = null
private var additionalQueryParams: MutableMap<String, MutableList<String>> = mutableMapOf()
private var additionalHeaders: MutableMap<String, MutableList<String>> = mutableMapOf()
private var additionalBodyProperties: MutableMap<String, JsonValue> = mutableMapOf()
@JvmSynthetic
internal fun from(customerCreditTopUpCreateParams: CustomerCreditTopUpCreateParams) =
apply {
this.customerId = customerCreditTopUpCreateParams.customerId
this.amount = customerCreditTopUpCreateParams.amount
this.currency = customerCreditTopUpCreateParams.currency
this.invoiceSettings = customerCreditTopUpCreateParams.invoiceSettings
this.perUnitCostBasis = customerCreditTopUpCreateParams.perUnitCostBasis
this.threshold = customerCreditTopUpCreateParams.threshold
this.expiresAfter = customerCreditTopUpCreateParams.expiresAfter
this.expiresAfterUnit = customerCreditTopUpCreateParams.expiresAfterUnit
additionalQueryParams(customerCreditTopUpCreateParams.additionalQueryParams)
additionalHeaders(customerCreditTopUpCreateParams.additionalHeaders)
additionalBodyProperties(customerCreditTopUpCreateParams.additionalBodyProperties)
}
fun customerId(customerId: String) = apply { this.customerId = customerId }
/** The amount to increment when the threshold is reached. */
fun amount(amount: String) = apply { this.amount = amount }
/**
* The currency or custom pricing unit to use for this top-up. If this is a real-world
* currency, it must match the customer's invoicing currency.
*/
fun currency(currency: String) = apply { this.currency = currency }
/** Settings for invoices generated by triggered top-ups. */
fun invoiceSettings(invoiceSettings: InvoiceSettings) = apply {
this.invoiceSettings = invoiceSettings
}
/** How much, in the customer's currency, to charge for each unit. */
fun perUnitCostBasis(perUnitCostBasis: String) = apply {
this.perUnitCostBasis = perUnitCostBasis
}
/**
* The threshold at which to trigger the top-up. If the balance is at or below this
* threshold, the top-up will be triggered.
*/
fun threshold(threshold: String) = apply { this.threshold = threshold }
/**
* The number of days or months after which the top-up expires. If unspecified, it does not
* expire.
*/
fun expiresAfter(expiresAfter: Long) = apply { this.expiresAfter = expiresAfter }
/** The unit of expires_after. */
fun expiresAfterUnit(expiresAfterUnit: ExpiresAfterUnit) = apply {
this.expiresAfterUnit = expiresAfterUnit
}
fun additionalQueryParams(additionalQueryParams: Map<String, List<String>>) = apply {
this.additionalQueryParams.clear()
putAllQueryParams(additionalQueryParams)
}
fun putQueryParam(name: String, value: String) = apply {
this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value)
}
fun putQueryParams(name: String, values: Iterable<String>) = apply {
this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values)
}
fun putAllQueryParams(additionalQueryParams: Map<String, Iterable<String>>) = apply {
additionalQueryParams.forEach(this::putQueryParams)
}
fun removeQueryParam(name: String) = apply {
this.additionalQueryParams.put(name, mutableListOf())
}
fun additionalHeaders(additionalHeaders: Map<String, Iterable<String>>) = apply {
this.additionalHeaders.clear()
putAllHeaders(additionalHeaders)
}
fun putHeader(name: String, value: String) = apply {
this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value)
}
fun putHeaders(name: String, values: Iterable<String>) = apply {
this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values)
}
fun putAllHeaders(additionalHeaders: Map<String, Iterable<String>>) = apply {
additionalHeaders.forEach(this::putHeaders)
}
fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) }
fun additionalBodyProperties(additionalBodyProperties: Map<String, JsonValue>) = apply {
this.additionalBodyProperties.clear()
this.additionalBodyProperties.putAll(additionalBodyProperties)
}
fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply {
this.additionalBodyProperties.put(key, value)
}
fun putAllAdditionalBodyProperties(additionalBodyProperties: Map<String, JsonValue>) =
apply {
this.additionalBodyProperties.putAll(additionalBodyProperties)
}
fun build(): CustomerCreditTopUpCreateParams =
CustomerCreditTopUpCreateParams(
checkNotNull(customerId) { "`customerId` is required but was not set" },
checkNotNull(amount) { "`amount` is required but was not set" },
checkNotNull(currency) { "`currency` is required but was not set" },
checkNotNull(invoiceSettings) { "`invoiceSettings` is required but was not set" },
checkNotNull(perUnitCostBasis) { "`perUnitCostBasis` is required but was not set" },
checkNotNull(threshold) { "`threshold` is required but was not set" },
expiresAfter,
expiresAfterUnit,
additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(),
additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(),
additionalBodyProperties.toUnmodifiable(),
)
}
/** Settings for invoices generated by triggered top-ups. */
@JsonDeserialize(builder = InvoiceSettings.Builder::class)
@NoAutoDetect
class InvoiceSettings
private constructor(
private val autoCollection: Boolean?,
private val netTerms: Long?,
private val memo: String?,
private val requireSuccessfulPayment: Boolean?,
private val additionalProperties: Map<String, JsonValue>,
) {
private var hashCode: Int = 0
/**
* Whether the credits purchase invoice should auto collect with the customer's saved
* payment method.
*/
@JsonProperty("auto_collection") fun autoCollection(): Boolean? = autoCollection
/**
* The net terms determines the difference between the invoice date and the issue date for
* the invoice. If you intend the invoice to be due on issue, set this to 0.
*/
@JsonProperty("net_terms") fun netTerms(): Long? = netTerms
/** An optional memo to display on the invoice. */
@JsonProperty("memo") fun memo(): String? = memo
/**
* If true, new credit blocks created by this top-up will require that the corresponding
* invoice is paid before they can be drawn down from.
*/
@JsonProperty("require_successful_payment")
fun requireSuccessfulPayment(): Boolean? = requireSuccessfulPayment
@JsonAnyGetter
@ExcludeMissing
fun _additionalProperties(): Map<String, JsonValue> = additionalProperties
fun toBuilder() = Builder().from(this)
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return other is InvoiceSettings &&
this.autoCollection == other.autoCollection &&
this.netTerms == other.netTerms &&
this.memo == other.memo &&
this.requireSuccessfulPayment == other.requireSuccessfulPayment &&
this.additionalProperties == other.additionalProperties
}
override fun hashCode(): Int {
if (hashCode == 0) {
hashCode =
Objects.hash(
autoCollection,
netTerms,
memo,
requireSuccessfulPayment,
additionalProperties,
)
}
return hashCode
}
override fun toString() =
"InvoiceSettings{autoCollection=$autoCollection, netTerms=$netTerms, memo=$memo, requireSuccessfulPayment=$requireSuccessfulPayment, additionalProperties=$additionalProperties}"
companion object {
@JvmStatic fun builder() = Builder()
}
class Builder {
private var autoCollection: Boolean? = null
private var netTerms: Long? = null
private var memo: String? = null
private var requireSuccessfulPayment: Boolean? = null
private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()
@JvmSynthetic
internal fun from(invoiceSettings: InvoiceSettings) = apply {
this.autoCollection = invoiceSettings.autoCollection
this.netTerms = invoiceSettings.netTerms
this.memo = invoiceSettings.memo
this.requireSuccessfulPayment = invoiceSettings.requireSuccessfulPayment
additionalProperties(invoiceSettings.additionalProperties)
}
/**
* Whether the credits purchase invoice should auto collect with the customer's saved
* payment method.
*/
@JsonProperty("auto_collection")
fun autoCollection(autoCollection: Boolean) = apply {
this.autoCollection = autoCollection
}
/**
* The net terms determines the difference between the invoice date and the issue date
* for the invoice. If you intend the invoice to be due on issue, set this to 0.
*/
@JsonProperty("net_terms")
fun netTerms(netTerms: Long) = apply { this.netTerms = netTerms }
/** An optional memo to display on the invoice. */
@JsonProperty("memo") fun memo(memo: String) = apply { this.memo = memo }
/**
* If true, new credit blocks created by this top-up will require that the corresponding
* invoice is paid before they can be drawn down from.
*/
@JsonProperty("require_successful_payment")
fun requireSuccessfulPayment(requireSuccessfulPayment: Boolean) = apply {
this.requireSuccessfulPayment = requireSuccessfulPayment
}
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(): InvoiceSettings =
InvoiceSettings(
checkNotNull(autoCollection) { "`autoCollection` is required but was not set" },
checkNotNull(netTerms) { "`netTerms` is required but was not set" },
memo,
requireSuccessfulPayment,
additionalProperties.toUnmodifiable(),
)
}
}
class ExpiresAfterUnit
@JsonCreator
private constructor(
private val value: JsonField<String>,
) : Enum {
@com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return other is ExpiresAfterUnit && this.value == other.value
}
override fun hashCode() = value.hashCode()
override fun toString() = value.toString()
companion object {
@JvmField val DAY = ExpiresAfterUnit(JsonField.of("day"))
@JvmField val MONTH = ExpiresAfterUnit(JsonField.of("month"))
@JvmStatic fun of(value: String) = ExpiresAfterUnit(JsonField.of(value))
}
enum class Known {
DAY,
MONTH,
}
enum class Value {
DAY,
MONTH,
_UNKNOWN,
}
fun value(): Value =
when (this) {
DAY -> Value.DAY
MONTH -> Value.MONTH
else -> Value._UNKNOWN
}
fun known(): Known =
when (this) {
DAY -> Known.DAY
MONTH -> Known.MONTH
else -> throw OrbInvalidDataException("Unknown ExpiresAfterUnit: $value")
}
fun asString(): String = _value().asStringOrThrow()
}
}
| 2 |
Kotlin
|
0
| 0 |
d2ad23f9ba9b60d46900e154bf3c3ef1d7736222
| 26,729 |
orb-kotlin
|
Apache License 2.0
|
plugins/filePrediction/src/com/intellij/filePrediction/features/FilePredictionFeatureProvider.kt
|
ingokegel
| 72,937,917 | false | null |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.filePrediction.features
import com.intellij.filePrediction.FileFeaturesComputationResult
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.annotations.ApiStatus
internal object FilePredictionFeaturesHelper {
internal val EP_NAME = ExtensionPointName<FilePredictionFeatureProvider>("com.intellij.filePrediction.featureProvider")
fun calculateFileFeatures(project: Project,
newFile: VirtualFile,
cache: FilePredictionFeaturesCache,
prevFile: VirtualFile?): FileFeaturesComputationResult {
val start = System.currentTimeMillis()
val result = HashMap<String, FilePredictionFeature>()
for (provider in EP_NAME.extensionList) {
val prefix = calculateProviderPrefix(provider)
val features = provider.calculateFileFeatures(project, newFile, prevFile, cache).mapKeys { prefix + it.key }
result.putAll(features)
}
return FileFeaturesComputationResult(result, start)
}
fun getFeaturesByProviders(): List<List<String>> {
val orderedFeatures = arrayListOf<List<String>>()
for (provider in getOrderedFeatureProviders()) {
val prefix = calculateProviderPrefix(provider)
orderedFeatures.add(provider.getFeatures().map { prefix + it }.toList())
}
return orderedFeatures
}
private fun getOrderedFeatureProviders(): List<FilePredictionFeatureProvider> {
return EP_NAME.extensionList.sortedBy { it.getName() }
}
private fun calculateProviderPrefix(provider: FilePredictionFeatureProvider) =
if (provider.getName().isNotEmpty()) provider.getName() + "_" else ""
}
@ApiStatus.Internal
interface FilePredictionFeatureProvider {
fun getName(): String
fun getFeatures(): List<String>
fun calculateFileFeatures(project: Project,
newFile: VirtualFile,
prevFile: VirtualFile?,
cache: FilePredictionFeaturesCache): Map<String, FilePredictionFeature>
}
| 1 | null |
1
| 2 |
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 2,274 |
intellij-community
|
Apache License 2.0
|
src/main/kotlin/net/technearts/Member.kt
|
suderio
| 148,840,146 | false |
{"Java": 25926, "Kotlin": 8079}
|
package net.technearts
import org.apache.commons.lang3.StringUtils.isNotBlank
class Member {
var title: String? = null
var column: String? = null
var converterName: String? = null
var converter: ((String) -> Any)? = null
var property: String? = null
var mappedBy: String? = null
var isMapped = true
val isTitleBased: Boolean
get() = isNotBlank(title)
val isReferenceBased: Boolean
get() = isNotBlank(title) || isNotBlank(column)
}
| 3 | null |
1
| 1 |
e1a69fad7477dd343b51678c030340695e8219ea
| 487 |
marxls
|
MIT License
|
library/file/src/commonTest/kotlin/io/matthewnelson/kmp/file/MkdirUnitTest.kt
|
05nelsonm
| 729,001,287 | false |
{"Kotlin": 135683, "Java": 105}
|
/*
* Copyright (c) 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package io.matthewnelson.kmp.file
import kotlin.test.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class MkdirUnitTest {
@Test
fun givenDir_whenExists_thenMkdirReturnsFalse() {
assertFalse(File(PROJECT_DIR_PATH).mkdir())
}
@Test
fun givenDir_whenDoesNotExist_thenMkdirReturnsTrue() {
val dir = randomTemp()
assertTrue(dir.mkdir())
assertTrue(dir.delete())
}
@Test
fun givenDir_when2DirsDeep_thenMkdirReturnsFalse() {
val dir = randomTemp().resolve(randomName())
assertFalse(dir.mkdir())
}
}
| 5 |
Kotlin
|
0
| 1 |
a5a9d4f0367fc44520da0dd6ed1a219916ce729e
| 1,196 |
kmp-file
|
Apache License 2.0
|
app/src/main/kotlin/com/sawrose/movielist/features/movies/MoviesRepository.kt
|
sawrose15
| 152,362,758 | false | null |
package com.sawrose.movielist.features.movies
import com.sawrose.movielist.core.exception.Failure
import com.sawrose.movielist.core.exception.Failure.NetworkConnection
import com.sawrose.movielist.core.exception.Failure.ServerError
import com.sawrose.movielist.core.functional.Either
import com.sawrose.movielist.core.functional.Either.Left
import com.sawrose.movielist.core.functional.Either.Right
import com.sawrose.movielist.core.platform.NetworkHandler
import com.sawrose.movielist.features.model.Movie
import com.sawrose.movielist.features.model.MovieDetails
import com.sawrose.movielist.features.model.MovieDetailsEntity
import com.sawrose.movielist.features.service.MoviesService
import retrofit2.Call
import javax.inject.Inject
interface MoviesRepository {
fun movies(): Either<Failure, List<Movie>>
fun movieDetail(movieId: Int): Either<Failure, MovieDetails>
class Network @Inject constructor(
private val networkHandler: NetworkHandler,
private val service: MoviesService
) : MoviesRepository {
override fun movies(): Either<Failure, List<Movie>> {
return when (networkHandler.isConnected) {
true -> request(service.movies(), { it.map { it.toMovie() } }, emptyList())
false,
null -> Left(NetworkConnection())
}
}
override fun movieDetail(movieId: Int): Either<Failure, MovieDetails> {
return when (networkHandler.isConnected) {
true -> request(service.movieDetails(movieId), { it.toMovieDetails() },
MovieDetailsEntity.empty())
false,
null -> Left(NetworkConnection())
}
}
}
fun <T, R> request(call: Call<T>, transform: (T) -> R, default: T): Either<Failure, R> {
return try {
val response = call.execute()
when (response.isSuccessful) {
true -> Right(transform((response.body() ?: default)))
false -> Left(ServerError())
}
} catch (exception: Throwable) {
Left(ServerError())
}
}
}
| 0 |
Kotlin
|
0
| 0 |
acc88f9454827562bef45f2c77afc3f09b8a3087
| 2,156 |
MovieList
|
Apache License 2.0
|
app/src/main/java/com/example/emapp/classes/PasswordValidator.kt
|
noidoRG
| 578,928,044 | false | null |
/*
* Copyright (c) 2023. Project for Mobile App Development course. <NAME> (@noidoRG).
*/
package com.example.emapp.classes
import android.widget.EditText
import androidx.core.view.isEmpty
import com.example.emapp.R
import com.example.emapp.view.CreateAccount
import com.example.emapp.view.MainActivity
import com.google.android.material.textfield.TextInputLayout
import com.google.firebase.database.IgnoreExtraProperties
@IgnoreExtraProperties
class PasswordValidatorMainActivity(view: MainActivity) {
private var messege: String = ""
private val view = view
public fun ValidatePassword(edPassword: String):Boolean{
if(edPassword.isEmpty()){
messege = view.getString(R.string.fill_field)
return false
}
if((edPassword.length<4) or (edPassword.length>12)){
messege = view.getString(R.string.short_password)
return false
}
return true
}
public fun GetError():String{
return messege
}
}
class PasswordValidatorCreateAccount(view: CreateAccount) {
private var messege: String = ""
private val view = view
public fun ValidatePassword(edPassword: String):Boolean{
if(edPassword.isEmpty()){
messege = view.getString(R.string.fill_field)
return false
}
if((edPassword.length<4) or (edPassword.length>12)){
messege = view.getString(R.string.short_password)
return false
}
return true
}
public fun GetError():String{
return messege
}
}
| 0 |
Kotlin
|
0
| 0 |
f0f8f619b8fa08f3f384387a5396e8e8c2e11c63
| 1,580 |
Beeple
|
MIT License
|
kira/src/main/java/com/popovanton0/kira/suppliers/dataclass/DataClassSupplierConfig.kt
|
popovanton0
| 489,662,148 | false |
{"Kotlin": 294584}
|
package com.popovanton0.kira.suppliers.dataclass
import com.popovanton0.kira.suppliers.BooleanInDataClass
import com.popovanton0.kira.suppliers.EnumInDataClass
import com.popovanton0.kira.suppliers.ObjectInDataClass
import com.popovanton0.kira.suppliers.StringInDataClass
import com.popovanton0.kira.suppliers.WholeNumberInDataClass
public object DataClassSupplierConfig {
internal val paramSupplierProviders: MutableList<DataClassSupplierSupport> = mutableListOf(
BooleanInDataClass,
WholeNumberInDataClass,
StringInDataClass,
EnumInDataClass,
ObjectInDataClass,
)
public fun addParamSupplierProvider(provider: DataClassSupplierSupport): Unit =
paramSupplierProviders.add(0, provider)
}
| 0 |
Kotlin
|
0
| 5 |
b65f7af94b94cd5334fd5070b1676b99a15fbffe
| 750 |
kira
|
Apache License 2.0
|
Kotlin - DigitalHouse/Aula08 e 09/ContaBancaria.kt
|
TVilella
| 291,855,237 | false | null |
abstract class ContaBancaria(val numeroDeConta:Int):Imprimivel{
var saldo: Double = 0.0
protected fun transferir(valorTransferencia:Double, contaDestino: ContaBancaria){
if(valorTransferencia < saldo ){
sacar(valorTransferencia)
contaDestino.depositar(valorTransferencia)
}
}
abstract fun sacar(valorSaque: Double)
abstract fun depositar(valorDeposito: Double)
override fun mostrarDados() {
println("--------------------------------------")
println("Numero da Conta: $numeroDeConta")
println("Saldo: ${"%.2f".format(saldo)}")
}
}
| 0 |
Kotlin
|
0
| 0 |
addf17e93188a53464f04becb47e8e8524ec76ff
| 624 |
mobileandroidcoders05
|
MIT License
|
app/src/main/java/com/qamar/composablewidgets/ui/dragexample/DragExample.kt
|
qamarelsafadi
| 540,119,629 | false |
{"Kotlin": 127484}
|
package com.qamar.composablewidgets.ui.dragexample
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.material.Surface
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.consumeAllChanges
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import kotlin.math.roundToInt
@Composable
fun DragExample(){
Surface() {
Box(modifier = Modifier.fillMaxSize()) {
var offsetX by remember { mutableStateOf(0f) }
var offsetY by remember { mutableStateOf(0f) }
Box(
Modifier
.offset { IntOffset(offsetX.roundToInt(), offsetY.roundToInt()) }
.background(Color.Blue)
.size(50.dp)
.pointerInput(Unit) {
detectDragGestures { change, dragAmount ->
change.consume()
offsetX += dragAmount.x
offsetY += dragAmount.y
}
}
)
}
}
}
| 1 |
Kotlin
|
14
| 48 |
a3a25d1591a6b22c0c9c7a23e87827f72c1da83c
| 1,488 |
ComposableWidgets
|
MIT License
|
kafkistry-web/src/main/kotlin/com/infobip/kafkistry/webapp/menu/MenuItem.kt
|
infobip
| 456,885,171 | false |
{"Kotlin": 2564768, "FreeMarker": 787246, "JavaScript": 296871, "CSS": 6804}
|
package com.infobip.kafkistry.webapp.menu
data class MenuItem(
val id: String,
val name: String,
val urlPath: String,
val newItem: Boolean
)
| 2 |
Kotlin
|
6
| 42 |
06616ab58ca8bf7708fb8c62d584394f4fa303ab
| 173 |
kafkistry
|
Apache License 2.0
|
features/mpmoviedetails/src/main/java/com/jpp/mpmoviedetails/MovieDetailsActionViewModel.kt
|
perettijuan
| 156,444,935 | false | null |
package com.jpp.mpmoviedetails
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jpp.mpdomain.MovieState
import com.jpp.mpdomain.usecase.GetMovieStateUseCase
import com.jpp.mpdomain.usecase.Try
import com.jpp.mpdomain.usecase.UpdateFavoriteMovieStateUseCase
import com.jpp.mpdomain.usecase.UpdateWatchlistMovieStateUseCase
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* [ViewModel] that supports the movie details actions (the data shown by the UI that is not
* related to the actions that the user can perform is controlled by [MovieDetailsViewModel]). The VM retrieves
* the data from the underlying layers and maps the business
* data to UI data, producing a [MovieDetailViewState] that represents the configuration of the view
* at any given moment.
*
* When the user performs an action (either fav, add to watchlist or rate) the VM updates the state
* of the movie internally and in the server side and updates the view layer according to the new
* state of the business layer.
*/
class MovieDetailsActionViewModel(
private val getMovieStateUseCase: GetMovieStateUseCase,
private val updateFavoriteUseCase: UpdateFavoriteMovieStateUseCase,
private val updateWatchListUseCase: UpdateWatchlistMovieStateUseCase,
private val ioDispatcher: CoroutineDispatcher,
private val savedStateHandle: SavedStateHandle
) : ViewModel() {
private val _viewState = MutableLiveData<MovieDetailActionViewState>()
internal val viewState: LiveData<MovieDetailActionViewState> = _viewState
private var movieId: Double
set(value) = savedStateHandle.set(MOVIE_ID_KEY, value)
get() = savedStateHandle.get(MOVIE_ID_KEY)
?: throw IllegalStateException("Trying to access $MOVIE_ID_KEY when it is not yet set")
/**
* Called when the view is initialized.
*/
fun onInit(movieId: Double) {
this.movieId = movieId
fetchMovieState(movieId)
}
fun onRetry() {
fetchMovieState(movieId)
}
/**
* Called when the user selects the main action. This will
* start the animation to show/hide the possible actions the
* user can take.
*/
fun onMainActionSelected() {
viewState.value?.let { currentViewState ->
_viewState.value = currentViewState.copy(
animate = true,
expanded = !currentViewState.expanded
)
}
}
/**
* Called when the user attempts to change the favorite state of
* the movie being handled.
*/
fun onFavoriteStateChanged() {
val currentFavorite = _viewState.value?.favoriteButtonState?.asFilled ?: return
_viewState.value = _viewState.value?.showLoadingFavorite()
viewModelScope.launch {
val result = withContext(ioDispatcher) {
updateFavoriteUseCase.execute(movieId, !currentFavorite)
}
when (result) {
is Try.Success -> processUpdateFavorite()
is Try.Failure -> processStateChangedError(result.cause)
}
}
}
/**
* Called when the user attempts to change the watchlist state of the
* movie being handled.
*/
fun onWatchlistStateChanged() {
val currentWatchlist = _viewState.value?.watchListButtonState?.asFilled ?: return
_viewState.value = _viewState.value?.showLoadingWatchlist()
viewModelScope.launch {
val result = withContext(ioDispatcher) {
updateWatchListUseCase.execute(movieId, !currentWatchlist)
}
when (result) {
is Try.Success -> processUpdateWatchlist()
is Try.Failure -> processStateChangedError(result.cause)
}
}
}
private fun fetchMovieState(movieId: Double) {
_viewState.value = MovieDetailActionViewState.showLoading()
viewModelScope.launch {
val result = withContext(ioDispatcher) {
getMovieStateUseCase.execute(movieId)
}
_viewState.value = processMovieStateUpdate(result.getOrNull())
}
}
/**
* Internally called when a new [MovieState] is ready to be processed.
* Syncs the current view state with [movieState] and produces a new
* view state to be rendered.
*/
private fun processMovieStateUpdate(movieState: MovieState?): MovieDetailActionViewState? {
return viewState.value?.let { currentViewState ->
val watchListButtonState = if (movieState != null && movieState.watchlist) {
currentViewState.watchListButtonState.asFilled()
} else {
currentViewState.watchListButtonState.asEmpty()
}
val favoriteButtonState = if (movieState != null && movieState.favorite) {
currentViewState.favoriteButtonState.asFilled()
} else {
currentViewState.favoriteButtonState.asEmpty()
}
currentViewState.showLoaded(
watchListButtonState,
favoriteButtonState
)
}
}
private fun processUpdateFavorite() {
viewState.value?.let { currentViewState ->
_viewState.value =
currentViewState.copy(favoriteButtonState = currentViewState.favoriteButtonState.flipState())
}
}
private fun processUpdateWatchlist() {
viewState.value?.let { currentViewState ->
_viewState.value =
currentViewState.copy(watchListButtonState = currentViewState.watchListButtonState.flipState())
}
}
private fun processStateChangedError(errorCause: Try.FailureCause) {
_viewState.value = when (errorCause) {
is Try.FailureCause.UserNotLogged -> _viewState.value?.showUserNotLogged()
else -> _viewState.value?.showReload()
}
}
private companion object {
const val MOVIE_ID_KEY = "MOVIE_ID_KEY"
}
}
| 9 |
Kotlin
|
7
| 46 |
7921806027d5a9b805782ed8c1cad447444f476b
| 6,223 |
moviespreview
|
Apache License 2.0
|
lib/klutter-test/src/main/kotlin/dev/buijs/klutter/test/integration/KittyElement.kt
|
buijs-dev
| 436,644,099 | false | null |
/* Copyright (c) 2021 - 2022 Buijs Software
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package dev.buijs.klutter.test.integration
import org.openqa.selenium.By
abstract class KittyElement {
abstract fun byIOS(): By
abstract fun byAndroid(): By
}
data class KittyTextField(
private val elementId: String,
): KittyElement() {
override fun byIOS(): By {
//TODO
return By.xpath("//fegfsgedfsfdfd\"$elementId\"]")
}
override fun byAndroid(): By {
//TODO
return By.xpath("//fdsfsdfsdfs\"$elementId\"]")
}
}
data class KittyButton(
private val elementId: String,
): KittyElement() {
override fun byIOS(): By {
return By.xpath("//XCUIElementTypeButton[@label=\"$elementId\"]")
}
override fun byAndroid(): By {
return By.xpath("//android.view.View[@content-desc=\"$elementId\"]")
}
}
| 2 |
Kotlin
|
3
| 167 |
95caba34119a7ca120ca6cd2ead8991dac22cb6a
| 1,922 |
klutter
|
MIT License
|
src/test/kotlin/cz/zubal/spring/multimodule/SpringBootMultimoduleApplicationTests.kt
|
mzubal
| 123,785,587 | false | null |
package cz.zubal.spring.multimodule
import cz.zubal.spring.multimodule.customer.api.Customer
import cz.zubal.spring.multimodule.customer.api.CustomerService
import cz.zubal.spring.multimodule.item.api.Item
import cz.zubal.spring.multimodule.item.api.ItemService
import cz.zubal.spring.multimodule.order.api.Order
import cz.zubal.spring.multimodule.order.api.OrderService
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringRunner
import java.math.BigDecimal
@RunWith(SpringRunner::class)
@SpringBootTest
class SpringBootMultimoduleApplicationTests {
@Autowired
internal lateinit var orderService: OrderService
@Autowired
internal lateinit var customerService: CustomerService
@Autowired
internal lateinit var itemService: ItemService
@Test
fun simpleIntegrationTest() {
val customer = Customer()
customer.username = "milos"
customer.firstName = "Milos"
customer.lastName = "Zubal"
customerService.create(customer)
val item = Item()
item.uuid = "item-1"
item.name = "vim"
item.description = "Text editor to learn."
item.type = "Text Editor"
item.price = BigDecimal(0)
itemService.create(item)
val order = Order()
order.customer = customer
order.items = listOf(item)
orderService.create(order)
}
}
| 0 |
Kotlin
|
3
| 26 |
083e6953c7baf5d82c75e3dc2ec555cbf984efcc
| 1,545 |
spring-gradle-kotlin-multimodule
|
MIT License
|
hebe-android/lib/src/androidTest/java/io/github/wulkanowy/signer/hebe/android/SignerTest.kt
|
wulkanowy
| 141,020,396 | false |
{"Kotlin": 46042, "Python": 15896, "C#": 14718, "JavaScript": 11590, "HTML": 6230, "Dart": 5394, "PHP": 4851, "CSS": 2183}
|
package io.github.wulkanowy.signer.hebe.android
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import java.text.SimpleDateFormat
import java.util.*
@RunWith(AndroidJUnit4::class)
class SignerTest {
private val fullUrl = "/powiatwulkanowy/123456/api/mobile/register/hebe"
private val fingerprint = "7EBA57E1DDBA1C249D097A9FF1C9CCDD45351A6A"
private val privateKey = "<KEY>A<KEY>"
private val body = "{}"
@Test
fun signerTest() {
val (digest, canonicalUrl, signature) = getSignatureValues(fingerprint, privateKey, body, fullUrl, getDate("2020-04-14 04:14:16"))
assertEquals("SHA-256=RBNvo1WzZ4oRRq0W9+hknpT7T8If536DEMBg9hyq/4o=", digest)
assertEquals("api%2fmobile%2fregister%2fhebe", canonicalUrl)
assertEquals("keyId=\"7EBA57E1DDBA1C249D097A9FF1C9CCDD45351A6A\"," +
"headers=\"vCanonicalUrl Digest vDate\"," +
"algorithm=\"sha256withrsa\"," +
"signature=Base64(SHA256withRSA(m<KEY>DDXsyJVo/LznQKOyvOaW4tEfrBobxtbtTnp7zYi54bdvAZa3pvM02yvkH4i/DvTLDKRO0R9UDZ1LraGrOTsIe3m3mQ21NOynVqCKadeqod8Y7l4YUlVYEmrtq/7xbCwr0qdne6G67eY4Amj6ffbG3TkVLpUrEETBnAC7oFjGYKhcRyvltAi+lcv6omANz1gwELf+Vmsa8NwFo/YGwY3R23z15athU/1iC1JcrECBLC8nRM1+KlvyIqx2HX6RG5R1cMOwBWVg6pRKUdrhxYbQ+VQ8Cag==))",
signature)
}
private fun getDate(date: String) = SimpleDateFormat("yyyy-MM-dd hh:mm:ss").apply {
timeZone = TimeZone.getTimeZone("UTC")
}.parse(date)
}
| 0 |
Kotlin
|
7
| 15 |
deefe47faaf4f062a97033a44534fd7ce6703563
| 1,566 |
uonet-request-signer
|
MIT License
|
hebe-android/lib/src/androidTest/java/io/github/wulkanowy/signer/hebe/android/SignerTest.kt
|
wulkanowy
| 141,020,396 | false |
{"Kotlin": 46042, "Python": 15896, "C#": 14718, "JavaScript": 11590, "HTML": 6230, "Dart": 5394, "PHP": 4851, "CSS": 2183}
|
package io.github.wulkanowy.signer.hebe.android
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import java.text.SimpleDateFormat
import java.util.*
@RunWith(AndroidJUnit4::class)
class SignerTest {
private val fullUrl = "/powiatwulkanowy/123456/api/mobile/register/hebe"
private val fingerprint = "7EBA57E1DDBA1C249D097A9FF1C9CCDD45351A6A"
private val privateKey = "<KEY>A<KEY>"
private val body = "{}"
@Test
fun signerTest() {
val (digest, canonicalUrl, signature) = getSignatureValues(fingerprint, privateKey, body, fullUrl, getDate("2020-04-14 04:14:16"))
assertEquals("SHA-256=RBNvo1WzZ4oRRq0W9+hknpT7T8If536DEMBg9hyq/4o=", digest)
assertEquals("api%2fmobile%2fregister%2fhebe", canonicalUrl)
assertEquals("keyId=\"7EBA57E1DDBA1C249D097A9FF1C9CCDD45351A6A\"," +
"headers=\"vCanonicalUrl Digest vDate\"," +
"algorithm=\"sha256withrsa\"," +
"signature=Base64(SHA256withRSA(m<KEY>DDXsyJVo/LznQKOyvOaW4tEfrBobxtbtTnp7zYi54bdvAZa3pvM02yvkH4i/DvTLDKRO0R9UDZ1LraGrOTsIe3m3mQ21NOynVqCKadeqod8Y7l4YUlVYEmrtq/7xbCwr0qdne6G67eY4Amj6ffbG3TkVLpUrEETBnAC7oFjGYKhcRyvltAi+lcv6omANz1gwELf+Vmsa8NwFo/YGwY3R23z15athU/1iC1JcrECBLC8nRM1+KlvyIqx2HX6RG5R1cMOwBWVg6pRKUdrhxYbQ+VQ8Cag==))",
signature)
}
private fun getDate(date: String) = SimpleDateFormat("yyyy-MM-dd hh:mm:ss").apply {
timeZone = TimeZone.getTimeZone("UTC")
}.parse(date)
}
| 0 |
Kotlin
|
7
| 15 |
deefe47faaf4f062a97033a44534fd7ce6703563
| 1,566 |
uonet-request-signer
|
MIT License
|
base/src/main/kotlin/browser/bookmarks/OnRemovedListener.kt
|
DATL4G
| 372,873,797 | false | null |
@file:JsModule("webextension-polyfill")
@file:JsQualifier("bookmarks")
package browser.bookmarks
/**
* Fired when a bookmark or folder is removed. When a folder is removed recursively, a single
* notification is fired for the folder, and none for its contents.
*/
public external interface OnRemovedListener {
public var id: String
public var removeInfo: RemoveInfoProperty
}
| 0 |
Kotlin
|
1
| 37 |
ab2a825dd8dd8eb704278f52c603dbdd898d1875
| 387 |
Kromex
|
Apache License 2.0
|
etherscanapi/src/main/java/jfyg/network/queries/AccountsApi.kt
|
EbenezerGH
| 122,701,093 | false | null |
package jfyg.network.queries
import io.reactivex.Single
import jfyg.network.response.account.AccountBalanceResponse
import jfyg.network.response.account.AccountBlockResponse
import jfyg.network.response.account.ERC20Response
import jfyg.network.response.account.AccountInternalTxResponse
import jfyg.network.response.account.AccountMultiBalanceResponse
import jfyg.network.response.account.AccountTxResponse
/**
* https://etherscan.io/apis#accounts
*/
internal interface AccountsApi {
/**
* Get Ether Balance for a single Address
*/
fun accountBalance(module: String,
action: String,
address: String,
tag: String): Single<AccountBalanceResponse>
/**
* Get Ether Balance for multiple Addresses in a single call
*/
fun accountMultiBalance(module: String,
action: String,
address: String,
tag: String?): Single<AccountMultiBalanceResponse>
/**
* Get list of blocks mined by address
*/
fun accountBlock(module: String,
action: String,
address: String,
blocktype: String): Single<AccountBlockResponse>
/**
* Get a list of 'Normal' Transactions By Address
*/
fun accountTxs(module: String,
action: String,
address: String,
startblock: String,
endblock: String,
sort: String): Single<AccountTxResponse>
/**
* [BETA] Get a list of "ERC20 - Token Transfer Events" by Address
*/
fun accountERC20Txs(module: String,
action: String,
address: String,
startblock: String,
endblock: String,
sort: String): Single<ERC20Response>
/**
* [BETA] Get a list of 'Internal' Transactions by Address
*/
fun accountInternalTxs(module: String,
action: String,
address: String,
startblock: String,
endblock: String,
sort: String): Single<AccountInternalTxResponse>
}
| 11 |
Kotlin
|
3
| 3 |
cbad4b28e4a22c3577b367c2ad68398ae3fa232f
| 2,323 |
etherscan-android-api
|
MIT License
|
src/main/kotlin/br/upf/sistemadevoos/model/Voo.kt
|
gcerbaro
| 702,686,292 | false |
{"Kotlin": 30040}
|
package br.upf.sistemadevoos.model
import jakarta.persistence.Entity
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
@Entity
data class Voo(
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long? = null,
val origem: String,
val destino: String,
val nAssentos: Int,
var assentosDisp: List<Int> = listOf()
)
| 0 |
Kotlin
|
0
| 0 |
92ff8508c07128587cb40d7a0d307a8d4ca579b7
| 413 |
SistemaVoosKotlin
|
MIT License
|
app/src/main/java/lt/getpet/getpet/glide/OptimizedImageSizeUrl.kt
|
GotPet
| 153,828,011 | false |
{"Kotlin": 78573}
|
package lt.getpet.getpet.glide
import android.net.Uri
class OptimizedImageSizeUrl(private val imageUrl: String) {
fun optimizedImageSizeUrl(width: Int, height: Int): String {
return Uri.parse(imageUrl).buildUpon()
.appendQueryParameter("w", width.toString())
.appendQueryParameter("h", height.toString())
.toString()
}
}
| 0 |
Kotlin
|
1
| 0 |
f1603cc232dd76a406c76231b229e2150f9ae70a
| 387 |
getpet-android
|
Apache License 2.0
|
src/main/kotlin/eZmaxApi/models/EzsigntemplatepackageMinusEditEzsigntemplatepackagesignersMinusV1MinusRequest.kt
|
eZmaxinc
| 271,950,932 | false | null |
/**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package eZmaxApi.models
import eZmaxApi.models.EzsigntemplatepackagesignerMinusRequestCompound
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Request for PUT /1/object/ezsigntemplatepackage/{pkiEzsigntemplatepackageID}/editEzsigntemplatepackagesigners
*
* @param aObjEzsigntemplatepackagesigner
*/
data class EzsigntemplatepackageMinusEditEzsigntemplatepackagesignersMinusV1MinusRequest (
@Json(name = "a_objEzsigntemplatepackagesigner")
val aObjEzsigntemplatepackagesigner: kotlin.collections.List<EzsigntemplatepackagesignerMinusRequestCompound>
)
| 0 |
Kotlin
|
0
| 0 |
885d51ce1f6a5ae02b253e68422693923f1e4e5e
| 869 |
eZmax-SDK-kotlin
|
MIT License
|
app/src/main/java/com/pns/lk/fragment/FourthFragment.kt
|
waplak
| 408,456,480 | false | null |
package com.pns.lk.fragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.pns.lk.R
/**
* A simple [Fragment] subclass.
*/
class FourthFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fourth, container, false)
}
}
| 0 |
Kotlin
|
0
| 0 |
6fa09da3e89e35bf4c3bfc16d857dbbc8377a207
| 553 |
PNSCallDetails
|
MIT License
|
src/main/kotlin/ui/settings/reducer/AddCategoryReducer.kt
|
gmatyszczak
| 171,290,380 | false | null |
package ui.settings.reducer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import model.Category
import model.CategoryScreenElements
import ui.settings.SettingsEffect
import ui.settings.SettingsState
import javax.inject.Inject
interface AddCategoryReducer {
operator fun invoke()
}
class AddCategoryReducerImpl @Inject constructor(
private val state: MutableStateFlow<SettingsState>,
effect: MutableSharedFlow<SettingsEffect>,
scope: CoroutineScope,
private val selectScreenElementReducer: SelectScreenElementReducer
) : BaseReducer(state, effect, scope), AddCategoryReducer {
override fun invoke() {
val newId = state.value.categories.size
val newCategories = state.value.categories.toMutableList()
.apply { add(CategoryScreenElements(Category.getDefault(newId), emptyList())) }
pushState {
copy(
isModified = true,
selectedElementIndex = null,
categories = newCategories,
selectedCategoryIndex = newCategories.size - 1
)
}
selectScreenElementReducer(-1)
}
}
| 5 |
Kotlin
|
27
| 130 |
1fcfbb0bf39d6f1dbe3b69016c39fb3d79214e7e
| 1,223 |
screen-generator-plugin
|
Apache License 2.0
|
domain/src/commonMain/kotlin/uk/co/sentinelweb/cuer/domain/ext/PlaylistItemDomainExt.kt
|
sentinelweb
| 220,796,368 | false |
{"Kotlin": 2627509, "CSS": 205156, "Java": 98919, "Swift": 85812, "HTML": 19322, "JavaScript": 12105, "Ruby": 2170}
|
import uk.co.sentinelweb.cuer.app.orchestrator.OrchestratorContract.Identifier.Locator
import uk.co.sentinelweb.cuer.app.orchestrator.OrchestratorContract.Source
import uk.co.sentinelweb.cuer.domain.PlaylistItemDomain
import uk.co.sentinelweb.cuer.domain.ext.rewriteIdsToSource
import uk.co.sentinelweb.cuer.domain.ext.summarise
fun PlaylistItemDomain.summarise(): String =
"ITEM: id: $id, order: $order, playlistId: $playlistId, media: ${media.summarise()}"
fun PlaylistItemDomain.rewriteIdsToSource(source: Source, locator: Locator?) = this.copy(
id = this.id?.copy(source = source, locator = locator),
media = this.media.rewriteIdsToSource(source, locator)
)
| 95 |
Kotlin
|
0
| 2 |
ededd667157400da44e696c2da5adaf6f9b763ee
| 677 |
cuer
|
Apache License 2.0
|
app/src/main/java/com/mean/traclock/ui/EditRecordActivity.kt
|
fossabot
| 469,648,263 | true |
{"Kotlin": 145245}
|
package com.mean.traclock.ui
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Circle
import androidx.compose.material.icons.filled.MoreHoriz
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.core.view.WindowCompat
import com.loper7.date_time_picker.dialog.CardDatePickerDialog
import com.mean.traclock.App
import com.mean.traclock.R
import com.mean.traclock.database.Record
import com.mean.traclock.ui.components.TopBar
import com.mean.traclock.ui.theme.TraclockTheme
import com.mean.traclock.ui.utils.SetSystemBar
import com.mean.traclock.utils.Database
import com.mean.traclock.utils.getDateTimeString
import com.mean.traclock.viewmodels.EditRecordViewModel
import com.mean.traclock.viewmodels.EditRecordViewModelFactory
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
class EditRecordActivity : AppCompatActivity() {
private var showDialog = MutableStateFlow(false)
private var isModified = false
@SuppressLint("UnrememberedMutableState")
@OptIn(
ExperimentalMaterial3Api::class,
androidx.compose.material.ExperimentalMaterialApi::class
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
val viewModel by viewModels<EditRecordViewModel> {
EditRecordViewModelFactory(
getRecord(intent)
)
}
isModified = viewModel.isModified()
setContent {
TraclockTheme {
SetSystemBar()
val project by viewModel.project.collectAsState("")
val startTime by viewModel.startTime.collectAsState(0L)
val endTime by viewModel.endTime.collectAsState(0L)
val showMenu = mutableStateOf(false)
val showDialogState by showDialog.collectAsState(false)
val builder = CardDatePickerDialog.builder(this).showBackNow(false)
.setThemeColor(MaterialTheme.colorScheme.primary.toArgb())
val scrollBehavior = remember { TopAppBarDefaults.pinnedScrollBehavior() }
Scaffold(
topBar = {
TopBar(
navigationIcon = {
IconButton(onClick = { finish() }) {
Icon(Icons.Filled.ArrowBack, getString(R.string.back))
}
},
title = getString(R.string.edit_record),
actions = {
IconButton(onClick = { showMenu.value = true }) {
Icon(Icons.Filled.MoreHoriz, stringResource(R.string.more))
}
DropdownMenu(
expanded = showMenu.value,
onDismissRequest = { showMenu.value = false }
) {
DropdownMenuItem(
text = { Text(stringResource(R.string.delete)) },
onClick = {
Database.deleteRecord(viewModel.record)
super.finish()
}
)
}
},
scrollBehavior = scrollBehavior
)
},
modifier = Modifier
.nestedScroll(scrollBehavior.nestedScrollConnection),
) {
val state = rememberModalBottomSheetState(ModalBottomSheetValue.Hidden)
val scope = rememberCoroutineScope()
ModalBottomSheetLayout(
sheetState = state,
sheetContent = {
Surface {
val projects by App.projects.collectAsState(listOf())
Column(
modifier = Modifier
.navigationBarsPadding()
.padding(
horizontal = 32.dp,
vertical = 16.dp
)
) {
Text(
stringResource(R.string.projects),
style = MaterialTheme.typography.headlineSmall,
modifier = Modifier.padding(vertical = 8.dp)
)
for (project1 in projects) {
Row(
modifier = Modifier
.fillMaxWidth()
.clickable {
viewModel.setProject(project1.name)
isModified = viewModel.isModified()
scope.launch {
state.hide()
}
}
.padding(vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Icon(
imageVector = Icons.Default.Circle,
contentDescription = null,
tint = Color(project1.color),
modifier = Modifier
.size(32.dp)
.padding(8.dp, 0.dp)
)
Text(
project1.name,
style = MaterialTheme.typography.headlineSmall
)
}
}
}
}
}
) {
Surface {
Column(
modifier = Modifier
.navigationBarsPadding()
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Text(
stringResource(R.string.project),
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.weight(1f)
)
OutlinedButton(
onClick = { scope.launch { state.show() } },
modifier = Modifier.weight(3f)
) {
Text(project)
}
}
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Text(
stringResource(R.string.start),
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.weight(1f)
)
OutlinedButton(
onClick = {
builder.setDefaultTime(startTime)
builder.setOnChoose {
viewModel.setStartTime(it)
isModified = viewModel.isModified()
}
builder.build().show()
},
modifier = Modifier.weight(3f)
) {
Text(getDateTimeString(startTime))
}
}
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Text(
stringResource(R.string.end),
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.weight(1f)
)
OutlinedButton(
onClick = {
builder.setDefaultTime(endTime)
builder.setOnChoose {
viewModel.setEndTime(it)
isModified = viewModel.isModified()
}
builder.build().show()
},
modifier = Modifier.weight(3f)
) {
Text(getDateTimeString(endTime))
}
}
Button(onClick = {
when (viewModel.updateRecord()) {
2 -> super.finish()
1 -> super.finish()
-1 -> Toast.makeText(
this@EditRecordActivity,
[email protected](R.string.please_enter_a_project_name),
Toast.LENGTH_SHORT
).show()
-2 -> Toast.makeText(
this@EditRecordActivity,
[email protected](R.string.no_such_project),
Toast.LENGTH_SHORT
).show()
}
}) {
Text(stringResource(R.string.save))
}
}
}
}
}
if (showDialogState) {
AlertDialog(
onDismissRequest = { showDialog.value = false },
title = { Text(stringResource(R.string.discard_changes)) },
confirmButton = {
TextButton(
onClick = {
showDialog.value = false
}
) {
Text(
stringResource(R.string.keep_editing),
fontWeight = FontWeight.Bold
)
}
},
dismissButton = {
TextButton(
onClick = {
super.finish()
}
) {
Text(
stringResource(R.string.discard),
fontWeight = FontWeight.Bold
)
}
},
text = { Text(stringResource(R.string.discard_text)) }
)
}
}
}
}
override fun finish() {
if (isModified) {
showDialog.value = true
} else {
super.finish()
}
}
private fun getRecord(intent: Intent): Record {
val record = Record(
intent.getStringExtra("project") ?: "",
intent.getLongExtra("startTime", 0L),
intent.getLongExtra("endTime", 0L),
intent.getIntExtra("date", 0)
)
record.id = intent.getIntExtra("id", 0)
return record
}
}
| 0 |
Kotlin
|
0
| 0 |
32c6d480508ed7d3a1c9486a91c45b4d97d29b91
| 16,031 |
Traclock
|
Apache License 2.0
|
app/src/main/java/com/nafanya/mp3world/features/remoteSongs/di/RemoteSongsComponentProvider.kt
|
AlexSoWhite
| 445,900,000 | false |
{"Kotlin": 324834}
|
package com.nafanya.mp3world.features.remoteSongs.di
interface RemoteSongsComponentProvider {
val remoteSongsComponent: RemoteSongsComponent
}
| 0 |
Kotlin
|
0
| 0 |
ee7cff2c21e4731caeb3064c21cc89fcfc8a49c2
| 149 |
mp3world
|
MIT License
|
InkBetterAndroidViews/src/main/java/com/inlacou/inkbetterandroidviews/helpers/recyclerview/StartSnapHelper.kt
|
inlacou
| 400,138,100 | false | null |
package com.inlacou.inkbetterandroidviews.helpers
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.OrientationHelper
import androidx.recyclerview.widget.RecyclerView
import io.reactivex.rxjava3.annotations.NonNull
import io.reactivex.rxjava3.annotations.Nullable
/**
* Created by amitshekhar on 15/01/17.
*/
class StartSnapHelper : LinearSnapHelper() {
private var mVerticalHelper: OrientationHelper? = null
private var mHorizontalHelper: OrientationHelper? = null
@Throws(IllegalStateException::class)
override fun attachToRecyclerView(@Nullable recyclerView: RecyclerView?) {
super.attachToRecyclerView(recyclerView)
}
override fun calculateDistanceToFinalSnap(@NonNull layoutManager: RecyclerView.LayoutManager,
@NonNull targetView: View): IntArray {
val out = IntArray(2)
if (layoutManager.canScrollHorizontally()) {
out[0] = distanceToStart(targetView, getHorizontalHelper(layoutManager))
} else {
out[0] = 0
}
if (layoutManager.canScrollVertically()) {
out[1] = distanceToStart(targetView, getVerticalHelper(layoutManager))
} else {
out[1] = 0
}
return out
}
override fun findSnapView(layoutManager: RecyclerView.LayoutManager): View? {
return if (layoutManager is LinearLayoutManager) {
if (layoutManager.canScrollHorizontally()) {
getStartView(layoutManager, getHorizontalHelper(layoutManager))
} else {
getStartView(layoutManager, getVerticalHelper(layoutManager))
}
} else super.findSnapView(layoutManager)
}
private fun distanceToStart(targetView: View, helper: OrientationHelper): Int {
return helper.getDecoratedStart(targetView) - helper.startAfterPadding
}
private fun getStartView(layoutManager: RecyclerView.LayoutManager,
helper: OrientationHelper): View? {
if (layoutManager is LinearLayoutManager) {
val firstChild = layoutManager.findFirstVisibleItemPosition()
val isLastItem = layoutManager
.findLastCompletelyVisibleItemPosition() == layoutManager.getItemCount() - 1
if (firstChild == RecyclerView.NO_POSITION || isLastItem) {
return null
}
val child = layoutManager.findViewByPosition(firstChild)
return if (helper.getDecoratedEnd(child) >= helper.getDecoratedMeasurement(child) / 2 && helper.getDecoratedEnd(child) > 0) {
child
} else {
if (layoutManager.findLastCompletelyVisibleItemPosition() == layoutManager.getItemCount() - 1) {
null
} else {
layoutManager.findViewByPosition(firstChild + 1)
}
}
}
return super.findSnapView(layoutManager)
}
private fun getVerticalHelper(layoutManager: RecyclerView.LayoutManager): OrientationHelper {
if (mVerticalHelper == null) {
mVerticalHelper = OrientationHelper.createVerticalHelper(layoutManager)
}
return mVerticalHelper!!
}
private fun getHorizontalHelper(layoutManager: RecyclerView.LayoutManager): OrientationHelper {
if (mHorizontalHelper == null) {
mHorizontalHelper = OrientationHelper.createHorizontalHelper(layoutManager)
}
return mHorizontalHelper!!
}
}
| 0 |
Kotlin
|
0
| 0 |
4c2ccb1a494d9410aec89736d08b8b613d61f149
| 3,201 |
InkCommons
|
MIT License
|
app/src/main/java/in/bitotsav/profile/data/RegistrationHistoryItem.kt
|
aksh1618
| 162,024,068 | false | null |
package `in`.bitotsav.profile.data
import `in`.bitotsav.shared.ui.SimpleRecyclerViewAdapter
data class RegistrationHistoryItem(
val eventId: Int,
val eventName: String,
val teamName: String,
val rank: String,
val members: List<String>
) : SimpleRecyclerViewAdapter.SimpleItem() {
override fun getUniqueIdentifier() = eventId.toString()
}
| 0 |
Kotlin
|
7
| 19 |
21014f34dcfc59a73fcc1d86be7f48d7a993f638
| 363 |
Bitotsav-19
|
Apache License 2.0
|
app/src/main/java/com/omarsalinas/btmessenger/dialogs/SaveUserNameDialog.kt
|
osalinasv
| 131,105,269 | false | null |
package com.omarsalinas.btmessenger.dialogs
import android.content.DialogInterface
import android.os.Bundle
import android.support.v7.app.AlertDialog
import com.omarsalinas.btmessenger.R
import com.omarsalinas.btmessenger.common.SimpleDialog
class SaveUserNameDialog : SimpleDialog() {
companion object {
private const val BUNDLE_USERNAME = "com.omarsalinas.btmessenger.bundle_username"
fun newInstance(userName: String, onPositive: (dialog: DialogInterface?) -> Unit, onCancel: () -> Unit): SaveUserNameDialog {
val bundle = Bundle()
bundle.putString(BUNDLE_USERNAME, userName)
val dialog = SaveUserNameDialog()
dialog.arguments = bundle
dialog.onPositive = onPositive
dialog.onCancel = onCancel
return dialog
}
}
var onPositive: (dialog: DialogInterface?) -> Unit = { }
var onCancel: () -> Unit = { }
override fun setup(dialog: AlertDialog.Builder) {
val userName: String = arguments?.getString(BUNDLE_USERNAME) ?: ""
dialog.setTitle(R.string.fragment_login_save_username)
.setMessage(this.activity!!.getString(R.string.fragment_login_save_username_message, userName))
.setPositiveButton(android.R.string.ok) { d: DialogInterface?, _: Int ->
run {
d?.dismiss()
onPositive(d)
}
}
.setNegativeButton(android.R.string.no) { d: DialogInterface?, _: Int ->
run {
d?.cancel()
}
}
this.isCancelable = true
}
override fun onCancel(dialog: DialogInterface?) {
onCancel()
}
}
| 0 |
Kotlin
|
0
| 0 |
85bdd93d82edcb2820dafb97fdc2945c04b88890
| 1,784 |
bt-messenger
|
Apache License 2.0
|
api/src/main/kotlin/com/seedcompany/cordtables/components/tables/common/blogs/Read.kt
|
CordField
| 409,237,733 | false | null |
package com.seedcompany.cordtables.components.tables.common.blogs
import com.seedcompany.cordtables.common.ErrorType
import com.seedcompany.cordtables.common.Utility
import com.seedcompany.cordtables.components.admin.GetSecureListQuery
import com.seedcompany.cordtables.components.admin.GetSecureListQueryRequest
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.CrossOrigin
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.ResponseBody
import java.sql.SQLException
import javax.sql.DataSource
data class CommonBlogsReadRequest(
val token: String?,
val id: String? = null,
)
data class CommonBlogsReadResponse(
val error: ErrorType,
val blog: blog? = null,
)
@CrossOrigin(origins = ["http://localhost:3333", "https://dev.cordtables.com", "https://cordtables.com", "*"])
@Controller("CommonBlogsRead")
class Read(
@Autowired
val util: Utility,
@Autowired
val ds: DataSource,
@Autowired
val secureList: GetSecureListQuery,
) {
var jdbcTemplate: NamedParameterJdbcTemplate = NamedParameterJdbcTemplate(ds)
@PostMapping("common/blogs/read")
@ResponseBody
fun readHandler(@RequestBody req: CommonBlogsReadRequest): CommonBlogsReadResponse {
if (req.token == null) return CommonBlogsReadResponse(ErrorType.InputMissingToken)
if (!util.isAdmin(req.token)) return CommonBlogsReadResponse(ErrorType.AdminOnly)
if (req.id == null) return CommonBlogsReadResponse(ErrorType.MissingId)
val paramSource = MapSqlParameterSource()
paramSource.addValue("token", req.token)
paramSource.addValue("id", req.id)
val query = secureList.getSecureListQueryHandler(
GetSecureListQueryRequest(
tableName = "common.blogs",
getList = false,
columns = arrayOf(
"id",
"title",
"created_at",
"created_by",
"modified_at",
"modified_by",
"owning_person",
"owning_group",
),
)
).query
try {
val jdbcResult = jdbcTemplate.queryForRowSet(query, paramSource)
while (jdbcResult.next()) {
var id: String? = jdbcResult.getString("id")
if (jdbcResult.wasNull()) id = null
var title: String? = jdbcResult.getString("title")
if (jdbcResult.wasNull()) title = null
var created_at: String? = jdbcResult.getString("created_at")
if (jdbcResult.wasNull()) created_at = null
var created_by: String? = jdbcResult.getString("created_by")
if (jdbcResult.wasNull()) created_by = null
var modified_at: String? = jdbcResult.getString("modified_at")
if (jdbcResult.wasNull()) modified_at = null
var modified_by: String? = jdbcResult.getString("modified_by")
if (jdbcResult.wasNull()) modified_by = null
var owning_person: String? = jdbcResult.getString("owning_person")
if (jdbcResult.wasNull()) owning_person = null
var owning_group: String? = jdbcResult.getString("owning_group")
if (jdbcResult.wasNull()) owning_group = null
val blog =
blog(
id = id,
title = title,
created_at = created_at,
created_by = created_by,
modified_at = modified_at,
modified_by = modified_by,
owning_person = owning_person,
owning_group = owning_group,
)
return CommonBlogsReadResponse(ErrorType.NoError, blog = blog)
}
} catch (e: SQLException) {
println("error while listing ${e.message}")
return CommonBlogsReadResponse(ErrorType.SQLReadError)
}
return CommonBlogsReadResponse(error = ErrorType.UnknownError)
}
}
| 93 |
Kotlin
|
1
| 3 |
7e5588a8b3274917f9a5df2ffa12d27db23fb909
| 4,513 |
cordtables
|
MIT License
|
app/src/main/java/com/example/androiddevchallenge/data/PuppyListProvider.kt
|
anhvt52
| 342,250,558 | false | null |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.data
import com.example.androiddevchallenge.R
val puppies = listOf<Puppy>(
Puppy(
1,
"Rex",
"male",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Nisl tincidunt eget nullam non. Quis hendrerit dolor magna eget est lorem ipsum dolor sit. Volutpat odio facilisis mauris sit amet massa.",
R.drawable.puppy1
),
Puppy(
2,
"Sophie",
"female",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Nisl tincidunt eget nullam non. Quis hendrerit dolor magna eget est lorem ipsum dolor sit. Volutpat odio facilisis mauris sit amet massa.",
R.drawable.puppy2
),
Puppy(
3,
"Bella",
"female",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Nisl tincidunt eget nullam non. Quis hendrerit dolor magna eget est lorem ipsum dolor sit. Volutpat odio facilisis mauris sit amet massa.",
R.drawable.puppy3
),
Puppy(4, "Katniss", "male", "abcdef", R.drawable.puppy4),
Puppy(5, "Oprah", "male", "abcdef", R.drawable.puppy5),
Puppy(6, "Madonna", "male", "abcdef", R.drawable.puppy6),
Puppy(7, "Rex", "male", "abcdef", R.drawable.puppy1),
Puppy(8, "Sophie", "female", "abcdef", R.drawable.puppy2),
Puppy(9, "Bella", "female", "abcdef", R.drawable.puppy3),
Puppy(10, "Katniss", "male", "abcdef", R.drawable.puppy4),
Puppy(11, "Oprah", "male", "abcdef", R.drawable.puppy5),
Puppy(12, "Madonna", "male", "abcdef", R.drawable.puppy6)
)
| 0 |
Kotlin
|
0
| 0 |
71dcdd56b730ab04e96009023e4f35f18ee16aef
| 2,374 |
puppy
|
Apache License 2.0
|
auth/src/main/java/studio/crud/feature/auth/authentication/model/CustomParamsDTO.kt
|
crud-studio
| 390,327,908 | false | null |
package studio.crud.feature.auth.authentication.model
data class CustomParamsDTO(
val param1: String = "",
val param2: String = "",
val param3: String = "",
val param4: String = "",
val param5: String = ""
)
| 6 |
Kotlin
|
0
| 0 |
6cb1d5f7b3fc7117c9fbaaf6708ac93ae631e674
| 248 |
feature-depot
|
MIT License
|
data/src/main/java/pokedroid/data/RxApolloClient.kt
|
esafirm
| 233,633,395 | true |
{"Kotlin": 15257}
|
package pokedroid.data
import com.apollographql.apollo.ApolloClient
import com.apollographql.apollo.api.Mutation
import com.apollographql.apollo.api.Operation
import com.apollographql.apollo.api.Query
import com.apollographql.apollo.api.Response
import com.apollographql.apollo.rx2.Rx2Apollo
import io.reactivex.Observable
class RxApolloClient(private val apolloClient: ApolloClient) : ApiCaller {
override fun <D : Operation.Data?, T, V : Operation.Variables?> query(
query: Query<D, T, V>
): Observable<Response<T>> {
return Rx2Apollo.from(apolloClient.query(query))
}
override fun <D : Operation.Data?, T, V : Operation.Variables?> mutate(
mutation: Mutation<D, T, V>
): Observable<Response<T>> {
return Rx2Apollo.from(apolloClient.mutate(mutation))
}
}
| 0 |
Kotlin
|
3
| 7 |
c1cbc6f7eb7572b5b272686325c3eea2be5f2ab2
| 816 |
pokedroid
|
MIT License
|
compiler/testData/codegen/bytecodeListing/inlineClasses/inlineCollection/set.kt
|
JetBrains
| 3,432,266 | false | null |
// IGNORE_ANNOTATIONS
inline class InlineSet<T>(private val s: Set<T>) : Set<T> {
override val size: Int get() = s.size
override fun contains(element: T): Boolean = s.contains(element)
override fun containsAll(elements: Collection<T>): Boolean = s.containsAll(elements)
override fun isEmpty(): Boolean = s.isEmpty()
override fun iterator(): Iterator<T> = s.iterator()
}
| 181 | null |
5748
| 49,172 |
33eb9cef3d146062c103f9853d772f0a1da0450e
| 392 |
kotlin
|
Apache License 2.0
|
src/main/kotlin/com/github/oduig/auctionswindler/blizzard/generated/WowAuctionPage.kt
|
Oduig
| 201,813,155 | false | null |
package com.github.oduig.auctionswindler.blizzard.generated
data class WowAuctionPage(
val pageNumber: Int,
val totalPages: Int,
val auctionList: WowAuctionList
)
| 0 |
Kotlin
|
0
| 0 |
fbe50b740e65280122d5677b7ca33d4c760539eb
| 176 |
auction-swindler
|
Apache License 2.0
|
autoplaylist-backend/src/main/kotlin/com.richodemus/autoplaylist/SpotifyClient.kt
|
eHammarstedt
| 140,621,705 | true |
{"Kotlin": 17717, "JavaScript": 10938, "HTML": 1716, "Shell": 587, "CSS": 440}
|
package com.richodemus.autoplaylist
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonValue
import com.fasterxml.jackson.module.kotlin.readValue
import com.github.kittinunf.fuel.Fuel
import com.github.kittinunf.fuel.core.Request
import com.github.kittinunf.result.Result
import io.github.vjames19.futures.jdk8.map
import org.slf4j.LoggerFactory
import java.net.URL
import java.net.URLEncoder
import java.util.Base64
import java.util.UUID
import java.util.concurrent.CompletableFuture
private val logger = LoggerFactory.getLogger("SpotifyClient")
private val s = "${clientId()}:${clientSecret()}"
private val authString = "Basic " + Base64.getEncoder().encodeToString(s.toByteArray())
internal fun buildClientUrl() = URL(
"https://accounts.spotify.com/authorize?response_type=code" +
"&client_id=${clientId().encode()}" +
"&scope=${scope()}" +
"&redirect_uri=${redirectUrl().encode()}" +
"&state=${UUID.randomUUID().toString().encode()}" +
"&show_dialog=false"
)
internal fun getToken(code: String): CompletableFuture<Tokens> {
return Fuel.post("https://accounts.spotify.com/api/token",
listOf(
"grant_type" to "authorization_code",
"code" to code,
"redirect_uri" to redirectUrl(),
"client_id" to clientId(),
"client_secret" to clientSecret()
))
.deserialize()
}
internal fun getUserId(accessToken: AccessToken): CompletableFuture<UserId> {
return Fuel.get("https://api.spotify.com/v1/me")
.header("Content-Type" to "application/json")
.header("Authorization" to "Bearer $accessToken")
.deserialize<User>()
.map { it.id }
}
internal fun getPlaylists(accessToken: AccessToken): CompletableFuture<PlayListsResponse> {
return Fuel.get("https://api.spotify.com/v1/me/playlists")
.header("Content-Type" to "application/json")
.header("Authorization" to "Bearer $accessToken")
.deserialize()
}
internal fun refreshToken(refreshToken: RefreshToken): CompletableFuture<Tokens> {
return Fuel.post("https://accounts.spotify.com/api/token",
listOf(
"grant_type" to "refresh_token",
"refresh_token" to refreshToken
))
.header("Authorization" to authString)
.deserialize()
}
internal fun findArtist(accessToken: AccessToken, name: ArtistName): CompletableFuture<List<Artist>> {
return Fuel.get("https://api.spotify.com/v1/search",
listOf(
"q" to name,
"type" to "artist"
))
.header("Content-Type" to "application/json")
.header("Authorization" to "Bearer $accessToken")
.deserialize<FindArtistResponse>()
.map { it.artists.items }
}
internal fun getAlbums(accessToken: AccessToken, artist: ArtistId): CompletableFuture<List<Album>> {
return Fuel.get("https://api.spotify.com/v1/artists/$artist/albums")
.header("Content-Type" to "application/json")
.header("Authorization" to "Bearer $accessToken")
.deserialize<GetAlbumsResponse>()
.map { it.items }
}
internal fun getTracks(accessToken: AccessToken, album: AlbumId): CompletableFuture<List<Track>> {
return Fuel.get("https://api.spotify.com/v1/albums/$album/tracks")
.header("Content-Type" to "application/json")
.header("Authorization" to "Bearer $accessToken")
.deserialize<GetTracksResponse>()
.map { it.items }
}
internal fun createPlaylist(accessToken: AccessToken,
userId: UserId,
name: PlaylistName,
description: String,
public: Boolean): CompletableFuture<PlayList> {
return Fuel.post("https://api.spotify.com/v1/users/$userId/playlists")
.header("Content-Type" to "application/json")
.header("Authorization" to "Bearer $accessToken")
.body("""
{
"name":"$name",
"description":"$description",
"public":$public
}
""".trimIndent())
.deserialize()
}
internal fun addTracks(accessToken: AccessToken,
user: UserId,
playList: PlayListId,
tracks: List<TrackUri>): CompletableFuture<SnapshotId> {
val request = AddTracksToPlaylistRequest(tracks)
val json = mapper.writeValueAsString(request)
return Fuel.post("https://api.spotify.com/v1/users/$user/playlists/$playList/tracks")
.header("Content-Type" to "application/json")
.header("Authorization" to "Bearer $accessToken")
.body(json)
.deserialize<AddTracksToPlaylistRespose>()
.map { it.snapshot_id }
}
private inline fun <reified T : Any> Request.deserialize(): CompletableFuture<T> {
val future = CompletableFuture<T>()
this.responseString { _, _, result ->
when (result) {
is Result.Failure -> {
val ex = result.getException()
logger.error("Call failed: ${result.error.response}", ex)
future.completeExceptionally(ex)
}
is Result.Success -> {
val data = result.get()
val playListsResponse: T
try {
playListsResponse = mapper.readValue(data)
future.complete(playListsResponse)
} catch (e: Exception) {
logger.info("Unable to deserialize {}", data, e)
throw kotlin.RuntimeException("Unable to deserialize $data: ${e.message}")
}
}
}
}
return future
}
private fun String.encode() = URLEncoder.encode(this, "utf-8")
internal data class Tokens(
@JsonProperty("access_token") val accessToken: AccessToken,
@JsonProperty("scope") val scope: String,
@JsonProperty("token_type") val tokenType: String,
@JsonProperty("expires_in") val expiresIn: Int,
@JsonProperty("refresh_token") val refreshToken: RefreshToken?
)
internal data class AccessToken(@get:JsonIgnore val value: String) {
init {
require(value.isNotBlank()) { "AccessToken can't be empty" }
}
@JsonValue
override fun toString() = value
}
internal data class RefreshToken(@get:JsonIgnore val value: String) {
init {
require(value.isNotBlank()) { "AccessToken can't be empty" }
}
@JsonValue
override fun toString() = value
}
internal data class User(val id: UserId)
internal data class UserId(@get:JsonIgnore val value: String) {
init {
require(value.isNotBlank()) { "UserId can't be empty" }
}
@JsonValue
override fun toString() = value
}
internal data class PlayListsResponse(val items: List<PlayList>, val total: Int)
internal data class PlayList(val id: PlayListId, val name: PlaylistName)
internal data class PlaylistName(@get:JsonIgnore val value: String) {
init {
require(value.isNotBlank()) { "PlaylistName can't be empty" }
}
@JsonValue
override fun toString() = value
}
internal data class PlayListId(@get:JsonIgnore val value: String) {
init {
require(value.isNotBlank()) { "PlayListId can't be empty" }
}
@JsonValue
override fun toString() = value
}
internal data class FindArtistResponse(val artists: Artists)
internal data class Artists(val items: List<Artist>, val total: Int)
internal data class Artist(val id: ArtistId, val name: ArtistName)
internal data class ArtistName(@get:JsonIgnore val value: String) {
init {
require(value.isNotBlank()) { "ArtistName can't be empty" }
}
@JsonValue
override fun toString() = value
}
internal data class ArtistId(@get:JsonIgnore val value: String) {
init {
require(value.isNotBlank()) { "ArtistId can't be empty" }
}
@JsonValue
override fun toString() = value
}
internal data class GetAlbumsResponse(val items: List<Album>, val total: Int)
internal data class Album(val id: AlbumId, val name: String, val album_group: String)
internal data class AlbumId(@get:JsonIgnore val value: String) {
init {
require(value.isNotBlank()) { "AlbumId can't be empty" }
}
@JsonValue
override fun toString() = value
}
internal data class GetTracksResponse(val items: List<Track>, val total: Int)
internal data class Track(val id: TrackId, val name: TrackName, val uri: TrackUri)
internal data class TrackId(@get:JsonIgnore val value: String) {
init {
require(value.isNotBlank()) { "TrackId can't be empty" }
}
@JsonValue
override fun toString() = value
}
internal data class TrackName(@get:JsonIgnore val value: String) {
init {
require(value.isNotBlank()) { "TrackName can't be empty" }
}
@JsonValue
override fun toString() = value
}
internal data class TrackUri(@get:JsonIgnore val value: String) {
init {
require(value.isNotBlank()) { "TrackUri can't be empty" }
}
@JsonValue
override fun toString() = value
}
internal data class AddTracksToPlaylistRequest(val uris: List<TrackUri>)
internal data class AddTracksToPlaylistRespose(val snapshot_id: SnapshotId)
internal data class SnapshotId(@get:JsonIgnore val value: String) {
init {
require(value.isNotBlank()) { "SnapshotId can't be empty" }
}
@JsonValue
override fun toString() = value
}
| 0 |
Kotlin
|
0
| 0 |
3c7ab616e1d87e91b2712d74763d0ee83c675a46
| 9,823 |
autoplaylist
|
Apache License 2.0
|
composeApp/src/androidMain/kotlin/backup/ImportJAlcoMeter.android.kt
|
thaapasa
| 702,418,399 | false |
{"Kotlin": 476702, "Swift": 661, "Shell": 262}
|
package fi.tuska.beerclock.backup
import androidx.compose.material3.Button
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import fi.tuska.beerclock.backup.jalcometer.ImportJAlkaMetriViewModel
import fi.tuska.beerclock.ui.composables.rememberWithDispose
actual fun isJAlcoMeterImportSupported(): Boolean {
return true
}
@Composable
actual fun ImportJAlkaMetriDataButton(
title: String,
modifier: Modifier,
snackbar: SnackbarHostState,
) {
val context = LocalContext.current
val vm = rememberWithDispose { ImportJAlkaMetriViewModel(context, snackbar) }
vm.Status()
FilePicker(
onFilePicked = { file -> file?.let(vm::import) },
) { onClick ->
Button(onClick = onClick, enabled = !vm.importing, modifier = modifier) {
Text(title)
}
}
}
| 1 |
Kotlin
|
0
| 2 |
ed954c500564d21d482609d62ff9b4178f4d6f64
| 984 |
beerclock
|
Apache License 2.0
|
browser-kotlin/src/main/kotlin/web/animations/AnimationTimeline.kt
|
karakum-team
| 393,199,102 | false | null |
// Automatically generated - do not modify!
package web.animations
sealed external class AnimationTimeline {
val currentTime: Double?
}
| 0 |
Kotlin
|
5
| 18 |
55e60996b5158706d44f9b652fba5a27bcf307e2
| 142 |
types-kotlin
|
Apache License 2.0
|
fearless-utils/src/main/java/jp/co/soramitsu/fearless_utils/runtime/definitions/types/primitives/IntType.kt
|
novasamatech
| 429,839,517 | false |
{"Kotlin": 630308, "Rust": 10890, "Java": 4260}
|
package jp.co.soramitsu.fearless_utils.runtime.definitions.types.primitives
import io.emeraldpay.polkaj.scale.ScaleCodecReader
import io.emeraldpay.polkaj.scale.ScaleCodecWriter
import jp.co.soramitsu.fearless_utils.extensions.fromSignedBytes
import jp.co.soramitsu.fearless_utils.extensions.toSignedBytes
import jp.co.soramitsu.fearless_utils.runtime.RuntimeSnapshot
import jp.co.soramitsu.fearless_utils.scale.utils.directWrite
import java.math.BigInteger
import java.nio.ByteOrder
val i8 = IntType(8)
val i16 = IntType(16)
val i32 = IntType(32)
val i64 = IntType(64)
val i128 = IntType(128)
val i256 = IntType(256)
class IntType(bits: Int) : NumberType("i$bits") {
init {
require(bits % 8 == 0)
}
val bytes = bits / 8
override fun encode(scaleCodecWriter: ScaleCodecWriter, runtime: RuntimeSnapshot, value: BigInteger) {
val bytes = value.toSignedBytes(
resultByteOrder = ByteOrder.LITTLE_ENDIAN,
expectedBytesSize = bytes
)
scaleCodecWriter.directWrite(bytes)
}
override fun decode(scaleCodecReader: ScaleCodecReader, runtime: RuntimeSnapshot): BigInteger {
val bytes = scaleCodecReader.readByteArray(bytes)
return bytes.fromSignedBytes(originByteOrder = ByteOrder.LITTLE_ENDIAN)
}
}
| 3 |
Kotlin
|
5
| 5 |
da027e7418e98ee558c48263eb954368031680e7
| 1,297 |
substrate-sdk-android
|
Apache License 2.0
|
app/src/main/java/com/example/marsphotos/network/MarsPhoto.kt
|
RyujiKoyama95
| 636,514,389 | false | null |
package com.example.marsphotos.network
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
// シリアル化可能にするため、@Serializableをつける
// JSONオブジェクトのキー名と対応するように変数名をつける
// kotlin規則的に変数名はキャメルケースを使用なので、@SerialNameでキー名を指定して紐づける
@Serializable
data class MarsPhoto(
val id: String,
@SerialName(value = "img_src")
val imgSrc: String
)
| 0 |
Kotlin
|
0
| 0 |
066afa3166240439b38e6f8fe80130e7e9d326e7
| 361 |
Get-data-from-the-internet
|
Apache License 2.0
|
src/nam/tran/factory/_method/ChicagoStyleVeggiePizza.kt
|
NamTranDev
| 229,420,809 | false | null |
package nam.tran.factory._method
class ChicagoStyleVeggiePizza : Pizza()
| 1 |
Kotlin
|
1
| 3 |
1222d4fadb460012819bd61841f59423eb6e8346
| 73 |
DesignPattern
|
Apache License 2.0
|
feature/my_notification/src/main/java/com/ku_stacks/ku_ring/my_notification/NotificationAdapter.kt
|
ku-ring
| 412,458,697 | false |
{"Kotlin": 588012, "Java": 8143}
|
package com.ku_stacks.ku_ring.my_notification
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.ku_stacks.ku_ring.my_notification.databinding.ItemDateBinding
import com.ku_stacks.ku_ring.my_notification.databinding.ItemNotificationBinding
import com.ku_stacks.ku_ring.my_notification.diff_callback.NotificationDiffCallback
import com.ku_stacks.ku_ring.my_notification.ui_model.PushContentUiModel
import com.ku_stacks.ku_ring.my_notification.ui_model.PushDataUiModel
import com.ku_stacks.ku_ring.my_notification.ui_model.PushDateHeaderUiModel
import com.ku_stacks.ku_ring.my_notification.viewholder.DateViewHolder
import com.ku_stacks.ku_ring.my_notification.viewholder.NotificationViewHolder
class NotificationAdapter(
private val itemClick: (PushContentUiModel) -> Unit,
private val onBindItem: (PushContentUiModel) -> Unit
) : ListAdapter<PushDataUiModel, NotificationAdapter.ViewHolder>(
NotificationDiffCallback()
) {
abstract class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return when (viewType) {
NOTIFICATION_CONTENT -> {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_notification, parent, false)
val binding = ItemNotificationBinding.bind(view)
NotificationViewHolder(binding, itemClick)
}
NOTIFICATION_DATE -> {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.item_date, parent, false)
val binding = ItemDateBinding.bind(view)
DateViewHolder(binding)
}
else -> throw Exception("no such viewType : $viewType")
}
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = getItem(position)
when (holder) {
is NotificationViewHolder -> {
holder.bind(item as PushContentUiModel)
onBindItem(item)
}
is DateViewHolder -> {
holder.bind(item as PushDateHeaderUiModel)
}
}
}
override fun getItemViewType(position: Int): Int {
return when (getItem(position)) {
is PushContentUiModel -> NOTIFICATION_CONTENT
is PushDateHeaderUiModel -> NOTIFICATION_DATE
}
}
companion object {
const val NOTIFICATION_CONTENT = 10
const val NOTIFICATION_DATE = 11
}
}
| 17 |
Kotlin
|
0
| 18 |
c16c77ef9af73d9efbd90750945fa54258c5b1c5
| 2,704 |
KU-Ring-Android
|
Apache License 2.0
|
src/main/java/net/eduard/essentials/command/DeleteHomeCommand.kt
|
EduardMaster
| 172,132,752 | false |
{"Java": 110127, "Kotlin": 78515}
|
package net.eduard.essentials.command
import net.eduard.api.lib.manager.CommandManager
import net.eduard.essentials.EduEssentials
import org.bukkit.entity.Player
class DeleteHomeCommand : CommandManager("deletehome","delhome",
"deletarcasa") {
var message = "§aVoce deletou sua home §2%home!"
var messageError = "§cNão existe a home %home!"
override fun playerCommand(player: Player, args: Array<String>) {
if (args.isEmpty()) {
sendUsage(player)
return
}
val homeName = args[0].toLowerCase()
val path = "homes." + player.name.toLowerCase() + "." + homeName
if (EduEssentials.getInstance().storage.contains(path)) {
EduEssentials.getInstance().storage.remove(path)
player.sendMessage(message.replace("%home", homeName))
} else {
player.sendMessage(messageError.replace("%home", homeName))
}
}
}
| 1 | null |
1
| 1 |
54e0d8c6b72d8d68510ff524f7f56fa66a033b97
| 934 |
EduEssentials
|
MIT License
|
jetcompose/sandbox/content/unit_3_kotlin_fundamentals/106_practice/05_profile.kt
|
haddagart
| 749,030,838 | false |
{"Kotlin": 26020}
|
fun main() {
val amanda = Person("Amanda", 33, "play tennis", null)
val atiqah = Person("Atiqah", 28, "climb", amanda)
amanda.showProfile()
atiqah.showProfile()
}
class Person(val name: String, val age: Int, val hobby: String?, val referrer: Person?) {
fun showProfile() {
println("Name: $name")
println("Age: $age")
println("Likes to $hobby. ${
if(referrer == null) {"Doesn't have a referrer."}
else {"Has a referrer named ${referrer.name}, who likes to ${referrer.hobby}."}
}")
println("")
}
}
| 0 |
Kotlin
|
0
| 0 |
785a615bb41f55a54ab86f0caf079cb916a3b8d3
| 586 |
haddag-learns
|
MIT License
|
godotopenxrpico/src/main/java/org/godotengine/openxr/vendors/pico/GodotOpenXRPico.kt
|
GodotVR
| 538,513,308 | false | null |
package org.godotengine.openxr.vendors.pico
import org.godotengine.godot.Godot
import org.godotengine.godot.plugin.GodotPlugin
/**
* Godot plugin for the Pico OpenXR loader.
*/
class GodotOpenXRPico(godot: Godot?) : GodotPlugin(godot) {
override fun getPluginName(): String {
return "GodotOpenXRPico"
}
}
| 7 | null |
9
| 29 |
a3499d9135e835fe3b07525ae25624a647f5259a
| 325 |
godot_openxr_vendors
|
MIT License
|
plugins/kotlin/idea/tests/testData/intentions/removeExplicitType/hasAnnotationOnTypeArgument.kt
|
ingokegel
| 72,937,917 | true | null |
// IS_APPLICABLE: false
// WITH_STDLIB
fun foo(): List<String> = emptyList()
@Target(AnnotationTarget.TYPE)
annotation class Foo
fun test(): <caret>List<@Foo String> = foo()
| 1 | null |
1
| 2 |
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 176 |
intellij-community
|
Apache License 2.0
|
presentation/src/main/kotlin/com/yossisegev/movienight/di/popular/PopularMoviesModule.kt
|
mrsegev
| 122,669,273 | false | null |
package com.yossisegev.movienight.di.popular
import com.yossisegev.domain.MoviesRepository
import com.yossisegev.domain.usecases.GetPopularMovies
import com.yossisegev.movienight.MovieEntityMovieMapper
import com.yossisegev.movienight.common.ASyncTransformer
import com.yossisegev.movienight.di.popular.PopularScope
import com.yossisegev.movienight.popularmovies.PopularMoviesVMFactory
import dagger.Module
import dagger.Provides
/**
* Created by Yossi Segev on 23/02/2018.
*/
@PopularScope
@Module
class PopularMoviesModule {
@Provides
fun provideGetPopularMoviesUseCase(moviesRepository: MoviesRepository): GetPopularMovies {
return GetPopularMovies(ASyncTransformer(), moviesRepository)
}
@Provides
fun providePopularMoviesVMFactory(useCase: GetPopularMovies, mapper: MovieEntityMovieMapper): PopularMoviesVMFactory {
return PopularMoviesVMFactory(useCase, mapper)
}
}
| 7 |
Kotlin
|
147
| 772 |
7df52e6c93d6932b4b58de9f4f906f86df93dce1
| 916 |
MovieNight
|
Apache License 2.0
|
app/src/main/java/exh/eh/tags/TagList.kt
|
Hero-Over
| 515,433,181 | false | null |
package exh.eh.tags
interface TagList {
fun getTags1(): List<String>
fun getTags2(): List<String> = emptyList()
fun getTags3(): List<String> = emptyList()
fun getTags4(): List<String> = emptyList()
fun getTags() = listOf(
getTags1(),
getTags2(),
getTags3(),
getTags4(),
)
}
| 0 |
Kotlin
|
0
| 4 |
233853823f45ddb7c11e0ce7f1feef3e7e7fc6b7
| 335 |
TachiyomiSY
|
Apache License 2.0
|
app/src/main/java/exh/eh/tags/TagList.kt
|
Hero-Over
| 515,433,181 | false | null |
package exh.eh.tags
interface TagList {
fun getTags1(): List<String>
fun getTags2(): List<String> = emptyList()
fun getTags3(): List<String> = emptyList()
fun getTags4(): List<String> = emptyList()
fun getTags() = listOf(
getTags1(),
getTags2(),
getTags3(),
getTags4(),
)
}
| 0 |
Kotlin
|
0
| 4 |
233853823f45ddb7c11e0ce7f1feef3e7e7fc6b7
| 335 |
TachiyomiSY
|
Apache License 2.0
|
core/src/main/java/com/bruhascended/core/model/FeatureExtractor.kt
|
ChiragKalra
| 272,775,912 | false | null |
package com.bruhascended.core.model
import android.content.Context
import com.bruhascended.core.db.Message
/*
Copyright 2020 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
class FeatureExtractor (context: Context) {
private var mContext = context
private val nonWordFeatures = arrayOf(
"Time",
"Digit",
"Decimal",
"URL",
"Date",
"NumberOfWords"
)
private var wordFeatures: Array<String>
private var mappedWordFeatures: Array<Int>
init {
wordFeatures = getWordFeatures()
val sorted = wordFeatures.clone().sortedArray()
val hashMap = HashMap<String, Int>()
for ((index, word) in wordFeatures.withIndex()) {
hashMap[word] = index
}
mappedWordFeatures = Array(wordFeatures.size) {
hashMap[sorted[it]]!!
}
wordFeatures = sorted
}
private fun getWordFeatures(): Array<String> {
val fileStr = mContext.assets.open("words.csv").bufferedReader().use{
it.readText()
}
return fileStr.split("\r\n").dropLast(1).toTypedArray()
}
fun getFeatureVector(message: Message) : Array<Float> {
val k = nonWordFeatures.size
val l = wordFeatures.size
val features = Array(k+l){0f}
var text = removeLines(message.text)
features[0] = time(message.time)
var yeah = removeDates(text)
text = yeah.first
features[1] = yeah.second
yeah = removeNumbers(text)
text = yeah.first
features[2] = yeah.second
yeah = removeDecimals(text)
text = yeah.first
features[3] = yeah.second
yeah = trimUrls(text)
text = yeah.first
features[4] = yeah.second
text = stem(text)
for (word in text.split(" ", ",", ".", "-", "!", "?", "(", ")", "\'", "\"")) {
val ind = wordFeatures.binarySearch(word)
if (ind > -1) {
val i = mappedWordFeatures[ind]
features[k + i] = 1f
}
features[5] += 1f
}
features[5] /= 150f
return features
}
fun getFeaturesLength() =
nonWordFeatures.size + wordFeatures.size
}
| 2 |
Kotlin
|
8
| 26 |
044536248f813f75afdbbd41c65eabf80f39946a
| 2,782 |
Organiso
|
Apache License 2.0
|
bezier/src/main/java/io/channel/bezier/icon/Briefcase.kt
|
channel-io
| 736,533,981 | false |
{"Kotlin": 2421787, "Python": 12500}
|
@file:Suppress("ObjectPropertyName", "UnusedReceiverParameter")
// Auto-generated by script/generate_compose_bezier_icon.py
package io.channel.bezier.icon
import androidx.compose.foundation.layout.size
import androidx.compose.material.Icon
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import io.channel.bezier.BezierIcon
import io.channel.bezier.BezierIcons
val BezierIcons.Briefcase: BezierIcon
get() = object : BezierIcon {
override val imageVector: ImageVector
get() = _briefcase ?: ImageVector.Builder(
name = "Briefcase",
defaultWidth = 24.dp,
defaultHeight = 24.dp,
viewportWidth = 24f,
viewportHeight = 24f,
).apply {
path(
fill = SolidColor(Color(0xFF313234)),
strokeLineWidth = 1f,
pathFillType = PathFillType.EvenOdd,
) {
moveTo(20.0f, 14.0f)
lineTo(4.0f, 14.0f)
lineTo(4.0f, 8.0f)
lineTo(20.0f, 8.0f)
close()
moveTo(20.0f, 18.0f)
lineTo(4.0f, 18.0f)
lineTo(4.0f, 16.0f)
lineTo(20.0f, 16.0f)
close()
moveTo(15.0f, 6.0f)
lineTo(9.0f, 6.0f)
lineTo(9.0f, 5.0f)
lineTo(15.0f, 5.0f)
close()
moveTo(17.0f, 6.0f)
lineTo(20.5f, 6.0f)
curveTo(21.326999999999998f, 6.0f, 22.0f, 6.673f, 22.0f, 7.5f)
lineTo(22.0f, 18.5f)
curveTo(22.0f, 19.326999999999998f, 21.326999999999998f, 20.0f, 20.5f, 20.0f)
lineTo(3.5f, 20.0f)
curveTo(2.673f, 20.0f, 2.0f, 19.326999999999998f, 2.0f, 18.5f)
lineTo(2.0f, 7.5f)
curveTo(2.0f, 6.673f, 2.673f, 6.0f, 3.5f, 6.0f)
lineTo(7.0f, 6.0f)
lineTo(7.0f, 4.5f)
curveTo(7.0f, 3.673f, 7.673f, 3.0f, 8.5f, 3.0f)
lineTo(15.5f, 3.0f)
curveTo(16.326999999999998f, 3.0f, 17.0f, 3.673f, 17.0f, 4.5f)
close()
moveTo(14.0f, 13.0f)
lineTo(10.0f, 13.0f)
lineTo(10.0f, 11.0f)
lineTo(14.0f, 11.0f)
close()
}
}.build().also {
_briefcase = it
}
}
private var _briefcase: ImageVector? = null
@Preview(showBackground = true)
@Composable
private fun BriefcaseIconPreview() {
Icon(
modifier = Modifier.size(128.dp),
imageVector = BezierIcons.Briefcase.imageVector,
contentDescription = null,
)
}
| 7 |
Kotlin
|
3
| 6 |
39cd58b0dd4a1543d54f0c1ce7c605f33ce135c6
| 3,313 |
bezier-compose
|
MIT License
|
client/src/main/kotlin/com/r3/corda/finance/cash/issuer/client/flows/ReceiveIssuedCash.kt
|
vitalrev
| 161,639,757 | true |
{"Kotlin": 144825}
|
package com.r3.corda.finance.cash.issuer.client.flows
import co.paralleluniverse.fibers.Suspendable
import com.r3.corda.finance.cash.issuer.common.flows.AbstractIssueCash
import net.corda.core.flows.*
import net.corda.core.node.StatesToRecord
import net.corda.core.transactions.SignedTransaction
@InitiatedBy(AbstractIssueCash::class)
class ReceiveIssuedCash(val otherSession: FlowSession) : FlowLogic<Unit>() {
@Suspendable
override fun call() {
logger.info("Starting ReceiveIssuedCash flow...")
//return subFlow(ReceiveTransactionFlow(otherSession, true, StatesToRecord.ALL_VISIBLE))
if (!serviceHub.myInfo.isLegalIdentity(otherSession.counterparty)) {
subFlow(ReceiveFinalityFlow(otherSession))
}
}
}
| 0 |
Kotlin
|
0
| 1 |
b18738612ce3300c701a62774b39479a414f0eda
| 761 |
cash-issuer
|
Apache License 2.0
|
domain/src/main/java/com/arjuj/domain/usecases/GetAllPokemonNamesUseCase.kt
|
arjunmehtaa
| 426,723,003 | false |
{"Kotlin": 69080}
|
package com.arjuj.domain.usecases
import com.arjuj.domain.model.PokemonResults
import com.arjuj.domain.repository.RepositoryInterface
class GetAllPokemonNamesUseCase(private val repository: RepositoryInterface) {
suspend fun getAllPokemonNames(limit: Int): PokemonResults = repository.getPokemonList(limit)
}
| 1 |
Kotlin
|
1
| 18 |
6435d31ba7f2f386b97c9a808ede0a0ee68d7de5
| 314 |
PokeFacts
|
Apache License 2.0
|
src/main/kotlin/io/github/hanseter/json/queryengine/queries/AttributeQueryBuilder.kt
|
Hanseter
| 244,838,139 | false |
{"Kotlin": 17592}
|
package io.github.hanseter.json.queryengine.queries
import io.github.hanseter.json.queryengine.AttributePath
import io.github.hanseter.json.queryengine.Query
import io.github.hanseter.json.queryengine.QueryBuilder
abstract class AttributeQueryBuilder<T> : QueryBuilder {
var attributePath: AttributePath? = null
private set
protected var queryCreator: ((AttributePath) -> Query)? = null
fun withAttributePath(path: String): T {
this.attributePath = if (path.isEmpty()) null
else AttributePath(path)
return this as T
}
fun withAttributePath(path: List<String>): T {
this.attributePath = if (path.isEmpty()) null
else AttributePath(path)
return this as T
}
fun withAttributePath(path: AttributePath?): T {
this.attributePath = path
return this as T
}
override fun isComplete(): Boolean = attributePath != null
&& queryCreator != null
override fun build(): Query? {
val attributePath = this.attributePath ?: return null
val queryCreator = this.queryCreator ?: return null
return queryCreator(attributePath)
}
}
| 1 |
Kotlin
|
0
| 0 |
b3bb3a434722757eaa286661dd0c04d8c3d573b6
| 1,167 |
JSONQueryEngine
|
MIT License
|
src/main/kotlin/jay/spawn/Spawn.kt
|
j4ys4j4
| 670,200,941 | false | null |
package jay.spawn
import jay.spawn.commands.CommandType
import jay.spawn.commands.SpawnCommand
import jay.spawn.config.MessageConfig
import jay.spawn.utils.Colour
import org.bukkit.plugin.java.JavaPlugin
class SpawnPlugin : JavaPlugin() {
private lateinit var messageConfig: MessageConfig
private lateinit var prefix: String
override fun onEnable() {
loadConfig()
registerCommands()
logger.info("${prefix}${Colour.GREEN}Plugin has been enabled!")
}
override fun onDisable() {
logger.info("${prefix}${Colour.RED}Plugin has been disabled!")
}
private fun loadConfig() {
saveDefaultConfig()
messageConfig = MessageConfig(this)
prefix = config.getString("prefix", "&7[SPAWN]&r ")
}
private fun registerCommands() {
// Register commands
getCommand("spawn")?.executor = SpawnCommand(this, CommandType.TELEPORT_TO_SPAWN)
getCommand("setspawn")?.executor = SpawnCommand(this, CommandType.SET_SPAWN)
}
fun getMessageConfig(): MessageConfig {
return messageConfig
}
fun getPrefix(): String {
return prefix
}
}
| 0 |
Kotlin
|
0
| 0 |
3dc092d5f46e4e3e05a35c9b027996118037d7ad
| 1,162 |
Spawn
|
Apache License 2.0
|
src/main/kotlin/Interpreter/core/ProgramNode.kt
|
xmmmmmovo
| 318,367,991 | false | null |
/*
* Copyright (c) xmmmmmovo 2021.
*/
package Interpreter.core
class ProgramNode : Node {
private var commandListNode = CommandListNode()
override fun parse(context: Context) {
context.skipToken("program")
commandListNode.parse(context)
}
override fun toString(): String {
return "[program $commandListNode]"
}
}
| 0 |
Kotlin
|
0
| 0 |
b9007e601c749451bfb4d7b0e059cfd5ffb6ae02
| 362 |
DesignPatterns
|
Apache License 2.0
|
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/GovernmentUser.kt
|
localhostov
| 808,861,591 | false |
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.straight.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Filled.GovernmentUser: ImageVector
get() {
if (_governmentUser != null) {
return _governmentUser!!
}
_governmentUser = Builder(name = "GovernmentUser", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(5.0f, 5.0f)
curveTo(5.0f, 2.243f, 7.243f, 0.0f, 10.0f, 0.0f)
reflectiveCurveToRelative(5.0f, 2.243f, 5.0f, 5.0f)
reflectiveCurveToRelative(-2.243f, 5.0f, -5.0f, 5.0f)
reflectiveCurveToRelative(-5.0f, -2.243f, -5.0f, -5.0f)
close()
moveTo(24.0f, 0.0f)
horizontalLineToRelative(-7.0f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(1.0f)
verticalLineToRelative(6.5f)
lineToRelative(2.5f, -2.5f)
lineToRelative(2.5f, 2.5f)
lineTo(23.0f, 2.0f)
horizontalLineToRelative(1.0f)
lineTo(24.0f, 0.0f)
close()
moveTo(0.0f, 22.0f)
horizontalLineToRelative(1.0f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(18.0f)
verticalLineToRelative(-2.0f)
horizontalLineToRelative(1.0f)
verticalLineToRelative(-2.0f)
lineTo(0.0f, 20.0f)
verticalLineToRelative(2.0f)
close()
moveTo(12.333f, 11.0f)
lineToRelative(-1.571f, 2.356f)
lineToRelative(1.055f, 4.644f)
horizontalLineToRelative(6.182f)
verticalLineToRelative(-2.0f)
curveToRelative(0.0f, -2.757f, -2.243f, -5.0f, -5.0f, -5.0f)
horizontalLineToRelative(-0.667f)
close()
moveTo(9.237f, 13.356f)
lineToRelative(-1.571f, -2.356f)
horizontalLineToRelative(-0.667f)
curveToRelative(-2.757f, 0.0f, -5.0f, 2.243f, -5.0f, 5.0f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(6.182f)
lineToRelative(1.055f, -4.644f)
close()
}
}
.build()
return _governmentUser!!
}
private var _governmentUser: ImageVector? = null
| 1 |
Kotlin
|
0
| 5 |
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 3,223 |
icons
|
MIT License
|
app/src/main/java/com/shashank/noteapp/viewModel/NotesViewModel.kt
|
Shashank02051997
| 360,072,568 | false | null |
package com.shashank.noteapp.viewModel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.shashank.noteapp.dao.NoteDao
import com.shashank.noteapp.database.NoteRoomDatabase
import com.shashank.noteapp.entity.Note
class NotesViewModel(application: Application) : AndroidViewModel(application) {
private val context = getApplication<Application>().applicationContext
private val listNotes = MutableLiveData<ArrayList<Note>>()
private var dao: NoteDao
init {
val database = NoteRoomDatabase.getDatabase(context)
dao = database.getNoteDao()
}
fun setNotes() {
val listItems = arrayListOf<Note>()
listItems.addAll(dao.getAll())
listNotes.postValue(listItems)
}
fun setNotesByLabel(label: String) {
val listItems = arrayListOf<Note>()
listItems.addAll(dao.getByLabel(label))
listNotes.postValue(listItems)
}
fun setNotesByTitle(title: String) {
val listItems = arrayListOf<Note>()
listItems.addAll(dao.getByTitle(title))
listNotes.postValue(listItems)
}
fun insertNote(note: Note) {
dao.insert(note)
}
fun updateNote(note: Note) {
dao.update(note)
}
fun deleteNote(note: Note) {
dao.delete(note)
}
fun getNotes(): LiveData<ArrayList<Note>> {
return listNotes
}
}
| 0 |
Kotlin
|
3
| 7 |
6a582609eddb65f1067524015a977214e85fc414
| 1,478 |
Note-App
|
The Unlicense
|
LottoPop/app/src/main/java/com/prangbi/android/lottopop/model/PLottoEntity.kt
|
hyuni
| 147,824,157 | false | null |
package com.prangbi.android.lottopop.model
/**
* Created by Prangbi on 2017. 10. 9..
*/
class PLottoInfo {
data class WinResult(
var pensionDrawDate: String? = null,
var rankClass: String? = null,
var rank: String? = null,
var rankNo: String? = null,
var rankAmt: String? = null,
var round: String? = null,
var drawDate: String? = null
)
data class MyLotto(
var rankClass: String? = null,
var rankNo: String? = null,
var round: String? = null
)
}
| 0 |
Kotlin
|
0
| 0 |
9b29d4c094c0b7b5e07eb491dc0e15b7a9e5a694
| 587 |
LottoPop-Android
|
MIT License
|
library/src/main/java/com/aminography/radixtree/MutableRadixTree.kt
|
aminography
| 339,017,598 | false | null |
package com.aminography.radixtree
/**
* A modifiable tree that holds values with [String] keys and supports efficiently retrieving the value corresponding
* to each key. [RadixTree] keys are unique; the tree holds only one value for each key.
*
* @param T the type of tree values. The mutable map is invariant in its values type.
*
* @author aminography
*/
interface MutableRadixTree<T> : RadixTree<T> {
/**
* Returns a read-only [MutableList] of all values in this map. Note that this collection may contain duplicate values.
*/
override val values: MutableList<T>
/**
* Returns a [MutableSet] of all key/value pairs in this tree.
*/
override val entries: MutableSet<MutableEntry<T>>
/**
* Associates the specified [value] with the specified [key] in the tree.
*
* @param key the key of the value to be inserted.
* @param value the value to be inserted.
*
* @return the previous value associated with the key, or `null` if the key was not present in the tree.
*/
fun put(key: String, value: T): T?
/**
* Associates the specified [value] with the specified key in the tree by calling [keyTransformer].
*
* @param value the value to be inserted.
* @param keyTransformer the transformer function that retrieves key from the [value] object.
*
* @return the previous value associated with the key, or `null` if the key was not present in the tree.
*/
fun put(value: T, keyTransformer: (T) -> String): T?
/**
* Updates this tree with key/value pairs from the specified tree [from].
*/
fun putAll(from: RadixTree<T>)
/**
* Removes the specified key and its corresponding value from this tree.
*
* @return the previous value associated with the key, or `null` if the key was not present in the tree.
*/
fun remove(key: String): T?
/**
* Removes the entry for the specified key only if it is mapped to the specified value.
*
* @return true if entry was removed
*/
fun remove(key: String, value: T): Boolean
/**
* Finds an existing entry and replace its value. If there is no existing entry for the given [key], does nothing.
*
* @param key the key of the value to be replaced.
* @param value the value to be replaced.
*
* @return `true` if an entry was found for the given key, `false` if not found.
*/
fun replace(key: String, value: T): Boolean
/**
* Removes all values from this tree.
*/
fun clear()
/**
* Represents a key/value pair held by a [MutableRadixTree].
*/
interface MutableEntry<T> : RadixTree.Entry<T> {
/**
* Changes the value associated with the key of this entry.
*
* @return the previous value corresponding to the key.
*/
fun setValue(newValue: T): T
}
}
| 1 |
Kotlin
|
0
| 4 |
5c916b6004aaea1e8407112955b5b43310171848
| 2,916 |
RadixTree
|
Apache License 2.0
|
nextgen-middleware/src/main/java/com/nextgenbroadcast/mobile/middleware/atsc3/serviceGuide/unit/SGUnit.kt
|
jjustman
| 418,004,011 | false | null |
package com.nextgenbroadcast.mobile.middleware.atsc3.serviceGuide.unit
import com.nextgenbroadcast.mobile.middleware.server.ServerUtils
internal abstract class SGUnit(
open var version: Long = 0,
) {
var duFileName: String? = null
var duIndex: Int? = null
fun toUrl() = duFileName?.let { fileName ->
duIndex?.let { index ->
ServerUtils.multipartFilePath(fileName, index)
}
}
}
| 0 |
Kotlin
|
0
| 5 |
f0d91240d7c68c57c7ebfd0739148c86a38ffa58
| 431 |
libatsc3-middleware-sample-app
|
MIT License
|
src/main/java/com/jchanghong/controller/admin/AdminArticleController.kt
|
jchanghong
| 91,967,260 | false |
{"JavaScript": 1172814, "HTML": 1121390, "CSS": 897428, "Kotlin": 83586, "XSLT": 5981, "Java": 988}
|
package com.jchanghong.controller.admin
import com.jchanghong.service.ArticleService
import com.jchanghong.service.CategoryService
import com.jchanghong.service.TagService
import com.jchanghong.util.PhotoUploadUtil
import com.jchanghong.util.ResultInfo
import com.jchanghong.util.ResultInfoFactory
import com.jchanghong.vo.Article
import com.jchanghong.vo.Pager
import com.jchanghong.vo.PhotoResult
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.multipart.MultipartFile
import java.io.File
import java.io.IOException
import java.net.URLDecoder
import java.util.*
import javax.annotation.Resource
/**
* 后台管理 文章controller
* FILE: AdminArticleController.java
* MOTTO: 不积跬步无以至千里,不积小流无以至千里
* AUTHOR: EumJi
* DATE: 2017/4/15
* TIME: 22:00
*/
@Controller
@RequestMapping("/admin/article")
class AdminArticleController {
private var log = LoggerFactory.getLogger(AdminArticleController::class.java)
//文章service
@Resource
lateinit private var articleService: ArticleService
@Resource
lateinit private var photoUploadUtil: PhotoUploadUtil
//标签service
@Resource
lateinit private var tagService: TagService
//分类service
@Resource
lateinit private var categoryService: CategoryService
/**
* 初始化文章分页信息
* @param pager
* *
* @return
*/
@RequestMapping("/initPage")
@ResponseBody
fun initPage(pager: Pager<*>): Pager<*> {
articleService.InitPager(pager)
return pager
}
/**
* 跳转到添加页面
* @return
*/
@RequestMapping("/addPage")
fun addPage(): String {
return "admin/article/articleAdd"
}
/**
* 初始化文章列表
* @param pager 分页对象
* *
* @param categoryId 搜索条件 分类id
* *
* @param tagIds 搜索条件 tag集合
* *
* @param title 搜索条件 文章标题
* *
* @param model
* *
* @return
*/
@RequestMapping("/load")
fun loadArticle(pager: Pager<*>, categoryId: Int?, tagIds: String?, title: String?, model: Model): String {
/**
* 设置start位置
*/
pager.start = pager.start
//封装查询条件
var param = HashMap<String, Any?>()
if (tagIds != null && "" != tagIds) {
param.put("tags", tagIds.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray())
} else {
param.put("tags", null)
}
param.put("categoryId", categoryId ?: 0)
param.put("title", title)
param.put("pager", pager)
//获取文章列表
var articleList = articleService.loadArticle(param)
model.addAttribute("articleList", articleList)
return "admin/article/articleTable"
}
/**
* 更新文章可用状态
* @param id
* *
* @param status
* *
* @return
*/
@RequestMapping("/updateStatue")
@ResponseBody
fun updateStatue(id: Int?, status: Int): ResultInfo {
try {
articleService.updateStatue(id ?: 0, status)
} catch (e: Exception) {
log.error(e.toString())
return ResultInfoFactory.getErrorResultInfo("更新状态失败,请稍后再尝试")
}
return ResultInfoFactory.successResultInfo
}
/**
* 获取条件,所有tag和category
* @param model
* *
* @return
*/
@RequestMapping("/term")
fun articleTerm(model: Model): String {
var tagList = tagService.tagList
var categoryList = categoryService.categoryList
model.addAttribute("tagList", tagList)
model.addAttribute("categoryList", categoryList)
return "admin/article/articleInfo"
}
/**
* 保存文章
* @param article
* *
* @param tags
* *
* @return
*/
@RequestMapping("/save")
@ResponseBody
fun SaveArticle(article: Article, tags: IntArray): ResultInfo {
try {
//解码文章内容防止出现部分特殊字符串被转义
article.description = URLDecoder.decode(article.description, "UTF-8")
article.title = URLDecoder.decode(article.title, "UTF-8")
article.content = URLDecoder.decode(article.content, "UTF-8")
articleService.saveArticle(article, tags)
} catch (e: Exception) {
log.error(e.toString())
return ResultInfoFactory.getErrorResultInfo("添加失败,请稍后再尝试")
}
return ResultInfoFactory.successResultInfo
}
/**
* 跳转到编辑页面
* @param id
* *
* @param model
* *
* @return
*/
@RequestMapping("/editJump")
fun updatePage(id: Int?, model: Model): String {
var article = articleService.getArticleById(id ?: 0)
model.addAttribute("article", article)
return "admin/article/articleEdit"
}
/**
* 获取更新文章信息
* @param articleId 文章标题 用于获取文章信息
* *
* @param model
* *
* @return
*/
@RequestMapping("/updateInfo")
fun updateInfo(articleId: Int?, model: Model): String {
var article = articleService.getArticleById(articleId ?: 0)
var categoryList = categoryService.categoryList
var tagList = tagService.tagList
model.addAttribute("article", article)
model.addAttribute("categoryList", categoryList)
model.addAttribute("tagList", tagList)
return "admin/article/articleEditInfo"
}
/**
* 更新文章
* @param article
* *
* @param tags
* *
* @return
*/
@RequestMapping("/update")
@ResponseBody
fun updateArticle(article: Article, tags: IntArray): ResultInfo {
try {
//解码文章内容防止出现部分特殊字符串被转义
article.description = URLDecoder.decode(article.description, "UTF-8")
article.title = URLDecoder.decode(article.title, "UTF-8")
article.content = URLDecoder.decode(article.content, "UTF-8")
articleService.updateArticle(article, tags)
} catch (e: Exception) {
log.error(e.toString())
ResultInfoFactory.getErrorResultInfo("修改失败,请稍后再试!")
}
return ResultInfoFactory.successResultInfo
}
@RequestMapping("/delete/{id}")
@ResponseBody
fun deleteArticle(@PathVariable id: Int?): ResultInfo {
try {
articleService.deleteArticle(id ?: 0)
} catch (e: Exception) {
log.error(e.toString())
return ResultInfoFactory.getErrorResultInfo("删除失败!")
}
return ResultInfoFactory.successResultInfo
}
@RequestMapping("/imageUpload")
@ResponseBody
fun imageUpload(@RequestParam(value = "editormd-image-file", required = true) file: MultipartFile) {
//设置filename
// String filename = new Random().nextInt(10000)+file.getOriginalFilename();
try {
var files = File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + file.originalFilename)
file.transferTo(files)
photoUploadUtil.uploadPhoto(files.absolutePath, file.originalFilename)
} catch (e: IOException) {
e.printStackTrace()
PhotoResult(0, "", "")
}
}
}
| 0 |
JavaScript
|
0
| 0 |
19b6fb3aae810c69cc567521205aea39f1e31fb7
| 7,381 |
kotlin-blog
|
Apache License 2.0
|
postgresql-async/src/test/scala/com/github/mauricio/async/db/postgresql/pool/SingleThreadedAsyncObjectPoolSpec.kt
|
dougEfresh
| 146,269,167 | false | null |
/*
* Copyright 2013 <NAME>
*
* <NAME> licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.github.mauricio.async.db.postgresql.pool
import com.github.mauricio.async.db.pool.{AsyncObjectPool, PoolConfiguration, PoolExhaustedException, SingleThreadedAsyncObjectPool}
import com.github.mauricio.async.db.postgresql.{DatabaseTestHelper, PostgreSQLConnection}
import java.nio.channels.ClosedChannelException
import java.util.concurrent.TimeUnit
import org.specs2.mutable.Specification
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
import scala.language.postfixOps
import com.github.mauricio.async.db.exceptions.ConnectionStillRunningQueryException
class SingleThreadedAsyncObjectPoolSpec extends Specification with DatabaseTestHelper {
"pool" should {
"give me a valid object when I ask for one" in {
withPool {
pool =>
val connection = get(pool)
val result = executeTest(connection)
pool.giveBack(connection)
result
}
}
"enqueue an action if the pool is full" in {
withPool({
pool =>
val connection = get(pool)
val promises: List[Future[PostgreSQLConnection]] = List(pool.take, pool.take, pool.take)
pool.availables.size === 0
pool.inUse.size === 1
pool.queued.size must be_<=(3)
/* pool.take call checkout that call this.mainPool.action,
so enqueuePromise called in executorService,
so there is no guaranties that all promises in queue at that moment
*/
val deadline = 5.seconds.fromNow
while(pool.queued.size < 3 || deadline.hasTimeLeft) {
Thread.sleep(50)
}
pool.queued.size === 3
executeTest(connection)
pool.giveBack(connection)
val pools: List[Future[AsyncObjectPool[PostgreSQLConnection]]] = promises.map {
promise =>
val connection = Await.result(promise, Duration(5, TimeUnit.SECONDS))
executeTest(connection)
pool.giveBack(connection)
}
Await.ready(pools.last, Duration(5, TimeUnit.SECONDS))
pool.availables.size === 1
pool.inUse.size === 0
pool.queued.size === 0
}, 1, 3)
}
"exhaust the pool" in {
withPool({
pool =>
1 to 2 foreach {
_ => pool.take
}
await(pool.take) must throwA[PoolExhaustedException]
}, 1, 1)
}
"it should remove idle connections once the time limit has been reached" in {
withPool({
pool =>
val connections = 1 to 5 map {
_ =>
val connection = get(pool)
executeTest(connection)
connection
}
connections.foreach(connection => await(pool.giveBack(connection)))
pool.availables.size === 5
Thread.sleep(2000)
pool.availables.isEmpty must beTrue
}, validationInterval = 1000)
}
"it should validate returned connections before sending them back to the pool" in {
withPool {
pool =>
val connection = get(pool)
await(connection.disconnect)
pool.inUse.size === 1
await(pool.giveBack(connection)) must throwA[ClosedChannelException]
pool.availables.size === 0
pool.inUse.size === 0
}
}
"it should not accept returned connections that aren't ready for query" in {
withPool {
pool =>
val connection = get(pool)
connection.sendPreparedStatement("SELECT pg_sleep(3)")
await(pool.giveBack(connection)) must throwA[ConnectionStillRunningQueryException]
pool.availables.size === 0
pool.inUse.size === 0
}
}
}
def withPool[T](
fn: (SingleThreadedAsyncObjectPool[PostgreSQLConnection]) => T,
maxObjects: Int = 5,
maxQueueSize: Int = 5,
validationInterval: Long = 3000
): T = {
val poolConfiguration = new PoolConfiguration(
maxIdle = 1000,
maxObjects = maxObjects,
maxQueueSize = maxQueueSize,
validationInterval = validationInterval
)
val factory = new PostgreSQLConnectionFactory(this.defaultConfiguration)
val pool = new SingleThreadedAsyncObjectPool[PostgreSQLConnection](factory, poolConfiguration)
try {
fn(pool)
} finally {
await(pool.close)
}
}
def executeTest(connection: PostgreSQLConnection) = executeQuery(connection, "SELECT 0").rows.get(0)(0) === 0
def get(pool: SingleThreadedAsyncObjectPool[PostgreSQLConnection]): PostgreSQLConnection = {
val future = pool.take
Await.result(future, Duration(5, TimeUnit.SECONDS))
}
}
| 1 | null |
1
| 1 |
c16a5772b46331c582c4d14939e6c4cad09edb98
| 5,393 |
jasync-sql
|
Apache License 2.0
|
postgresql-async/src/test/scala/com/github/mauricio/async/db/postgresql/pool/SingleThreadedAsyncObjectPoolSpec.kt
|
dougEfresh
| 146,269,167 | false | null |
/*
* Copyright 2013 <NAME>
*
* <NAME> licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.github.mauricio.async.db.postgresql.pool
import com.github.mauricio.async.db.pool.{AsyncObjectPool, PoolConfiguration, PoolExhaustedException, SingleThreadedAsyncObjectPool}
import com.github.mauricio.async.db.postgresql.{DatabaseTestHelper, PostgreSQLConnection}
import java.nio.channels.ClosedChannelException
import java.util.concurrent.TimeUnit
import org.specs2.mutable.Specification
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
import scala.language.postfixOps
import com.github.mauricio.async.db.exceptions.ConnectionStillRunningQueryException
class SingleThreadedAsyncObjectPoolSpec extends Specification with DatabaseTestHelper {
"pool" should {
"give me a valid object when I ask for one" in {
withPool {
pool =>
val connection = get(pool)
val result = executeTest(connection)
pool.giveBack(connection)
result
}
}
"enqueue an action if the pool is full" in {
withPool({
pool =>
val connection = get(pool)
val promises: List[Future[PostgreSQLConnection]] = List(pool.take, pool.take, pool.take)
pool.availables.size === 0
pool.inUse.size === 1
pool.queued.size must be_<=(3)
/* pool.take call checkout that call this.mainPool.action,
so enqueuePromise called in executorService,
so there is no guaranties that all promises in queue at that moment
*/
val deadline = 5.seconds.fromNow
while(pool.queued.size < 3 || deadline.hasTimeLeft) {
Thread.sleep(50)
}
pool.queued.size === 3
executeTest(connection)
pool.giveBack(connection)
val pools: List[Future[AsyncObjectPool[PostgreSQLConnection]]] = promises.map {
promise =>
val connection = Await.result(promise, Duration(5, TimeUnit.SECONDS))
executeTest(connection)
pool.giveBack(connection)
}
Await.ready(pools.last, Duration(5, TimeUnit.SECONDS))
pool.availables.size === 1
pool.inUse.size === 0
pool.queued.size === 0
}, 1, 3)
}
"exhaust the pool" in {
withPool({
pool =>
1 to 2 foreach {
_ => pool.take
}
await(pool.take) must throwA[PoolExhaustedException]
}, 1, 1)
}
"it should remove idle connections once the time limit has been reached" in {
withPool({
pool =>
val connections = 1 to 5 map {
_ =>
val connection = get(pool)
executeTest(connection)
connection
}
connections.foreach(connection => await(pool.giveBack(connection)))
pool.availables.size === 5
Thread.sleep(2000)
pool.availables.isEmpty must beTrue
}, validationInterval = 1000)
}
"it should validate returned connections before sending them back to the pool" in {
withPool {
pool =>
val connection = get(pool)
await(connection.disconnect)
pool.inUse.size === 1
await(pool.giveBack(connection)) must throwA[ClosedChannelException]
pool.availables.size === 0
pool.inUse.size === 0
}
}
"it should not accept returned connections that aren't ready for query" in {
withPool {
pool =>
val connection = get(pool)
connection.sendPreparedStatement("SELECT pg_sleep(3)")
await(pool.giveBack(connection)) must throwA[ConnectionStillRunningQueryException]
pool.availables.size === 0
pool.inUse.size === 0
}
}
}
def withPool[T](
fn: (SingleThreadedAsyncObjectPool[PostgreSQLConnection]) => T,
maxObjects: Int = 5,
maxQueueSize: Int = 5,
validationInterval: Long = 3000
): T = {
val poolConfiguration = new PoolConfiguration(
maxIdle = 1000,
maxObjects = maxObjects,
maxQueueSize = maxQueueSize,
validationInterval = validationInterval
)
val factory = new PostgreSQLConnectionFactory(this.defaultConfiguration)
val pool = new SingleThreadedAsyncObjectPool[PostgreSQLConnection](factory, poolConfiguration)
try {
fn(pool)
} finally {
await(pool.close)
}
}
def executeTest(connection: PostgreSQLConnection) = executeQuery(connection, "SELECT 0").rows.get(0)(0) === 0
def get(pool: SingleThreadedAsyncObjectPool[PostgreSQLConnection]): PostgreSQLConnection = {
val future = pool.take
Await.result(future, Duration(5, TimeUnit.SECONDS))
}
}
| 1 | null |
1
| 1 |
c16a5772b46331c582c4d14939e6c4cad09edb98
| 5,393 |
jasync-sql
|
Apache License 2.0
|
src/Application.kt
|
yoshixmk
| 258,681,385 | false | null |
package yoshixmk
import com.fasterxml.jackson.databind.SerializationFeature
import io.ktor.application.Application
import io.ktor.application.call
import io.ktor.application.install
import io.ktor.application.log
import io.ktor.auth.Authentication
import io.ktor.auth.UserIdPrincipal
import io.ktor.auth.basic
import io.ktor.auth.jwt.jwt
import io.ktor.features.*
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpMethod
import io.ktor.http.HttpStatusCode
import io.ktor.http.cio.websocket.pingPeriod
import io.ktor.http.cio.websocket.timeout
import io.ktor.jackson.jackson
import io.ktor.request.path
import io.ktor.response.respond
import io.ktor.response.respondText
import io.ktor.routing.post
import io.ktor.routing.routing
import io.ktor.util.KtorExperimentalAPI
import org.jetbrains.exposed.sql.Database
import org.koin.ktor.ext.Koin
import org.slf4j.event.Level
import yoshixmk.jwt.sample.JwtConfig
import yoshixmk.jwt.sample.JwtUser
import yoshixmk.routes.routes
import java.time.Duration
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
@KtorExperimentalAPI
//@Suppress("unused") // Referenced in application.conf
@kotlin.jvm.JvmOverloads
fun Application.module(@Suppress("UNUSED_PARAMETER") testing: Boolean = false) {
install(ContentNegotiation) {
jackson {
enable(SerializationFeature.INDENT_OUTPUT)
}
}
install(AutoHeadResponse)
install(CallLogging) {
level = Level.INFO
filter { call -> call.request.path().startsWith("/") }
}
install(ConditionalHeaders)
install(io.ktor.websocket.WebSockets) {
pingPeriod = Duration.ofSeconds(15)
timeout = Duration.ofSeconds(15)
maxFrameSize = Long.MAX_VALUE
masking = false
}
install(CORS) {
method(HttpMethod.Options)
method(HttpMethod.Put)
method(HttpMethod.Delete)
method(HttpMethod.Patch)
header(HttpHeaders.Authorization)
header("MyCustomHeader")
allowCredentials = true
anyHost() // @TODO: Don't do this in production if possible. Try to limit it.
}
install(Koin) {
modules(koinModules)
}
if (!testing) {
val config = environment.config
Database.connect(
url = config.property("database.url").getString(),
user = environment.config.property("database.user").getString(),
password = environment.config.property("database.password").getString(),
driver = "org.postgresql.Driver"
)
}
install(Authentication) {
basic(name = "basic-auth") {
realm = "Ktor Server"
validate { credentials ->
if (credentials.name == name && credentials.password == name) {
UserIdPrincipal(credentials.name)
} else {
null
}
}
}
jwt(name = "jwt") {
verifier(JwtConfig.verifier)
realm = "ktor.io"
validate {
if (it.payload.claims.contains("id")) JwtUser.testUser else null
}
}
}
routing {
routes()
post("/login") {
// val credentials = call.receive<UserPasswordCredential>()
val user = JwtUser.testUser // user by credentials
val token = JwtConfig.makeToken(user)
call.respondText(token)
}
install(StatusPages) {
exception<AuthenticationException> { e ->
log.info(e.stackTrace.toString())
call.respond(HttpStatusCode.Unauthorized)
}
exception<AuthorizationException> { e ->
log.info(e.stackTrace.toString())
call.respond(HttpStatusCode.Forbidden)
}
exception<Exception> { e ->
log.error(e.message)
e.printStackTrace()
call.respond(HttpStatusCode.BadRequest)
}
}
}
}
class AuthenticationException : RuntimeException()
class AuthorizationException : RuntimeException()
| 1 |
Kotlin
|
0
| 0 |
2d8b7c4bf83a8386604017318a5014f3deb82e21
| 4,139 |
ktor-sample
|
MIT License
|
app/src/main/java/com/yureka/technology/ytc/data/model/activity/ActivityResponse.kt
|
hafidrf
| 347,619,244 | false | null |
package com.yureka.technology.ytc.data.model.activity
import com.google.gson.annotations.SerializedName
data class ActivityResponse(
@SerializedName("data")
val `data`: Data,
@SerializedName("message")
val message: String,
@SerializedName("status")
val status: Int,
@SerializedName("validation")
val validation: Validation
)
| 0 |
Kotlin
|
0
| 0 |
3d63f924b9438f497280459d91f891892758a519
| 359 |
ytc-android
|
Apache License 2.0
|
app/src/main/java/pini/mattia/coachtimer/ui/leaderboardscreen/TrainingSessionUI.kt
|
martirius
| 559,459,763 | false | null |
package pini.mattia.coachtimer.ui.leaderboardscreen
import pini.mattia.coachtimer.model.player.Player
data class TrainingSessionUI(
val player: Player,
val peakSpeed: String,
val endurance: String
)
| 0 |
Kotlin
|
0
| 0 |
7853e31b3a436087e79690a9abbd652f20d47856
| 213 |
coach-timer
|
MIT License
|
yandex_smart_home/src/main/java/ru/hse/miem/yandex_smart_home/capabilities/Mode.kt
|
mkolpakov2002
| 713,131,056 | true |
{"Java Properties": 2, "Gradle": 4, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Ignore List": 5, "Gradle Kotlin DSL": 2, "Kotlin": 239, "XML": 102, "HTML": 219, "JavaScript": 1, "CSS": 1, "INI": 2, "Proguard": 3, "Java": 160, "JSON": 1}
|
package ru.hse.miem.yandex_smart_home.capabilities
data class Mode(var value: String, var instance: ModeFunctions) : BaseCapability("mode") {
val state: Map<String, Any>
get() = mapOf("instance" to instance, "value" to value)
operator fun invoke(): Map<String, Any> {
return mapOf("type" to _type, "state" to state)
}
}
| 0 |
Java
|
0
| 0 |
6c12490c1bbc62e3918ea525c51ec188f07dee24
| 349 |
ROS-Mobile-Android
|
MIT License
|
api/invtx/src/integration/kotlin/org/rsmod/api/invtx/InvTransactionsTest.kt
|
rsmod
| 293,875,986 | false | null |
package org.rsmod.api.invtx
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.parallel.Execution
import org.junit.jupiter.api.parallel.ExecutionMode
import org.rsmod.api.config.refs.invs
import org.rsmod.api.config.refs.objs
import org.rsmod.api.testing.GameTestState
import org.rsmod.api.testing.assertions.assertNotNullContract
import org.rsmod.api.testing.assertions.assertTrueContract
import org.rsmod.api.testing.params.TestArgs
import org.rsmod.api.testing.params.TestArgsProvider
import org.rsmod.api.testing.params.TestWithArgs
import org.rsmod.game.obj.InvObj
import org.rsmod.game.type.obj.ObjType
import org.rsmod.game.type.obj.Wearpos
import org.rsmod.objtx.isOk
/**
* The transaction system uses a shared list in the backend for performance enhancements. Due to
* this, we require thread-safety and set the execution mode to fit that requirement.
*
* @see [org.rsmod.objtx.TransactionInventory.reusableIndexList]
*/
@Execution(ExecutionMode.SAME_THREAD)
class InvTransactionsTest {
@Test
fun GameTestState.`add obj successfully`() = runGameTest {
withPlayerInit {
check(inv.isEmpty())
invAdd(inv, objs.abyssal_whip.obj(count = 2), slot = 3)
assertEquals(objs.abyssal_whip.id, inv[3]?.id)
assertEquals(objs.abyssal_whip.id, inv[4]?.id)
assertEquals(2, inv.occupiedSpace())
}
}
@Test
fun GameTestState.`delete obj successfully`() = runGameTest {
withPlayerInit {
inv[5] = objs.fire_cape
val transaction = invDel(inv, objs.fire_cape.obj(count = 2), strict = false).single()
assertTrueContract(transaction.isOk())
assertTrue(transaction.partialSuccess)
assertEquals(1, transaction.completed)
assertNull(inv[5])
assertTrue(inv.isEmpty())
}
}
@Test
fun GameTestState.`swap inv objs`() = runGameTest {
val fromSlot = 10
val toSlot = 4
withPlayerInit {
check(inv.isEmpty())
inv[fromSlot] = objs.coins.obj(100_000)
val transaction = invSwap(inv, fromSlot = fromSlot, intoSlot = toSlot).single()
assertTrueContract(transaction.isOk())
assertTrue(transaction.fullSuccess)
assertNull(inv[fromSlot])
assertNotNull(inv[toSlot])
assertEquals(transaction.completed, 100_000)
assertEquals(InvObj(objs.coins, 100_000), inv[toSlot])
}
}
@Test
fun GameTestState.`insert obj into bank`() = runGameTest {
withPlayerInit {
check(inv.isEmpty())
val bank = invMap.getOrPut(cacheTypes.invs[invs.bank])
inv[0] = objs.abyssal_whip
inv[1] = objs.abyssal_whip
val transaction = invTransfer(inv, fromSlot = 0, count = 2, into = bank).single()
assertTrueContract(transaction.isOk())
assertTrue(transaction.fullSuccess)
assertNull(inv[0])
assertNull(inv[1])
assertNotNull(bank[0])
assertEquals(InvObj(objs.abyssal_whip, 2), bank[0])
assertEquals(1, bank.occupiedSpace())
}
}
@Test
fun GameTestState.`withdraw obj from bank with placeholder`() = runGameTest {
withPlayerInit {
check(inv.isEmpty())
val placeholder = cacheTypes.objs[objs.abyssal_whip].placeholderlink
val bank = invMap.getOrPut(cacheTypes.invs[invs.bank])
bank[0] = objs.rune_arrow.obj(500)
bank[1] = objs.abyssal_whip
val transaction =
invTransfer(bank, fromSlot = 1, count = 1, into = inv, placehold = true).single()
assertTrueContract(transaction.isOk())
assertTrue(transaction.fullSuccess)
assertEquals(objs.abyssal_whip.obj(), inv[0])
assertNotNull(bank[1])
assertEquals(placeholder, bank[1]?.id)
assertEquals(objs.rune_arrow.obj(500), bank[0])
assertEquals(2, bank.occupiedSpace())
}
}
@Test
fun GameTestState.`equip stackable obj in worn with overflow leftover`() = runGameTest {
withPlayerInit {
check(worn.isEmpty())
check(inv.isEmpty())
val addArrows = objs.rune_arrow.obj(5000)
inv[3] = addArrows
worn[Wearpos.Quiver.slot] = objs.rune_arrow.obj(Int.MAX_VALUE - 1000)
val transaction =
invSwap(
from = inv,
fromSlot = 3,
intoSlot = Wearpos.Quiver.slot,
into = worn,
mergeStacks = true,
)
.single()
val quiver = worn[Wearpos.Quiver.slot]
assertTrueContract(transaction.isOk())
assertTrue(transaction.partialSuccess)
assertEquals(objs.rune_arrow.obj(4000), inv[3])
assertNotNull(quiver)
assertEquals(Int.MAX_VALUE, quiver?.count)
}
}
@Test
fun GameTestState.`swap inv obj slots`() = runGameTest {
withPlayerInit {
check(inv.isEmpty())
val item1 = objs.berserker_ring.obj()
val item2 = objs.coins.obj(100_000)
val slot1 = 2
val slot2 = 5
inv[slot1] = item1
inv[slot2] = item2
check(inv[slot1] == item1)
check(inv[slot2] == item2)
val transaction = invSwap(from = inv, fromSlot = slot1, intoSlot = slot2).single()
assertTrueContract(transaction.isOk())
assertTrue(transaction.fullSuccess)
assertEquals(item2, inv[slot1])
assertEquals(item1, inv[slot2])
assertEquals(2, inv.occupiedSpace())
}
}
@TestWithArgs(WearposProvider::class)
fun `equip obj in wearpos`(wearpos: Wearpos, type: ObjType, count: Int, test: GameTestState) =
test.runGameTest {
val invSlot = 5
withPlayerInit {
check(worn.isEmpty())
check(inv.isEmpty())
inv[invSlot] = type.obj(count)
val transaction =
invSwap(
from = inv,
fromSlot = invSlot,
into = worn,
intoSlot = wearpos.slot,
mergeStacks = true,
)
.single()
assertNotNullContract(transaction)
assertTrueContract(transaction.isOk())
assertTrue(transaction.fullSuccess)
assertEquals(0, inv.occupiedSpace())
assertEquals(1, worn.occupiedSpace())
assertEquals(type.id, worn[wearpos.slot]?.id)
assertEquals(count, worn[wearpos.slot]?.count)
}
}
private object WearposProvider : TestArgsProvider {
override fun args(): List<TestArgs> =
listOf(
TestArgs(Wearpos.Hat, objs.helm_of_neitiznot, 1),
TestArgs(Wearpos.Back, objs.fire_cape, 1),
TestArgs(Wearpos.RightHand, objs.abyssal_whip, 1),
TestArgs(Wearpos.Torso, objs.bandos_chestplate, 1),
TestArgs(Wearpos.LeftHand, objs.dragon_defender, 1),
TestArgs(Wearpos.Legs, objs.bandos_tassets, 1),
TestArgs(Wearpos.Hands, objs.barrows_gloves, 1),
TestArgs(Wearpos.Feet, objs.dragon_boots, 1),
TestArgs(Wearpos.Ring, objs.berserker_ring, 1),
TestArgs(Wearpos.Quiver, objs.rune_arrow, 500),
)
}
}
| 0 | null |
64
| 95 |
3ba446ed70bcde0870ef431e1a8527efc6837d6c
| 7,968 |
rsmod
|
ISC License
|
app/src/main/kotlin/com/muedsa/agetv/model/dandanplay/DanSearchAnime.kt
|
muedsa
| 713,334,832 | false |
{"Kotlin": 321497}
|
package com.muedsa.agetv.model.dandanplay
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class DanSearchAnime(
@SerialName("animeId") val animeId: Int,
@SerialName("animeTitle") val animeTitle: String,
@SerialName("type") val type: String,
@SerialName("typeDescription") val typeDescription: String,
@SerialName("imageUrl") val imageUrl: String,
@SerialName("startDate") val startDate: String,
@SerialName("episodeCount") val episodeCount: Int,
@SerialName("rating") val rating: Float,
@SerialName("isFavorited") val isFavorited: Boolean
)
| 5 |
Kotlin
|
2
| 3 |
4ffd6435d30578575ce9479b55e97df6ca0ab590
| 632 |
AGETV
|
MIT License
|
Scientory-by-PHJ-STUDIO-android/app/src/main/java/com/example/scientorybyphjstudio/yes24/yes24_2018.kt
|
Ttakttae
| 388,518,361 | false | null |
package com.example.scientorybyphjstudio.yes24
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.scientorybyphjstudio.R
class yes24_2018 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_yes24_2018)
}
}
| 0 |
Kotlin
|
0
| 0 |
1f9babe63736857dde325e7994a7164283dc76b3
| 365 |
repositiories_from_PHJ_STUDIO
|
MIT License
|
app/src/main/java/com/omdb/app/source/MovieDataSource.kt
|
amanghuman30
| 783,510,986 | false |
{"Kotlin": 19918}
|
package com.omdb.app.source
import com.omdb.app.api.ResultWrapper
import com.omdb.app.models.MoviesResponse
interface MovieDataSource {
suspend fun searchMovies(str: String) : MoviesResponse
}
| 0 |
Kotlin
|
0
| 0 |
a72641a48fa247959f9e5b0802d6e3fbc7bba6d0
| 200 |
OmdbApp
|
Apache License 2.0
|
app/src/main/java/me/phh/treble/app/Desktop.kt
|
DogDayAndroid
| 461,521,113 | false | null |
package me.phh.treble.app
import android.app.Activity
import android.app.AlertDialog
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.hardware.display.DisplayManager
import android.hardware.input.InputManager
import android.os.*
import android.util.Log
import android.view.InputDevice
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileInputStream
import kotlin.concurrent.thread
object Desktop: EntryStartup {
val devices = HashMap<Int, InputDevice>()
val managedDevices = HashMap<Int, String>()
override fun startup(ctxt: Context) {
val im = ctxt.getSystemService(InputManager::class.java)!!
val dm = ctxt.getSystemService(DisplayManager::class.java)!!
im.registerInputDeviceListener(object: InputManager.InputDeviceListener {
override fun onInputDeviceRemoved(p0: Int) {
if(p0 !in devices) return
val device = devices.remove(p0)!!
Log.d("PHH", "Removing device $device")
val location = managedDevices.remove(p0) ?: return
val m = InputManager::class.java.getMethod("removePortAssociation", String::class.java)
Log.d("PHH", "Removing association for $location")
m.invoke(im, location)
}
override fun onInputDeviceAdded(p0: Int) {
val device = im.getInputDevice(p0)
devices[p0] = device
Log.d("PHH", "Received new device! $device")
if(Build.VERSION.SDK_INT < 29 || !device.isExternal) return
val nDisplays = dm.displays.size
if(nDisplays<=1) return
val inputflinger = ServiceManager.getService("input")
val outStream = ParcelFileDescriptor.createPipe()
var result: String? = null
val resultLock = Object()
thread {
try {
Log.d("PHH", "Starting thread to receive dump!")
val res = FileInputStream(outStream[0].fileDescriptor).bufferedReader().readText()
synchronized(resultLock) {
result = res
resultLock.notifyAll()
}
Log.d("PHH", "Closing thread to receive dump!")
outStream[0].close()
} catch(e: java.lang.Exception) {
Log.d("PHH", "Failed getting dump result because of ", e)
result = "fail"
}
}
Log.d("PHH", "Asking for dump!")
inputflinger.dump(outStream[1].fileDescriptor, emptyArray())
outStream[1].close()
Log.d("PHH", "Closed dump!")
while(result == null) {
synchronized(resultLock) {
resultLock.wait()
}
}
var currentLocation = ""
var currentUnique = ""
var found = false
val locationMatcher = Regex("^\\s*Location:(.*)")
val uniqueMatcher = Regex("^\\s*UniqueId:(.*)")
val idMatcher = Regex("\\s*Identifier: .*vendor=0x([0-9a-fA-F]{4}).*product=0x([0-9a-fA-F]{4}).*")
for(line in result!!.split("\n")) {
val locationMatch = locationMatcher.matchEntire(line)
val uniqueMatch = uniqueMatcher.matchEntire(line)
val idMatch = idMatcher.matchEntire(line)
if(locationMatch != null) {
currentLocation = locationMatch.groupValues[1].trim()
}
if(uniqueMatch != null) {
currentUnique = uniqueMatch.groupValues[1].trim()
}
if(idMatch != null) {
val vendor = Integer.parseInt(idMatch.groupValues[1], 16)
val product = Integer.parseInt(idMatch.groupValues[2], 16)
if(vendor == device.vendorId && product == device.productId) {
found = true
break
}
}
}
if(!found) return
val portLocation = if(currentLocation.isNotEmpty()) currentLocation else currentUnique
managedDevices[p0] = portLocation
val m = Context::class.java.getMethod("startActivityAsUser", Intent::class.java, UserHandle::class.java)
m.invoke(ctxt,
Intent()
.setComponent(ComponentName(ctxt, DesktopInput::class.java))
.putExtra("deviceName", device.name)
.putExtra("portLocation", portLocation)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
UserHandle.getUserHandleForUid(10105)
)
}
override fun onInputDeviceChanged(p0: Int) {
}
}, Handler(Looper.getMainLooper()))
}
}
class DesktopInput : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
Log.d("PHH", "Creating desktop input activity!")
super.onCreate(savedInstanceState)
setFinishOnTouchOutside(true)
}
override fun onResume() {
super.onResume()
val portLocation = intent.getStringExtra("portLocation")
if(portLocation == null || portLocation.isEmpty()) throw Exception("Meeeeeeeeeeeeeeeeeeh")
val deviceName = intent.getStringExtra("deviceName") ?: "Unknown"
val im = getSystemService(InputManager::class.java)!!
val m = InputManager::class.java.getMethod("addPortAssociation", String::class.java, Int::class.java)
val dm = getSystemService(DisplayManager::class.java)!!
val displays = dm.getDisplays()
val primaryDisplay = if(displays.size == 2) displays[0] else displays[2]
val secondaryDisplay = dm.getDisplays()[1]
val getAddressMethod = secondaryDisplay.javaClass.getMethod("getAddress")
val primaryAddress = getAddressMethod.invoke(primaryDisplay)
val secondaryAddress = getAddressMethod.invoke(secondaryDisplay)
val getPortMethod = secondaryAddress.javaClass.getMethod("getPort")
val primaryPort = ((getPortMethod.invoke(primaryAddress) as Byte).toInt() + 256) % 256
val secondaryPort = getPortMethod.invoke(secondaryAddress)
Log.d("PHH", "Associating device $portLocation to display port $primaryAddress $primaryPort or $secondaryAddress $secondaryPort")
AlertDialog.Builder(this)
.setMessage("You connected a new input device ($deviceName) while having a secondary screen.\nDo you want to assign that device to the screen called ${secondaryDisplay.name}?")
.setPositiveButton("Yes") { p0, p1 ->
m.invoke(im, portLocation, secondaryPort)
finish()
}
.setNeutralButton("Set to ${primaryDisplay.getName()} screen") { p0, p1 ->
m.invoke(im, portLocation, primaryPort)
finish()
}
.setNegativeButton("No") { p0, p1 ->
finish()
}
.show()
}
}
| 0 |
Kotlin
|
0
| 0 |
cf7cd1bef9379cf4fdb6c1d6bb26d9f86aad4b38
| 7,574 |
Treble_App
|
MIT License
|
data/src/main/java/com/sekthdroid/marvel/data/api/NetworkDatasource.kt
|
SekthDroid
| 423,296,060 | false |
{"Kotlin": 54990}
|
package com.sekthdroid.marvel.data.api
import com.sekthdroid.marvel.domain.models.MarvelCharacter
import com.sekthdroid.marvel.domain.models.Page
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.client.request.parameter
import javax.inject.Inject
internal class ApiEndpoints(private val baseUrl: String) {
fun characters() = "$baseUrl/characters"
}
internal class NetworkDatasource @Inject constructor(
private val httpClient: HttpClient,
private val endpoints: ApiEndpoints
) {
suspend fun getCharacters(): Page<MarvelCharacter> {
val response = httpClient.get(endpoints.characters())
.body<MarvelResponse<CharacterApiModel>>()
return response.data.toPage(CharacterApiModel::toCharacter)
}
suspend fun getCharacters(limit: Int = 20, offset: Int = 0): Page<MarvelCharacter> {
val response = httpClient.get(endpoints.characters()) {
parameter("limit", limit)
parameter("offset", offset)
}.body<MarvelResponse<CharacterApiModel>>()
return response.data.toPage(CharacterApiModel::toCharacter)
}
}
| 0 |
Kotlin
|
0
| 4 |
e4baefc192c41b9dd48d8bbf53e378f775723c1c
| 1,168 |
MarvelComposeSample
|
Apache License 2.0
|
android/app/src/main/java/com/labstyle/darioandroid/myapplicationtestrichtext/MainActivity.kt
|
myDario
| 447,595,750 | false |
{"Kotlin": 3106}
|
package com.labstyle.darioandroid.myapplicationtestrichtext
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import com.labstyle.darioandroid.dariorichtextclickable.DarioRichTextClickable
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val richText = "The <b>quick</b> <span style='color:#a52a2a;'>brown</span> <i>fox</i> jumps <a href='#'>over</a> <u>the</u> <a href='#'>lazy dog</a>."
findViewById<TextView>(R.id.textview01)?.let { textview ->
DarioRichTextClickable.transform(textview, richText, listOf(
Runnable {
Log.d("rafff", "1st handler")
},
Runnable {
Log.d("rafff", "2nd handler")
}
))
}
}
}
| 0 |
Kotlin
|
0
| 0 |
f4768a2d97c3b0204102f31b32a227983fbc8a42
| 983 |
DarioRichClickableTextView
|
Apache License 2.0
|
libraries/tools/kdoc/src/main/kotlin/org/jetbrains/kotlin/doc/templates/PackageListTemplate.kt
|
chirino
| 3,596,099 | false | null |
package org.jetbrains.kotlin.doc.templates
import kotlin.*
import org.jetbrains.kotlin.template.*
import kotlin.io.*
import kotlin.util.*
import java.util.*
import org.jetbrains.kotlin.doc.model.KModel
class PackageListTemplate(val model: KModel) : KDocTemplate() {
override fun render() {
for (p in model.packages) {
println(p.name)
}
}
}
| 0 | null |
28
| 71 |
ac434d48525a0e5b57c66b9f61b388ccf3d898b5
| 368 |
kotlin
|
Apache License 2.0
|
src/test/kotlin/no/nav/helse/arbeidsgiver/utils/RecurringJobTest.kt
|
navikt
| 293,487,810 | false | null |
package no.nav.helse.arbeidsgiver.utils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.test.TestCoroutineDispatcher
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.io.IOException
internal class RecurringJobTest {
private val testCoroutineDispatcher = TestCoroutineDispatcher()
val delay = 100L
val job = TestRecurringJob(CoroutineScope(testCoroutineDispatcher), delay)
@Test
internal fun `StartAsync does job in coroutine and then waits`() {
testCoroutineDispatcher.pauseDispatcher()
job.startAsync()
assertThat(job.getJobCompletedCounter()).isEqualTo(0)
testCoroutineDispatcher.runCurrent()
assertThat(job.getJobCompletedCounter()).isEqualTo(1)
testCoroutineDispatcher.advanceTimeBy(delay)
testCoroutineDispatcher.runCurrent()
assertThat(job.getJobCompletedCounter()).isEqualTo(2)
}
@Test
internal fun `When job fails and retry is on, ignore errors and run job again`() {
testCoroutineDispatcher.pauseDispatcher()
job.failOnJob = true
job.startAsync(retryOnFail = true)
testCoroutineDispatcher.runCurrent()
assertThat(job.getCallCounter()).isEqualTo(1)
assertThat(job.getJobCompletedCounter()).isEqualTo(0)
testCoroutineDispatcher.advanceTimeBy(delay)
testCoroutineDispatcher.runCurrent()
assertThat(job.getCallCounter()).isEqualTo(2)
assertThat(job.getJobCompletedCounter()).isEqualTo(0)
}
@Test
internal fun `When job fails and retry is off, stop processing`() {
testCoroutineDispatcher.pauseDispatcher()
job.failOnJob = true
job.startAsync(retryOnFail = false)
testCoroutineDispatcher.runCurrent()
assertThat(job.getCallCounter()).isEqualTo(1)
assertThat(job.getJobCompletedCounter()).isEqualTo(0)
testCoroutineDispatcher.advanceTimeBy(delay)
testCoroutineDispatcher.runCurrent()
assertThat(job.getCallCounter()).isEqualTo(1)
}
@Test
internal fun `Stopping the job prevents new execution`() {
testCoroutineDispatcher.pauseDispatcher()
job.startAsync()
testCoroutineDispatcher.runCurrent()
job.stop()
assertThat(job.getJobCompletedCounter()).isEqualTo(1)
testCoroutineDispatcher.advanceTimeBy(delay)
testCoroutineDispatcher.runCurrent()
assertThat(job.getJobCompletedCounter()).isEqualTo(1)
}
internal class TestRecurringJob(coroutineScope: CoroutineScope, waitMillisBetweenRuns: Long) : RecurringJob(coroutineScope, waitMillisBetweenRuns) {
public var failOnJob: Boolean = false
private var jobCompletedCounter = 0
fun getJobCompletedCounter(): Int {
return jobCompletedCounter
}
private var callCounter = 0
fun getCallCounter(): Int {
return callCounter
}
override fun doJob() {
callCounter++
if (failOnJob) throw IOException()
jobCompletedCounter++
}
}
}
| 6 |
Kotlin
|
1
| 0 |
b593afffda0fc069673b94beb1f22363cba2e18c
| 3,139 |
helse-arbeidsgiver-felles-backend
|
MIT License
|
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/curl_import/CurlImportViewState.kt
|
Waboodoo
| 34,525,124 | false |
{"Kotlin": 1970466, "HTML": 200869, "CSS": 2316, "Python": 1548}
|
package ch.rmy.android.http_shortcuts.activities.curl_import
import androidx.compose.runtime.Stable
@Stable
data class CurlImportViewState(
val submitButtonEnabled: Boolean = false,
val unsupportedOptions: List<String> = emptyList(),
)
| 26 |
Kotlin
|
105
| 999 |
34ec1652d431d581c3c275335eb4dbcf24ced9f5
| 246 |
HTTP-Shortcuts
|
MIT License
|
app/src/main/java/com/mundocode/dragonballapp/repositories/FirebaseRepositoryImpl.kt
|
juanppdev
| 835,842,388 | false |
{"Kotlin": 104157}
|
package com.mundocode.dragonballapp.repositories
import android.util.Log
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.mundocode.dragonballapp.data.Favorite
import javax.inject.Inject
class FirebaseRepositoryImpl @Inject constructor(
firestore: FirebaseFirestore,
auth: FirebaseAuth
) : FirebaseRepository {
private val favoritesCollection = firestore.collection("users")
.document(auth.currentUser?.uid ?: "")
.collection("favoriteCharacters")
override fun addFavorite(favorite: Favorite) {
favoritesCollection.document(favorite.id.toString()).set(favorite)
}
override fun removeFavorite(favorite: Favorite) {
favoritesCollection.whereEqualTo("id", favorite.id)
.get()
.addOnSuccessListener { documents ->
for (document in documents) {
favoritesCollection.document(document.id).delete()
}
}
}
override fun getAllFavorites(callback: (List<Favorite>) -> Unit) {
favoritesCollection.addSnapshotListener { snapshot, _ ->
if (snapshot != null) {
val favorites = snapshot.toObjects(Favorite::class.java)
Log.d("Favorites", "Favorites: $favorites")
callback(favorites)
}
}
}
}
interface FirebaseRepository {
fun addFavorite(favorite: Favorite)
fun removeFavorite(favorite: Favorite)
fun getAllFavorites(callback: (List<Favorite>) -> Unit)
}
| 0 |
Kotlin
|
0
| 3 |
53f8f928c6fe8ce60487d567383f91182328807e
| 1,562 |
dragon-ball-app
|
Apache License 2.0
|
app/src/main/java/net/oldbigbuddha/taskwallpaper/activities/MainActivity.kt
|
WallPaperTask
| 151,455,316 | false | null |
package net.oldbigbuddha.taskwallpaper.activities
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.SharedPreferences
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
import net.oldbigbuddha.taskwallpaper.*
import net.oldbigbuddha.taskwallpaper.Adapters.TaskAdapter
import net.oldbigbuddha.taskwallpaper.Fragments.DescriptionDialogFragment
class MainActivity : AppCompatActivity() {
companion object {
const val KEY = "TASKS"
}
private lateinit var adapter: TaskAdapter
private lateinit var preferences: SharedPreferences
private lateinit var editor: SharedPreferences.Editor
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val fragment = DescriptionDialogFragment.newInstance()
fragment.onNext = DialogInterface.OnClickListener { _, _ ->
}
fragment.show(supportFragmentManager, "Description-WallPaper")
initialize()
}
private fun initialize() {
setSupportActionBar(toolbar_main)
toolbar_main.inflateMenu(R.menu.menu_main)
preferences = getSharedPreferences(packageName, Context.MODE_PRIVATE)
enableEditText(et_task)
recycler_tasks.layoutManager = LinearLayoutManager(this)
adapter = TaskAdapter(ArrayList(), this)
adapter.onItemRemoveListener = View.OnClickListener {
if (!bt_add_task.isEnabled) {
cover.visibility = View.INVISIBLE
enableEditText(et_task)
enableImageButton(bt_add_task)
et_task.requestFocus()
}
}
bt_add_task.setOnClickListener {
if ( !TextUtils.isEmpty( et_task.text.toString() ) ) {
val task = et_task.text.toString()
adapter.addTask(task)
if (adapter.itemCount >= 5) {
disableEditText(et_task)
disableImageButton(bt_add_task)
cover.visibility = View.VISIBLE
}
} else {
Snackbar.make(container_main, "Task is empty", Snackbar.LENGTH_SHORT).show();
}
et_task.setText("")
}
recycler_tasks.adapter = adapter
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
R.id.action_next -> {
saveTasks()
startActivity( Intent( this, CheckActivity::class.java ) )
true
}
else -> {
super.onOptionsItemSelected(item)
}
}
override fun onPause() {
saveTasks()
super.onPause()
}
override fun onDestroy() {
saveTasks()
super.onDestroy()
}
override fun onResume() {
super.onResume()
adapter.mTasks = loadTasks()
}
private fun saveTasks() {
editor = preferences.edit()
editor.putString(MainActivity.KEY, adapter.mTasks.toString())
editor.apply()
}
private fun loadTasks(): ArrayList<String> {
val array = ArrayList<String>()
array.addAll(parseToArray( preferences.getString(KEY, "[No Task]") ))
return array
}
}
| 9 |
Kotlin
|
0
| 0 |
1edafe2ee6c7a833f028cac573a7d7faa410e23a
| 3,745 |
WallPaperTask-Android
|
MIT License
|
app/src/main/java/car/pace/cofu/util/views/WrapWidthMaterialButton.kt
|
pace
| 383,417,951 | false | null |
package car.pace.cofu.util.views
import android.content.Context
import android.graphics.Canvas
import android.text.Layout
import android.util.AttributeSet
import com.google.android.material.button.MaterialButton
import kotlin.math.ceil
/**
* A material button that does not automatically fill the parent when it is multiline
* but orientates on the widest line while still being compatible with icons
* Inspired by https://stackoverflow.com/a/13203729/2549828
*/
class WrapWidthMaterialButton : MaterialButton {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int)
: super(context, attrs, defStyleAttr)
private var actualWidthToParentWidthDifference = 0
private var isDrawing = false
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
if (layout == null || layout.lineCount < 2) return
val actualWidth = getActualWidth(layout)
if (actualWidth < measuredWidth) {
actualWidthToParentWidthDifference = measuredWidth - actualWidth
setMeasuredDimension(actualWidth, measuredHeight)
}
}
/**
* computes the actual width the view should be measured to by using the width
* of the widest line plus the paddings for the compound drawables
*/
private fun getActualWidth(layout: Layout): Int {
val maxLineWidth = (0 until layout.lineCount)
.map { layout.getLineWidth(it) }
.maxOrNull() ?: 0.0f
return ceil(maxLineWidth).toInt() + compoundPaddingLeft + compoundPaddingRight
}
override fun onDraw(canvas: Canvas) {
isDrawing = true
super.onDraw(canvas)
isDrawing = false
}
/**
* a workaround to make the TextView.onDraw method draw the text in the new centre of the view
* by substracting half of the actual width difference from the returned value
* This should only be done during drawing however, since otherwise the initial width calculation will fail
*/
override fun getCompoundPaddingLeft(): Int {
return super.getCompoundPaddingLeft().let { value ->
if (isDrawing) value - actualWidthToParentWidthDifference / 2 else value
}
}
}
| 0 |
Kotlin
|
0
| 2 |
46b82a471309baa6441ed5f319545bcf57646ed9
| 2,417 |
connectedfueling-app-android
|
MIT License
|
app/src/main/java/ru/aasmc/cryptocurrencies/CryptoCurrenciesApplication.kt
|
aasmc
| 406,902,301 | false |
{"Kotlin": 42348}
|
package ru.aasmc.cryptocurrencies
import android.app.Application
import ru.aasmc.cryptocurrencies.data.api.CoinCapApi
import ru.aasmc.cryptocurrencies.data.mappers.CoinMapper
import ru.aasmc.cryptocurrencies.data.mappers.HistoryMapper
import ru.aasmc.cryptocurrencies.data.repositories.CoinCapCoinsRepository
import ru.aasmc.cryptocurrencies.domain.repositories.CoinsRepository
import ru.aasmc.cryptocurrencies.presentation.CoinsSharedViewModelFactory
import ru.aasmc.cryptocurrencies.presentation.coinhistory.CoinHistoryFragmentViewModelFactory
import ru.aasmc.cryptocurrencies.presentation.coinlist.CoinListFragmentViewModelFactory
import ru.aasmc.cryptocurrencies.utils.DefaultDispatchersProvider
class CryptoCurrenciesApplication : Application() {
override fun onCreate() {
super.onCreate()
val repo = createRepository()
CoinsSharedViewModelFactory.inject(repo)
CoinListFragmentViewModelFactory.inject(repo)
CoinHistoryFragmentViewModelFactory.inject(repo)
}
private fun createRepository(): CoinsRepository {
return CoinCapCoinsRepository(
DefaultDispatchersProvider(),
CoinMapper(),
HistoryMapper(),
CoinCapApi.create(this)
)
}
}
| 0 |
Kotlin
|
0
| 0 |
83bc114f38ba7f8edafbbbb107a3aa495de1141c
| 1,259 |
CryptoCurrencies
|
The Unlicense
|
app/src/main/java/app/nexd/android/ui/seeker/create/articles/SeekerCreateRequestEnterArticlesFragment.kt
|
NexdApp
| 248,949,675 | false |
{"Java": 179711, "Kotlin": 130178, "Shell": 1827, "Scala": 1080}
|
package app.nexd.android.ui.seeker.create.articles
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isEmpty
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import app.nexd.android.R
import app.nexd.android.databinding.FragmentSeekerCreateRequestEnterArticlesBinding
import app.nexd.android.di.sharedGraphViewModel
import app.nexd.android.ui.common.DefaultSnackBar
import app.nexd.android.ui.common.HelpRequestCreateArticleBinder
import app.nexd.android.ui.seeker.create.SeekerCreateRequestViewModel
import app.nexd.android.ui.seeker.create.SeekerCreateRequestViewModel.Progress.*
import com.google.android.material.snackbar.Snackbar
import mva2.adapter.ListSection
import mva2.adapter.MultiViewAdapter
class SeekerCreateRequestEnterArticlesFragment : Fragment() {
private val vm: SeekerCreateRequestViewModel by sharedGraphViewModel(R.id.nav_seeker_create_request)
private lateinit var adapter: MultiViewAdapter
private lateinit var binding: FragmentSeekerCreateRequestEnterArticlesBinding
private var articleListSection: ListSection<HelpRequestCreateArticleBinder.ArticleInput>? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding =
FragmentSeekerCreateRequestEnterArticlesBinding.inflate(inflater, container, false)
binding.viewModel = vm
binding.lifecycleOwner = viewLifecycleOwner
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
initUi()
initRecyclerView()
setVmData()
setVmObserver()
}
private fun initUi() {
binding.buttonAccept.setOnClickListener {
vm.confirmSelectedArticles()
}
}
private fun initRecyclerView() {
binding.recyclerViewRequests.layoutManager = LinearLayoutManager(context)
adapter = MultiViewAdapter()
binding.recyclerViewRequests.adapter = adapter
adapter.registerItemBinders(HelpRequestCreateArticleBinder())
}
private fun setVmData() {
vm.setArticleListSection()
vm.setUserInfo()
}
private fun setVmObserver() {
vm.articles.observe(viewLifecycleOwner, Observer { articles ->
if (binding.recyclerViewRequests.isEmpty()) {
articleListSection = ListSection<HelpRequestCreateArticleBinder.ArticleInput>()
articleListSection!!.addAll(articles)
adapter.addSection(articleListSection!!)
}
})
vm.progress.observe(viewLifecycleOwner, Observer {
when (it) {
is Idle -> {
//nothing to do
}
is Loading -> {
findNavController().navigate(SeekerCreateRequestEnterArticlesFragmentDirections.toSeekerCreateRequestConfirmAddressFragment())
}
is Finished -> {
// state not reachable
}
is Error -> {
it.message?.let { errorMessageId ->
DefaultSnackBar(binding.root, errorMessageId, Snackbar.LENGTH_SHORT)
}
}
else -> Log.d(
SeekerCreateRequestEnterArticlesFragment::class.simpleName,
"unhandled state $it"
)
}
})
}
}
| 35 |
Java
|
4
| 12 |
8c24048adc38a886447c69c7e6b4cedb2168a9a0
| 3,743 |
nexd-android
|
MIT License
|
App-Compose/app/src/main/java/com/example/accessibilitydemo_compose/ui/theme/Color.kt
|
otsembo
| 483,208,619 | false | null |
package com.example.accessibilitydemo_compose.ui.theme
import androidx.compose.ui.graphics.Color
val md_theme_light_primary = Color(0xFFab00a0)
val md_theme_light_onPrimary = Color(0xFFffffff)
val md_theme_light_primaryContainer = Color(0xFFffd7f4)
val md_theme_light_onPrimaryContainer = Color(0xFF390036)
val md_theme_light_secondary = Color(0xFF6e5868)
val md_theme_light_onSecondary = Color(0xFFffffff)
val md_theme_light_secondaryContainer = Color(0xFFf8daed)
val md_theme_light_onSecondaryContainer = Color(0xFF271623)
val md_theme_light_tertiary = Color(0xFF815343)
val md_theme_light_onTertiary = Color(0xFFffffff)
val md_theme_light_tertiaryContainer = Color(0xFFffdbce)
val md_theme_light_onTertiaryContainer = Color(0xFF321206)
val md_theme_light_error = Color(0xFFba1b1b)
val md_theme_light_errorContainer = Color(0xFFffdad4)
val md_theme_light_onError = Color(0xFFffffff)
val md_theme_light_onErrorContainer = Color(0xFF410001)
val md_theme_light_background = Color(0xFFfcfcfc)
val md_theme_light_onBackground = Color(0xFF1f1a1d)
val md_theme_light_surface = Color(0xFFfcfcfc)
val md_theme_light_onSurface = Color(0xFF1f1a1d)
val md_theme_light_surfaceVariant = Color(0xFFefdee7)
val md_theme_light_onSurfaceVariant = Color(0xFF4f444b)
val md_theme_light_outline = Color(0xFF80747b)
val md_theme_light_inverseOnSurface = Color(0xFFf8eef2)
val md_theme_light_inverseSurface = Color(0xFF342f32)
val md_theme_light_inversePrimary = Color(0xFFffabed)
val md_theme_light_shadow = Color(0xFF000000)
val md_theme_dark_primary = Color(0xFFffabed)
val md_theme_dark_onPrimary = Color(0xFF5d0058)
val md_theme_dark_primaryContainer = Color(0xFF83007c)
val md_theme_dark_onPrimaryContainer = Color(0xFFffd7f4)
val md_theme_dark_secondary = Color(0xFFdbbfd1)
val md_theme_dark_onSecondary = Color(0xFF3e2a39)
val md_theme_dark_secondaryContainer = Color(0xFF564050)
val md_theme_dark_onSecondaryContainer = Color(0xFFf8daed)
val md_theme_dark_tertiary = Color(0xFFf5b9a4)
val md_theme_dark_onTertiary = Color(0xFF4c2618)
val md_theme_dark_tertiaryContainer = Color(0xFF663c2d)
val md_theme_dark_onTertiaryContainer = Color(0xFFffdbce)
val md_theme_dark_error = Color(0xFFffb4a9)
val md_theme_dark_errorContainer = Color(0xFF930006)
val md_theme_dark_onError = Color(0xFF680003)
val md_theme_dark_onErrorContainer = Color(0xFFffdad4)
val md_theme_dark_background = Color(0xFF1f1a1d)
val md_theme_dark_onBackground = Color(0xFFe9e0e3)
val md_theme_dark_surface = Color(0xFF1f1a1d)
val md_theme_dark_onSurface = Color(0xFFe9e0e3)
val md_theme_dark_surfaceVariant = Color(0xFF4f444b)
val md_theme_dark_onSurfaceVariant = Color(0xFFd2c2cb)
val md_theme_dark_outline = Color(0xFF9b8d95)
val md_theme_dark_inverseOnSurface = Color(0xFF1f1a1d)
val md_theme_dark_inverseSurface = Color(0xFFe9e0e3)
val md_theme_dark_inversePrimary = Color(0xFFab00a0)
val md_theme_dark_shadow = Color(0xFF000000)
val seed = Color(0xFFc516b7)
val error = Color(0xFFba1b1b)
| 0 |
Kotlin
|
0
| 0 |
eb3a9eb7d7f3ee8927508556274ce52abcf26ef7
| 2,952 |
KotlinKenyaAccessibility
|
MIT License
|
src/main/kotlin/dev/divinegenesis/soulbound/config/Config.kt
|
DivineGenesis
| 98,762,739 | false | null |
package dev.divinegenesis.soulbound.config
import org.spongepowered.configurate.objectmapping.ConfigSerializable
import org.spongepowered.configurate.objectmapping.meta.Comment
import org.spongepowered.configurate.objectmapping.meta.Setting
@ConfigSerializable
class Config {
@Setting("Modules")
val modules: Modules = Modules()
}
@ConfigSerializable
class Modules {
@Setting("Interact-Item")
val interactItemModule = true
@Setting("Pickup-Item")
val pickupItemModule = true
@Setting("Craft-Item")
val craftItemModule = true
@Setting("Item-DeSpawn")
@Comment("Prevents bound items from de-spawning due to Minecrafts natural clear cycle")
val itemDeSpawnModule = true
@Setting("OnDeath-Return")
@Comment("Returns bound items upon players death")
val onDeathModule = true
}
| 4 |
Kotlin
|
3
| 3 |
1edf8ea69fec84a419bb254140ebc9a8d3cfbc08
| 834 |
BetterSoulBinding
|
MIT License
|
app/src/commonMain/kotlin/com/materialkolor/builder/core/Platform.kt
|
jordond
| 860,167,006 | false |
{"Kotlin": 441363, "Shell": 6336, "HTML": 4360, "Swift": 614, "CSS": 102}
|
package com.materialkolor.builder.core
import com.mohamedrejeb.calf.core.PlatformContext
import com.mohamedrejeb.calf.io.KmpFile
import com.mohamedrejeb.calf.io.readByteArray
import kotlinx.coroutines.flow.Flow
expect val baseUrl: String
/**
* Whether the platform supports exporting the current theme to code.
*/
expect val exportSupported: Boolean
expect val platformContext: PlatformContext
suspend fun KmpFile.readBytes(): ByteArray = readByteArray(platformContext)
expect fun updatePlatformQueryParams(queryParams: String)
expect fun readPlatformQueryParams(): String?
expect fun observePlatformQueryParams(): Flow<String>
expect val isMobile: Boolean
expect val shareToClipboard: Boolean
expect fun shareUrl(url: String)
| 5 |
Kotlin
|
2
| 26 |
acd61c7309d24df1e014d5a0e1b9674ad8cb692b
| 740 |
MaterialKolorBuilder
|
MIT License
|
frontend/src/main/kotlin/org/jetbrains/kotlin/gradle/frontend/webpack/WebpackDevServerStopTask.kt
|
aSoft-Ltd
| 258,530,471 | false | null |
package org.jetbrains.kotlin.gradle.frontend.webpack
import org.apache.tools.ant.taskdefs.condition.Os
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.Nested
import org.gradle.api.tasks.TaskAction
import org.jetbrains.kotlin.com.intellij.ide.plugins.IdeaPluginDescriptorImpl
import org.jetbrains.kotlin.gradle.frontend.npm.NpmExtension
import org.jetbrains.kotlin.gradle.frontend.util.frontendExtension
import org.jetbrains.kotlin.gradle.frontend.util.mkdirsOrFail
import org.jetbrains.kotlin.gradle.frontend.util.nodePath
import org.jetbrains.kotlin.gradle.frontend.util.startWithRedirectOnFail
open class WebpackDevServerStopTask : DefaultTask() {
@TaskAction
fun stop() {
val processBuilderCommands = if (Os.isFamily(Os.FAMILY_WINDOWS)) {
arrayListOf("taskkill", "/f", "/im", "node")
} else {
arrayListOf("killall", "-9", "node")
}
ProcessBuilder(processBuilderCommands)
.directory(project.rootProject.buildDir)
.start()
}
}
| 0 |
Kotlin
|
3
| 1 |
8233558139144a26c40ae30526bfd0b26bc7b3cb
| 1,119 |
kotlin
|
MIT License
|
data/dialogs/src/main/kotlin/com/lillicoder/android/data/dialogs/DialogsDatabase.kt
|
lillicoder
| 323,515,594 | false |
{"Kotlin": 104155}
|
/*
* Copyright 2024 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this project 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.lillicoder.android.data.dialogs
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
private const val DATABASE_NAME = "dialogs.db"
@Database(
entities = [
DialogEntity::class,
],
version = 1,
)
abstract class DialogsDatabase : RoomDatabase() {
/**
* Gets the [DialogsDao] for this database.
* @return Dialogs DAO.
*/
abstract fun dialogsDao(): DialogsDao
companion object {
/**
* Needs to be:
*
* 1) Volatile for thread-safe visibility
* 2) Double-locked so that different threads get the right instance on creation
*/
@Volatile
private var instance: DialogsDatabase? = null
/**
* Gets an instance of [DialogsDatabase] with the given [Context]..
* @param context Database context.
* @return Dialogs database.
*/
fun getInstance(context: Context): DialogsDatabase {
return instance ?: synchronized(this) {
instance ?: buildDatabase(context).also { instance = it }
}
}
/**
* Builds a [DialogsDatabase] instance with the given [Context].
* @param context Database context.
* @return Dialogs database.
*/
private fun buildDatabase(context: Context): DialogsDatabase =
Room.databaseBuilder(
context.applicationContext,
DialogsDatabase::class.java,
DATABASE_NAME,
).build()
}
}
| 0 |
Kotlin
|
0
| 0 |
6447f297c978cecdd613c936e8cbd01d6cfe44ed
| 2,198 |
swwm-app-android
|
Apache License 2.0
|
bot/connector-twitter/src/main/kotlin/model/Attachment.kt
|
kchiron
| 192,942,545 | true |
{"Kotlin": 3816372, "TypeScript": 606849, "HTML": 212373, "CSS": 63959, "JavaScript": 4142, "Shell": 3046}
|
package ai.tock.bot.connector.twitter.model
data class Attachment(
val type: String,
val media: AttachmentMedia
)
| 0 |
Kotlin
|
0
| 0 |
0f06c44cd851dded24177ff8e0c53b6fc6fa4dd0
| 122 |
tock
|
Apache License 2.0
|
include-build/roborazzi-core/src/commonMain/kotlin/com/github/takahirom/roborazzi/RoborazziReportConst.kt
|
takahirom
| 594,307,070 | false |
{"Kotlin": 440745, "HTML": 2244, "CSS": 408}
|
package com.github.takahirom.roborazzi
@InternalRoborazziApi
object RoborazziReportConst {
@Deprecated(
message = "Use resultsSummaryFilePathFromBuildDir instead",
replaceWith = ReplaceWith("resultsSummaryFilePathFromBuildDir"),
level = DeprecationLevel.ERROR
)
const val resultsSummaryFilePath = "build/test-results/roborazzi/results-summary.json"
@Deprecated(
message = "Use resultDirPathFromBuildDir instead",
replaceWith = ReplaceWith("resultDirPathFromBuildDir"),
level = DeprecationLevel.ERROR
)
const val resultDirPath = "build/test-results/roborazzi/results/"
@Deprecated(
message = "Use reportFilePathFromBuildDir instead",
replaceWith = ReplaceWith("reportFilePathFromBuildDir"),
level = DeprecationLevel.ERROR
)
const val reportFilePath = "build/reports/roborazzi/index.html"
const val resultsSummaryFilePathFromBuildDir = "test-results/roborazzi/results-summary.json"
const val resultDirPathFromBuildDir = "test-results/roborazzi/results/"
const val reportFilePathFromBuildDir = "reports/roborazzi/index.html"
sealed interface DefaultContextData {
val key: String
val title: String
object DescriptionClass : DefaultContextData {
override val key = "roborazzi_description_class"
override val title = "Class"
}
companion object {
fun keyToTitle(key: String): String {
return when (key) {
DescriptionClass.key -> DescriptionClass.title
else -> key
}
}
}
}
}
| 83 |
Kotlin
|
34
| 712 |
0f528a13d085a8d2e3d218639f986fbbc21ce400
| 1,519 |
roborazzi
|
Apache License 2.0
|
app/src/main/java/com/iamsdt/pssd/ui/main/MainVM.kt
|
uzzal-mondal
| 187,579,574 | false |
{"Kotlin": 180364}
|
/*
* Developed By <NAME>
* on 8/17/18 12:55 PM
* Copyright (c) 2018 <NAME>.
*/
package com.iamsdt.pssd.ui.main
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.paging.LivePagedListBuilder
import androidx.paging.PagedList
import com.iamsdt.pssd.database.WordTable
import com.iamsdt.pssd.database.WordTableDao
import com.iamsdt.pssd.ext.ScopeViewModel
import com.iamsdt.pssd.ext.SingleLiveEvent
import com.iamsdt.pssd.utils.Bookmark
import com.iamsdt.pssd.utils.PAGE_CONFIG
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.util.*
class MainVM(val wordTableDao: WordTableDao) : ScopeViewModel() {
val searchEvent = SingleLiveEvent<WordTable>()
val singleWord = SingleLiveEvent<WordTable>()
private val queryLiveData = MutableLiveData<String>()
val myLiveData: LiveData<PagedList<WordTable>> =
Transformations.switchMap(queryLiveData, ::temp)
private fun temp(string: String = ""): LiveData<PagedList<WordTable>> {
val source = wordTableDao.getSearchData(string)
return LivePagedListBuilder(source, PAGE_CONFIG)
.build()
}
fun submitQuery(query: String = "") {
queryLiveData.value = query
}
fun getSingleWord(id: Int) {
uiScope.launch(Dispatchers.IO) {
val word = wordTableDao.getWordByID(id)
singleWord.postValue(word)
}
}
fun submit(query: String?) {
if (query?.isEmpty() == true) {
return
}
query?.let {
//make first latter capital
uiScope.launch {
val w = it.replaceFirst(it[0], it[0].toUpperCase(), false)
val word: WordTable? = withContext(Dispatchers.IO) { wordTableDao.getSearchResult(w) }
Timber.i("Word:$word")
//complete 10/23/2018 fix latter
searchEvent.postValue(word)
}
}
}
//track bookmark
val singleLiveEvent = SingleLiveEvent<Bookmark>()
//get single word
fun getWord(id: Int) = wordTableDao.getSingleWord(id)
private fun setBookmark(id: Int) {
uiScope.launch {
val update = withContext(Dispatchers.IO) {
wordTableDao.setBookmark(id)
}
if (update > 0)
singleLiveEvent.postValue(Bookmark.SET)
}
}
private fun deleteBookmark(id: Int) {
uiScope.launch {
val delete = withContext(Dispatchers.IO) {
wordTableDao.deleteBookmark(id)
}
if (delete > 0)
singleLiveEvent.postValue(Bookmark.DELETE)
}
}
fun setRecent(id: Int) {
val date = Date().time
uiScope.launch(Dispatchers.IO) {
wordTableDao.setRecent(id, date)
}
}
fun requestBookmark(id: Int, bookmarked: Boolean) {
if (bookmarked)
deleteBookmark(id)
else
setBookmark(id)
}
}
| 0 |
Kotlin
|
1
| 0 |
9ee1041a5a808f3b3f0a297c7e7aab8c77263e3a
| 3,132 |
SoilScienceDictionary
|
Apache License 2.0
|
core/src/main/java/fr/coppernic/lib/utils/os/AppHelper.kt
|
dukererenst
| 433,549,237 | false |
{"Java": 186744, "Kotlin": 137957, "Shell": 193}
|
package fr.coppernic.lib.utils.os
import android.annotation.SuppressLint
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.content.pm.Signature
import android.os.Build
import android.os.Looper
import android.os.PowerManager
import androidx.annotation.RequiresApi
import fr.coppernic.lib.utils.BuildConfig
import fr.coppernic.lib.utils.core.HashHelpers
import fr.coppernic.lib.utils.io.BytesHelper
import fr.coppernic.lib.utils.log.LogDefines.LOG
import fr.coppernic.lib.utils.result.RESULT
import java.io.ByteArrayOutputStream
import java.io.IOException
const val UID_SYSTEM = 1000
@Suppress("MemberVisibilityCanBePrivate", "unused")
object AppHelper {
private val DEBUG = BuildConfig.DEBUG
/**
* Return the unique id of the context's package
*
* @param context Context
* @return UID
*/
fun getPackageUid(context: Context): Int {
var ret = 0
val packageName = context.packageName
val pm = context.packageManager
try {
val pi = pm.getPackageInfo(packageName, PackageManager.GET_GIDS)
ret = pi.applicationInfo.uid
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
return ret
}
/**
* Return true if the app is a system one
*
* @param context Context
* @return true if system, false otherwise
*/
fun isSharingSystemUid(context: Context): Boolean {
return UID_SYSTEM == getPackageUid(context)
}
/**
* @return true if the current thread is the UI one
*/
fun isUiThread(): Boolean {
return Looper.getMainLooper() == Looper.myLooper()
}
/**
* Tell is an app is installed
*
* @param ctx Context
* @param packageName app's package name
* @return true if app is installed, false otherwise
*/
fun isPackageInstalled(ctx: Context, packageName: String): Boolean {
val pm = ctx.packageManager
return try {
val info = pm.getPackageInfo(packageName, 0)
info != null
} catch (e: PackageManager.NameNotFoundException) {
LOG.trace(e.toString())
false
}
}
/**
* Get first package found according to regex provided in input
*
* @param ctx Context
* @param pattern Regex pattern of the package to find
* @return Package name found of empty string
*/
fun getFirstInstalledPackageWithPattern(ctx: Context, pattern: String): String {
val pm = ctx.packageManager
val packages = pm.getInstalledPackages(PackageManager.GET_META_DATA)
for (info in packages) {
if (info.packageName.matches(pattern.toRegex())) {
return info.packageName
}
}
return ""
}
/**
* Return the application's version name.
*
* @param packageName The name of the package.
* @return the application's version name
*/
fun getAppVersionName(context: Context, packageName: String = context.packageName): String {
if (packageName.trim().isEmpty()) return ""
return try {
context.packageManager.getPackageInfo(packageName, 0).versionName
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
""
}
}
/**
* Return the application's version code.
*
* @param packageName The name of the package.
* @return the application's version code
*/
fun getAppVersionCode(context: Context, packageName: String = context.packageName): Int {
if (packageName.trim().isEmpty()) return -1
return try {
context.packageManager.getPackageInfo(packageName, 0).versionCode
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
-1
}
}
/**
* Return the application's signature.
*
* @param packageName The name of the package.
* @return the application's signature
*/
@SuppressLint("PackageManagerGetSignatures")
fun getAppSignatures(context: Context, packageName: String = context.packageName): List<Signature> {
if (packageName.trim().isEmpty()) return emptyList()
return try {
val pm = context.packageManager
pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES).signatures.toList()
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
emptyList()
}
}
fun getAppSignaturesHash(context: Context, packageName: String, algorithm: String): String {
if (packageName.trim().isEmpty()) return ""
return try {
val outputStream = ByteArrayOutputStream()
getAppSignatures(context, packageName).forEach { outputStream.write(it.toByteArray()) }
val hash = HashHelpers.hashTemplate(outputStream.toByteArray(), algorithm)
BytesHelper.byteArrayToString(hash)
} catch (e: IOException) {
""
}
}
/**
* Return the application's signature for SHA1 value.
*
* @param packageName The name of the package.
* @return the application's signature for SHA1 value
*/
fun getAppSignaturesSHA1(context: Context, packageName: String = context.packageName): String {
return getAppSignaturesHash(context, packageName, "SHA1")
}
/**
* Return the application's signature for SHA256 value.
*
* @param packageName The name of the package.
* @return the application's signature for SHA256 value
*/
fun getAppSignaturesSHA256(context: Context, packageName: String = context.packageName): String {
return getAppSignaturesHash(context, packageName, "SHA256")
}
/**
* Return the application's signature for MD5 value.
*
* @param packageName The name of the package.
* @return the application's signature for MD5 value
*/
fun getAppSignaturesMD5(context: Context, packageName: String = context.packageName): String {
return getAppSignaturesHash(context, packageName, "MD5")
}
/**
* Reboot device
*
* @param ctx Context
*/
@SuppressLint("MissingPermission")
fun reboot(ctx: Context) {
val pm = ctx.getSystemService(Context.POWER_SERVICE) as PowerManager?
pm?.reboot(null)
}
/**
* Shutdown device
*
* @param ctx Context
*/
fun shutdown(ctx: Context) {
ctx.startActivity(IntentHelper.getShutdownIntent())
}
/**
* Tell if a service is currently running
*
* @param context Context
* @param serviceClass Service class
* @return true if the service is running
*/
@Deprecated(message = "As of {@link android.os.Build.VERSION_CODES#O}, this method\n" +
"is no longer available to third party applications. For backwards compatibility,\n" +
"it will still return the caller's own services.")
fun isServiceRunning(context: Context, serviceClass: Class<*>): Boolean {
val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
for (service in manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.name == service.service.className) {
return true
}
}
return false
}
/**
* Kill background process
*
* Needs KILL_BACKGROUND_PROCESSES permission
*
* @param context Android context
* @param pack App package to kill
* @return RESULT.OK or RESULT.NOT_FOUND
*/
@SuppressLint("MissingPermission")
fun killApp(context: Context, pack: String): RESULT {
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val processes = am.runningAppProcesses
for (info in processes) {
if (DEBUG) {
LOG.trace("$pack vs ${info.processName}")
}
if (info.processName == pack) {
LOG.info("Killing {}", info.processName)
am.killBackgroundProcesses(info.processName)
return RESULT.OK
}
}
return RESULT.NOT_FOUND
}
/**
* Get an activity info of a launchable activity from app's name
*
* @param context Android context
* @param appName Application's name
* @return Activity info or null if not found
*/
fun appNameToLaunchAbleActivityInfo(context: Context, appName: String): ActivityInfo? {
val pm = context.packageManager
val intent = Intent(Intent.ACTION_MAIN)
intent.addCategory(Intent.CATEGORY_LAUNCHER)
val resolveInfos = pm.queryIntentActivities(intent, 0)
for (info in resolveInfos) {
if (info != null && info.loadLabel(pm) == appName) {
return info.activityInfo
}
}
return null
}
/**
* Helper to send a broadcast when app can be system.
*
* Main goal is to suppress a warning in logcat
*
* @param context Android context
* @param intent Intent to broadcast
*/
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
@SuppressLint("MissingPermission")
fun sendBroadcast(context: Context, intent: Intent) {
if (isSharingSystemUid(context)) {
// Permissions android.permission.INTERACT_ACROSS_USERS shall be hold by app
context.sendBroadcastAsUser(intent, android.os.Process.myUserHandle())
} else {
context.sendBroadcast(intent)
}
}
/**
* Helper to send a broadcast when app can be system.
*
*
* Main goal is to suppress a warning in logcat
*
* @param context Android context
* @param intent Intent to broadcast
*/
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
@SuppressLint("MissingPermission")
fun sendBroadcast(context: Context, intent: Intent, permission: String?) {
if (isSharingSystemUid(context)) {
// Permissions android.permission.INTERACT_ACROSS_USERS shall be hold by app
context.sendBroadcastAsUser(intent, android.os.Process.myUserHandle(), permission)
} else {
context.sendBroadcast(intent, permission)
}
}
}
| 2 |
Java
|
1
| 0 |
217913a1d9b730d8dd9b006475061e82c4395801
| 10,535 |
AndroidUtils-1
|
Apache License 2.0
|
app/src/main/java/com/mohmmed/mosa/eg/towmmen/domin/usecases/localuser/SaveAppEntry.kt
|
M4A28
| 842,519,543 | false |
{"Kotlin": 877792}
|
package com.mohmmed.mosa.eg.towmmen.domin.usecases.localuser
import com.mohmmed.mosa.eg.towmmen.domin.localusermanger.LocalUserManger
class SaveAppEntry(
private val localUserManger: LocalUserManger
) {
suspend operator fun invoke(){
localUserManger.saveAppEntry()
}
}
| 0 |
Kotlin
|
0
| 0 |
37a6e192262f4995f599978957d1b39257fd88a9
| 291 |
Towmmen
|
MIT License
|
data/RF00311/rnartist.kts
|
fjossinet
| 449,239,232 | false |
{"Kotlin": 8214424}
|
import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF00311"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
2 to 7
122 to 127
}
value = "#0abc56"
}
color {
location {
8 to 121
}
value = "#588bd2"
}
color {
location {
1 to 1
}
value = "#d792ed"
}
color {
location {
128 to 128
}
value = "#d4a020"
}
}
}
| 0 |
Kotlin
|
0
| 0 |
3016050675602d506a0e308f07d071abf1524b67
| 784 |
Rfam-for-RNArtist
|
MIT License
|
app/src/main/java/com/example/photosapp/data/LoginDataSource.kt
|
aav-98
| 796,190,792 | false |
{"Kotlin": 104579}
|
package com.example.photosapp.data
import android.content.Context
import android.util.Log
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.example.photosapp.R
import com.example.photosapp.data.model.LoggedInUser
import com.example.photosapp.ui.login.LoginResult
import com.google.gson.Gson
import java.io.IOException
import java.math.BigInteger
import java.security.MessageDigest
/**
* Class that handles authentication w/ login credentials and retrieves user information.
*/
class LoginDataSource(context: Context) {
private val TAG = javaClass.simpleName
private val appContext = context.applicationContext
private val sharedPreferences = appContext.getSharedPreferences("com.example.photosapp.USER_DETAILS", Context.MODE_PRIVATE)
private val queue = Volley.newRequestQueue(appContext)
/**
* Initiates a login request to authenticate a user.
*
* This function sends a POST request to a predefined server URL to authenticate a user using
* their username and password. Upon receiving a response, it parses the JSON response into
* a `LoggedInUser` object if successful, or handles errors accordingly.
*
* Error Handling:
* - On a successful HTTP response containing non-empty content, the JSON is parsed into a `LoggedInUser`.
* - On empty response or network errors, the callback is invoked with an error.
*
* @param username The username of the user attempting to log in.
* @param password The password of the user, which will be hashed using MD5 before sending.
* @param callback A callback interface through which results are returned. Results include successful
* user login data or error information in case of failure.
*
*/
fun login(username: String, password: String, callback: LoginResultCallback) {
val url = "http://10.0.2.2:8080/methodPostRemoteLogin"
val hashedPassword = md5(password)
val stringRequest = object : StringRequest(
Method.POST, url,
Response.Listener { response ->
Log.d(TAG, "Response from login post request: $response")
if (response != "") {
val gson = Gson()
val user: LoggedInUser = gson.fromJson(response, LoggedInUser::class.java)
callback.onResult(LoginResult(success = user))
} else {
callback.onResult(LoginResult(error = IOException("Error logging in")))
}
},
Response.ErrorListener { error ->
Log.e(TAG, "Login failed: ${error.message}")
callback.onResult(LoginResult(error = IOException("Error logging in")))
}) {
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
params["em"] = username
params["ph"] = hashedPassword
return params
}
}
queue.add(stringRequest)
}
/**
* Invoked when user chooses to log out of application
*
* This function clears the user information and corresponding photos stored in Shared Preferences.
*
*/
fun logout() {
sharedPreferences.edit().clear().apply()
with (sharedPreferences.edit()) {
putBoolean(appContext.getString(R.string.is_logged_in), false)
apply()
}
}
/**
* This function hashes the cleartext using the MD5 hashing algorithm
*
* @param password The <PASSWORD>
*
*/
private fun md5(password: String): String {
val md = MessageDigest.getInstance("MD5")
val hash = BigInteger(1, md.digest(password.toByteArray(Charsets.UTF_8)))
return String.format("%032x", hash)
}
/**
* Submits a request to change the user's password on the server.
*
* This function sends a POST request to change the password of the user identified by an email
* stored in SharedPreferences. The function listens for a response to determine whether the
* password change was successful or if an error occurred.
*
* Error Handling:
* - The server is expected to return "OK" if the password change is successful. Any other response or network errors
* will trigger a callback indicating an error.
*
* @param newPassword The new password the user wants to set, which will be hashed using MD5 before sending.
* @param callback A callback interface through which results are returned. Results include
* success or error information.
*
*/
fun changePassword(newPassword: String, callback: ChangePasswordResultCallback) {
val url = "http://10.0.2.2:8080/methodPostChangePasswd"
val hashedNewPassword = md5(<PASSWORD>)
val email = sharedPreferences.getString(appContext.getString(R.string.email_key), appContext.getString(R.string.no_value)).toString()
val stringRequest = object : StringRequest(
Method.POST, url,
Response.Listener { response ->
Log.d(TAG, response)
if (response == "OK") {
Result.Success(response)
callback.onResult(Result.Success(response))
} else {
callback.onResult(Result.Error(IOException("Error changing password")))
}
},
Response.ErrorListener { error ->
Log.e(TAG, "Login failed: ${error.message}")
callback.onResult(Result.Error(IOException("Error changing password", error)))
}) {
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
params["em"] = email
params["np"] = newPassword
params["ph"] = <PASSWORD>
return params
}
}
queue.add(stringRequest)
}
}
/**
* Interface that will be used for callbacks when the login request is completed
*/
interface LoginResultCallback {
fun onResult(result: LoginResult)
}
/**
* Interface that will be used for callbacks when the change password request is completed
*/
interface ChangePasswordResultCallback {
fun onResult(result: Result<String>)
}
| 0 |
Kotlin
|
0
| 0 |
7ed803d62db552ae8ba07b90e1b9b214b39d5746
| 6,443 |
PhotoTaggingApp
|
MIT License
|
src/test/kotlin/eu/quiqua/geojson/model/geometry/PolygonSpec.kt
|
quiqua
| 145,003,416 | false | null |
package eu.quiqua.geojson.model.geometry
import com.natpryce.hamkrest.assertion.assert
import com.natpryce.hamkrest.isA
import eu.quiqua.geojson.model.Type
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
internal class PolygonSpec : Spek({
describe("A Polygon object") {
context("Create with valid 2D coordinates") {
val coordinates = listOf(
listOf(
Position(longitude = 1.0, latitude = 2.0),
Position(longitude = 1.0, latitude = 3.0),
Position(longitude = 2.0, latitude = 3.0),
Position(longitude = 2.0, latitude = 2.0),
Position(longitude = 1.0, latitude = 2.0)
)
)
val polygon = Polygon(coordinates = coordinates)
it("Will validate successfully") {
assert.that(polygon.validate(), isA<ValidationResult.Ok>())
}
it("Is of Type.Polygon") {
assert.that(polygon.type, isA<Type.Polygon>())
}
}
context("Create with valid 3D coordinates") {
val coordinates = listOf(
listOf(
Position(longitude = 1.0, latitude = 2.0),
Position(longitude = 1.0, latitude = 3.0),
Position(longitude = 2.0, latitude = 3.0),
Position(longitude = 2.0, latitude = 2.0),
Position(longitude = 1.0, latitude = 2.0)
)
)
val polygon = Polygon(coordinates = coordinates)
it("Will validate successfully") {
assert.that(polygon.validate(), isA<ValidationResult.Ok>())
}
}
context("Create with different coordinate dimensions") {
val coordinates = listOf(
listOf(
Position(longitude = 1.0, latitude = 2.0),
Position(longitude = 1.0, latitude = 3.0, altitude = 1.2),
Position(longitude = 2.0, latitude = 3.0),
Position(longitude = 2.0, latitude = 2.0),
Position(longitude = 1.0, latitude = 2.0)
)
)
val polygon = Polygon(coordinates = coordinates)
it("Returns a Validation.Error.IncompatibleCoordinateDimensions") {
assert.that(polygon.validate(), isA<ValidationResult.Error.IncompatibleCoordinateDimensions>())
}
}
context("Create with invalid coordinate boundaries") {
val coordinates = listOf(
listOf(
Position(longitude = 1.0, latitude = 2.0),
Position(longitude = 100.0, latitude = 93.0),
Position(longitude = 2.0, latitude = 3.0),
Position(longitude = 2.0, latitude = 2.0),
Position(longitude = 1.0, latitude = 2.0)
)
)
val polygon = Polygon(coordinates = coordinates)
it("Returns a Validation.Error.OutOfRange") {
assert.that(polygon.validate(), isA<ValidationResult.Error.OutOfRange>())
}
}
context("Coordinates are not closed") {
val coordinates = listOf(
listOf(
Position(longitude = 1.0, latitude = 2.0),
Position(longitude = 1.0, latitude = 3.0),
Position(longitude = 2.0, latitude = 3.0),
Position(longitude = 2.0, latitude = 2.0)
)
)
val polygon = Polygon(coordinates = coordinates)
it("Returns a Validation.Error.NoLinearRing") {
assert.that(polygon.validate(), isA<ValidationResult.Error.NoLinearRing>())
}
}
context("Coordinates only represent a closed line") {
val coordinates = listOf(
listOf(
Position(longitude = 1.0, latitude = 2.0),
Position(longitude = 1.0, latitude = 3.0),
Position(longitude = 1.0, latitude = 2.0)
)
)
val polygon = Polygon(coordinates = coordinates)
it("Returns a Validation.Error.NoLinearRing") {
assert.that(polygon.validate(), isA<ValidationResult.Error.NoLinearRing>())
}
}
}
})
| 3 |
Kotlin
|
2
| 3 |
fdebb2285923d82dcdb8f3b2c93fcb2526321bbd
| 4,474 |
kotlin-geojson-moshi
|
MIT License
|
data-bus/src/main/kotlin/io/kommons/designpatterns/databus/data/StoppingData.kt
|
debop
| 235,066,649 | false | null |
package io.kommons.designpatterns.databus.data
import io.kommons.designpatterns.databus.AbstractDataType
import io.kommons.logging.KLogging
import java.time.LocalDateTime
/**
* StoppingData
*
* @author debop
*/
class StoppingData(val stoppedAt: LocalDateTime): AbstractDataType() {
companion object: KLogging() {
fun of(stoppedAt: LocalDateTime) = StoppingData(stoppedAt)
}
}
| 0 |
Kotlin
|
11
| 53 |
c00bcc0542985bbcfc4652d0045f31e5c1304a70
| 398 |
kotlin-design-patterns
|
Apache License 2.0
|
app/src/main/kotlin/org/sirekanyan/devtools/Profile.kt
|
sirekanian
| 745,856,082 | false |
{"Kotlin": 12961, "Shell": 483}
|
package org.sirekanyan.devtools
data class Profile(
val dev: Int,
val adb: Int,
val dka: Int,
val font: Float,
val screen: Long,
val windowAnimation: Float,
val transitionAnimation: Float,
val animatorDuration: Float,
val stayAwake: Int,
) {
fun isDefault(): Boolean =
this == DefaultProfile
fun isDevelop(): Boolean =
this == DevelopProfile
companion object {
val DefaultProfile =
Profile(
dev = 0,
adb = 0,
dka = 0,
font = 1.0f,
screen = 30,
windowAnimation = 1f,
transitionAnimation = 1f,
animatorDuration = 1f,
stayAwake = 0,
)
val DevelopProfile =
Profile(
dev = 1,
adb = 1,
dka = 0,
font = 1.15f,
screen = 120,
windowAnimation = 1f,
transitionAnimation = 1f,
animatorDuration = 1f,
stayAwake = 7,
)
}
}
| 0 |
Kotlin
|
0
| 0 |
c8a8ebc64f68b476d691e3a1c675aa9ee266feb1
| 1,133 |
devtools
|
MIT License
|
components/src/main/java/com/mercadolibre/android/andesui/bottomsheet/title/AndesBottomSheetTitleAlignment.kt
|
maaguero
| 252,283,086 | false |
{"Gradle": 9, "Markdown": 17, "Java Properties": 1, "Shell": 1, "Ignore List": 4, "Batchfile": 1, "YAML": 5, "XML": 150, "Proguard": 3, "Kotlin": 311, "INI": 1, "HTML": 1, "JSON": 1, "Java": 1}
|
package com.mercadolibre.android.andesui.bottomsheet.title
enum class AndesBottomSheetTitleAlignment {
LEFT_ALIGN,
CENTERED;
companion object {
fun fromString(value: String): AndesBottomSheetTitleAlignment = valueOf(value.toUpperCase())
}
internal val alignment get() = getAndesBottomSheetTitleAlignment()
private fun getAndesBottomSheetTitleAlignment(): AndesBottomSheetTitleAlignmentInterface {
return when (this) {
LEFT_ALIGN -> AndesBottomSheetTitleLeftAligned
CENTERED -> AndesBottomSheetTitleCenterAligned
}
}
}
| 1 | null |
1
| 1 |
bc12913d8a91c4a71faed6ba7e5d6fdfa16de123
| 598 |
fury_andesui-android
|
MIT License
|
src/main/kotlin/com/donaldwu/ecommerceapispring/helper/Helper.kt
|
yeukfei02
| 516,201,604 | false | null |
package com.donaldwu.ecommerceapispring.helper
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import com.auth0.jwt.exceptions.JWTCreationException
class Helper {
companion object {
fun getJwtToken(id: Long, email: String): String {
var token = ""
try {
val payload = mutableMapOf<String, Any>()
payload["id"] = id
payload["email"] = email
val jwtSecret = System.getenv("JWT_SECRET") ?: "secret"
val algorithm: Algorithm = Algorithm.HMAC256(jwtSecret)
token = JWT.create()
.withIssuer("auth0")
.withPayload(payload)
.sign(algorithm)
} catch (e: JWTCreationException) {
println("getJwtToken error = ${e.message}")
}
return token
}
}
}
| 1 |
Kotlin
|
0
| 0 |
25ec56f6aa83bc25504046f15248a3dab6b1359b
| 915 |
ecommerce-api-spring
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.