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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mordant/src/jvmTest/kotlin/com/github/ajalt/mordant/terminal/TerminalCursorTest.kt
|
caleb-lewis
| 318,118,618
| true
|
{"Kotlin": 272310, "Python": 5498}
|
package com.github.ajalt.mordant.terminal
import com.github.ajalt.mordant.internal.CSI
import io.kotest.data.blocking.forAll
import io.kotest.data.row
import io.kotest.matchers.shouldBe
import org.junit.Test
private fun c(b: TerminalCursor.() -> Unit): String {
val t = VirtualTerminal()
t.cursor.b()
return t.buffer()
}
class TerminalCursorTest {
@Test
fun `disabled commands`() {
val t = VirtualTerminal(AnsiLevel.NONE)
val c = t.cursor
forAll(
row(c.up(1)),
row(c.down(1)),
row(c.right(1)),
row(c.left(1)),
row(c.startOfLine()),
row(c.setPosition(1, 1)),
row(c.show()),
row(c.hide(showOnExit = false)),
row(c.clearScreen()),
row(c.clearScreenAfterCursor()),
) {
t.buffer() shouldBe ""
t.clearBuffer()
}
}
@Test
fun `cursor directions 0 count`() = forAll(
row(c { up(0) }),
row(c { down(0) }),
row(c { left(0) }),
row(c { right(0) }),
) { actual ->
actual shouldBe ""
}
@Test
fun `cursor commands`() = forAll(
row(c { up(2) }, "${CSI}2A"),
row(c { down(3) }, "${CSI}3B"),
row(c { right(4) }, "${CSI}4C"),
row(c { left(5) }, "${CSI}5D"),
row(c { setPosition(6, 7) }, "${CSI}8;7H"),
row(c { show() }, "$CSI?25h"),
row(c { hide(showOnExit = false) }, "$CSI?25l"),
row(c { clearScreen() }, "${CSI}2J"),
) { actual, expected ->
actual shouldBe expected
}
@Test
fun `cursor commands negative count`() {
forAll(
row(c { up(-1) }, c { down(1) }),
row(c { down(-2) }, c { up(2) }),
row(c { left(-3) }, c { right(3) }),
row(c { right(-4) }, c { left(4) }),
) { actual, expected ->
actual shouldBe expected
}
}
}
| 0
| null |
0
| 0
|
0b52548c3a8f84074ea7f2726700257a163af267
| 2,062
|
mordant
|
Apache License 2.0
|
src/ru/vkurdin/idea/php/lambdafolding/TreeUtils.kt
|
vkurdin
| 63,182,447
| false
| null |
package ru.vkurdin.idea.php.lambdafolding
import com.intellij.psi.PsiElement
fun PsiElement.prevSiblings() = elementSeq { it.prevSibling }
fun PsiElement.nextSiblings() = elementSeq { it.nextSibling }
fun PsiElement.parents() = elementSeq { it.parent }
inline private fun <T> T.elementSeq(crossinline elementProvider: (T) -> T?) =
object : Sequence<T> {
override fun iterator() =
object : Iterator<T> {
private var next: T? = elementProvider(this@elementSeq)
override fun hasNext() = next != null
override fun next() : T = next!!.let {
val current = it
next = elementProvider(current)
current
}
}
}
| 5
|
Kotlin
|
3
| 32
|
7a18d84585b70a74256b63c10bb8269b5a268c6e
| 772
|
idea-php-lambda-folding
|
MIT License
|
sdk/src/main/java/com/appsci/panda/sdk/data/subscriptions/google/PurchasesGoogleStore.kt
|
AppSci
| 303,741,765
| false
|
{"Kotlin": 143280, "HTML": 82124}
|
package com.appsci.panda.sdk.data.subscriptions.google
import com.android.billingclient.api.*
import com.appsci.panda.sdk.data.subscriptions.PurchasesMapper
import com.appsci.panda.sdk.data.subscriptions.local.PurchaseEntity
import com.appsci.panda.sdk.data.subscriptions.local.TYPE_PRODUCT
import com.appsci.panda.sdk.data.subscriptions.local.TYPE_SUBSCRIPTION
import com.appsci.panda.sdk.domain.utils.rx.Schedulers
import com.gen.rxbilling.client.RxBilling
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Single
import kotlinx.coroutines.*
import kotlinx.coroutines.rx2.await
import timber.log.Timber
interface PurchasesGoogleStore {
fun getPurchases(): Single<List<PurchaseEntity>>
fun consumeProducts(): Completable
fun fetchHistory(): Completable
fun acknowledge(): Completable
suspend fun getProductsDetails(requests: Map<String, List<String>>): List<ProductDetails>
}
class PurchasesGoogleStoreImpl(
private val rxBilling: RxBilling,
private val mapper: PurchasesMapper,
) : PurchasesGoogleStore {
override fun getPurchases(): Single<List<PurchaseEntity>> {
return rxBilling.getPurchases(BillingClient.SkuType.SUBS)
.map { mapper.mapFromBillingPurchases(it, TYPE_SUBSCRIPTION) }
.flatMap { purchases ->
//we don't use zip() here because it crashes in case of errors in both sources
return@flatMap rxBilling.getPurchases(BillingClient.SkuType.INAPP)
.map { mapper.mapFromBillingPurchases(it, TYPE_PRODUCT) }
.map { subscriptions -> return@map subscriptions + purchases }
}
.doOnSuccess { Timber.d("getPurchases $it") }
.doOnError { Timber.e(it) }
//by default billing client pushes result to UI thread, so we need to switch it to IO
.observeOn(Schedulers.io())
}
override fun consumeProducts(): Completable {
return rxBilling.getPurchases(BillingClient.SkuType.INAPP)
.flatMapPublisher { Flowable.fromIterable(it) }
.concatMapCompletable {
rxBilling.consumeProduct(ConsumeParams.newBuilder()
.setPurchaseToken(it.purchaseToken)
.build())
}
.observeOn(Schedulers.io())
}
override fun fetchHistory(): Completable {
return rxBilling.getPurchaseHistory(BillingClient.SkuType.SUBS)
.ignoreElement()
.andThen(rxBilling.getPurchaseHistory(BillingClient.SkuType.INAPP))
.ignoreElement()
.observeOn(Schedulers.io())
}
override fun acknowledge(): Completable =
rxBilling.getPurchases(BillingClient.SkuType.SUBS)
.flatMap { subscriptions ->
rxBilling.getPurchases(BillingClient.SkuType.INAPP)
.map { products ->
subscriptions + products
}
}.map { list -> list.filter { !it.isAcknowledged } }
.flatMapPublisher { Flowable.fromIterable(it) }
.flatMapCompletable {
rxBilling.acknowledge(AcknowledgePurchaseParams
.newBuilder()
.setPurchaseToken(it.purchaseToken)
.build())
}
.observeOn(Schedulers.io())
override suspend fun getProductsDetails(requests: Map<String, List<String>>): List<ProductDetails> =
withContext(Dispatchers.IO) {
val scope = CoroutineScope(SupervisorJob())
val params: List<QueryProductDetailsParams> = requests
.map { group ->
val type = group.key
val ids = group.value
QueryProductDetailsParams.newBuilder()
.setProductList(
ids.map {
QueryProductDetailsParams.Product.newBuilder()
.setProductId(it)
.setProductType(type)
.build()
}
).build()
}
return@withContext params.map {
scope.async {
rxBilling.getProductDetails(it).await()
}
}.awaitAll().flatten()
}
}
| 0
|
Kotlin
|
0
| 1
|
99d2c07a480164fa6e7bee59b13f820510fabc04
| 4,776
|
panda-sdk-android
|
MIT License
|
0485.Max Consecutive Ones.kt
|
sarvex
| 842,260,390
| false
|
{"Kotlin": 1775678, "PowerShell": 418}
|
internal class Solution {
fun findMaxConsecutiveOnes(nums: IntArray): Int {
var ans = 0
var cnt = 0
for (x in nums) {
if (x == 1) {
ans = max(ans, ++cnt)
} else {
cnt = 0
}
}
return ans
}
}
| 0
|
Kotlin
|
0
| 0
|
17a80985d970c8316fb694e4952692e598d700af
| 248
|
kotlin-leetcode
|
MIT License
|
src/test/kotlin/org/xpathqs/core/reflection/parser/ObjectWithNoScanTest.kt
|
xpathqs
| 363,898,788
| false
| null |
/*
* Copyright (c) 2021 XPATH-QS
*
* 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 org.xpathqs.core.reflection.parser
import assertk.assertThat
import assertk.assertions.hasSize
import assertk.assertions.isEmpty
import assertk.assertions.isEqualTo
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.xpathqs.core.reflection.PageWithBase
import org.xpathqs.core.reflection.PageWithNoScan
import org.xpathqs.core.reflection.SelectorParser
import org.xpathqs.xpathShouldBe
internal class ObjectWithNoScanTest {
@BeforeEach
fun before() {
SelectorParser(PageWithNoScan).parse()
}
@Test
fun checkSelectorName() {
assertThat(PageWithNoScan.s1.name)
.isEqualTo("PageWithNoScan.s1")
}
@Test
fun checkSelectorNoScanName() {
assertThat(PageWithNoScan.s2.name)
.isEmpty()
}
@Test
fun checkSelectorXpath() {
PageWithNoScan.s1
.xpathShouldBe("//base//s1")
}
@Test
fun checkSelectorNoScanXpath() {
PageWithNoScan.s2
.xpathShouldBe("//s2")
}
@Test
fun checkSelectorForMemberField() {
PageWithNoScan.holder1.sel1
.xpathShouldBe("//base//base//s1")
}
@Test
fun checkSelectorNoScanForMemberField() {
PageWithNoScan.holder2.sel1
.xpathShouldBe("//s1")
}
@Test
fun checkSelectorForMemberClsField() {
PageWithNoScan.holder_ns1.sel1
.xpathShouldBe("//base//base_2//s1")
}
@Test
fun checkSelectorForMemberClsNoScanField() {
PageWithNoScan.holder_ns1.sel2
.xpathShouldBe("//s2")
}
@Test
fun checkSelectorForMemberClsAllNoScanField() {
PageWithNoScan.holder_ns2.sel1
.xpathShouldBe("//s1")
}
@Test
fun checkSelectorForMemberObjectField() {
PageWithNoScan.Holder3.sel1
.xpathShouldBe("//base//base//s1")
}
@Test
fun checkSelectorForMemberObjectAllNoScanField() {
PageWithNoScan.Holder4.sel1
.xpathShouldBe("//s1")
}
@Test
fun checkSelectorForMemberObjectInheritanceAllNoScanField() {
PageWithNoScan.InnerObject2.s1
.xpathShouldBe("//s1")
}
}
| 3
|
Kotlin
|
6
| 3
|
1e026264117655efa7f20fa8120065376e80d9ae
| 3,307
|
core
|
MIT License
|
src/main/kotlin/de/fruiture/cor/ccs/CCSApplication.kt
|
fruiture
| 750,555,472
| false
|
{"Kotlin": 75404}
|
package de.fruiture.cor.ccs
import de.fruiture.cor.ccs.git.Git
import de.fruiture.cor.ccs.semver.PreRelease
import de.fruiture.cor.ccs.semver.PreReleaseIndicator.Strategy
import de.fruiture.cor.ccs.semver.Release
import de.fruiture.cor.ccs.semver.Version
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
class CCSApplication(
private val git: Git
) {
private fun getChangeType(latestVersion: Version, mapping: ChangeMapping) =
mapping.of(git.getLog(latestVersion))
fun getNextRelease(changeMapping: ChangeMapping = ChangeMapping()): Release {
val latestVersion = git.getLatestVersion() ?: return Version.initial
val changeType = getChangeType(latestVersion, changeMapping)
return latestVersion.next(changeType)
}
fun getNextPreRelease(strategy: Strategy, changeMapping: ChangeMapping = ChangeMapping()): PreRelease {
val latestVersion = git.getLatestVersion() ?: return initialPreRelease(strategy)
val changeType = getChangeType(latestVersion, changeMapping)
return latestVersion.nextPreRelease(changeType, strategy)
}
private fun initialPreRelease(strategy: Strategy) =
Version.initial + strategy.start()
@OptIn(ExperimentalSerializationApi::class)
private val json = Json { explicitNulls = false }
fun getChangeLogJson(release: Boolean = false, before: Version? = null): String {
val commits = getChanges(release, before)
return json.encodeToString(commits)
}
private fun getChanges(release: Boolean, before: Version? = null) =
getLatest(release, before)?.let { git.getLog(from = it, to = before) } ?: git.getLog(to = before)
fun getLatestVersion(release: Boolean = false, before: Version? = null): String? =
getLatest(release, before)?.toString()
private fun getLatest(release: Boolean, before: Version? = null) =
if (release) git.getLatestRelease(before)
else git.getLatestVersion(before)
fun getChangeLogMarkdown(
release: Boolean = false,
target: Version? = null,
sections: Sections = Sections.default(),
level: Int = 2
) =
sequence {
val hl = "#".repeat(level)
val commits = getChanges(release, target).map { it.conventional }
val breakingChanges = commits.mapNotNull { it.breakingChange }
if (breakingChanges.isNotEmpty()) {
yield("$hl ${sections.breakingChanges}\n")
breakingChanges.forEach {
yield("* $it")
}
yield("")
}
sections.forEach { headline, types ->
val selectedCommits = commits.filter { it.type in types }
if (selectedCommits.isNotEmpty()) {
yield("$hl $headline\n")
selectedCommits.forEach {
yield("* ${it.description}")
}
yield("")
}
}
}.joinToString("\n")
}
| 0
|
Kotlin
|
0
| 0
|
db20c964acd2f615e3a9929396fef0162cde2169
| 3,137
|
git-ccs
|
MIT License
|
buildSrc/src/main/kotlin/ProjectConfig.kt
|
HiWay-Media
| 777,670,503
| false
|
{"Kotlin": 159872}
|
import org.gradle.api.JavaVersion
object ProjectConfig {
const val compileSdk = 34
const val applicationId = "com.hiway.media"
const val minSdk = 24
const val targetSdk = 34
const val versionCode = 1
const val versionName = "1.0.4e"
const val jvmTarget = "17"
const val kotlinCompilerExtensionVersion = "1.5.8"
val javaSourceCompatibility = JavaVersion.VERSION_17
val javaTargetCompatibility = JavaVersion.VERSION_17
}
| 0
|
Kotlin
|
0
| 2
|
6b3ac251e0475d1815b7295ea9cc7058eeb2e9f5
| 459
|
Hiway-Media-Player
|
MIT License
|
cassandra-service/src/main/kotlin/fund/cyber/markets/cassandra/model/TokensPair.kt
|
cybercongress
| 97,112,173
| false
|
{"Kotlin": 330007, "HTML": 7008, "Dockerfile": 907}
|
package fund.cyber.markets.cassandra.model
import fund.cyber.markets.common.model.TokensPair
import org.springframework.data.cassandra.core.mapping.UserDefinedType
@UserDefinedType("tokenpair")
data class CqlTokensPair(
val base: String,
val quote: String
) {
constructor(pair: TokensPair): this(
base = pair.base,
quote = pair.quote
)
constructor(pair: String): this(
pair.substringBefore("_"), pair.substringAfter("_")
)
}
| 17
|
Kotlin
|
10
| 46
|
f3254bc93784f4d570a7d6bfda58f76413cf6444
| 475
|
cyber-markets
|
MIT License
|
diskordin-base/src/main/kotlin/org/tesserakt/diskordin/impl/core/entity/Guild.kt
|
ITesserakt
| 218,969,129
| false
| null |
@file:Suppress("DEPRECATION")
package org.tesserakt.diskordin.impl.core.entity
import org.tesserakt.diskordin.core.cache.CacheProcessor
import org.tesserakt.diskordin.core.data.*
import org.tesserakt.diskordin.core.data.json.response.*
import org.tesserakt.diskordin.core.entity.*
import org.tesserakt.diskordin.core.entity.`object`.IBan
import org.tesserakt.diskordin.core.entity.`object`.IGuildInvite
import org.tesserakt.diskordin.core.entity.`object`.IRegion
import org.tesserakt.diskordin.core.entity.builder.*
import org.tesserakt.diskordin.core.entity.query.BanQuery
import org.tesserakt.diskordin.core.entity.query.MemberQuery
import org.tesserakt.diskordin.core.entity.query.PruneQuery
import org.tesserakt.diskordin.core.entity.query.query
import org.tesserakt.diskordin.impl.core.entity.`object`.Region
import org.tesserakt.diskordin.rest.flow
import java.awt.Color
import java.io.File
import java.util.*
import kotlin.time.Duration
import kotlin.time.ExperimentalTime
@Suppress("UNCHECKED_CAST", "CANDIDATE_CHOSEN_USING_OVERLOAD_RESOLUTION_BY_LAMBDA_ANNOTATION")
internal class Guild(override val raw: GuildResponse) : IGuild,
ICacheable<IGuild, UnwrapContext.EmptyContext, GuildResponse> {
override val region: IRegion = Region(
VoiceRegionResponse(
raw.region,
raw.region,
vip = false,
optimal = false,
deprecated = false,
custom = false
)
)
override val isEmbedEnabled: Boolean = raw.embed_enabled ?: false
override val defaultMessageNotificationLevel: IGuild.DefaultMessageNotificationLevel =
IGuild.DefaultMessageNotificationLevel.values().first { raw.default_message_notifications == it.ordinal }
override val explicitContentFilter: IGuild.ExplicitContentFilter =
IGuild.ExplicitContentFilter.values().first { raw.explicit_content_filter == it.ordinal }
override val mfaLevel: IGuild.MFALevel =
IGuild.MFALevel.values().first { it.ordinal == raw.mfa_level }
override val isWidgetEnabled: Boolean = raw.widget_enabled ?: false
override val widgetChannel: LazyIdentified<IGuildChannel>? = raw.widget_channel_id?.lazy {
getChannel(it)
}
override val systemChannel: LazyIdentified<IGuildChannel>? = raw.system_channel_id?.lazy {
getChannel(it)
}
override val maxMembers: Long? = raw.max_members
override val maxPresences: Long = raw.max_presences ?: 5000
override val description: String? = raw.description
override val bannerHash: String? = raw.banner
override val premiumTier: IGuild.PremiumTier =
IGuild.PremiumTier.values().first { it.ordinal == (raw.premium_tier ?: 0) }
override val premiumSubscriptions: Int? = raw.premiumSubscribersCount
override val features: EnumSet<IGuild.Feature> = if (raw.features.isEmpty())
EnumSet.noneOf(IGuild.Feature::class.java)
else EnumSet.copyOf(raw.features.map { IGuild.Feature.valueOf(it) })
override val id: Snowflake = raw.id
override fun getRole(id: Snowflake) = roles.find { it.id == id }
override suspend fun getEmoji(emojiId: Snowflake) =
rest.callRaw { emojiService.getGuildEmoji(id, emojiId) }.unwrap(id)
override suspend fun createEmoji(name: String, image: File, roles: Array<Snowflake>): ICustomEmoji = rest.callRaw {
emojiService.createGuildEmoji(id, EmojiCreateBuilder().apply {
this.name = name
this.image = image
this.roles = roles
}.create())
}.unwrap(id)
override suspend fun editOwnNickname(newNickname: String): String? = rest.callRaw {
guildService.editCurrentNickname(id, NicknameEditBuilder(newNickname).create())
}
override suspend fun addTextChannel(name: String, builder: TextChannelCreateBuilder.() -> Unit): ITextChannel =
addChannelJ(TextChannelCreateBuilder(name), builder)
override suspend fun addVoiceChannel(name: String, builder: VoiceChannelCreateBuilder.() -> Unit): IVoiceChannel =
addChannelJ(VoiceChannelCreateBuilder(name), builder)
private suspend inline fun <C : IGuildChannel, reified B : GuildChannelCreateBuilder<out C>> addChannelJ(
instance: B,
noinline builder: B.() -> Unit
): C = rest.call {
instance.apply(builder)
guildService.createGuildChannel(id, instance.create(), instance.reason)
} as C
override suspend fun moveChannels(vararg builder: Pair<Snowflake, Int>) = rest.effect {
guildService.editGuildChannelPositions(
id, builder.map { PositionEditBuilder(it.first, it.second).create() }.toTypedArray()
)
}
override suspend fun addMember(userId: Snowflake, accessToken: String, builder: MemberAddBuilder.() -> Unit) =
rest.callRaw {
guildService.newMember(id, userId, MemberAddBuilder(accessToken).apply(builder).create())
}.unwrap(id)
override suspend fun kick(member: IMember, reason: String?) = kick(member.id, reason)
override suspend fun kick(memberId: Snowflake, reason: String?) = rest.effect {
guildService.removeMember(id, memberId, reason)
}
override suspend fun addRole(name: String, color: Color, builder: RoleCreateBuilder.() -> Unit) =
rest.callRaw {
val inst = builder.instance { RoleCreateBuilder(name, color) }
guildService.createRole(id, inst.create(), inst.reason)
}.unwrap(id)
override suspend fun moveRoles(vararg builder: Pair<Snowflake, Int>): List<IRole> =
rest.callRaw {
guildService.editRolePositions(id, builder.map { (id, pos) ->
PositionEditBuilder(id, pos).create()
}.toTypedArray())
}.map { it.unwrap(id) }
override suspend fun getBan(userId: Snowflake): IBan = rest.call {
guildService.getBan(id, userId)
}
@ExperimentalTime
override suspend fun ban(member: IMember, builder: BanQuery.() -> Unit) = ban(member.id, builder)
@ExperimentalTime
override suspend fun ban(memberId: Snowflake, builder: BanQuery.() -> Unit) = rest.effect {
guildService.ban(id, memberId, builder.query(::BanQuery))
}
override suspend fun pardon(userId: Snowflake, reason: String?) = rest.effect {
guildService.removeBan(id, userId, reason)
}
override suspend fun getPruneCount(builder: PruneQuery.() -> Unit): Int = rest.callRaw {
guildService.getPruneCount(id, builder.query(::PruneQuery))
}
override suspend fun addIntegration(id: Snowflake, type: String): Unit = rest.effect {
guildService.createIntegration(id, IntegrationCreateBuilder(id, type).create())
}
override fun getEveryoneRole(): LazyIdentified<IRole> = id lazy { getRole(it)!! } //everyone role id == guild id
override fun <C : IGuildChannel> getChannel(channelId: Snowflake) =
cacheSnapshot.getGuildChannel(id, channelId) as C
override suspend fun getWidget(): IGuildWidget = rest.call {
guildService.getGuildWidget(id)
}
override suspend fun getVanityUrl(): IGuildInvite? =
if (IGuild.Feature.VANITY_URL !in features) null
else rest.call {
guildService.getVanityUrl(id)
}
override val invites = rest.flow {
guildService.getInvites(id)
}
override val emojis = rest.flow<ICustomEmoji, EmojiResponse<ICustomEmoji>>(id) {
emojiService.getGuildEmojis(id)
}
override val bans = rest.flow {
guildService.getBans(id)
}
override val integrations = rest.flow<IIntegration, GuildIntegrationResponse>(id) {
guildService.getIntegrations(id)
}
override suspend fun edit(builder: GuildEditBuilder.() -> Unit): IGuild = rest.call {
guildService.editGuild(id, builder.build(::GuildEditBuilder))
}
override fun copy(changes: (GuildResponse) -> GuildResponse): IGuild =
raw.let(changes).unwrap()
override val iconHash: String? = raw.icon
override val splashHash: String? = raw.splash
override val owner: DeferredIdentified<IMember> =
raw.owner_id deferred { userId -> client.getMember(userId, id) }
override val afkChannel = raw.afk_channel_id?.deferred { id ->
(cachedChannels.find { it.id == id } ?: client.getChannel(id)) as IVoiceChannel
}
@ExperimentalTime
override val afkChannelTimeout: Duration = Duration.seconds(raw.afk_timeout)
override val verificationLevel =
IGuild.VerificationLevel.values().first { it.ordinal == raw.verification_level }
override val roles = raw.roles.map { it.unwrap(id) }
override suspend fun getMembers(query: MemberQuery.() -> Unit) = rest.callRaw {
guildService.getMembers(id, query.query(::MemberQuery))
}.map { it.unwrap(id) }.onEach { client.context[CacheProcessor].updateData(it) }
override val cachedChannels = raw.channels.filter { it.guild_id != null }.map { it.unwrap() }
override val name: String = raw.name
override val members: List<IMember> = raw.members.map { it.unwrap(id) }
override val isFullyLoaded: Boolean = true
@ExperimentalTime
override fun toString(): String {
return "Guild(region=$region, isEmbedEnabled=$isEmbedEnabled, defaultMessageNotificationLevel=$defaultMessageNotificationLevel, explicitContentFilter=$explicitContentFilter, mfaLevel=$mfaLevel, isWidgetEnabled=$isWidgetEnabled, widgetChannel=$widgetChannel, systemChannel=$systemChannel, maxMembers=$maxMembers, maxPresences=$maxPresences, description=$description, bannerHash=$bannerHash, premiumTier=$premiumTier, premiumSubscriptions=$premiumSubscriptions, features=$features, id=$id, invites=$invites, emojis=$emojis, bans=$bans, integrations=$integrations, iconHash=$iconHash, splashHash=$splashHash, owner=$owner, afkChannel=$afkChannel, afkChannelTimeout=$afkChannelTimeout, verificationLevel=$verificationLevel, name='$name')"
}
}
| 1
|
Kotlin
|
1
| 12
|
e93964fcb5ecb0e1d03dd0fc7d3dd2637a0e08ae
| 9,934
|
diskordin
|
Apache License 2.0
|
library/src/main/java/ru/yoomoney/sdk/kassa/payments/model/ConfirmationType.kt
|
yoomoney
| 140,608,545
| false
| null |
/*
* The MIT License (MIT)
* Copyright © 2021 NBCO YooMoney LLC
*
* 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 ru.yoomoney.sdk.kassa.payments.model
import androidx.annotation.Keep
/**
* Type of payment confirmation.
*/
@Keep
enum class ConfirmationType(val value: String) {
/**
* Confirmation with external service
*/
@Keep
EXTERNAL("external"),
/**
* Confirmation with webview
*/
@Keep
REDIRECT("redirect"),
/**
* Confirmation with mobile app
*/
@Keep
MOBILE_APPLICATION("mobile_application"),
/**
* Unknown type of confirmation
*/
@Keep
UNKNOWN("unknown")
}
| 9
|
Kotlin
|
21
| 35
|
421619230cce92280641ea943c5ecb00f3dd8827
| 1,691
|
yookassa-android-sdk
|
MIT License
|
src/commonTest/kotlin/net.iceyleagons.klarity.test/customization/FunctionTest.kt
|
IceyLeagons
| 669,827,661
| false
|
{"Kotlin": 93338, "ANTLR": 496}
|
/*
* MIT License
*
* Copyright (c) 2023 IceyLeagons and Contributors
*
* 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 net.iceyleagons.klarity.test.customization
import net.iceyleagons.klarity.DefaultValueSource
import net.iceyleagons.klarity.KlarityAPI
import net.iceyleagons.klarity.parsers.generated.StringCodeParser
import net.iceyleagons.klarity.script.KlarityASTVisitor
import net.iceyleagons.klarity.script.KlarityFunction
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
class FunctionTest {
@BeforeTest
fun init() {
val function = TestFunction()
KlarityAPI.configure {
sourceManagement {
registerSource("en", DefaultValueSource())
}
pluginManagement {
registerFunction("TEST", function)
assertFails {
registerFunction("TEST", function)
}
}
}
}
@Test
fun testPrefixSuffix() {
val expected = "working"
val actual = KlarityAPI.translate("test", "{IF(TEST(), 'working', 'lol')}")
assertEquals(expected, actual)
}
}
class TestFunction : KlarityFunction {
override fun parse(ctx: StringCodeParser.FunctionContext, visitor: KlarityASTVisitor): String {
return true.toStringRepresentation()
}
}
| 0
|
Kotlin
|
0
| 1
|
59e85a24587addfb9c16e0f3a22e57b23e4bf259
| 2,431
|
Klarity
|
MIT License
|
shared/src/commonMain/kotlin/com/jerryokafor/networth/Greeting.kt
|
jerryOkafor
| 696,975,183
| false
|
{"Kotlin": 42659, "Ruby": 2447, "Swift": 2337, "Shell": 228}
|
package com.jerryokafor.networth
class Greeting {
private val platform: Platform = DefaultPlatform()
fun greet(): String {
return "Hello, ${platform.name}!"
}
}
| 0
|
Kotlin
|
1
| 15
|
3ac464f74ddde82389a5b39c070835c2afc35b2d
| 183
|
NetWorth
|
Apache License 2.0
|
src/main/kotlin/org/generousg/fruitylib/util/NetUtils.kt
|
wingertge
| 95,062,948
| false
| null |
package org.generousg.fruitylib.util
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableSet
import io.netty.channel.ChannelFutureListener
import net.minecraft.entity.player.EntityPlayerMP
import net.minecraft.world.WorldServer
import net.minecraftforge.fml.common.network.handshake.NetworkDispatcher
import java.lang.reflect.Field
class NetUtils {
companion object {
val LOGGING_LISTENER = ChannelFutureListener {
if(!it.isSuccess) {
val cause = it.cause()
Log.severe(cause, "Crash in pipeline handler")
}
}
private var trackingPlayers: Field? = null
fun getPlayersWatchingBlock(world: WorldServer, blockX: Int, blockZ: Int) = getPlayersWatchingChunk(world, blockX shr 4, blockZ shr 4)
fun getPlayersWatchingChunk(world: WorldServer, chunkX: Int, chunkZ: Int): List<EntityPlayerMP> {
return ImmutableList.copyOf(world.playerChunkMap.getEntry(chunkX, chunkZ)?.players ?: arrayListOf())
}
fun getPlayerDispatcher(player: EntityPlayerMP): NetworkDispatcher? = player.connection.netManager.channel().attr(NetworkDispatcher.FML_DISPATCHER).get()
fun getPlayersWatchingEntity(server: WorldServer, entityId: Int): Set<EntityPlayerMP> {
val tracker = server.entityTracker
val entry = tracker.trackedEntityHashTable.lookup(entityId)
return ImmutableSet.copyOf(entry?.trackingPlayers) ?: setOf()
}
}
}
| 0
|
Kotlin
|
0
| 1
|
c7d0d67c07b0b47c3a3ae8371795d2b6f59687aa
| 1,519
|
FruityLib
|
MIT License
|
core/src/test/kotlin/dev/andrewohara/getit/api/AuthorizerTest.kt
|
oharaandrew314
| 517,856,092
| false
| null |
package dev.andrewohara.getit.api
import com.nimbusds.jose.JWSAlgorithm
import com.nimbusds.jose.jwk.source.ImmutableSecret
import dev.andrewohara.getit.UserId
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
import java.time.Clock
import java.time.Instant
import java.time.ZoneOffset
class AuthorizerTest {
private val authorizer = Authorizer.jwt(
audience = listOf("getit-test"),
issuer = "jwtTest",
clock = Clock.fixed(Instant.parse("2022-11-05T12:00:00Z"), ZoneOffset.UTC),
algorithm = JWSAlgorithm.HS256,
jwkSource = ImmutableSecret("qwertyuiopasdfghjklzxcvbnm123456".toByteArray())
)
@Test
fun `verify malformed jwt`() {
authorizer("token") shouldBe null
}
@Test
fun `verify jwt`() {
val jwt = javaClass.classLoader.getResourceAsStream("valid.jwt")!!.reader().readText()
authorizer(jwt) shouldBe UserId.of("user123")
}
@Test
fun `verify expired`() {
val jwt = javaClass.classLoader.getResourceAsStream("expired.jwt")!!.reader().readText()
authorizer(jwt) shouldBe null
}
@Test
fun `verify invalid issuer`() {
val jwt = javaClass.classLoader.getResourceAsStream("invalidIss.jwt")!!.reader().readText()
authorizer(jwt) shouldBe null
}
@Test
fun `verify invalid audience`() {
val jwt = javaClass.classLoader.getResourceAsStream("invalidAud.jwt")!!.reader().readText()
authorizer(jwt) shouldBe null
}
}
| 0
|
Kotlin
|
0
| 2
|
fad5595f8f51bc366e0ec1e21b5caef7c50f9809
| 1,517
|
getit-api
|
Apache License 2.0
|
android/app/src/main/kotlin/com/example/dart_builder/MainActivity.kt
|
zeeshux7860
| 317,635,428
| false
|
{"C++": 24649, "CMake": 14872, "Dart": 6871, "HTML": 1513, "C": 1383, "Swift": 1258, "Kotlin": 129, "Objective-C": 38}
|
package com.example.dart_builder
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0
|
C++
|
0
| 0
|
09fc59cfb8b030eb1edd0866e657a088e751e3e3
| 129
|
dart_builder
|
MIT License
|
src/main/kotlin/config/manager/GuildConfigImporter.kt
|
holasoyender
| 540,916,134
| false
| null |
package config.manager
import interfaces.CommandResponse
import net.dv8tion.jda.api.entities.Guild
import net.dv8tion.jda.api.entities.Message.Attachment
import org.json.JSONObject
import org.yaml.snakeyaml.Yaml
import org.yaml.snakeyaml.error.YAMLException
import plugins.twitch.TwitchManager
object GuildConfigImporter {
@Suppress("UNCHECKED_CAST")
fun import(file: Attachment, guild: Guild): CommandResponse {
if (file.fileExtension != "yaml" && file.fileExtension != "yml") return CommandResponse.error("El archivo adjuntado no es un archivo YAML")
if (file.fileName != "${guild.id}.yaml" && file.fileName != "${guild.id}.yml") return CommandResponse.error("El archivo adjuntado no es el archivo de configuración de este servidor")
if (file.size > 1000000) return CommandResponse.error("El archivo es demasiado grande, el tamaño máximo es de 1MB")
try {
val content = file.proxy.download().get().readAllBytes().toString(Charsets.UTF_8)
if(content.length < 100) return CommandResponse.error("El archivo está vacío o no es válido")
val config = Yaml().load(content) as Map<String, Any>
val (isValid, error) = GuildConfigValidator(config, guild).validate()
if(!isValid) return CommandResponse.error("El archivo no es válido: `\n```$error\nPuedes consultar la documentación en https://miniender.kenabot.xyz``")
/*
* A partir de este punto sabemos que la configuración es válida
* y que no va a causar ningún error al importarla, excepto los mapeos de arrays
*/
val guildConfig = database.schema.Guild.get(guild.id)
if(guildConfig == null) {
database.schema.Guild(
id = guild.id,
prefix = config["prefix"] as String,
welcomeRoleId = (config["welcomes"] as Map<*, *>)["role_id"] as String,
welcomeChannelId = (config["welcomes"] as Map<*, *>)["channel_id"] as String,
welcomeMessage = (config["welcomes"] as Map<*, *>)["message"] as String,
muteRoleId = (config["roles"] as Map<*, *>)["mute_role_id"] as String,
moderationSilent = (config["moderation"] as Map<*, *>)["silent"] as Boolean,
moderationChannelId = (config["moderation"] as Map<*, *>)["moderation_channel_id"] as String,
permissions = (config["permissions"] as Map<Long, Int>).map { it.key.toString() to it.value }.toMap(),
logsChannelId = (config["logs"] as Map<*, *>)["channel_id"] as String,
moderationLogsChannelId = (config["logs"] as Map<*, *>)["moderation_channel_id"] as String,
antiLinksEnabled = (config["anti_links"] as Map<*, *>)["enabled"] as Boolean,
antiLinksAllowedLinks = try {
((config["anti_links"] as Map<*, *>)["allowed_links"] as ArrayList<String>).toTypedArray()
} catch (e: Exception) {
e.printStackTrace()
arrayOf()
},
antiLinksChannelId = (config["anti_links"] as Map<*, *>)["channel_id"] as String,
antiLinksIgnoredRoles = try {
((config["anti_links"] as Map<*, *>)["ignore_roles"] as ArrayList<String>).toTypedArray()
} catch (e: Exception) {
arrayOf()
},
antiLinksIgnoredChannels = try {
((config["anti_links"] as Map<*, *>)["ignore_channels"] as ArrayList<String>).toTypedArray()
} catch (e: Exception) {
arrayOf()
},
antiPhishingEnabled = (config["anti_links"] as Map<*, *>)["anti_phishing"] as Boolean,
twitchChannel = (config["twitch"] as Map<*, *>)["channel"] as String,
twitchAnnounceChannelId = (config["twitch"] as Map<*, *>)["announce_channel_id"] as String,
twitchAnnounceMessage = (config["twitch"] as Map<*, *>)["message"] as String,
twitchLiveChannelId = (config["twitch"] as Map<*, *>)["live_channel_id"] as String,
twitchOpenLiveMessage = (config["twitch"] as Map<*, *>)["live_open_message"] as String,
twitchCloseLiveMessage = (config["twitch"] as Map<*, *>)["live_close_message"] as String,
sanctionMessage = (config["messages"] as Map<*, *>)["sanction"] as String,
antiLinksNewLinkMessage = (config["messages"] as Map<*, *>)["anti_links_new_link"] as String,
antiLinksUnderRevisionMessage = (config["messages"] as Map<*, *>)["anti_links_under_revision"] as String,
antiLinksSanctionMessage = (config["messages"] as Map<*, *>)["anti_links_sanction"] as String,
customCommands = try {
(config["custom_commands"] as Map<*, *>).map {
val values = it.value as Map<*, *>
JSONObject()
.put("name", it.key)
.put("response", values["response"])
.put("description", values["description"])
.put("aliases", values["aliases"] as List<String>)
}.toTypedArray()
} catch (e: Exception) {
arrayOf()
},
raw = content
).save()
} else {
guildConfig.id = guild.id
guildConfig.prefix = config["prefix"] as String
guildConfig.welcomeRoleId = (config["welcomes"] as Map<*, *>)["role_id"] as String
guildConfig.welcomeChannelId = (config["welcomes"] as Map<*, *>)["channel_id"] as String
guildConfig.welcomeMessage = (config["welcomes"] as Map<*, *>)["message"] as String
guildConfig.muteRoleId = (config["roles"] as Map<*, *>)["mute_role_id"] as String
guildConfig.moderationSilent = (config["moderation"] as Map<*, *>)["silent"] as Boolean
guildConfig.moderationChannelId = (config["moderation"] as Map<*, *>)["moderation_channel_id"] as String
guildConfig.permissions = (config["permissions"] as Map<Long, Int>).map { it.key.toString() to it.value }.toMap()
guildConfig.logsChannelId = (config["logs"] as Map<*, *>)["channel_id"] as String
guildConfig.moderationLogsChannelId = (config["logs"] as Map<*, *>)["moderation_channel_id"] as String
guildConfig.antiLinksEnabled = (config["anti_links"] as Map<*, *>)["enabled"] as Boolean
guildConfig.antiLinksAllowedLinks = try {
((config["anti_links"] as Map<*, *>)["allowed_links"] as ArrayList<String>).toTypedArray()
} catch (e: Exception) {
e.printStackTrace()
arrayOf()
}
guildConfig.antiLinksChannelId = (config["anti_links"] as Map<*, *>)["channel_id"] as String
guildConfig.antiLinksIgnoredRoles = try {
((config["anti_links"] as Map<*, *>)["ignore_roles"] as ArrayList<String>).toTypedArray()
} catch (e: Exception) {
arrayOf()
}
guildConfig.antiLinksIgnoredChannels = try {
((config["anti_links"] as Map<*, *>)["ignore_channels"] as ArrayList<String>).toTypedArray()
} catch (e: Exception) {
arrayOf()
}
guildConfig.antiPhishingEnabled = (config["anti_links"] as Map<*, *>)["anti_phishing"] as Boolean
guildConfig.twitchChannel = (config["twitch"] as Map<*, *>)["channel"] as String
guildConfig.twitchAnnounceChannelId = (config["twitch"] as Map<*, *>)["announce_channel_id"] as String
guildConfig.twitchAnnounceMessage = (config["twitch"] as Map<*, *>)["message"] as String
guildConfig.twitchLiveChannelId = (config["twitch"] as Map<*, *>)["live_channel_id"] as String
guildConfig.twitchOpenLiveMessage = (config["twitch"] as Map<*, *>)["live_open_message"] as String
guildConfig.twitchCloseLiveMessage = (config["twitch"] as Map<*, *>)["live_close_message"] as String
guildConfig.sanctionMessage = (config["messages"] as Map<*, *>)["sanction"] as String
guildConfig.antiLinksNewLinkMessage = (config["messages"] as Map<*, *>)["anti_links_new_link"] as String
guildConfig.antiLinksUnderRevisionMessage = (config["messages"] as Map<*, *>)["anti_links_under_revision"] as String
guildConfig.antiLinksSanctionMessage = (config["messages"] as Map<*, *>)["anti_links_sanction"] as String
guildConfig.customCommands = try {
(config["custom_commands"] as Map<*, *>).map {
val values = it.value as Map<*, *>
JSONObject()
.put("name", it.key)
.put("response", values["response"])
.put("description", values["description"])
.put("aliases", values["aliases"] as List<String>)
}.toTypedArray()
} catch (e: Exception) {
arrayOf()
}
guildConfig.raw = content
guildConfig.save()
}
if (guildConfig?.twitchChannel?.isNotEmpty() == true)
TwitchManager.doChecks()
return CommandResponse.success()
} catch (e: Exception) {
return if (e is YAMLException)
CommandResponse.error("El archivo de configuración no es valido: `\n```${e.message ?: "Error desconocido"}\nPuedes consultar la documentación en https://miniender.kenabot.xyz``")
else {
e.printStackTrace()
CommandResponse.error("Ha ocurrido un error inesperado: `\n```${e.message ?: "Error desconocido"}``")
}
}
}
}
| 4
|
Kotlin
|
3
| 4
|
8dc0f45df7d8373df5198e75a173440ae36dcfad
| 10,426
|
mini-ender
|
Apache License 2.0
|
app/src/main/java/com/example/fatecplayground/ui/ProjetosScreen.kt
|
h4mn
| 603,062,062
| false
| null |
package com.example.fatecplayground.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.selectable
import androidx.compose.material.Button
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.outlined.CheckCircle
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Alignment.Companion.CenterVertically
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.example.fatecplayground.DataProjetos.listaDeProjetos
@Composable
@Preview
fun ProjetosScreen(
navController: NavController = rememberNavController()
) {
val scrollState = rememberScrollState()
Column(
modifier = Modifier.scrollable(
state = scrollState,
orientation = Orientation.Vertical
)
) {
listaDeProjetos.forEach { item ->
CardListItem(
concluido = item.concluido,
titulo = item.titulo,
description = item.description,
aoClicar = { navController.navigate(item.rota) }
)
}
}
}
@Composable
fun CardListItem(
concluido: Boolean,
titulo: String,
description: String,
aoClicar: () -> Unit
) {
// Regra de negócio
var iconImage: ImageVector = Icons.Outlined.CheckCircle
var iconDescription = "Pendente"
var iconTint: Color = Color.Gray
if (concluido) {
iconImage = Icons.Filled.CheckCircle
iconDescription = "Concluído"
iconTint = Color.Green
}
// Layout
Column(
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = aoClicar)
) {
Row(
verticalAlignment = Alignment.Bottom,
modifier = Modifier
.fillMaxWidth()
.height(48.dp)
) {
Icon(
imageVector = iconImage,
contentDescription = iconDescription,
tint = iconTint,
modifier = Modifier
.width(64.dp)
.size(32.dp)
)
Spacer(modifier = Modifier.width(8.dp))
CardItemTitulo(titulo)
}
Text(
text = description,
style = MaterialTheme.typography.body1,
maxLines = Int.MAX_VALUE,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp)
)
Spacer(modifier = Modifier.height(8.dp))
}
}
@Composable
fun CardItemTitulo(texto: String = "Fatec Playground") {
Row(
verticalAlignment = CenterVertically,
modifier = Modifier
.fillMaxWidth()
.height(32.dp)
) {
Text(
text = texto,
fontWeight = FontWeight.Bold,
style = MaterialTheme.typography.subtitle1,
)
}
}
| 1
|
Kotlin
|
0
| 0
|
529ac9ec2553c1d669e917564dd2cca7d79a6c53
| 3,260
|
fatec_mobile
|
MIT License
|
FlowStateFlowPoc/app/src/main/java/com/example/flowstateflowpoc/shared/Result.kt
|
brunogabriel
| 335,454,794
| false
| null |
package com.example.flowstateflowpoc.shared
sealed class Result<out R> {
object Empty : Result<Nothing>()
object Loading : Result<Nothing>()
object DismissLoading : Result<Nothing>()
data class Success<out T>(val data: T) : Result<T>()
data class Error(val throwable: Throwable) : Result<Nothing>()
}
| 0
|
Kotlin
|
0
| 2
|
f7853a80ce9465552beec2395037f25bfb8bc817
| 321
|
android-flow-stateflow-poc
|
MIT License
|
app/src/main/java/fr/mcgalanes/rectus/RectusApp.kt
|
McGalanes
| 504,936,229
| false
|
{"Kotlin": 46792}
|
package fr.mcgalanes.rectus
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class RectusApp : Application()
| 0
|
Kotlin
|
0
| 0
|
575d456b0708a588b3979f244b44da543f90f06e
| 150
|
rectus
|
Apache License 2.0
|
app/src/main/java/com/weather/android/logic/network/PlaceService.kt
|
wujiandao233
| 526,502,460
| false
| null |
package com.weather.android.logic.network
import com.weather.android.logic.model.PlaceResponse
import retrofit2.Call
import com.weather.android.weatherApplication
import retrofit2.http.GET
import retrofit2.http.Query
interface PlaceService {
@GET("v2/place?token=${weatherApplication.TOKEN}&lang=zn_CN")
//TOKEN是一个参数,表示令牌值。
fun searchPlaces(@Query("query") query: String): Call<PlaceResponse>
/*我们在searchPlaces()方法的上面声明了一个@GET注解,这样当调用
searchPlaces()方法的时候,Retrofit就会自动发起一条GET请求,去访问@GET注解中配
置的地址。其中,搜索城市数据的API中只有query这个参数是需要动态指定的,我们使用
@Query注解的方式来进行实现,另外两个参数是不会变的,因此固定写在@GET注解中即可。
另外,searchPlaces()方法的返回值被声明成了Call<PlaceResponse>,这样Retrofit
就会将服务器返回的JSON数据自动解析成PlaceResponse对象了*/
}
| 0
|
Kotlin
|
0
| 0
|
d255ad783e43a1abcfbe52ab7613030d4722d117
| 697
|
weather
|
The Unlicense
|
core-types/src/main/java/lang/taxi/services/operations/constraints/ExpressionConstraint.kt
|
taxilang
| 601,101,781
| false
|
{"Kotlin": 1587516, "ANTLR": 67682, "TypeScript": 7231, "JavaScript": 4324, "Shell": 1468, "Java": 1454, "MDX": 286}
|
package lang.taxi.services.operations.constraints
import lang.taxi.expressions.Expression
import lang.taxi.types.CompilationUnit
/**
* A Simple wrapper around Expressions to make them implement the Constraint contract
*/
class ExpressionConstraint(val expression: Expression) : Constraint {
override fun asTaxi(): String = expression.asTaxi()
override val compilationUnits: List<CompilationUnit> = expression.compilationUnits
}
| 8
|
Kotlin
|
5
| 71
|
26a3d83b98f73f7fbbba8b0b98c6d97a651f3b3a
| 441
|
taxilang
|
Apache License 2.0
|
androidApp/src/main/java/com/blackmidori/familyexpenses/android/ui/workspace/AddChargesModelScreen.kt
|
BLACKMIDORI
| 744,320,391
| false
|
{"Kotlin": 192024, "Swift": 342}
|
package com.blackmidori.familyexpenses.android.ui.workspace
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.blackmidori.familyexpenses.android.AppScreen
import com.blackmidori.familyexpenses.android.MyApplicationTheme
import com.blackmidori.familyexpenses.android.core.HttpClientJavaImpl
import com.blackmidori.familyexpenses.android.shared.ui.SimpleAppBar
import com.blackmidori.familyexpenses.android.shared.ui.SimpleScaffold
import com.blackmidori.familyexpenses.models.ChargesModel
import com.blackmidori.familyexpenses.repositories.ChargesModelRepository
import kotlinx.coroutines.launch
import kotlinx.datetime.Instant
@Composable
fun AddChargesModelScreen(
navController: NavHostController,
workspaceId: String,
) {
val coroutineScope = rememberCoroutineScope()
val context = LocalContext.current
var name by remember {
mutableStateOf("")
}
SimpleScaffold(topBar = {
SimpleAppBar(
navController = navController,
title = { Text(stringResource(AppScreen.AddChargesModel.title)) },
)
}) {
Column {
TextField(value = name, onValueChange = {
name = it
})
Button(onClick = {
Thread {
val TAG = "AddChargesModel.submit"
val chargesModel = ChargesModel("", Instant.DISTANT_PAST, name)
val chargesModelResult =
ChargesModelRepository(httpClient = HttpClientJavaImpl()).add(workspaceId, chargesModel)
if (chargesModelResult.isFailure) {
Log.w(TAG, "Error: " + chargesModelResult.exceptionOrNull())
coroutineScope.launch {
Toast.makeText(
context,
"Error: ${chargesModelResult.exceptionOrNull()}",
Toast.LENGTH_SHORT
).show()
}
} else {
coroutineScope.launch {
Toast.makeText(
context,
"Added",
Toast.LENGTH_SHORT
).show()
navController.navigateUp()
}
}
}.start()
}) {
Text("Submit")
}
}
}
}
@Preview
@Composable
private fun Preview() {
MyApplicationTheme {
AddChargesModelScreen(rememberNavController(),"fake")
}
}
| 0
|
Kotlin
|
0
| 0
|
8afe58ae1642f6b436a81cd0c4dc8c5c630abf3f
| 3,357
|
family-expenses-mobile
|
MIT License
|
app-main/src/main/kotlin/com/github/fj/board/service/board/impl/GetBoardServiceImpl.kt
|
oen142
| 449,552,568
| true
|
{"Kotlin": 584930, "Groovy": 179252, "Java": 88552, "Dart": 11943, "HTML": 1113, "Batchfile": 488, "Shell": 479, "Swift": 404, "Vim Snippet": 314, "Objective-C": 38}
|
/*
* spring-message-board-demo
* Refer to LICENCE.txt for licence details.
*/
package com.github.fj.board.service.board.impl
import com.github.fj.board.persistence.entity.board.Board
import com.github.fj.board.persistence.model.board.BoardAccess
import com.github.fj.board.persistence.model.board.BoardStatus
import com.github.fj.board.persistence.repository.board.BoardRepository
import com.github.fj.board.service.board.GetBoardService
import com.github.fj.board.vo.auth.ClientAuthInfo
import com.github.fj.board.vo.board.BoardInfo
import com.github.fj.board.vo.board.BoardsSortBy
import org.springframework.data.domain.Sort
import org.springframework.data.jpa.domain.Specification
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Isolation
import org.springframework.transaction.annotation.Transactional
import java.util.*
import javax.persistence.criteria.CriteriaBuilder
import javax.persistence.criteria.CriteriaQuery
import javax.persistence.criteria.Predicate
import javax.persistence.criteria.Root
/**
* @author <NAME>(<EMAIL>)
* @since 22 - Jul - 2020
*/
@Service
internal class GetBoardServiceImpl(
override val boardRepo: BoardRepository
) : GetBoardService {
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
override fun getOne(accessId: UUID, clientInfo: ClientAuthInfo?): BoardInfo {
val board = accessId.getBoard().also {
it.checkAccessibleFor(clientInfo)
}
return BoardInfo.from(board, board.getPostsCount())
}
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
override fun getList(
sortBy: BoardsSortBy,
sortDirection: Sort.Direction,
clientInfo: ClientAuthInfo?
): List<BoardInfo> {
val boards = if (clientInfo == null) {
boardRepo.findAllByAccess(BoardAccess.PUBLIC, sortBy.toPropertyName(), sortDirection)
} else {
boardRepo.findAll(NormalBoardSearchSpec(), Sort.by(sortDirection, sortBy.toPropertyName()))
}
return boards.map { BoardInfo.from(it, it.getPostsCount()) }
}
}
private class NormalBoardSearchSpec : Specification<Board> {
override fun toPredicate(root: Root<Board>, query: CriteriaQuery<*>, criteriaBuilder: CriteriaBuilder): Predicate? =
ArrayList<Predicate>().apply {
add(criteriaBuilder.`in`(root.get<BoardStatus>("status")).apply { value(BoardStatus.NORMAL) })
}.mergeBy(criteriaBuilder)
private fun List<Predicate>.mergeBy(cb: CriteriaBuilder): Predicate? {
var p: Predicate? = null
forEach { p = cb.and(it) }
return p
}
}
| 0
| null |
0
| 0
|
9a3860f780a1c994fcc7f2bed1525a0d73a3fa64
| 2,645
|
spring-board-demo
|
Beerware License
|
src/main/kotlin/com/cycode/plugin/components/toolWindow/components/violationCardContentTab/common/shortSummary/CardShortSummary.kt
|
cycodehq
| 661,784,325
| false
|
{"Kotlin": 198842}
|
package com.cycode.plugin.components.toolWindow.components.violationCardContentTab.common.shortSummary
import com.intellij.ui.components.JBLabel
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import javax.swing.JComponent
import javax.swing.JPanel
open class CardShortSummary {
fun getContent(shortSummary: String? = null): JComponent {
val gbc = GridBagConstraints()
gbc.fill = GridBagConstraints.NONE
gbc.anchor = GridBagConstraints.NORTHWEST
gbc.weightx = 1.0
val panel = JPanel(GridBagLayout())
if (shortSummary != null) {
panel.add(JBLabel(shortSummary).apply { isAllowAutoWrapping = true; setCopyable(true) }, gbc)
}
return panel
}
}
| 0
|
Kotlin
|
0
| 1
|
5a9aa8d537c5dda60df5ead08c3b4d53d4f4b545
| 747
|
intellij-platform-plugin
|
MIT License
|
app/src/main/java/ru/serguun42/android/ats/model/BusinessDetails.kt
|
serguun42
| 695,939,084
| false
|
{"Kotlin": 26003}
|
package ru.serguun42.android.ats.model
abstract class BusinessDetails(
var companyName: String,
var companyLocation: String,
var jobPosition: String,
var startDate: String,
var endDate: String,
var duties: String
)
| 0
|
Kotlin
|
0
| 0
|
2743a484c68593fc3c353c4090f6f3182213843d
| 240
|
ATS-App
|
Boost Software License 1.0
|
src/main/kotlin/me/ftmc/hotpot/soup/effects/HotpotEffectHelper.kt
|
FishMagic
| 723,117,949
| false
|
{"Kotlin": 211369, "Java": 15622}
|
package me.ftmc.hotpot.soup.effects
import me.ftmc.hotpot.HotpotTagsHelper
import net.minecraft.entity.effect.StatusEffectInstance
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NbtCompound
import net.minecraft.nbt.NbtElement
import net.minecraft.nbt.NbtList
import java.util.stream.Collectors
object HotpotEffectHelper {
fun saveEffects(itemStack: ItemStack, mobEffectInstance: StatusEffectInstance) {
val effects =
HotpotTagsHelper.getHotpotTag(itemStack).getList("HotpotEffects", NbtElement.COMPOUND_TYPE.toInt())
.map { tag -> tag as NbtCompound }.mapNotNull(StatusEffectInstance::fromNbt).toMutableList()
mergeEffects(effects, mobEffectInstance)
HotpotTagsHelper.updateHotpotTag(itemStack) { compoundTag ->
compoundTag.put(
"HotpotEffects",
effects.map { it.writeNbt(NbtCompound()) }.stream().collect(Collectors.toCollection(::NbtList))
)
}
}
fun hasEffects(itemStack: ItemStack): Boolean {
return HotpotTagsHelper.hasHotpotTag(itemStack) && HotpotTagsHelper.getHotpotTag(itemStack)
.contains("HotpotEffects", NbtElement.LIST_TYPE.toInt())
}
fun listEffects(itemStack: ItemStack, consumer: (StatusEffectInstance) -> Unit) {
if (!hasEffects(itemStack)) return
HotpotTagsHelper.getHotpotTag(itemStack).getList("HotpotEffects", NbtElement.COMPOUND_TYPE.toInt())
.mapNotNull { tag -> StatusEffectInstance.fromNbt(tag as NbtCompound) }
.forEach(consumer)
}
fun getListEffects(itemStack: ItemStack): List<StatusEffectInstance> {
val effects: MutableList<StatusEffectInstance> = mutableListOf()
listEffects(itemStack) { effects.add(it) }
return effects
}
fun mergeEffects(effects: List<StatusEffectInstance>): List<StatusEffectInstance> {
val list: MutableList<StatusEffectInstance> = mutableListOf()
effects.forEach { mergeEffects(list, it) }
return list
}
fun mergeEffects(effects: MutableList<StatusEffectInstance>, mobEffectInstance: StatusEffectInstance) {
for (effect in effects) {
if (effect.effectType.equals(mobEffectInstance.effectType)) {
effect.upgrade(mobEffectInstance)
return
}
}
effects.add(mobEffectInstance)
}
}
| 0
|
Kotlin
|
0
| 3
|
cb4528a99d120e892844a615c11bae58458ad045
| 2,402
|
EveryXHotpot-Fabric
|
MIT License
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/ShareAltSquare.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.rounded.outline
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.rounded.Icons
public val Icons.Outline.ShareAltSquare: ImageVector
get() {
if (_shareAltSquare != null) {
return _shareAltSquare!!
}
_shareAltSquare = Builder(name = "ShareAltSquare", defaultWidth = 512.0.dp, defaultHeight =
512.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(16.0f, 10.0f)
curveToRelative(1.654f, 0.0f, 3.0f, -1.346f, 3.0f, -3.0f)
reflectiveCurveToRelative(-1.346f, -3.0f, -3.0f, -3.0f)
reflectiveCurveToRelative(-3.0f, 1.346f, -3.0f, 3.0f)
curveToRelative(0.0f, 0.17f, 0.015f, 0.337f, 0.042f, 0.5f)
lineToRelative(-4.057f, 2.254f)
curveToRelative(-0.529f, -0.468f, -1.224f, -0.753f, -1.985f, -0.753f)
curveToRelative(-1.654f, 0.0f, -3.0f, 1.346f, -3.0f, 3.0f)
reflectiveCurveToRelative(1.346f, 3.0f, 3.0f, 3.0f)
curveToRelative(0.761f, 0.0f, 1.456f, -0.285f, 1.985f, -0.753f)
lineToRelative(4.057f, 2.254f)
curveToRelative(-0.027f, 0.163f, -0.042f, 0.329f, -0.042f, 0.5f)
curveToRelative(0.0f, 1.654f, 1.346f, 3.0f, 3.0f, 3.0f)
reflectiveCurveToRelative(3.0f, -1.346f, 3.0f, -3.0f)
reflectiveCurveToRelative(-1.346f, -3.0f, -3.0f, -3.0f)
curveToRelative(-0.761f, 0.0f, -1.456f, 0.285f, -1.985f, 0.753f)
lineToRelative(-4.057f, -2.254f)
curveToRelative(0.027f, -0.163f, 0.042f, -0.329f, 0.042f, -0.5f)
reflectiveCurveToRelative(-0.015f, -0.337f, -0.042f, -0.5f)
lineToRelative(4.057f, -2.254f)
curveToRelative(0.529f, 0.468f, 1.224f, 0.753f, 1.985f, 0.753f)
close()
moveTo(16.0f, 6.0f)
curveToRelative(0.552f, 0.0f, 1.0f, 0.449f, 1.0f, 1.0f)
reflectiveCurveToRelative(-0.448f, 1.0f, -1.0f, 1.0f)
reflectiveCurveToRelative(-1.0f, -0.449f, -1.0f, -1.0f)
reflectiveCurveToRelative(0.448f, -1.0f, 1.0f, -1.0f)
close()
moveTo(7.0f, 13.0f)
curveToRelative(-0.552f, 0.0f, -1.0f, -0.449f, -1.0f, -1.0f)
reflectiveCurveToRelative(0.448f, -1.0f, 1.0f, -1.0f)
reflectiveCurveToRelative(1.0f, 0.449f, 1.0f, 1.0f)
reflectiveCurveToRelative(-0.448f, 1.0f, -1.0f, 1.0f)
close()
moveTo(16.0f, 16.0f)
curveToRelative(0.552f, 0.0f, 1.0f, 0.449f, 1.0f, 1.0f)
reflectiveCurveToRelative(-0.448f, 1.0f, -1.0f, 1.0f)
reflectiveCurveToRelative(-1.0f, -0.449f, -1.0f, -1.0f)
reflectiveCurveToRelative(0.448f, -1.0f, 1.0f, -1.0f)
close()
moveTo(19.0f, 0.0f)
lineTo(5.0f, 0.0f)
curveTo(2.243f, 0.0f, 0.0f, 2.243f, 0.0f, 5.0f)
verticalLineToRelative(14.0f)
curveToRelative(0.0f, 2.757f, 2.243f, 5.0f, 5.0f, 5.0f)
horizontalLineToRelative(14.0f)
curveToRelative(2.757f, 0.0f, 5.0f, -2.243f, 5.0f, -5.0f)
lineTo(24.0f, 5.0f)
curveToRelative(0.0f, -2.757f, -2.243f, -5.0f, -5.0f, -5.0f)
close()
moveTo(22.0f, 19.0f)
curveToRelative(0.0f, 1.654f, -1.346f, 3.0f, -3.0f, 3.0f)
lineTo(5.0f, 22.0f)
curveToRelative(-1.654f, 0.0f, -3.0f, -1.346f, -3.0f, -3.0f)
lineTo(2.0f, 5.0f)
curveToRelative(0.0f, -1.654f, 1.346f, -3.0f, 3.0f, -3.0f)
horizontalLineToRelative(14.0f)
curveToRelative(1.654f, 0.0f, 3.0f, 1.346f, 3.0f, 3.0f)
verticalLineToRelative(14.0f)
close()
}
}
.build()
return _shareAltSquare!!
}
private var _shareAltSquare: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 4,796
|
icons
|
MIT License
|
support/samples/sample-android/app/src/androidTest/java/io/github/marcelbraghetto/mockifer/example/android/MockiferTestRule.kt
|
MarcelBraghetto
| 96,596,914
| false
|
{"Shell": 10, "Text": 4, "Ignore List": 6, "Markdown": 1, "CMake": 1, "Gradle": 5, "Proguard": 2, "Batchfile": 3, "Java Properties": 5, "XML": 16, "Java": 1, "C++": 23, "C": 5, "OpenStep Property List": 4, "Swift": 20, "Objective-C++": 2, "Objective-C": 2, "JSON": 14, "Kotlin": 34, "JavaScript": 2, "HTML": 1}
|
package io.github.marcelbraghetto.mockifer.example.android
import android.net.Uri
import androidx.test.platform.app.InstrumentationRegistry
import androidx.appcompat.app.AppCompatActivity
import androidx.test.rule.ActivityTestRule
import io.github.marcelbraghetto.mockifer.Mockifer
import io.github.marcelbraghetto.mockifer.example.android.main.BaseApplication
class MockiferTestRule<T : AppCompatActivity>(activityClass: Class<T>) : ActivityTestRule<T>(activityClass, true, false) {
private companion object {
var mockiferInitialised = false
}
init {
if (!mockiferInitialised) {
mockiferInitialised = true
val uri = Uri.parse(BuildConfig.SERVER_BASE_URL)
val port = uri.port
Mockifer.installOnPort(BaseApplication.get(), InstrumentationRegistry.getInstrumentation().context, port)
Mockifer.setCommandUrl(uri.host, port)
}
}
}
| 0
|
C
|
1
| 21
|
d9e18d4979176ff149f36fc646474456704fbd7c
| 932
|
mockifer
|
MIT License
|
java_pro/src/main/kotlin/kt/com/tencent/cain/desigin_pattern/bridge/HandsetBrandHuaWei.kt
|
JayRichrd
| 510,423,945
| false
|
{"Java": 77189, "Kotlin": 54914, "C++": 5055, "CMake": 529}
|
package kt.com.tencent.cain.desigin_pattern.bridge
/**
* @author : jiangyu
* @date : 2020/7/11
* @desc : xxx
*/
class HandsetBrandHuaWei(brandName:String):HandsetBrand(brandName) {
override fun run() {
println("$brandName 手机")
soft?.run()
}
}
| 1
| null |
1
| 1
|
00e247591b9e95083d6de362bca512429169af96
| 275
|
design_pattern_structure
|
MIT License
|
platform/build-scripts/src/org/jetbrains/intellij/build/impl/productRunner/ModuleBasedProductRunner.kt
|
koxudaxi
| 196,571,905
| false
|
{"Text": 9778, "INI": 517, "YAML": 423, "Ant Build System": 11, "Batchfile": 34, "Dockerfile": 10, "Shell": 634, "Markdown": 752, "Ignore List": 141, "Git Revision List": 1, "Git Attributes": 11, "EditorConfig": 261, "XML": 7881, "SVG": 4447, "Kotlin": 59448, "Java": 84016, "HTML": 3792, "Java Properties": 217, "Gradle": 460, "Maven POM": 95, "JavaScript": 229, "CSS": 79, "JSON": 1424, "JFlex": 33, "Makefile": 5, "Diff": 137, "XSLT": 113, "Gradle Kotlin DSL": 742, "Groovy": 3109, "desktop": 1, "JAR Manifest": 17, "PHP": 47, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 13, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 15, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 72, "GraphQL": 125, "Nginx": 1, "HAProxy": 1, "OpenStep Property List": 47, "Python": 17066, "C": 109, "C++": 42, "Protocol Buffer": 3, "fish": 2, "PowerShell": 3, "Go": 36, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "HCL": 4, "F#": 1, "GLSL": 1, "Elixir": 2, "Ruby": 4, "XML Property List": 84, "E-mail": 18, "Roff": 283, "Roff Manpage": 40, "Swift": 3, "TOML": 196, "Checksums": 49, "Java Server Pages": 11, "Vue": 1, "Dotenv": 1, "reStructuredText": 67, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 15, "Handlebars": 1, "Rust": 20, "Go Checksums": 1, "Go Module": 1, "NSIS": 8, "PlantUML": 6, "SCSS": 2, "Thrift": 3, "Cython": 13, "Regular Expression": 3, "JSON5": 4, "OASv3-json": 3, "OASv3-yaml": 1}
|
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build.impl.productRunner
import com.intellij.platform.runtime.repository.RuntimeModuleId
import org.jetbrains.intellij.build.BuildContext
import org.jetbrains.intellij.build.impl.VmOptionsGenerator
import kotlin.io.path.pathString
/**
* Runs the product using the module-based loader which will take class-files from module output directories.
*/
internal class ModuleBasedProductRunner(private val rootModuleForModularLoader: String, private val context: BuildContext) : IntellijProductRunner {
override suspend fun runProduct(arguments: List<String>, additionalSystemProperties: Map<String, String>, isLongRunning: Boolean) {
val systemProperties = mutableMapOf(
"intellij.platform.runtime.repository.path" to context.originalModuleRepository.repositoryPath.pathString,
"intellij.platform.root.module" to rootModuleForModularLoader,
"intellij.platform.product.mode" to context.productProperties.productMode.id,
"idea.vendor.name" to context.applicationInfo.shortCompanyName,
)
//todo include jna.boot.library.path, pty4j.preferred.native.folder and related properties?
val loaderModule = context.originalModuleRepository.repository.getModule(RuntimeModuleId.module("intellij.platform.runtime.loader"))
val ideClasspath = loaderModule.moduleClasspath.map { it.pathString }
systemProperties.putAll(additionalSystemProperties)
runApplicationStarter(
context,
ideClasspath = ideClasspath,
arguments = arguments,
systemProperties = systemProperties,
vmOptions = VmOptionsGenerator.computeVmOptions(context)
+ context.productProperties.additionalIdeJvmArguments
+ context.productProperties.getAdditionalContextDependentIdeJvmArguments(context),
)
}
}
| 1
| null |
1
| 1
|
641c9567cc039e31dd60adbe4011f1b80a168b59
| 1,937
|
intellij-community
|
Apache License 2.0
|
app/src/test/java/com/duckduckgo/app/widget/AddWidgetCompatLauncherTest.kt
|
hojat72elect
| 822,396,044
| false
|
{"Kotlin": 11626231, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784}
|
package com.duckduckgo.app.widget
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.duckduckgo.app.widget.ui.WidgetCapabilities
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
@RunWith(AndroidJUnit4::class)
class AddWidgetCompatLauncherTest {
private val defaultAddWidgetLauncher: AddWidgetLauncher = mock()
private val legacyAddWidgetLauncher: AddWidgetLauncher = mock()
private val widgetCapabilities: WidgetCapabilities = mock()
private val testee = AddWidgetCompatLauncher(
defaultAddWidgetLauncher,
legacyAddWidgetLauncher,
widgetCapabilities,
)
@Test
fun whenAutomaticWidgetAddIsNotSupportedThenDelegateToLegacyAddWidgetLauncher() {
whenever(widgetCapabilities.supportsAutomaticWidgetAdd).thenReturn(false)
testee.launchAddWidget(null)
verify(legacyAddWidgetLauncher).launchAddWidget(null)
}
@Test
fun whenAutomaticWidgetAddIsSupportedThenDelegateToAppWidgetManagerAddWidgetLauncher() {
whenever(widgetCapabilities.supportsAutomaticWidgetAdd).thenReturn(true)
testee.launchAddWidget(null)
verify(defaultAddWidgetLauncher).launchAddWidget(null)
}
}
| 0
|
Kotlin
|
0
| 0
|
b89591136b60933d6a03fac43a38ee183116b7f8
| 1,299
|
DuckDuckGo
|
Apache License 2.0
|
components/flow/flow-service/src/main/kotlin/net/corda/flow/pipeline/handlers/requests/SubFlowFinishedRequestHandler.kt
|
corda
| 346,070,752
| false
|
{"Kotlin": 20585393, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244}
|
package net.corda.flow.pipeline.handlers.requests
import net.corda.data.flow.state.waiting.SessionConfirmation
import net.corda.data.flow.state.waiting.SessionConfirmationType
import net.corda.data.flow.state.waiting.WaitingFor
import net.corda.flow.fiber.FlowIORequest
import net.corda.flow.pipeline.events.FlowEventContext
import net.corda.flow.pipeline.exceptions.FlowFatalException
import net.corda.flow.pipeline.handlers.requests.sessions.service.CloseSessionService
import org.osgi.service.component.annotations.Activate
import org.osgi.service.component.annotations.Component
import org.osgi.service.component.annotations.Reference
@Component(service = [FlowRequestHandler::class])
class SubFlowFinishedRequestHandler @Activate constructor(
@Reference(service = CloseSessionService::class)
private val closeSessionService: CloseSessionService
) : FlowRequestHandler<FlowIORequest.SubFlowFinished> {
override val type = FlowIORequest.SubFlowFinished::class.java
private fun getSessionsToClose(request: FlowIORequest.SubFlowFinished): List<String> {
return request.sessionIds.toMutableList()
}
override fun getUpdatedWaitingFor(
context: FlowEventContext<Any>,
request: FlowIORequest.SubFlowFinished
): WaitingFor {
val sessionsToClose = try {
closeSessionService.getSessionsToCloseForWaitingFor(context.checkpoint, getSessionsToClose(request))
} catch (e: Exception) {
val msg = e.message ?: "An error occurred in the platform - A session in ${request.sessionIds} was missing from the checkpoint"
throw FlowFatalException(msg, e)
}
return if (sessionsToClose.isEmpty()) {
WaitingFor(net.corda.data.flow.state.waiting.Wakeup())
} else {
WaitingFor(SessionConfirmation(sessionsToClose, SessionConfirmationType.CLOSE))
}
}
override fun postProcess(
context: FlowEventContext<Any>,
request: FlowIORequest.SubFlowFinished
): FlowEventContext<Any> {
val checkpoint = context.checkpoint
try {
closeSessionService.handleCloseForSessions(checkpoint, getSessionsToClose(request))
} catch (e: Exception) {
// TODO CORE-4850 Wakeup with error when session does not exist
val msg = e.message ?: "An error occurred in the platform - A session in ${request.sessionIds} was missing from the checkpoint"
throw FlowFatalException(msg, e)
}
return context
}
}
| 14
|
Kotlin
|
27
| 69
|
0766222eb6284c01ba321633e12b70f1a93ca04e
| 2,533
|
corda-runtime-os
|
Apache License 2.0
|
projects/pathfinder-and-delius/src/main/kotlin/uk/gov/justice/digital/hmpps/service/UserService.kt
|
ministryofjustice
| 500,855,647
| false
|
{"Kotlin": 4133825, "HTML": 70066, "D2": 40497, "Ruby": 25921, "Shell": 15549, "SCSS": 6370, "HCL": 2712, "Dockerfile": 2414, "JavaScript": 1372, "Python": 268}
|
package uk.gov.justice.digital.hmpps.service
import org.springframework.ldap.core.LdapTemplate
import org.springframework.stereotype.Service
import uk.gov.justice.digital.hmpps.ldap.addRole
import uk.gov.justice.digital.hmpps.ldap.removeRole
import uk.gov.justice.digital.hmpps.model.DeliusRole
@Service
class UserService(private val ldapTemplate: LdapTemplate) {
fun addRole(username: String, role: DeliusRole) = ldapTemplate.addRole(username, role)
fun removeRole(username: String, role: DeliusRole) = ldapTemplate.removeRole(username, role)
}
| 5
|
Kotlin
|
0
| 2
|
f7042c113b7cfd4d439c6c77231a1a28f93e9485
| 558
|
hmpps-probation-integration-services
|
MIT License
|
src/test/kotlin/uk/co/agware/carpet/TestChange.kt
|
philipw1988
| 57,885,380
| false
| null |
package uk.co.agware.carpet
import org.jetbrains.spek.api.SubjectSpek
import org.jetbrains.spek.api.dsl.Dsl
import org.jetbrains.spek.api.dsl.SubjectDsl
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.junit.platform.runner.JUnitPlatform
import org.junit.runner.RunWith
import uk.co.agware.carpet.change.Change
import uk.co.agware.carpet.exception.MagicCarpetParseException
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNotEquals
import kotlin.test.assertTrue
private val spek: SubjectDsl<Change>.() -> Unit = {
describe("A Change object") {
subject { Change("1.0.0") }
it("should equal a Change with the same version") {
assertEquals(subject, Change("1.0.0"))
}
it("should not equal a Change with a different version") {
assertNotEquals(subject, Change("2.0.0"))
}
it("should fail when a supplied version does not match SemVer") {
assertFailsWith<MagicCarpetParseException> {
Change("1")
}
}
it("should fail when a supplied version contains invalid characters") {
assertFailsWith<MagicCarpetParseException> {
Change("1.d.0")
}
}
it("should order changes using the version number") {
assertTrue { subject < Change("1.1.0") }
}
it("should be ok with a patch version above 9") {
Change("1.0.10")
}
it("should be ok with a minor version above 9") {
Change("1.10.0")
}
it("should be ok with a major version above 9") {
Change("10.0.0")
}
}
}
@RunWith(JUnitPlatform::class)
class TestChange : SubjectSpek<Change>(spek)
| 1
|
Kotlin
|
1
| 0
|
4faa9e1ae38728f3b69ba32ab03deb72e3082f12
| 1,589
|
MagicCarpet
|
Apache License 2.0
|
ldb/kodein-leveldb/src/commonTest/kotlin/org/kodein/db/leveldb/test/LDBTests_01_Snapshot.kt
|
Kodein-Framework
| 147,318,269
| false
| null |
package org.kodein.db.leveldb.test
import org.kodein.db.leveldb.LevelDB
import org.kodein.db.leveldb.LevelDBFactory
import org.kodein.db.leveldb.default
import org.kodein.db.leveldb.inDir
import org.kodein.db.leveldb.inmemory.inMemory
import org.kodein.db.test.utils.assertBytesEquals
import org.kodein.db.test.utils.array
import org.kodein.memory.file.FileSystem
import org.kodein.memory.use
import kotlin.test.Test
import kotlin.test.assertNull
@Suppress("ClassName")
abstract class LDBTests_01_Snapshot : LevelDBTests() {
class LDB : LDBTests_01_Snapshot() { override val factory: LevelDBFactory = LevelDB.default.inDir(FileSystem.tempDirectory.path) }
class IM : LDBTests_01_Snapshot() { override val factory: LevelDBFactory = LevelDB.inMemory }
@Test
fun test_00_PutGet() {
ldb!!.newSnapshot().use { snapshot ->
ldb!!.put(native("key"), native("newValueBuffer"))
assertNull(ldb!!.get(native("key"), LevelDB.ReadOptions(snapshot = snapshot)))
}
}
@Test
fun test_01_PutDeleteGet() {
ldb!!.put(native("key"), native("newValueBuffer"))
ldb!!.newSnapshot().use { snapshot ->
ldb!!.delete(native("key"))
val value = ldb!!.get(native("key"), LevelDB.ReadOptions(snapshot = snapshot))!!
assertBytesEquals(array("newValueBuffer"), value)
value.close()
}
}
}
| 13
|
Kotlin
|
22
| 273
|
044ad75e88d14c2702a3716c8150a7ba158d97b6
| 1,407
|
Kodein-DB
|
MIT License
|
location/src/main/java/com/example/location/LocationActivity.kt
|
hamzeh-pourshabanan
| 576,882,359
| false
| null |
package com.example.location
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.annotation.DrawableRes
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import com.example.location.databinding.ActivityLocationBinding
import com.example.location.domain.TerminalsDomainModel
import com.example.location.presentation.BottomSheetFragment
import com.example.location.utils.LocationPermissionHelper
import com.mapbox.android.gestures.MoveGestureDetector
import com.mapbox.geojson.Point
import com.mapbox.maps.CameraOptions
import com.mapbox.maps.EdgeInsets
import com.mapbox.maps.MapView
import com.mapbox.maps.Style
import com.mapbox.maps.extension.style.expressions.generated.Expression.Companion.interpolate
import com.mapbox.maps.plugin.LocationPuck2D
import com.mapbox.maps.plugin.PuckBearingSource
import com.mapbox.maps.plugin.annotation.annotations
import com.mapbox.maps.plugin.annotation.generated.PointAnnotationOptions
import com.mapbox.maps.plugin.annotation.generated.createPointAnnotationManager
import com.mapbox.maps.plugin.gestures.OnMoveListener
import com.mapbox.maps.plugin.gestures.gestures
import com.mapbox.maps.plugin.locationcomponent.OnIndicatorPositionChangedListener
import com.mapbox.maps.plugin.locationcomponent.location
import com.mapbox.maps.plugin.locationcomponent.location2
import java.lang.ref.WeakReference
import java.text.NumberFormat
class LocationActivity : AppCompatActivity() {
private lateinit var locationPermissionHelper: LocationPermissionHelper
private lateinit var binding: ActivityLocationBinding
private lateinit var model: TerminalsDomainModel
private val onIndicatorPositionChangedListener = OnIndicatorPositionChangedListener {
Log.d(this.javaClass.simpleName, "point: $it")
// Create a polygon
val triangleCoordinates =
mutableListOf(
Point.fromLngLat(model.origin!!.long, model.origin!!.lat),
it,
)
model.destinations.onEach { destination ->
triangleCoordinates.add(Point.fromLngLat(destination.long, destination.lat))
}
// Convert to a camera options from a given geometry and padding
val cameraPositionCoor = mapView.getMapboxMap()
.cameraForCoordinates(triangleCoordinates, EdgeInsets(1.0, 55.0, 20.0, 55.0))
// Set camera position
mapView.getMapboxMap().setCamera(cameraPositionCoor)
}
private val onMoveListener = object : OnMoveListener {
override fun onMoveBegin(detector: MoveGestureDetector) {
onCameraTrackingDismissed()
}
override fun onMove(detector: MoveGestureDetector): Boolean {
return false
}
override fun onMoveEnd(detector: MoveGestureDetector) {}
}
private lateinit var mapView: MapView
@SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(this.javaClass.simpleName, "From: onCreate called")
binding = ActivityLocationBinding.inflate(layoutInflater)
setContentView(binding.root)
mapView = binding.mapView
locationPermissionHelper = LocationPermissionHelper(WeakReference(this))
locationPermissionHelper.checkPermissions {
onMapReady()
}
val i: Intent = intent
model = i.getParcelableExtra<TerminalsDomainModel>("response") as TerminalsDomainModel
Log.d(this.javaClass.simpleName, "From model: $model")
val ft = supportFragmentManager.beginTransaction()
val fragment = BottomSheetFragment.newInstance(model)
ft.replace(R.id.bottomSheet, fragment)
ft.commit()
onMapReady(model)
val myFormat = NumberFormat.getInstance().apply { isGroupingUsed = true }
binding.priceButton.text = getString(R.string.rial, myFormat.format(model.price))
}
private fun onMapReady(model: TerminalsDomainModel? = null) {
mapView.getMapboxMap().loadStyleUri(
Style.MAPBOX_STREETS
) {
initLocationComponent()
setupGesturesListener()
addAnnotationToMap(model?.origin?.long ?: 0.0, model?.origin?.lat ?: 0.0, 0)
model?.destinations?.onEach {
addAnnotationToMap(it.long, it.lat, it.destNumber)
}
}
}
private fun setupGesturesListener() {
mapView.gestures.addOnMoveListener(onMoveListener)
}
private fun initLocationComponent() {
val locationComponentPlugin = mapView.location
locationComponentPlugin.updateSettings {
this.enabled = true
this.locationPuck = LocationPuck2D(
bearingImage = AppCompatResources.getDrawable(
this@LocationActivity,
com.mapbox.maps.R.drawable.mapbox_user_bearing_icon,
),
shadowImage = AppCompatResources.getDrawable(
this@LocationActivity,
com.mapbox.maps.R.drawable.mapbox_mylocation_icon_bearing,
),
scaleExpression = interpolate {
linear()
zoom()
stop {
literal(0.0)
literal(0.6)
}
stop {
literal(20.0)
literal(1.0)
}
}.toJson()
)
}
locationComponentPlugin.addOnIndicatorPositionChangedListener(
onIndicatorPositionChangedListener
)
mapView.location2.puckBearingSource = PuckBearingSource.HEADING
}
private fun onCameraTrackingDismissed() {
Toast.makeText(this, "onCameraTrackingDismissed", Toast.LENGTH_SHORT).show()
mapView.location
.removeOnIndicatorPositionChangedListener(onIndicatorPositionChangedListener)
mapView.gestures.removeOnMoveListener(onMoveListener)
}
private fun addAnnotationToMap(long: Double, lat: Double, destNumber: Int) {
val resId = when (destNumber) {
0 -> R.drawable.ic_top
1 -> R.drawable.ic_dest_one
2 -> R.drawable.ic_dest_two
else -> R.drawable.red_marker
}
// Create an instance of the Annotation API and get the PointAnnotationManager.
bitmapFromDrawableRes(
this,
resId
)?.let {
val annotationApi = mapView?.annotations
val pointAnnotationManager = annotationApi?.createPointAnnotationManager(mapView)
// Set options for the resulting symbol layer.
val pointAnnotationOptions: PointAnnotationOptions = PointAnnotationOptions()
// Define a geographic coordinate.
.withPoint(Point.fromLngLat(long, lat))
// Specify the bitmap you assigned to the point annotation
// The bitmap will be added to map style automatically.
.withIconImage(it)
// Add the resulting pointAnnotation to the map.
pointAnnotationManager?.create(pointAnnotationOptions)
pointAnnotationManager?.addClickListener {
mapView.getMapboxMap().setCamera(
CameraOptions.Builder().zoom(14.8).anchor(
mapView.getMapboxMap().pixelForCoordinate(
Point.fromLngLat(long, lat)
)
).build()
)
true
}
}
}
private fun bitmapFromDrawableRes(context: Context, @DrawableRes resourceId: Int) =
convertDrawableToBitmap(AppCompatResources.getDrawable(context, resourceId))
private fun convertDrawableToBitmap(sourceDrawable: Drawable?): Bitmap? {
if (sourceDrawable == null) {
return null
}
return if (sourceDrawable is BitmapDrawable) {
sourceDrawable.bitmap
} else {
// copying drawable object to not manipulate on the same reference
val constantState = sourceDrawable.constantState ?: return null
val drawable = constantState.newDrawable().mutate()
val bitmap: Bitmap = Bitmap.createBitmap(
drawable.intrinsicWidth, drawable.intrinsicHeight,
Bitmap.Config.ARGB_8888
)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
bitmap
}
}
override fun onDestroy() {
super.onDestroy()
mapView.location
.removeOnIndicatorPositionChangedListener(onIndicatorPositionChangedListener)
mapView.gestures.removeOnMoveListener(onMoveListener)
}
}
data class DestinationsUiModel(
val address: String = "",
@DrawableRes val image: Int
)
| 0
|
Kotlin
|
1
| 0
|
166bf7078f631bc11731c451f359b0982a8365de
| 9,219
|
Box-Bike
|
MIT License
|
flutter-projects/scrum_deck/android/app/src/main/kotlin/com/example/scrum_deck/MainActivity.kt
|
vitorecomp
| 292,507,661
| false
| null |
package com.example.scrum_deck
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0
|
Rust
|
0
| 0
|
4f2580debf281cf43061c497295fca53f3151bab
| 127
|
learning-projects
|
MIT License
|
app/src/main/kotlin/com/github/premnirmal/ticker/BaseFragment.kt
|
sanshao27
| 88,776,729
| true
|
{"Kotlin": 191856, "Shell": 217}
|
package com.github.premnirmal.ticker
import android.app.Activity
import android.os.Bundle
import android.support.v4.app.Fragment
import android.util.AndroidRuntimeException
import android.view.View
import com.trello.rxlifecycle.FragmentEvent
import com.trello.rxlifecycle.RxLifecycle
import rx.Observable
import rx.subjects.BehaviorSubject
/**
* Created by premnirmal on 2/25/16.
*/
abstract class BaseFragment : Fragment() {
private val lifecycleSubject = BehaviorSubject.create<FragmentEvent>()
private var called: Boolean = false
protected fun lifecycle(): Observable<FragmentEvent> {
return lifecycleSubject.asObservable()
}
override fun onAttach(activity: Activity?) {
super.onAttach(activity)
lifecycleSubject.onNext(FragmentEvent.ATTACH)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleSubject.onNext(FragmentEvent.CREATE)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
lifecycleSubject.onNext(FragmentEvent.CREATE_VIEW)
called = true
}
override fun onStart() {
super.onStart()
lifecycleSubject.onNext(FragmentEvent.START)
}
override fun onResume() {
if (!called) {
throw AndroidRuntimeException(
"You didn't call super.onViewCreated() when in " + javaClass.simpleName)
}
super.onResume()
lifecycleSubject.onNext(FragmentEvent.RESUME)
}
override fun onPause() {
lifecycleSubject.onNext(FragmentEvent.PAUSE)
super.onPause()
}
override fun onStop() {
lifecycleSubject.onNext(FragmentEvent.STOP)
super.onStop()
}
override fun onDestroyView() {
lifecycleSubject.onNext(FragmentEvent.DESTROY_VIEW)
super.onDestroyView()
}
override fun onDetach() {
lifecycleSubject.onNext(FragmentEvent.DETACH)
super.onDetach()
}
override fun onDestroy() {
lifecycleSubject.onNext(FragmentEvent.DESTROY)
super.onDestroy()
}
/**
* Using this to automatically unsubscribe from observables on lifecycle events
*/
protected fun <T> bind(observable: Observable<T>): Observable<T> {
return observable.compose(RxLifecycle.bindFragment<T>(lifecycle()));
}
}
| 0
|
Kotlin
|
0
| 0
|
5fd50934a75277add91288804862874bef24a526
| 2,252
|
StockTicker
|
MIT License
|
src/main/kotlin/engine/scene/components/ParticleEffectComponent.kt
|
CozmicGames
| 560,807,673
| false
|
{"Kotlin": 612419}
|
package engine.scene.components
import com.cozmicgames.utils.Updateable
import engine.graphics.particles.ParticleEffect
import engine.scene.Component
class ParticleEffectComponent : Component(), Updateable {
var create: ParticleEffect.() -> Unit = {}
set(value) {
isDirty = true
field = value
}
var maxParticles = 100
set(value) {
isDirty = true
field = value
}
var emitRate = 10.0f
set(value) {
isDirty = true
field = value
}
var layer = 0
lateinit var effect: ParticleEffect
private set
private var isDirty = true
override fun update(delta: Float) {
if (isDirty) {
effect = ParticleEffect(maxParticles, emitRate)
create(effect)
isDirty = false
}
effect.update(delta)
}
}
| 0
|
Kotlin
|
0
| 0
|
d85d016431fb0490dcb6b125be5fd285e409bfc4
| 900
|
GameOff2022
|
MIT License
|
feature/notes-list/api/src/main/java/ru/maksonic/beresta/feature/notes_list/api/NotesListApi.kt
|
maksonic
| 580,058,579
| false
| null |
package ru.maksonic.beresta.feature.notes_list.api
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import ru.maksonic.beresta.feature.notes_list.api.ui.NoteUi
import ru.maksonic.beresta.navigation.router.router.MainScreenRouter
/**
* @Author maksonic on 21.02.2023
*/
interface NotesListApi {
interface Ui {
@Composable
fun FetchedNotesWidget(
notes: NoteUi.Collection,
scrollState: () -> LazyListState,
router: MainScreenRouter,
modifier: Modifier
)
@Composable
fun EmptyNotesListWidget(modifier: Modifier)
@Composable
fun NoteItem(
onNoteClicked: (id: Long) -> Unit,
onNoteLongClicked: (id: Long) -> Unit,
note: NoteUi,
modifier: Modifier
)
}
}
| 0
|
Kotlin
|
0
| 0
|
5704d413cd57a8eabe27b02a185a999fce2ca1e4
| 905
|
Beresta
|
MIT License
|
app/src/main/java/com/vikaspatidar/shvan/home/HomePage.kt
|
vikaspatidar
| 343,876,445
| 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.vikaspatidar.shvan.home
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.vikaspatidar.shvan.R
@ExperimentalFoundationApi
@Composable
fun HomePage(
viewModel: PetViewModel,
onPetSelected: (id: Int) -> Unit
) {
Scaffold(
topBar = {
Toolbar()
},
content = {
viewModel.liveData.observeAsState(
emptyList()
).value?.let { pets ->
PetsGrid(
pets,
onPetSelected
)
}
}
)
}
@Composable
fun Toolbar() {
TopAppBar(
backgroundColor = MaterialTheme.colors.primary,
elevation = 1.dp
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
painter = painterResource(id = R.drawable.ic_baseline_pet_24),
contentDescription = null,
modifier = Modifier.padding(16.dp),
)
Text(
text = stringResource(id = R.string.app_name),
modifier = Modifier.padding(8.dp),
style = MaterialTheme.typography.h6,
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
6b537fdb96b6c86fc54acce5756b6d9e64d5e59d
| 2,254
|
Shvan
|
Apache License 2.0
|
app/src/main/java/com/duckduckgo/app/global/rating/AppEnjoymentPromptCriteria.kt
|
hojat72elect
| 822,396,044
| false
|
{"Kotlin": 11626231, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784}
|
package com.duckduckgo.app.global.rating
const val MINIMUM_SEARCHES_THRESHOLD = 5
const val MINIMUM_DAYS_USAGE_BEFORE_FIRST_PROMPT = 3
const val MINIMUM_DAYS_USAGE_SINCE_INITIAL_PROMPT_BEFORE_SECOND_PROMPT = 4
| 0
|
Kotlin
|
0
| 0
|
b89591136b60933d6a03fac43a38ee183116b7f8
| 213
|
DuckDuckGo
|
Apache License 2.0
|
flutter_ml_vision_app/android/app/src/main/kotlin/com/fby/flutter/ml/vision/app/MainActivity.kt
|
fbernaly
| 366,480,242
| false
|
{"Dart": 5811, "HTML": 3735, "Ruby": 1286, "Swift": 404, "Kotlin": 134, "Objective-C": 38}
|
package com.fby.flutter.ml.vision.app
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0
|
Dart
|
0
| 0
|
e3b938bbce8f911b7eb44eee160e3a638c9108e3
| 134
|
flutter-ml-kit-vision
|
MIT License
|
tanker-bindings/src/main/kotlin/io/tanker/api/HttpClient.kt
|
TankerHQ
| 160,205,806
| false
|
{"Kotlin": 204429, "Python": 9014, "Java": 1665, "Assembly": 693, "CMake": 384, "C++": 373, "Shell": 174}
|
package io.tanker.api
import com.sun.jna.Memory
import com.sun.jna.Pointer
import io.tanker.bindings.TankerHttpRequest
import io.tanker.bindings.TankerHttpResponse
import io.tanker.bindings.TankerLib
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.IOException
class HttpClient(private val tankerLib: TankerLib, private val sdkType: String, private val sdkVersion: String) : TankerLib.HttpSendRequestCallback {
companion object {
val JSON = "application/json; charset=utf-8".toMediaTypeOrNull()!!
}
private val client = OkHttpClient()
internal val calls = HashMap<Int, Call>()
private var lastId = 0
override fun callback(crequest: TankerHttpRequest, data: Pointer?): Pointer? {
try {
val body =
when {
crequest.bodySize != 0 -> crequest.body?.getByteArray(0, crequest.bodySize)
crequest.method!! == "POST" ->
// okhttp really wants a body when we do a POST
byteArrayOf()
else ->
// okhttp really doesn't want a body when we do a GET (an empty body is not ok)
null
}
val requestBuilder = Request.Builder()
.url(crequest.url!!)
.method(crequest.method!!, body?.toRequestBody(JSON))
.header("X-Tanker-SdkType", sdkType)
.header("X-Tanker-SdkVersion", sdkVersion)
if (crequest.authorization != null)
requestBuilder.header("Authorization", crequest.authorization!!)
if (crequest.instanceId != null)
requestBuilder.header("X-Tanker-Instanceid", crequest.instanceId!!)
val request = requestBuilder.build()
val call = client.newCall(request)
val requestId = synchronized(this) {
val requestId = ++lastId
calls[requestId] = call
requestId
}
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
// Note that onFailure is called also for canceled requests, but we bail out
// before calling back sdk-native in that case
val cresponse = TankerHttpResponse()
cresponse.errorMsg = e.message
synchronized(this) {
if (calls.remove(requestId) == null)
return // the request was canceled
tankerLib.tanker_http_handle_response(crequest.pointer, cresponse)
}
}
override fun onResponse(call: Call, response: Response) {
response.use {
val cresponse = TankerHttpResponse()
cresponse.statusCode = it.code
cresponse.contentType = it.header("content-type")
val bodyData = it.body?.bytes()
if (bodyData != null && bodyData.isNotEmpty()) {
val bodyMemory = Memory(bodyData.size.toLong())
bodyMemory.write(0, bodyData, 0, bodyData.size)
cresponse.body = bodyMemory
cresponse.bodySize = bodyData.size.toLong()
}
synchronized(this) {
if (calls.remove(requestId) == null)
return // the request was canceled
tankerLib.tanker_http_handle_response(crequest.pointer, cresponse)
}
}
}
})
return Pointer.createConstant(requestId)
} catch (e: Throwable) {
val cresponse = TankerHttpResponse()
cresponse.errorMsg = "${e::class.java.canonicalName}: ${e.message}"
tankerLib.tanker_http_handle_response(crequest.pointer, cresponse)
return Pointer.NULL
}
}
}
class HttpClientCanceler(private val httpClient: HttpClient) : TankerLib.HttpCancelRequestCallback {
override fun callback(crequest: TankerHttpRequest, requestHandle: Pointer?, data: Pointer?) {
val requestId = Pointer.nativeValue(requestHandle).toInt()
synchronized(httpClient) {
val call = httpClient.calls.remove(requestId)
call?.cancel()
}
}
}
| 0
|
Kotlin
|
1
| 13
|
8bba26a4b6376669ea53712def3dcac6387005f7
| 4,668
|
sdk-android
|
Apache License 2.0
|
spring-social-slideshare/src/main/kotlin/io/t28/springframework/social/slideshare/api/impl/xml/FavoriteMixin.kt
|
t28hub
| 280,412,223
| false
| null |
/*
* 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.
*/
package io.t28.springframework.social.slideshare.api.impl.xml
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement
import io.t28.springframework.social.slideshare.api.Favorite
/**
* Annotated mixin to add annotations to [Favorite].
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@JacksonXmlRootElement(localName = "favorite")
internal interface FavoriteMixin {
@get:JacksonXmlProperty(localName = "slideshow_id")
val slideshowId: String
@get:JacksonXmlProperty(localName = "tag_text")
@get:JsonDeserialize(using = TagTextDeserializer::class)
val tags: List<String>
}
| 1
|
Kotlin
|
0
| 0
|
a87b4991dbe121f84253825a5c5dc147603be998
| 1,406
|
spring-social-slideshare
|
Apache License 2.0
|
android/app/src/main/java/uvg/edu/gt/smartfridge/models/LightIngredient.kt
|
DanielRasho
| 680,686,449
| false
|
{"Kotlin": 174774, "Rust": 90196, "Nix": 710}
|
package uvg.edu.gt.smartfridge.models
import kotlinx.serialization.Serializable
@Serializable
data class LightIngredient(
val Name: String,
val Display : String
)
| 0
|
Kotlin
|
0
| 0
|
db66b15b88c12123fad7b87db0f01b352a504019
| 173
|
SmartFridge
|
MIT License
|
android/app/src/main/kotlin/de/stuermerbenjamin/ble/ui/scan/ScanScreen.kt
|
thebino
| 518,865,547
| false
|
{"Kotlin": 52876, "C": 35607, "CMake": 2148, "C++": 685}
|
package de.stuermerbenjamin.ble.ui.scan
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.rememberScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.google.accompanist.navigation.animation.rememberAnimatedNavController
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.rememberPermissionState
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.SwipeRefreshIndicator
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
import de.stuermerbenjamin.ble.AppDestination
import de.stuermerbenjamin.ble.R
import de.stuermerbenjamin.ble.data.bluetooth.model.Device
import java.time.Instant
import org.koin.androidx.compose.getViewModel
import timber.log.Timber
/**
* Scan for nearby bluetooth LE devices and show a list.
*/
@Composable
fun ScanScreen(
navController: NavHostController = rememberAnimatedNavController()
) {
val viewModel: ScanViewModel = getViewModel()
if (viewModel.uiState.value.isBluetoothConnected) {
navController.navigate(AppDestination.Connected.route) {
popUpTo(AppDestination.Connected.route)
}
}
ScanScreen(
uiState = viewModel.uiState.value,
handleEvent = viewModel::handleEvent,
)
}
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun ScanScreen(
uiState: ScanUiState,
handleEvent: (event: ScanEvent) -> Unit
) {
val permissionState = rememberPermissionState(
android.Manifest.permission.BLUETOOTH_SCAN
)
LaunchedEffect(Unit) {
Timber.e("LaunchedEffect")
if (permissionState.hasPermission) {
handleEvent(ScanEvent.StartScan)
} else {
// TODO: start scan after permission has been granted
}
}
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner) {
onDispose {
handleEvent(ScanEvent.StopScan)
}
}
val scaffoldState = rememberScaffoldState()
Scaffold(
scaffoldState = scaffoldState,
topBar = {
TopAppBar(
title = {
Text(stringResource(id = R.string.scan_title))
},
backgroundColor = MaterialTheme.colors.surface
)
},
) {
SwipeRefresh(
state = rememberSwipeRefreshState(false),
onRefresh = { handleEvent(ScanEvent.StartScan) },
indicator = { state, trigger ->
SwipeRefreshIndicator(
state = state,
refreshTriggerDistance = trigger,
scale = true,
backgroundColor = MaterialTheme.colors.primary,
)
}
) {
Column(
modifier = Modifier
.padding(vertical = 8.dp)
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
text = stringResource(id = R.string.scan_description)
)
if (uiState.foundDevices.isNotEmpty()) {
LazyColumn {
items(
count = uiState.foundDevices.size,
) { item ->
val device = uiState.foundDevices[item]
BleDevice(
device = device,
onDeviceClick = {
handleEvent(ScanEvent.Connect(device))
}
)
}
}
}
}
}
}
}
@Preview(showSystemUi = true)
@Composable
private fun ScanScreenPreview() {
MaterialTheme {
ScanScreen(
uiState = ScanUiState(
foundDevices = listOf(
Device(
name = "IoT Device",
address = "aa:bb:cc:dd:ee:ff",
lastSeen = Instant.now().minusSeconds(1873),
device = null,
),
Device(
name = "IoT Device",
address = "aa:bb:cc:dd:ee:ff",
lastSeen = Instant.now().minusSeconds(23),
device = null,
),
)
),
handleEvent = {}
)
}
}
| 0
|
Kotlin
|
0
| 2
|
110ed892ae7f9aab82d810b92012e8f0767bb415
| 5,648
|
esp_iot_template
|
Apache License 2.0
|
src/main/kotlin/com/atsuya046/random/RandomizerRegistry.kt
|
atsuya046
| 123,290,518
| false
| null |
package com.atsuya046.random
import kotlin.reflect.KClass
internal abstract class AbstractRandomizerRegistry : Choosable, Registrable {
protected val randomizers: MutableMap<KClass<out Any>, Randomizer<Any>> = mutableMapOf()
override fun <T : Any> register(clazz: KClass<T>, randomizer: Randomizer<T>) {
randomizers.set(clazz, randomizer)
}
override fun <T : Any> choose(clazz: KClass<T>): List<Randomizer<T>> =
randomizers[clazz]?.let { listOf(it as Randomizer<T>) } ?: emptyList()
}
internal interface Choosable {
fun <T : Any> choose(clazz: KClass<T>): List<Randomizer<T>>
}
internal interface Registrable {
fun <T : Any> register(clazz: KClass<T>, randomizer: Randomizer<T>)
}
internal inline fun <reified T : Any> Registrable.register(randomizer: Randomizer<T>) = this.register(T::class, randomizer)
internal class RandomizerRegistry : AbstractRandomizerRegistry() {
private val customRegistry = CustomRandomizerRegistry()
private val registries: List<AbstractRandomizerRegistry> = listOf(customRegistry, InnerRandomizerRegistry)
override fun <T : Any> register(clazz: KClass<T>, randomizer: Randomizer<T>) = customRegistry.register(clazz, randomizer)
override fun <T : Any> choose(clazz: KClass<T>): List<Randomizer<T>> =
registries.foldRight(emptyList()) { registry, randomizers ->
registry.choose(clazz) + randomizers
}
}
internal object InnerRandomizerRegistry : AbstractRandomizerRegistry() {
init {
register(IntRandomizer)
register(LongRandomizer)
register(FloatRandomizer)
register(DoubleRandomizer)
register(StringRandomizer)
register(CharArrayRandomizer)
register(BooleanRandomizer)
}
}
internal class CustomRandomizerRegistry : AbstractRandomizerRegistry()
| 0
|
Kotlin
|
1
| 2
|
a39c165329d36c4a5dc9675aa3d87b2f018fa940
| 1,848
|
random-seed-kotlin
|
MIT License
|
photoselector/src/test/java/software/ninetofive/photoselector/PhotoSelectorTest.kt
|
Borek321
| 242,739,859
| false
| null |
package software.ninetofive.photoselector
import android.app.Activity
import android.app.Dialog
import android.content.ContentResolver
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import com.nhaarman.mockitokotlin2.*
import org.junit.Assert.assertEquals
import org.junit.Assert.fail
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito
import software.ninetofive.photoselector.exception.GenericException
import software.ninetofive.photoselector.exception.PhotoSelectorException
import software.ninetofive.photoselector.exception.RequiredOptionException
import software.ninetofive.photoselector.factory.DialogFactory
import software.ninetofive.photoselector.factory.FileUriFactory
import software.ninetofive.photoselector.factory.IntentFactory
import software.ninetofive.photoselector.interfaces.PhotoSelectorListener
import software.ninetofive.photoselector.util.BitmapUtil
import software.ninetofive.photoselector.util.FileUtil
import software.ninetofive.photoselector.util.MimeUtil
import software.ninetofive.photoselector.util.PermissionUtil
import java.io.File
class PhotoSelectorTest {
lateinit var dialogFactory: DialogFactory
lateinit var permissionUtil: PermissionUtil
lateinit var intentFactory: IntentFactory
lateinit var fileUtil: FileUtil
lateinit var fileUriFactory: FileUriFactory
lateinit var mimeUtil: MimeUtil
lateinit var bitmapUtil: BitmapUtil
lateinit var photoSelector: PhotoSelector
@Before
fun setUp() {
dialogFactory = mock()
permissionUtil = mock()
intentFactory = mock()
fileUriFactory = mock()
fileUtil = mock()
mimeUtil = mock()
bitmapUtil = mock()
photoSelector = PhotoSelector(dialogFactory, permissionUtil, intentFactory, fileUtil, fileUriFactory, mimeUtil, bitmapUtil)
}
@Test
fun start_doesNothingWhenAuthorityNotProvidedAreNotValidAndCallsListener() {
val options: Map<PhotoSelector.Options, Any> = mapOf()
val activity: Activity = mock()
photoSelector.start(activity = activity, options = options, listener = object : PhotoSelectorListener {
override fun onSuccessPhotoSelected(imageFile: File) {
fail()
}
override fun onFailurePhotoSelected(exception: PhotoSelectorException) {
assertEquals(
RequiredOptionException(
PhotoSelector.Options.FILE_PROVIDER_AUTHORITY_NAME
).message, exception.message)
}
})
verifyZeroInteractions(dialogFactory)
}
@Test
fun start_doesNothingWhenHandlerNotProvidedButRequireddAndCallsListener() {
val options: Map<PhotoSelector.Options, Any> = mapOf(PhotoSelector.Options.FILE_PROVIDER_AUTHORITY_NAME to "asdf")
val activity: Activity = mock()
Mockito.`when`(permissionUtil.shouldShowRationale(activity, null)).thenReturn(true)
photoSelector.start(activity = activity, options = options, listener = object : PhotoSelectorListener {
override fun onSuccessPhotoSelected(imageFile: File) {
fail()
}
override fun onFailurePhotoSelected(exception: PhotoSelectorException) {
assertEquals(
RequiredOptionException(
PhotoSelector.Options.RATIONALE_HANDLER
).message, exception.message)
}
})
verifyZeroInteractions(dialogFactory)
}
@Test
fun start_showsDialog() {
val options: Map<PhotoSelector.Options, Any> = mapOf(PhotoSelector.Options.FILE_PROVIDER_AUTHORITY_NAME to "asdf")
val activity: Activity = mock()
val dialog: Dialog = mock()
doNothing().`when`(dialog).show()
Mockito.`when`(permissionUtil.shouldShowRationale(eq(activity), any())).thenReturn(false)
Mockito.`when`(dialogFactory.createTypeSelectionDialog(eq(activity), any(), any(), any(), any(), any())).then {
dialog
}
photoSelector.start(activity = activity, options = options, listener = mock())
verify(dialog).show()
}
@Test
fun startTakePicture_doesNothingWhenAuthorityNotProvidedAreNotValidAndCallsListener() {
val options: Map<PhotoSelector.Options, Any> = mapOf()
val activity: Activity = mock()
photoSelector.startTakePicture(activity = activity, options = options, listener = object : PhotoSelectorListener {
override fun onSuccessPhotoSelected(imageFile: File) {
fail()
}
override fun onFailurePhotoSelected(exception: PhotoSelectorException) {
assertEquals(
RequiredOptionException(
PhotoSelector.Options.FILE_PROVIDER_AUTHORITY_NAME
).message, exception.message)
}
})
verifyZeroInteractions(dialogFactory)
}
@Test
fun startTakePicture_doesNothingWhenHandlerNotProvidedButRequireddAndCallsListener() {
val options: Map<PhotoSelector.Options, Any> = mapOf(PhotoSelector.Options.FILE_PROVIDER_AUTHORITY_NAME to "asdf")
val activity: Activity = mock()
Mockito.`when`(permissionUtil.shouldShowRationale(activity, null)).thenReturn(true)
photoSelector.startTakePicture(activity = activity, options = options, listener = object : PhotoSelectorListener {
override fun onSuccessPhotoSelected(imageFile: File) {
fail()
}
override fun onFailurePhotoSelected(exception: PhotoSelectorException) {
assertEquals(
RequiredOptionException(
PhotoSelector.Options.RATIONALE_HANDLER
).message, exception.message)
}
})
verifyZeroInteractions(dialogFactory)
}
@Test
fun startTakePicture_requestsPermissionIfNoPermissions() {
val options: Map<PhotoSelector.Options, Any> = mapOf(PhotoSelector.Options.FILE_PROVIDER_AUTHORITY_NAME to "asdf")
val activity: Activity = mock()
Mockito.`when`(permissionUtil.shouldShowRationale(eq(activity), any())).thenReturn(false)
Mockito.`when`(permissionUtil.hasCameraPermission(activity)).doReturn(false)
photoSelector.startTakePicture(activity = activity, options = options, listener = mock())
verify(permissionUtil).requestCameraPermissions(activity, null)
}
@Test
fun startTakePicture_createsImageAndStartsActivity() {
val options: Map<PhotoSelector.Options, Any> = mapOf(PhotoSelector.Options.FILE_PROVIDER_AUTHORITY_NAME to "asdf")
val activity: Activity = mock()
val imageFile: File = mock()
val intent: Intent = mock()
Mockito.`when`(permissionUtil.shouldShowRationale(eq(activity), any())).thenReturn(false)
Mockito.`when`(permissionUtil.hasCameraPermission(activity)).doReturn(true)
Mockito.`when`(fileUtil.createImageFile(activity, "jpeg")).thenReturn(imageFile)
Mockito.`when`(intentFactory.createTakePictureIntent(activity)).thenReturn(intent)
photoSelector.startTakePicture(activity = activity, options = options, listener = mock())
verify(intentFactory).createTakePictureIntent(activity)
verify(fileUriFactory).createUriForFile(imageFile, "asdf", activity)
verify(activity).startActivityForResult(eq(intent), any())
}
@Test
fun startSelectImage_startsActivity() {
val activity: Activity = mock()
val intent: Intent = mock()
Mockito.`when`(intentFactory.createSelectImageIntent(activity)).doReturn(intent)
photoSelector.startSelectImage(activity, options = mapOf(), listener = mock())
verify(activity).startActivityForResult(eq(intent), any())
}
@Test
fun onActivityResult_callsOnFailureIfSomethingWentWrong() {
val activity: Activity = mock()
val intent: Intent = mock()
Mockito.`when`(intentFactory.createSelectImageIntent(activity)).doReturn(intent)
photoSelector.startSelectImage(activity, options = mapOf(), listener = object : PhotoSelectorListener {
override fun onSuccessPhotoSelected(imageFile: File) {
fail()
}
override fun onFailurePhotoSelected(exception: PhotoSelectorException) {
assertEquals(GenericException().message, exception.message)
}
})
photoSelector.onActivityResult(24, Activity.RESULT_OK - 1, mock())
}
@Test
fun onActivityResult_TakePicture_callsOnFailureIfNoFile() {
val activity: Activity = mock()
val intent: Intent = mock()
Mockito.`when`(intentFactory.createSelectImageIntent(activity)).doReturn(intent)
photoSelector.startSelectImage(activity, options = mapOf(), listener = object : PhotoSelectorListener {
override fun onSuccessPhotoSelected(imageFile: File) {
fail()
}
override fun onFailurePhotoSelected(exception: PhotoSelectorException) {
assertEquals(GenericException().message, exception.message)
}
})
photoSelector.onActivityResult(PhotoSelector.TAKE_PICTURE_REQUEST_CODE, Activity.RESULT_OK, mock())
}
@Test
fun onActivityResult_TakePicture_callsOnSuccessIfFile() {
val options: Map<PhotoSelector.Options, Any> = mapOf(PhotoSelector.Options.FILE_PROVIDER_AUTHORITY_NAME to "asdf")
val activity: Activity = mock()
val imageFile: File = mock()
val intent: Intent = mock()
Mockito.`when`(permissionUtil.shouldShowRationale(eq(activity), any())).thenReturn(false)
Mockito.`when`(permissionUtil.hasCameraPermission(activity)).doReturn(true)
Mockito.`when`(fileUtil.createImageFile(activity, "jpeg")).thenReturn(imageFile)
Mockito.`when`(intentFactory.createTakePictureIntent(activity)).thenReturn(intent)
photoSelector.startTakePicture(activity = activity, options = options, listener = object : PhotoSelectorListener {
override fun onSuccessPhotoSelected(file: File) {
assertEquals(imageFile, file)
}
override fun onFailurePhotoSelected(exception: PhotoSelectorException) {
fail()
}
})
photoSelector.onActivityResult(PhotoSelector.TAKE_PICTURE_REQUEST_CODE, Activity.RESULT_OK, mock())
}
@Test
fun onActivityResult_selectImage_persistsImageAndCallsSuccess() {
val contentResolver: ContentResolver = mock()
val activity: Activity = mock {
on { this.contentResolver } doReturn contentResolver
}
val intent: Intent = mock()
val uri: Uri = mock()
val bitmap: Bitmap = mock()
val imageFile: File = mock()
val mimeType = "mime"
val dataIntent: Intent = mock {
on { this.data } doReturn uri
}
Mockito.`when`(intentFactory.createSelectImageIntent(activity)).doReturn(intent)
Mockito.`when`(mimeUtil.getMimeType(contentResolver, uri)).doReturn(mimeType)
Mockito.`when`(bitmapUtil.getBitmap(contentResolver, uri)).doReturn(bitmap)
Mockito.`when`(fileUtil.persistBitmap(activity, bitmap, mimeType)).doReturn(imageFile)
photoSelector.startSelectImage(activity, options = mapOf(), listener = object : PhotoSelectorListener {
override fun onSuccessPhotoSelected(file: File) {
assertEquals(imageFile, file)
}
override fun onFailurePhotoSelected(exception: PhotoSelectorException) {
fail()
}
})
photoSelector.onActivityResult(PhotoSelector.SELECT_IMAGE_REQUEST_CODE, Activity.RESULT_OK, dataIntent)
}
@Test
fun allowedRationale_setsIsRationaleShownAndWillAskPermission() {
val options: Map<PhotoSelector.Options, Any> = mapOf(
PhotoSelector.Options.FILE_PROVIDER_AUTHORITY_NAME to "asdf",
PhotoSelector.Options.RATIONALE_HANDLER to { }
)
val activity: Activity = mock()
Mockito.`when`(permissionUtil.shouldShowRationale(eq(activity), any())).thenReturn(true)
Mockito.`when`(permissionUtil.hasCameraPermission(activity)).doReturn(false)
photoSelector.startTakePicture(activity = activity, options = options, listener = mock())
photoSelector.allowedRationale()
verify(permissionUtil, times(2)).requestCameraPermissions(activity)
}
}
| 0
|
Kotlin
|
0
| 1
|
b9d69134827d1face68c136760bb0f3215c6118c
| 12,657
|
9to5-tools
|
MIT License
|
app/src/main/java/com/alanLobo/nycschools/data/entities/SchoolDetails.kt
|
alanl279447
| 342,117,687
| false
| null |
package com.example.nycschools.data.entities
class SchoolDetails : ArrayList<SchoolDetailsItem>()
| 0
|
Kotlin
|
0
| 0
|
6a4e4e7264be6f47e8e74dd47bd4c4e43f0ea8e7
| 98
|
20210224-AlanLobo-NYCSchools
|
Apache License 2.0
|
dlang/psi-impl/src/main/kotlin/io/github/intellij/dlanguage/psi/ext/DLanguageCommaExpressionImplMixin.kt
|
intellij-dlanguage
| 27,922,930
| false
|
{"D": 1787183, "Kotlin": 1068238, "Java": 834373, "Lex": 22913, "DTrace": 3220, "HTML": 1386, "Makefile": 457}
|
package io.github.intellij.dlanguage.psi.ext
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import io.github.intellij.dlanguage.psi.DLanguageCommaExpression
import io.github.intellij.dlanguage.psi.types.DPrimitiveType
import io.github.intellij.dlanguage.psi.types.DType
abstract class DLanguageCommaExpressionImplMixin(node: ASTNode) : ASTWrapperPsiElement(node),
DLanguageCommaExpression {
override fun getDType(): DType? = DPrimitiveType.fromText("void")
}
| 160
|
D
|
51
| 328
|
298d1db45d2b35c1715a1b1b2e1c548709101f05
| 509
|
intellij-dlanguage
|
MIT License
|
app/src/main/java/io/github/drumber/kitsune/data/repository/MediaUnitRepository.kt
|
Drumber
| 406,471,554
| false
|
{"Kotlin": 993796, "Ruby": 2109}
|
package io.github.drumber.kitsune.data.repository
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.map
import io.github.drumber.kitsune.constants.Repository
import io.github.drumber.kitsune.data.mapper.MediaUnitMapper.toMediaUnit
import io.github.drumber.kitsune.data.source.network.media.ChapterNetworkDataSource
import io.github.drumber.kitsune.data.source.network.media.ChapterPagingDataSource
import io.github.drumber.kitsune.data.source.network.media.EpisodeNetworkDataSource
import io.github.drumber.kitsune.data.source.network.media.EpisodePagingDataSource
import io.github.drumber.kitsune.data.common.Filter
import kotlinx.coroutines.flow.map
class MediaUnitRepository(
private val episodeNetworkDataSource: EpisodeNetworkDataSource,
private val chapterNetworkDataSource: ChapterNetworkDataSource
) {
fun mediaUnitPager(type: MediaUnitType, filter: Filter, pageSize: Int) = Pager(
config = PagingConfig(
pageSize = pageSize,
maxSize = Repository.MAX_CACHED_ITEMS
),
pagingSourceFactory = {
when (type) {
MediaUnitType.EPISODE -> EpisodePagingDataSource(episodeNetworkDataSource, filter.pageLimit(pageSize))
MediaUnitType.CHAPTER -> ChapterPagingDataSource(chapterNetworkDataSource, filter.pageLimit(pageSize))
}
}
).flow.map { pagingData ->
pagingData.map { it.toMediaUnit() }
}
enum class MediaUnitType {
EPISODE,
CHAPTER
}
}
| 6
|
Kotlin
|
4
| 92
|
ba6f2a69cb71a9fd71d4825921ff6d9b6300471e
| 1,541
|
Kitsune
|
Apache License 2.0
|
AndroidArchitectureStudy/presentation/src/main/java/com/mtjin/presentation/views/search/MovieSearchViewModel.kt
|
mtjin
| 333,763,532
| false
| null |
package com.mtjin.presentation.views.search
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.mtjin.domain.model.search.Movie
import com.mtjin.domain.usecase.GetLocalMoviesUseCase
import com.mtjin.domain.usecase.GetMoviesUseCase
import com.mtjin.domain.usecase.GetPagingMoviesUseCase
import com.mtjin.presentation.base.BaseViewModel
import com.mtjin.data.utils.LAST_PAGE
import com.mtjin.presentation.utils.NetworkManager
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
open class MovieSearchViewModel(
private val getMoviesUseCase: GetMoviesUseCase,
private val getPagingMoviesUseCase: GetPagingMoviesUseCase,
private val getLocalMoviesUseCase: GetLocalMoviesUseCase,
private val networkManager: NetworkManager
) : BaseViewModel() {
private var currentQuery: String = "" // 현재 검색어
val query = MutableLiveData<String>() // 검색어(EditText two-way binding)
private val _movieList = MutableLiveData<MutableList<Movie>>() // 영화리스트
private val _toastMsg = MutableLiveData<MessageSet>() //검색결과 토스트 메시지
val movieList: LiveData<MutableList<Movie>> get() = _movieList
val toastMsg: LiveData<MessageSet> get() = _toastMsg
// 영화검색 (15개)
fun requestMovie() {
currentQuery = query.value.toString().trim()
if (currentQuery.isEmpty()) {
_toastMsg.value = MessageSet.EMPTY_QUERY
return
}
if (!checkNetworkState()) return //네트워크연결 유무
compositeDisposable.add(
getMoviesUseCase.execute(currentQuery)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe { showProgress() }
.doAfterTerminate { hideProgress() }
.subscribe({ movies ->
if (movies.isEmpty()) {
_toastMsg.value = MessageSet.NO_RESULT
} else {
_movieList.value = movies as ArrayList<Movie>
_toastMsg.value = MessageSet.SUCCESS
}
}, {
_toastMsg.value = MessageSet.ERROR
})
)
}
// 검색한 영화 더 불러오기(페이징, 무한스크롤)
fun requestPagingMovie(offset: Int) {
if (!checkNetworkState()) return //네트워크연결 유무
compositeDisposable.add(
getPagingMoviesUseCase.execute(currentQuery, offset)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe { showProgress() }
.doAfterTerminate { hideProgress() }
.subscribe({ movies ->
val pagingMovieList = _movieList.value
pagingMovieList?.addAll(movies)
_movieList.value = pagingMovieList
_toastMsg.value = MessageSet.SUCCESS
}, {
when (it.message) {
LAST_PAGE -> _toastMsg.value = MessageSet.LAST_PAGE
else -> _toastMsg.value = MessageSet.ERROR
}
})
)
}
private fun checkNetworkState(): Boolean {
return if (networkManager.checkNetworkState()) {
true
} else {
requestLocalMovies()
false
}
}
private fun requestLocalMovies() {
compositeDisposable.add(
getLocalMoviesUseCase.execute(currentQuery)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe { showProgress() }
.doAfterTerminate { hideProgress() }
.subscribe({ movies ->
if (movies.isEmpty()) {
_toastMsg.value = MessageSet.NETWORK_NOT_CONNECTED
} else {
_movieList.value = movies as ArrayList<Movie>
_toastMsg.value = MessageSet.LOCAL_SUCCESS
}
}, {
_toastMsg.value = MessageSet.NETWORK_NOT_CONNECTED
})
)
}
enum class MessageSet {
LAST_PAGE,
EMPTY_QUERY,
NETWORK_NOT_CONNECTED,
ERROR,
SUCCESS,
NO_RESULT,
LOCAL_SUCCESS
}
}
| 1
|
Kotlin
|
1
| 9
|
edc3e6aad017063bf00ef17126eb9aae7100bdb8
| 4,402
|
mtjin-android-clean-architecture-movieapp
|
MIT License
|
src/main/kotlin/com/github/parkee/messenger/model/response/ResponseRecipient.kt
|
parkee
| 58,060,512
| false
| null |
package com.github.parkee.messenger.model.response
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
@JsonIgnoreProperties(ignoreUnknown = true)
data class ResponseRecipient(
@JsonProperty("id") val id: Long? = null
)
| 0
|
Kotlin
|
3
| 5
|
ddde00d68f36f26978426cfe5ebb1a6cecb310af
| 291
|
messenger-send-api-client
|
MIT License
|
app/src/main/java/dev/marcosfarias/pokedex/ui/dashboard/evolution/EvolutionFragment.kt
|
zsmb13
| 232,301,179
| true
| null |
package dev.marcosfarias.pokedex.ui.dashboard.evolution
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProviders
import dev.marcosfarias.pokedex.R
import dev.marcosfarias.pokedex.ui.dashboard.DashboardViewModel
class EvolutionFragment : Fragment() {
private lateinit var dashboardViewModel: DashboardViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
dashboardViewModel = ViewModelProviders.of(this).get(DashboardViewModel::class.java)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_evolution, container, false)
}
}
| 0
|
Kotlin
|
8
| 48
|
a2ab162c1de76700e16ba521b1193c503b6b3f84
| 894
|
Kotlin-Pokedex
|
MIT License
|
Repairs/app/src/main/java/com/rooio/repairs/ChooseServiceProvider.kt
|
roopairs
| 212,211,326
| false
|
{"XML": 431086, "Kotlin": 299391, "Java": 26386}
|
package com.rooio.repairs
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.media.AudioManager
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.appcompat.widget.AppCompatEditText
import androidx.arch.core.util.Function
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.volley.Request
import org.json.JSONArray
// For job requests, after the user chooses a piece of equipment
class ChooseServiceProvider : RestApi() {
private lateinit var serviceProviderList: RecyclerView
private lateinit var searchBar : AppCompatEditText
private lateinit var preferredButton: Button
private lateinit var networkButton: Button
private lateinit var backButton: ImageView
private lateinit var networkText: TextView
private lateinit var errorMessage: TextView
private lateinit var loadingPanel: ProgressBar
private var providerDataList: ArrayList<ProviderData> = ArrayList()
private lateinit var adapter: ChooseServiceProviderAdapter
private var equipmentId: String = "1"
private var equipmentType: Int = 1
private lateinit var noProviderMessage: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_choose_service_provider)
// gets rid of sound when the user clicks on the spinner when editing the equipment type
onResume()
initializeVariables()
setActionBar()
populateList()
onPreferred()
onNetwork()
onBackClick()
onPause()
}
//Initializes UI variables
private fun initializeVariables() {
serviceProviderList = findViewById(R.id.serviceProviderList)
searchBar = findViewById(R.id.searchBar)
preferredButton = findViewById(R.id.preferredButton)
networkButton = findViewById(R.id.networkButton)
networkText = findViewById(R.id.networkText)
errorMessage = findViewById(R.id.errorMessage)
backButton = findViewById(R.id.backButton)
loadingPanel = findViewById(R.id.loadingPanel)
noProviderMessage = findViewById(R.id.noProvider)
}
//Click to go back to Dashboard
private fun onBackClick() {
backButton.setOnClickListener{
val intent = Intent(this@ChooseServiceProvider, ChooseEquipment::class.java)
intent.putExtra("equipmentType", equipmentType)
startActivity(intent)
}
}
//Populates a list from API call
private fun populateList() {
loadingPanel.visibility = View.VISIBLE
val id = intent.getStringExtra("equipment")
if (id != null) equipmentId = id
else equipmentId = ""
equipmentType = intent.getIntExtra("type", 1)
val request = JsonRequest(false, "service-providers/?servicable_equipment_type_id=$equipmentType", null, providerResponseFunc, providerErrorFunc, true)
requestJson(Request.Method.GET, JsonType.ARRAY, request)
}
//Response from the API call after getting providers
@JvmField
var providerResponseFunc = Function<Any, Void?> { response: Any? ->
loadingPanel.visibility = View.GONE
val jsonArray = response as JSONArray
loadServiceProviders(jsonArray)
null
}
//Response from the API call if there is an error
@JvmField
var providerErrorFunc = Function<String, Void?> { error: String? ->
loadingPanel.visibility = View.GONE
errorMessage.text = error
null
}
//Parses JSONArray for service provider information
private fun loadServiceProviders(response: JSONArray) {
providerDataList.clear()
for (i in 0 until response.length()) {
val provider = ProviderData(response.getJSONObject(i))
providerDataList.add(provider)
}
changeAdapter()
}
// When preferred tab is clicked, set page to list
private fun onPreferred() {
preferredButton.setOnClickListener{
preferredButton.setBackgroundResource(R.drawable.provider_tab)
preferredButton.setTextColor(Color.parseColor("#00CA8F"))
networkButton.setBackgroundResource(R.drawable.blank_border)
networkButton.setTextColor(Color.parseColor("#6D7377"))
networkText.visibility = View.GONE
serviceProviderList.visibility = View.VISIBLE
}
}
// When network tab is clicked, set page to message
private fun onNetwork() {
networkButton.setOnClickListener{
networkButton.setBackgroundResource(R.drawable.provider_tab)
networkButton.setTextColor(Color.parseColor("#00CA8F"))
preferredButton.setBackgroundResource(R.drawable.blank_border)
preferredButton.setTextColor(Color.parseColor("#6D7377"))
networkText.visibility = View.VISIBLE
serviceProviderList.visibility = View.GONE
}
}
//Sets the list adapter to a custom one that handles providers
private fun changeAdapter() {
adapter = ChooseServiceProviderAdapter(this, providerDataList, equipmentId)
val layoutManager = LinearLayoutManager(this)
serviceProviderList.layoutManager = layoutManager
serviceProviderList.adapter = adapter
if (adapter.checkList() == 0)
{
//make the no equipment message visible
noProviderMessage.visibility = View.VISIBLE
}
else {
noProviderMessage.visibility = View.INVISIBLE
}
setFilter()
}
//Sets the filter on the list
private fun setFilter() {
searchBar.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
adapter.filter(charSequence.toString())
if (adapter.checkList() == 0)
{
//make the no equipment message visible
noProviderMessage.visibility = View.VISIBLE
}
else {
noProviderMessage.visibility = View.INVISIBLE
}
}
override fun afterTextChanged(editable: Editable) {}
})
}
}
| 0
|
XML
|
0
| 0
|
e81487aba0a997812769e893dc8e34d21935647f
| 6,684
|
Rooio
|
MIT License
|
contrib/rqjava/src/com/dhsdevelopments/rqjava/PotatoConnection.kt
|
cicakhq
| 48,153,988
| false
| null |
package com.dhsdevelopments.rqjava
import com.google.gson.Gson
import com.rabbitmq.client.*
import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.InputStreamReader
import java.nio.charset.Charset
import java.util.logging.Level
import java.util.logging.Logger
class PotatoConnection(val host: String,
val virtualHost: String,
val username: String,
val password: String) {
companion object {
val SEND_MESSAGE_EXCHANGE_NAME = "chat-image-response-ex"
}
private var conn: Connection? = null
val amqpConn: Connection
get() = conn!!
fun connect() {
val fac = ConnectionFactory()
fac.virtualHost = virtualHost
fac.username = username
fac.password = password
fac.host = host
conn = fac.newConnection()
}
fun disconnect() {
val connCopy = synchronized(this) {
conn.apply { conn = null }
}
if (connCopy == null) {
throw IllegalStateException("Already disconnected")
}
connCopy.close()
}
fun subscribeChannel(cid: String, callback: (Message) -> Unit): ChannelSubscription {
return ChannelSubscription(this, cid, callback)
}
fun registerCmd(cmd: String, callback: (Command) -> Unit): CmdRegistration {
return CmdRegistration(this, cmd, callback)
}
fun sendMessage(sender: String, cid: String, text: String, extraHtml: String? = null) {
val channel = amqpConn.createChannel()
try {
val content = StringBuilder()
content.append("(:POST (\"")
content.append(cid)
content.append("\" :SENDER \"")
content.append(sender)
content.append("\" :TEXT \"")
content.append(escapeSexpString(text))
content.append("\"")
if(extraHtml != null) {
content.append(" :EXTRA-HTML \"")
content.append(escapeSexpString(extraHtml))
content.append("\"")
}
content.append("))")
channel.basicPublish(SEND_MESSAGE_EXCHANGE_NAME, cid, null, content.toString().toByteArray(CHARSET_NAME_UTF8))
}
finally {
channel.close()
}
}
private fun escapeSexpString(text: String) = text.replace("\"", "\\\"")
}
| 1
|
Common Lisp
|
16
| 168
|
88b6c92dbbc80a6c9552435604f7b1ae6f2a4026
| 2,414
|
potato
|
Apache License 2.0
|
app/src/main/java/info/hzvtc/hipixiv/util/AppMessage.kt
|
Tait4198
| 94,422,381
| false
| null |
package info.hzvtc.hipixiv.util
import android.content.Context
import android.util.Log
import android.widget.Toast
class AppMessage {
companion object{
fun toastMessageLong(resId : Int,context: Context){
Toast.makeText(context,context.getString(resId),Toast.LENGTH_LONG).show()
}
fun toastMessageShort(resId : Int,context: Context){
Toast.makeText(context,context.getString(resId),Toast.LENGTH_SHORT).show()
}
fun toastMessageLong(msg : String,context: Context){
Toast.makeText(context,msg,Toast.LENGTH_LONG).show()
}
fun toastMessageShort(msg : String,context: Context){
Toast.makeText(context,msg,Toast.LENGTH_SHORT).show()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
35def2de39973a82e0fcf03f63733bb34c32d98d
| 757
|
hi_pixiv
|
MIT License
|
ktoroauth2/src/main/java/com/eldersoss/ktoroauth2/OAuth2.kt
|
Elders
| 421,793,019
| false
| null |
package com.eldersoss.ktoroauth2
import com.eldersoss.ktoroauth2.authorizer.Authorizer
import com.eldersoss.ktoroauth2.throwable.*
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.features.*
import io.ktor.client.request.*
import io.ktor.client.request.forms.*
import io.ktor.client.statement.*
import io.ktor.client.utils.*
import io.ktor.http.*
import io.ktor.http.auth.*
import io.ktor.util.*
import io.ktor.util.pipeline.*
import io.ktor.utils.io.core.*
class OAuth2 {
internal var authorizer: Authorizer? = null
companion object Feature : HttpClientFeature<OAuth2, OAuth2> {
val authRequestAttribute = AttributeKey<Unit>("AuthenticationRequest")
override val key: AttributeKey<OAuth2> = AttributeKey("DigestAuth")
override fun prepare(block: OAuth2.() -> Unit): OAuth2 {
return OAuth2().apply(block)
}
override fun install(feature: OAuth2, scope: HttpClient) {
scope.requestPipeline.intercept(HttpRequestPipeline.State) {
if (this.context.attributes.contains(authRequestAttribute)) return@intercept
feature.authorizer?.authorize(this.context, scope)
}
scope.requestPipeline.intercept(HttpRequestPipeline.Before) {
try {
proceedWith(it)
} catch (cause: Throwable) {
try {
(cause as ResponseException).response.receive<OAuth2Error>().getException()
} catch (t: Throwable) {
null
}?.let { oAuth2Exception ->
throw oAuth2Exception
}
val unwrappedCause = cause.unwrapCancellationException()
throw unwrappedCause
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
aec463d3b5d0f1bc5229cb09a2c26d69f8b00da6
| 1,874
|
KtorOAuth2
|
MIT License
|
app/src/main/java/com/dew/aihua/download/background/DownloadMissionManagerImpl.kt
|
ed828a
| 172,828,123
| false
| null |
package com.dew.aihua.download.background
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.util.Log
import android.widget.Toast
import com.dew.aihua.database.downloadDB.MissionEntity
import com.dew.aihua.download.background.MissionControl.Companion.NO_ERROR
import com.dew.aihua.download.ui.activity.ExtSDDownloadFailedActivity
import com.dew.aihua.util.Utility
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableCompletableObserver
import java.io.File
import java.io.IOException
import java.io.RandomAccessFile
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
/**
* Created by Edward on 3/2/2019.
*/
class DownloadMissionManagerImpl(
directories: Collection<String>,
val context: Context
) : DownloadMissionManager {
private val mDownloadDataSource: DownloadMissionDataSource = DownloadMissionDataSourceImpl(context)
private val mMissionControls = ArrayList<MissionControl>()
init {
loadMissionControls(directories)
}
// return: the index of this missionControl in the Array<MissionControl>
override fun startMission(url: String, location: String, name: String, isAudio: Boolean, threads: Int): Int {
var fileName = name
val existingMission = getMissionByLocation(location, fileName)
if (existingMission != null) {
// Already downloaded or downloading
if (existingMission.finished) {
// Overwrite missionControl
deleteMission(mMissionControls.indexOf(existingMission))
} else {
// Rename file (?)
try {
fileName = generateUniqueName(location, fileName)
} catch (e: Exception) {
Log.e(TAG, "Unable to generate unique name", e)
fileName = System.currentTimeMillis().toString() + fileName
Log.i(TAG, "Using $fileName")
}
}
}
val missionEntity = MissionEntity(fileName, url, location)
val missionControl = MissionControl(missionEntity)
missionControl.mission.timestamp = System.currentTimeMillis()
missionControl.threadCount = threads
missionControl.addListener(MissionControlListener(missionControl))
Initializer(missionControl).start()
return insertMission(missionControl)
}
override fun resumeMission(missionId: Int) {
val missionControl = getMission(missionId)
if (!missionControl.running && missionControl.errCode == NO_ERROR) {
missionControl.start()
}
}
override fun pauseMission(missionId: Int) {
val missionControl = getMission(missionId)
if (missionControl.running) {
missionControl.pause()
}
}
override fun deleteMission(missionId: Int) {
val missionControl = getMission(missionId)
if (missionControl.finished) {
val disposable = mDownloadDataSource.deleteMission(missionControl).subscribe()
disposable.dispose()
}
missionControl.delete()
mMissionControls.removeAt(missionId)
}
private fun loadMissionControls(searchLocations: Iterable<String>) {
mMissionControls.clear()
Thread(Runnable {
loadFinishedMissions()
}).start()
for (location in searchLocations) {
loadMissionControls(location)
}
}
/**
* Loads finished missions getTabFrom the data source
*/
private fun loadFinishedMissions() {
val finishedMissions = ArrayList<MissionControl>()
val disposable = mDownloadDataSource.loadMissions()
.subscribe {
finishedMissions.addAll(it)
}
disposable.dispose()
sortByTimestamp(finishedMissions)
mMissionControls.ensureCapacity(mMissionControls.size + finishedMissions.size)
for (missionControl in finishedMissions) {
val downloadedFile = missionControl.downloadedFile
if (!downloadedFile.isFile) {
Log.d(TAG, "file ${downloadedFile.absolutePath} removed getTabFrom Database.")
mDownloadDataSource.deleteMission(missionControl)
.subscribe {
Log.d(TAG, "removed one missionEntry getTabFrom Database")
}
.dispose()
} else {
missionControl.length = downloadedFile.length()
missionControl.finished = true
missionControl.running = false
mMissionControls.add(missionControl)
}
}
}
private fun loadMissionControls(location: String) {
val file = File(location)
if (file.exists() && file.isDirectory) {
val subs = file.listFiles() // get the list of files under the Directory
if (subs == null) {
Log.e(TAG, "listFiles() returned null, no files under the directory")
return
}
for (sub in subs) {
if (sub.isFile && sub.name.endsWith(".giga")) {
val missionControl = Utility.readFromFile<MissionControl>(sub.absolutePath)
if (missionControl != null) {
if (missionControl.finished) {
if (!sub.delete()) {
Log.w(TAG, "Unable to delete .giga file: ${sub.path}")
}
continue
}
missionControl.running = false
missionControl.recovered = true
insertMission(missionControl)
}
}
}
}
}
override fun getMission(missionId: Int): MissionControl {
Log.d(TAG, "mMissionControls: $mMissionControls")
return mMissionControls[missionId]
}
override val count: Int
get() = mMissionControls.size
private fun insertMission(missionControl: MissionControl): Int {
var index = -1
var mc: MissionControl
// looking for the right index
if (mMissionControls.size > 0) {
do {
mc = mMissionControls[++index]
} while (mc.mission.timestamp > missionControl.mission.timestamp && index < mMissionControls.size - 1)
} else {
index = 0
}
mMissionControls.add(index, missionControl)
return index
}
/**
* Get a missionControl by its location and name
*
* @param location the location
* @param name the file name
* @return the missionControl or null if no such missionControl exists
*/
private fun getMissionByLocation(location: String, name: String): MissionControl? {
for (missionControl in mMissionControls) {
if (location == missionControl.mission.location && name == missionControl.mission.name) {
return missionControl
}
}
return null
}
private inner class Initializer(private val missionControl: MissionControl) : Thread() {
private val handler: Handler = Handler()
override fun run() {
try {
val url = URL(missionControl.mission.url)
var conn = url.openConnection() as HttpURLConnection
missionControl.length = conn.contentLength.toLong()
if (missionControl.length <= 0) {
missionControl.errCode = MissionControl.ERROR_SERVER_UNSUPPORTED
missionControl.notifyError(MissionControl.ERROR_SERVER_UNSUPPORTED)
return
}
// Open again
conn = url.openConnection() as HttpURLConnection
conn.setRequestProperty("Range", "bytes=${missionControl.length - 10}-${missionControl.length}")
if (conn.responseCode != 206) {
// Fallback to single thread if no partial content support
missionControl.fallback = true
Log.d(TAG, "falling back")
}
Log.d(TAG, "response = ${conn.responseCode}")
missionControl.blocks = missionControl.length / DownloadMissionManager.BLOCK_SIZE
if (missionControl.threadCount > missionControl.blocks) {
missionControl.threadCount = missionControl.blocks.toInt()
}
if (missionControl.threadCount <= 0) {
missionControl.threadCount = 1
}
if (missionControl.blocks * DownloadMissionManager.BLOCK_SIZE < missionControl.length) {
missionControl.blocks += 1
}
File(missionControl.mission.location).mkdirs()
File("${missionControl.mission.location}/${missionControl.mission.name}").createNewFile()
Log.d(TAG, "${missionControl.mission.name} file has been created.")
val af = RandomAccessFile("${missionControl.mission.location}/${missionControl.mission.name}", "rw")
af.setLength(missionControl.length)
af.close()
missionControl.start()
} catch (ie: IOException) {
if (ie.message != null && ie.message!!.contains("Permission denied")) {
handler.post { context.startActivity(Intent(context, ExtSDDownloadFailedActivity::class.java)) }
} else if (ie.message!!.contains("No such file or directory")) {
handler.post {
// inform user that the input name is illegal, please use legal name.
Toast.makeText(
context,
"The file name contains illegal characters, please use legal name and try again!",
Toast.LENGTH_LONG
).show()
}
} else
throw RuntimeException(ie)
} catch (e: Exception) {
// TODO Notify
throw RuntimeException(e)
}
}
}
/**
* Waits for missionControl to finish to add it to the [.mDownloadDataSource]
*/
private inner class MissionControlListener(private val mMissionControl: MissionControl) : com.dew.aihua.download.background.MissionControlListener {
override fun onFinish(missionControl: MissionControl) {
Thread {
val disposable = mDownloadDataSource.addMission(mMissionControl)
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableCompletableObserver() {
override fun onComplete() {
Log.d(TAG, "one mission has been added into Database")
}
override fun onError(e: Throwable) {
Log.d(TAG, "addMission Error: ${e.message}")
}
})
disposable.dispose()
Log.d(TAG, "DownloadMissionManagerImpl: onFinish() called.")
}
}
override fun onProgressUpdate(missionControl: MissionControl, done: Long, total: Long) {
// todo: need to show the progress on notification bar
// no need because DownloadManagerService.onProgressUpdate will do it.
}
override fun onError(missionControl: MissionControl, errCode: Int) {
// todo: show a Toast/snackbar and remove the notification icon on state bar.
}
}
companion object {
private val TAG = DownloadMissionManagerImpl::class.java.simpleName
/**
* Sort a list of missionControl by its timestamp. Oldest first
* @param missions the missions to sort
*/
fun sortByTimestamp(missions: MutableList<MissionControl>) {
missions.sortWith(Comparator { o1, o2 ->
java.lang.Long.compare(o1.mission.timestamp, o2.mission.timestamp)
})
}
/**
* Splits the filename into name and extension
*
*
* Dots are ignored if they appear: not at all, at the beginning of the file,
* at the end of the file
*
* @param name the name to split
* @return a string array with a length of 2 containing the name and the extension
*/
private fun splitName(name: String): Array<String> {
val dotIndex = name.lastIndexOf('.')
return if (dotIndex <= 0 || dotIndex == name.length - 1) {
arrayOf(name, "")
} else {
arrayOf(name.substring(0, dotIndex), name.substring(dotIndex + 1))
}
}
/**
* Generates a unique file name.
*
*
* e.g. "myname (1).txt" if the name "myname.txt" exists.
*
* @param location the location (to check for existing files)
* @param name the name of the file
* @return the unique file name
* @throws IllegalArgumentException if the location is not a directory
* @throws SecurityException if the location is not readable
*/
private fun generateUniqueName(location: String?, name: String?): String {
if (location == null) throw NullPointerException("location is null")
if (name == null) throw NullPointerException("name is null")
val destination = File(location)
if (!destination.isDirectory) {
throw IllegalArgumentException("location is not a directory: $location")
}
val nameParts = splitName(name)
val existingName = destination.list { _, name1 -> name1.startsWith(nameParts[0]) }
Arrays.sort(existingName)
var newName: String
var downloadIndex = 0
do {
newName = nameParts[0] + " (" + downloadIndex + ")." + nameParts[1]
++downloadIndex
if (downloadIndex == 1000) { // Probably an error on our side
throw RuntimeException("Too many existing files")
}
} while (Arrays.binarySearch(existingName, newName) >= 0)
return newName
}
}
}
| 0
|
Kotlin
|
0
| 1
|
1896f46888b5a954b367e83f40b845ce174a2328
| 14,633
|
Aihua
|
Apache License 2.0
|
todo-sample/src/main/java/com/toggl/komposable/sample/todo/AppState.kt
|
toggl
| 316,494,344
| false
|
{"Kotlin": 90172}
|
package com.toggl.komposable.sample.todo
import com.toggl.komposable.architecture.Effect
import com.toggl.komposable.architecture.Mutable
import com.toggl.komposable.extensions.mutateWithoutEffects
import com.toggl.komposable.sample.todo.data.EditableTodoItem
import com.toggl.komposable.sample.todo.data.Identity
import com.toggl.komposable.sample.todo.data.TodoItem
data class AppState(
val todoList: List<TodoItem> = emptyList(),
val editableTodo: EditableTodoItem = EditableTodoItem(title = "", description = ""),
val identity: Identity = Identity.Unknown,
override val backStack: BackStack = listOf(AppDestination.List),
) : BackStackAwareState<AppState> {
override fun changeBackStack(backStack: BackStack): AppState =
copy(backStack = backStack)
}
typealias BackStack = List<AppDestination>
fun BackStack.push(destination: AppDestination) =
this + destination
fun BackStack.pop() =
this.dropLast(1)
interface BackStackAwareState<T> {
val backStack: BackStack
fun popBackStack(): T = changeBackStack(backStack.pop())
fun changeBackStack(backStack: BackStack): T
}
fun <State : BackStackAwareState<State>, Action> Mutable<State>.popBackStackWithoutEffects(): List<Effect<Action>> =
mutateWithoutEffects { popBackStack() }
| 5
|
Kotlin
|
17
| 223
|
49c47a30dcb71fd35d9c70fa468cf91820b34f33
| 1,286
|
komposable-architecture
|
Apache License 2.0
|
learn_note/src/main/java/com/ablechange/learn/kotlin/NonNull.kt
|
AbelChange
| 420,311,870
| false
|
{"Kotlin": 210159, "Java": 26553, "CMake": 1695, "C++": 990, "AIDL": 931}
|
package com.ablechange.learn.kotlin
import com.google.gson.Gson
val jsonStr = """{}"""
//存在参数没有默认值->不会生成无参构造
//gson:使用unsafe方式创建对象,默认值无效(java行为一致),同时绕过了kotlin的空安全监测
//非基本类型使用时可能会导致npe
data class NonNull(val id: String, val age: Int) {
init {
println("init 函数 在主构造方法之后执行")
}
}
//所有参数都有默认值->生成无参构造
//先使用无参构造,然后赋值
//只要存在某个参数没有给默认值,就会导致不生成 无参构造,导致其余默认值不生效
data class NullableDefault(val id: String? = null, val age: Int? = -1)
fun main() {
val default = Gson().fromJson<NullableDefault>(jsonStr, NullableDefault::class.java)
println(default)
}
| 0
|
Kotlin
|
0
| 1
|
13cc81a9c4037253b573b2f4174c7d276cf245eb
| 571
|
MyArchiteture
|
Apache License 2.0
|
rider/buildSrc/src/main/kotlin/com/jetbrains/rider/plugins/gradle/BackendPaths.kt
|
20chan
| 254,533,394
| true
|
{"C#": 2979478, "Kotlin": 407975, "ShaderLab": 67905, "Lex": 36697, "GLSL": 7572, "HLSL": 7370, "Java": 5463, "PowerShell": 1036, "Shell": 129}
|
package com.jetbrains.rider.plugins.gradle
import com.jetbrains.rider.plugins.gradle.buildServer.buildServer
import org.apache.tools.ant.taskdefs.condition.Os
import org.gradle.api.Project
import org.gradle.api.logging.Logger
import org.jetbrains.intellij.IntelliJPluginExtension
import java.io.File
class BackendPaths(private val project: Project,
private val logger: Logger,
private val repositoryRoot: File,
private val productVersion: String) {
private var riderSdkPath: File? = null
val backendRoot: File
val unityPluginSolution: File
val resharperHostPluginSolution: File
init {
assert(repositoryRoot.isDirectory)
backendRoot = File(repositoryRoot, "resharper")
assert(backendRoot.isDirectory)
val unityRoot = File(repositoryRoot, "unity")
unityPluginSolution = File(unityRoot, "JetBrains.Rider.Unity.Editor.sln")
// Temporary workaround - the R# SDK contains yFile assembly that is obfuscated, and kills msbuild on mac
val sln = if (!Os.isFamily(Os.FAMILY_WINDOWS)) "rider-unity.sln" else "resharper-unity.sln"
resharperHostPluginSolution = File(backendRoot, sln)
assert(resharperHostPluginSolution.isFile)
}
private fun getRiderSdkRootPath(): File {
if (riderSdkPath == null) {
if (project.buildServer.isAutomatedBuild) {
riderSdkPath = File(repositoryRoot, "rider/dependencies")
if (riderSdkPath?.isDirectory == true) {
logger.lifecycle("Rider SDK bundle found: ${riderSdkPath?.canonicalPath}")
} else {
logger.error("Bundle Rider SDK not found in '$riderSdkPath'. Falling back to public SDK")
}
}
if (riderSdkPath == null || riderSdkPath?.isDirectory == false)
{
val intellij = project.extensions.findByType(IntelliJPluginExtension::class.java)!!
var root = File(repositoryRoot, "rider/build/riderRD-$productVersion-SNAPSHOT")
if (intellij.ideaDependencyCachePath != null) {
root = File(intellij.ideaDependencyCachePath)
}
if (!root.isDirectory) {
// If this assert fires, then you've likely called getRiderSdkPath during configuration
// Try to wrap this call in a closure, so that it's evaluated at execution time, once the
// intellij dependencies have been downloaded
assert(intellij.ideaDependency != null)
root = File(intellij.ideaDependency.classes.absolutePath)
}
riderSdkPath = root
logger.lifecycle("Rider SDK bundle found: ${root.canonicalPath}")
}
}
assert(riderSdkPath?.isDirectory ?: false)
return riderSdkPath!!
}
fun getDotNetSdkPath(): File {
val sdkRoot = File(getRiderSdkRootPath(), "lib/DotNetSdkForRdPlugins")
assert(sdkRoot.isDirectory)
return sdkRoot
}
private fun getRdLibDirectory(): File {
val rdLib = File(getRiderSdkRootPath(),"lib/rd")
assert(rdLib.isDirectory)
return rdLib
}
fun getRiderModelJar(): File {
val jarFile = File(getRdLibDirectory(), "rider-model.jar").canonicalFile
assert(jarFile.isFile)
return jarFile
}
}
| 0
| null |
0
| 1
|
1e0db52a0144ac83206bf71a79eacffe4307cdba
| 3,476
|
resharper-unity
|
Apache License 2.0
|
.teamcity/delivery/staging/manifest/PublishLocal.kts
|
JetBrains
| 261,739,564
| false
|
{"C#": 191431, "Dockerfile": 179109, "Kotlin": 50785, "Batchfile": 18825, "Shell": 13946, "Python": 6106, "PowerShell": 4921}
|
package delivery.staging.manifest
import jetbrains.buildServer.configs.kotlin.v2019_2.BuildType
import jetbrains.buildServer.configs.kotlin.v2019_2.BuildTypeSettings
import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.script
import utils.dsl.general.teamCityImageBuildFeatures
import utils.dsl.general.teamCityStagingImagesSnapshot
import utils.dsl.steps.publishLinuxManifests
import utils.dsl.steps.publishWindowsManifests
object publish_local : BuildType({
name = "[All] [Staging] Release Manifests as 'version' into Staging Registry"
buildNumberPattern = "%dockerImage.teamcity.buildNumber%-%build.counter%"
description = "Publish Docker Manifests into staging repository."
enablePersonalBuilds = false
type = BuildTypeSettings.Type.DEPLOYMENT
maxRunningBuilds = 1
steps {
script {
name = "remove manifests"
scriptContent =
"""if exist "%%USERPROFILE%%\.docker\manifests\" rmdir "%%USERPROFILE%%\.docker\manifests\" /s /q"""
}
publishLinuxManifests(name = "%tc.image.version%",
repo = "%docker.buildRepository%",
postfix = "%docker.buildImagePostfix%")
publishWindowsManifests(name = "%tc.image.version%",
repo = "%docker.buildRepository%",
postfix = "%docker.buildImagePostfix%")
}
dependencies {
teamCityStagingImagesSnapshot()
}
requirements {
noLessThanVer("docker.version", "18.05.0")
contains("docker.server.osType", "windows")
// In order to correctly build AMD-based images, we wouldn't want it to be scheduled on ARM-based agent
doesNotContain("teamcity.agent.name", "arm")
contains("teamcity.agent.jvm.os.name", "Windows 10")
}
features {
teamCityImageBuildFeatures()
}
})
| 9
|
C#
|
57
| 91
|
16ea3a7aa8e4d17050bde5a7932246fb337c0090
| 1,838
|
teamcity-docker-images
|
Apache License 2.0
|
src/commonMain/kotlin/com/adyen/model/transferwebhooks/UKLocalAccountIdentification.kt
|
tjerkw
| 733,432,442
| false
|
{"Kotlin": 5043126, "Makefile": 6356}
|
/**
* Transfer webhooks
*
* Adyen sends webhooks to inform your system about incoming and outgoing transfers in your platform. You can use these webhooks to build your implementation. For example, you can use this information to update balances in your own dashboards or to keep track of incoming funds.
*
* The version of the OpenAPI document: 4
*
*
* 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 com.adyen.model.transferwebhooks
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
/**
*
*
* @param accountNumber The 8-digit bank account number, without separators or whitespace.
* @param sortCode The 6-digit [sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or whitespace.
* @param type **ukLocal**
*/
@Serializable
data class UKLocalAccountIdentification (
/* The 8-digit bank account number, without separators or whitespace. */
@SerialName(value = "accountNumber") @Required val accountNumber: kotlin.String,
/* The 6-digit [sort code](https://en.wikipedia.org/wiki/Sort_code), without separators or whitespace. */
@SerialName(value = "sortCode") @Required val sortCode: kotlin.String,
/* **ukLocal** */
@SerialName(value = "type") @Required val type: UKLocalAccountIdentification.Type = Type.UkLocal
) {
/**
* **ukLocal**
*
* Values: UkLocal
*/
@Serializable
enum class Type(val value: kotlin.String) {
@SerialName(value = "ukLocal") UkLocal("ukLocal");
}
}
| 0
|
Kotlin
|
0
| 0
|
2da5aea5519b2dfa84454fe1665e9699edc87507
| 1,766
|
adyen-kotlin-multiplatform-api-library
|
MIT License
|
src/chapter3/section5/ex10.kt
|
w1374720640
| 265,536,015
| false
|
{"Kotlin": 1373556}
|
package chapter3.section5
import chapter3.section3.RedBlackBST
/**
* 修改红黑树RedBlackBST,允许在树中保存重复的键
* 对于get()方法,返回给定键所关联的任意值,对于delete()方法,删除树中所有和给顶尖相等的结点
*/
class DuplicateKeysRedBlackBST<K : Comparable<K>, V : Any> : RedBlackBST<K, V>(), DuplicateKeysST<K, V> {
class Node<K : Comparable<K>, V : Any>(
key: K,
value: V,
left: RedBlackBST.Node<K, V>? = null,
right: RedBlackBST.Node<K, V>? = null,
count: Int = 1,
color: Boolean = RED,
val set: SequentialSearchSET<V> = SequentialSearchSET()
) : RedBlackBST.Node<K, V>(key, value, left, right, count, color) {
init {
set.add(value)
}
}
override fun getAllValues(key: K): Iterable<V>? {
if (isEmpty()) return null
val node = get(root!!, key)
return (node as? Node)?.set
}
override fun put(key: K, value: V) {
if (root == null) {
root = Node(key, value, color = BLACK)
} else {
root = put(root, key, value)
root!!.color = BLACK
}
}
override fun put(node: RedBlackBST.Node<K, V>?, key: K, value: V): RedBlackBST.Node<K, V> {
if (node == null) return Node(key, value)
when {
key < node.key -> node.left = put(node.left, key, value)
key > node.key -> node.right = put(node.right, key, value)
else -> (node as Node).set.add(value)
}
var h: RedBlackBST.Node<K, V> = node
if (!h.left.isRed() && h.right.isRed()) h = rotateLeft(h)
if (h.left.isRed() && h.left?.left.isRed()) h = rotateRight(h)
if (h.left.isRed() && h.right.isRed()) flipColors(h)
resize(h)
return h
}
}
fun main() {
testDuplicateKeysST(DuplicateKeysRedBlackBST())
}
| 0
|
Kotlin
|
1
| 6
|
879885b82ef51d58efe578c9391f04bc54c2531d
| 1,826
|
Algorithms-4th-Edition-in-Kotlin
|
MIT License
|
library-mvvmlazy/src/main/java/com/rui/mvvmlazy/binding/viewadapter/view/ViewAdapter.kt
|
jirywell
| 418,722,038
| false
|
{"Kotlin": 779701, "Java": 48117}
|
package com.rui.mvvmlazy.binding.viewadapter.view
import android.os.SystemClock
import android.view.View
import android.view.View.OnFocusChangeListener
import androidx.databinding.BindingAdapter
/**
* Created by zjr on 2020/6/16.
*/
object ViewAdapter {
/**
* requireAll 是意思是是否需要绑定全部参数, false为否
* View的onClick事件绑定
* onClickCommand 绑定的命令,
* isThrottleFirst 是否开启防止过快点击
*/
@JvmStatic
@BindingAdapter(value = ["onClickCommand", "isThrottleFirst"], requireAll = false)
fun onClickCommand(view: View, clickCommand: () -> Unit, isThrottleFirst: Boolean) {
if (isThrottleFirst) {
view.setOnClickListener { clickCommand.invoke() }
} else {
val mHits = LongArray(2)
view.setOnClickListener {
System.arraycopy(mHits, 1, mHits, 0, mHits.size - 1)
mHits[mHits.size - 1] = SystemClock.uptimeMillis()
if (mHits[0] < SystemClock.uptimeMillis() - 500) {
clickCommand.invoke()
}
}
}
}
/**
* view的onLongClick事件绑定
*/
@JvmStatic
@BindingAdapter(value = ["onLongClickCommand"], requireAll = false)
fun onLongClickCommand(view: View, clickCommand: () -> Unit) {
view.setOnLongClickListener {
clickCommand.invoke()
true
}
}
/**
* 回调控件本身
*
* @param currentView
* @param bindingCommand
*/
@JvmStatic
@BindingAdapter(value = ["currentView"], requireAll = false)
fun replyCurrentView(currentView: View, bindingCommand: (View) -> Unit) {
bindingCommand.invoke(currentView)
}
/**
* view是否需要获取焦点
*/
@JvmStatic
@BindingAdapter("requestFocus")
fun requestFocusCommand(view: View, needRequestFocus: Boolean) {
if (needRequestFocus) {
view.isFocusableInTouchMode = true
view.requestFocus()
} else {
view.clearFocus()
}
}
/**
* view的焦点发生变化的事件绑定
*/
@JvmStatic
@BindingAdapter("onFocusChangeCommand")
fun onFocusChangeCommand(view: View, onFocusChangeCommand: (Boolean) -> Unit) {
view.onFocusChangeListener =
OnFocusChangeListener { v, hasFocus -> onFocusChangeCommand.invoke(hasFocus) }
}
/**
* view的显示隐藏
*/
@JvmStatic
@BindingAdapter(value = ["isVisible"], requireAll = false)
fun isVisible(view: View, visibility: Boolean) {
if (visibility) {
view.visibility = View.VISIBLE
} else {
view.visibility = View.GONE
}
}
}
| 0
|
Kotlin
|
7
| 27
|
b37dcb02d8b93699299aada9ec98a1c3ae10e346
| 2,636
|
MvvmLazy-kotlin
|
Apache License 2.0
|
app/src/main/java/com/lonard/camerlangproject/api/ApiConfig.kt
|
lonard2
| 490,593,898
| false
| null |
package com.lonard.camerlangproject.api
import com.lonard.camerlangproject.BuildConfig
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class ApiConfig {
companion object {
fun getApiProduct(): ApiInterface {
val interceptLog = if(BuildConfig.DEBUG) {
HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
} else {
HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.NONE
)
}
val okClient = OkHttpClient.Builder()
.addInterceptor(interceptLog)
.build()
val rf = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BuildConfig.URL_BASE)
.client(okClient)
.build()
return rf.create(ApiInterface::class.java)
}
}
}
| 0
|
Kotlin
|
2
| 2
|
52f69ed3312071307b5c8c9221a45ccdde6c7351
| 1,019
|
CAMerlang-Mobile-Development
|
MIT License
|
TIM-Android-lib/src/main/java/com/trifork/timandroid/models/openid/OpenIDScope.kt
|
trifork
| 399,110,548
| false
| null |
package com.trifork.timandroid.models.openid
val OIDScopeOpenID = "openid"
val OIDScopeProfile = "profile"
val OIDScopeEmail = "email"
val OIDScopeAddress = "address"
val OIDScopePhone = "phone"
| 0
|
Kotlin
|
3
| 5
|
0a8bcccd84d981853a56678f4a04e64171a16a73
| 195
|
TIM-Android
|
MIT License
|
plugins/analysis/common/src/main/kotlin/arrow/meta/plugins/analysis/phases/analysis/solver/ast/context/elements/TypeParameter.kt
|
arrow-kt
| 217,378,939
| false
| null |
package arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.elements
import arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.types.Variance
interface TypeParameter {
val variance: Variance
val extendsBounds: List<TypeReference>
}
| 97
|
Kotlin
|
40
| 316
|
8d2a80cf3a1275a752c18baceed74cb61aa13b4d
| 261
|
arrow-meta
|
Apache License 2.0
|
game-server/game/src/main/kotlin/com/osrs/game/world/service/LoginService.kt
|
runetopic
| 613,076,716
| false
|
{"Kotlin": 296499, "Witcher Script": 2511}
|
package com.osrs.game.world.service
import com.google.inject.Inject
import com.google.inject.Singleton
import com.osrs.cache.entry.config.enum.EnumEntryProvider
import com.osrs.cache.entry.config.obj.ObjEntryProvider
import com.osrs.api.ui.InterfaceInfoMap
import com.osrs.game.actor.player.Player
import com.osrs.game.container.Inventory
import com.osrs.game.ui.Interfaces
import com.osrs.game.ui.listener.InterfaceListener
import kotlin.reflect.KClass
@Singleton
class LoginService @Inject constructor(
private val interfaceInfoMap: InterfaceInfoMap,
private val enumEntryProvider: EnumEntryProvider,
private val objEntryProvider: ObjEntryProvider,
private val interfaceListeners: Map<KClass<*>, InterfaceListener<*>>
) {
fun login(player: Player) {
player.initialize(
interfaces = Interfaces(
player,
interfaceInfoMap,
enumEntryProvider,
interfaceListeners
),
inventory = Inventory(player, objEntryProvider)
)
player.login()
}
}
| 1
|
Kotlin
|
1
| 10
|
2a5186b2b7befa7c364e0b989da68ed83070a926
| 1,082
|
osrs-server
|
MIT License
|
app/src/main/java/me/alexdevs/tictactoe/feature_tictactoe/data/data_source/HistoryDatabase.kt
|
Ale32bit
| 703,467,051
| false
|
{"Kotlin": 60151}
|
package me.alexdevs.tictactoe.feature_tictactoe.data.data_source
import androidx.room.Database
import androidx.room.RoomDatabase
import me.alexdevs.tictactoe.feature_tictactoe.domain.model.History
@Database(
entities = [History::class],
version = 1,
exportSchema = true,
)
abstract class HistoryDatabase: RoomDatabase() {
abstract val historyDao: HistoryDao
companion object {
const val DATABASE_NAME = "history_db"
}
}
| 0
|
Kotlin
|
0
| 1
|
40eb841864f1bd327888f424c52b996138e2a813
| 455
|
TicTacToe
|
MIT License
|
app/src/main/java/com/cp15/mapres/ui/view/activity/DetailEventActivity.kt
|
Refanz
| 626,299,891
| false
|
{"Kotlin": 32145, "HTML": 2675}
|
package com.cp15.mapres.ui.view.activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import com.cp15.mapres.R
class DetailEventActivity : AppCompatActivity() {
private lateinit var btnBack : ImageButton
private lateinit var btn_presence : ImageButton
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detail_event)
// Set up title page in partial_header.xml
val title_page = findViewById<TextView>(R.id.title_page)
val pageTitle = "Detail Acara" // Ganti dengan teks halaman yang sesuai
title_page.text = pageTitle
// Function back button (to dashboard layout)
btnBack = findViewById(R.id.btnBack)
btnBack.setOnClickListener {
val fragmentManager = DetailEventActivity().supportFragmentManager
if (fragmentManager.backStackEntryCount > 0) {
fragmentManager.popBackStack()
} else {
// Tidak ada fragment sebelumnya di tumpukan kembali, jadi kita tutup aktivitas
DetailEventActivity().finish()
}
}
// Funstion for direct to History Presence
btn_presence = findViewById(R.id.btn_presence)
btn_presence.setOnClickListener{
val intent = Intent(this, HistoryPrecenseActivity::class.java)
startActivity(intent)
}
}
}
| 0
|
Kotlin
|
0
| 2
|
0706bfb9b8a1d0b8250233b48119c553487193c6
| 1,662
|
MAPRES
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsassessforearlyreleaseapi/service/prison/AddressService.kt
|
ministryofjustice
| 836,190,144
| false
|
{"Kotlin": 226428, "Shell": 3815, "Dockerfile": 1400}
|
package uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.service.prison
import jakarta.transaction.Transactional
import org.springframework.stereotype.Service
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.entity.Address
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.entity.CasCheckRequest
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.entity.StandardAddressCheckRequest
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.entity.currentAssessment
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.model.AddCasCheckRequest
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.model.AddStandardAddressCheckRequest
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.model.AddressSummary
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.model.CasCheckRequestSummary
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.model.StandardAddressCheckRequestSummary
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.repository.AddressRepository
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.repository.CasCheckRequestRepository
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.repository.OffenderRepository
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.repository.StandardAddressCheckRequestRepository
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.service.os.OsPlacesApiClient
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.service.os.OsPlacesApiDPA
@Service
class AddressService(
private val addressRepository: AddressRepository,
private val casCheckRequestRepository: CasCheckRequestRepository,
private val offenderRepository: OffenderRepository,
private val osPlacesApiClient: OsPlacesApiClient,
private val standardAddressCheckRequestRepository: StandardAddressCheckRequestRepository,
) {
fun getAddressesForPostcode(postcode: String): List<AddressSummary> =
osPlacesApiClient.getAddressesForPostcode(postcode).map { it.toAddressSummary() }
@Transactional
fun getAddressForUprn(uprn: String): AddressSummary {
val existingAddress = addressRepository.findByUprn(uprn)
if (existingAddress != null) {
return existingAddress.toAddressSummary()
}
val osAddress = osPlacesApiClient.getAddressForUprn(uprn)
addressRepository.save(osAddress.toAddress())
return osAddress.toAddressSummary()
}
@Transactional
fun addStandardAddressCheckRequest(
prisonNumber: String,
addStandardAddressCheckRequest: AddStandardAddressCheckRequest,
): StandardAddressCheckRequestSummary {
val address = addressRepository.findByUprn(addStandardAddressCheckRequest.addressUprn)
?: error("Couldn't find an existing address with UPRN: ${addStandardAddressCheckRequest.addressUprn}")
val offender = offenderRepository.findByPrisonNumber(prisonNumber)
?: error("Cannot find offender with prisonNumber $prisonNumber")
val standardAddressCheckRequest = standardAddressCheckRequestRepository.save(
StandardAddressCheckRequest(
caAdditionalInfo = addStandardAddressCheckRequest.caAdditionalInfo,
ppAdditionalInfo = addStandardAddressCheckRequest.ppAdditionalInfo,
preferencePriority = addStandardAddressCheckRequest.preferencePriority,
address = address,
assessment = offender.currentAssessment(),
),
)
return standardAddressCheckRequest.toSummary()
}
@Transactional
fun addCasCheckRequest(
prisonNumber: String,
addCasCheckRequest: AddCasCheckRequest,
): CasCheckRequestSummary {
val offender = offenderRepository.findByPrisonNumber(prisonNumber)
?: error("Cannot find offender with prisonNumber $prisonNumber")
val casCheckRequest = casCheckRequestRepository.save(
CasCheckRequest(
caAdditionalInfo = addCasCheckRequest.caAdditionalInfo,
ppAdditionalInfo = addCasCheckRequest.ppAdditionalInfo,
preferencePriority = addCasCheckRequest.preferencePriority,
assessment = offender.currentAssessment(),
),
)
return casCheckRequest.toSummary()
}
private fun OsPlacesApiDPA.toAddressSummary(): AddressSummary =
AddressSummary(
uprn = this.uprn,
firstLine = if (this.buildingNumber != null) this.buildingNumber + " " + this.thoroughfareName else this.thoroughfareName,
secondLine = this.locality,
town = this.postTown,
county = this.county,
postcode = this.postcode,
country = this.countryDescription.split("\\s+".toRegex()).last(),
xCoordinate = this.xCoordinate,
yCoordinate = this.yCoordinate,
addressLastUpdated = this.lastUpdateDate,
)
private fun OsPlacesApiDPA.toAddress(): Address =
Address(
uprn = this.uprn,
firstLine = if (this.buildingNumber != null) this.buildingNumber + " " + this.thoroughfareName else this.thoroughfareName,
secondLine = this.locality,
town = this.postTown,
county = this.county,
postcode = this.postcode,
country = this.countryDescription.split("\\s+".toRegex()).last(),
xCoordinate = this.xCoordinate,
yCoordinate = this.yCoordinate,
addressLastUpdated = this.lastUpdateDate,
)
private fun Address.toAddressSummary() = AddressSummary(
uprn = this.uprn,
firstLine = this.firstLine,
secondLine = this.secondLine,
town = this.town,
county = this.county,
postcode = this.postcode,
country = this.country,
xCoordinate = this.xCoordinate,
yCoordinate = this.yCoordinate,
addressLastUpdated = this.addressLastUpdated,
)
private fun StandardAddressCheckRequest.toSummary(): StandardAddressCheckRequestSummary =
StandardAddressCheckRequestSummary(
caAdditionalInfo = this.caAdditionalInfo,
ppAdditionalInfo = this.ppAdditionalInfo,
preferencePriority = this.preferencePriority,
dateRequested = this.dateRequested,
status = this.status,
address = this.address.toAddressSummary(),
)
private fun CasCheckRequest.toSummary(): CasCheckRequestSummary =
CasCheckRequestSummary(
caAdditionalInfo = this.caAdditionalInfo,
ppAdditionalInfo = this.ppAdditionalInfo,
preferencePriority = this.preferencePriority,
dateRequested = this.dateRequested,
status = this.status,
allocatedAddress = this.allocatedAddress?.toAddressSummary(),
)
}
| 0
|
Kotlin
|
0
| 1
|
f9c1ddf00811109b2b01b8379047d248eda3a18f
| 6,495
|
hmpps-assess-for-early-release-api
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsassessforearlyreleaseapi/service/prison/AddressService.kt
|
ministryofjustice
| 836,190,144
| false
|
{"Kotlin": 226428, "Shell": 3815, "Dockerfile": 1400}
|
package uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.service.prison
import jakarta.transaction.Transactional
import org.springframework.stereotype.Service
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.entity.Address
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.entity.CasCheckRequest
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.entity.StandardAddressCheckRequest
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.entity.currentAssessment
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.model.AddCasCheckRequest
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.model.AddStandardAddressCheckRequest
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.model.AddressSummary
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.model.CasCheckRequestSummary
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.model.StandardAddressCheckRequestSummary
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.repository.AddressRepository
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.repository.CasCheckRequestRepository
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.repository.OffenderRepository
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.repository.StandardAddressCheckRequestRepository
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.service.os.OsPlacesApiClient
import uk.gov.justice.digital.hmpps.hmppsassessforearlyreleaseapi.service.os.OsPlacesApiDPA
@Service
class AddressService(
private val addressRepository: AddressRepository,
private val casCheckRequestRepository: CasCheckRequestRepository,
private val offenderRepository: OffenderRepository,
private val osPlacesApiClient: OsPlacesApiClient,
private val standardAddressCheckRequestRepository: StandardAddressCheckRequestRepository,
) {
fun getAddressesForPostcode(postcode: String): List<AddressSummary> =
osPlacesApiClient.getAddressesForPostcode(postcode).map { it.toAddressSummary() }
@Transactional
fun getAddressForUprn(uprn: String): AddressSummary {
val existingAddress = addressRepository.findByUprn(uprn)
if (existingAddress != null) {
return existingAddress.toAddressSummary()
}
val osAddress = osPlacesApiClient.getAddressForUprn(uprn)
addressRepository.save(osAddress.toAddress())
return osAddress.toAddressSummary()
}
@Transactional
fun addStandardAddressCheckRequest(
prisonNumber: String,
addStandardAddressCheckRequest: AddStandardAddressCheckRequest,
): StandardAddressCheckRequestSummary {
val address = addressRepository.findByUprn(addStandardAddressCheckRequest.addressUprn)
?: error("Couldn't find an existing address with UPRN: ${addStandardAddressCheckRequest.addressUprn}")
val offender = offenderRepository.findByPrisonNumber(prisonNumber)
?: error("Cannot find offender with prisonNumber $prisonNumber")
val standardAddressCheckRequest = standardAddressCheckRequestRepository.save(
StandardAddressCheckRequest(
caAdditionalInfo = addStandardAddressCheckRequest.caAdditionalInfo,
ppAdditionalInfo = addStandardAddressCheckRequest.ppAdditionalInfo,
preferencePriority = addStandardAddressCheckRequest.preferencePriority,
address = address,
assessment = offender.currentAssessment(),
),
)
return standardAddressCheckRequest.toSummary()
}
@Transactional
fun addCasCheckRequest(
prisonNumber: String,
addCasCheckRequest: AddCasCheckRequest,
): CasCheckRequestSummary {
val offender = offenderRepository.findByPrisonNumber(prisonNumber)
?: error("Cannot find offender with prisonNumber $prisonNumber")
val casCheckRequest = casCheckRequestRepository.save(
CasCheckRequest(
caAdditionalInfo = addCasCheckRequest.caAdditionalInfo,
ppAdditionalInfo = addCasCheckRequest.ppAdditionalInfo,
preferencePriority = addCasCheckRequest.preferencePriority,
assessment = offender.currentAssessment(),
),
)
return casCheckRequest.toSummary()
}
private fun OsPlacesApiDPA.toAddressSummary(): AddressSummary =
AddressSummary(
uprn = this.uprn,
firstLine = if (this.buildingNumber != null) this.buildingNumber + " " + this.thoroughfareName else this.thoroughfareName,
secondLine = this.locality,
town = this.postTown,
county = this.county,
postcode = this.postcode,
country = this.countryDescription.split("\\s+".toRegex()).last(),
xCoordinate = this.xCoordinate,
yCoordinate = this.yCoordinate,
addressLastUpdated = this.lastUpdateDate,
)
private fun OsPlacesApiDPA.toAddress(): Address =
Address(
uprn = this.uprn,
firstLine = if (this.buildingNumber != null) this.buildingNumber + " " + this.thoroughfareName else this.thoroughfareName,
secondLine = this.locality,
town = this.postTown,
county = this.county,
postcode = this.postcode,
country = this.countryDescription.split("\\s+".toRegex()).last(),
xCoordinate = this.xCoordinate,
yCoordinate = this.yCoordinate,
addressLastUpdated = this.lastUpdateDate,
)
private fun Address.toAddressSummary() = AddressSummary(
uprn = this.uprn,
firstLine = this.firstLine,
secondLine = this.secondLine,
town = this.town,
county = this.county,
postcode = this.postcode,
country = this.country,
xCoordinate = this.xCoordinate,
yCoordinate = this.yCoordinate,
addressLastUpdated = this.addressLastUpdated,
)
private fun StandardAddressCheckRequest.toSummary(): StandardAddressCheckRequestSummary =
StandardAddressCheckRequestSummary(
caAdditionalInfo = this.caAdditionalInfo,
ppAdditionalInfo = this.ppAdditionalInfo,
preferencePriority = this.preferencePriority,
dateRequested = this.dateRequested,
status = this.status,
address = this.address.toAddressSummary(),
)
private fun CasCheckRequest.toSummary(): CasCheckRequestSummary =
CasCheckRequestSummary(
caAdditionalInfo = this.caAdditionalInfo,
ppAdditionalInfo = this.ppAdditionalInfo,
preferencePriority = this.preferencePriority,
dateRequested = this.dateRequested,
status = this.status,
allocatedAddress = this.allocatedAddress?.toAddressSummary(),
)
}
| 0
|
Kotlin
|
0
| 1
|
f9c1ddf00811109b2b01b8379047d248eda3a18f
| 6,495
|
hmpps-assess-for-early-release-api
|
MIT License
|
dccomics/src/main/java/com/cubidevs/dccomics/maps/MapsFragment.kt
|
Team-111-MisionTic
| 426,814,942
| false
|
{"Kotlin": 36927}
|
package com.cubidevs.dccomics.maps
import androidx.fragment.app.Fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.cubidevs.dccomics.R
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
class MapsFragment : Fragment() {
private val callback = OnMapReadyCallback { googleMap ->
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera.
* In this case, we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to
* install it inside the SupportMapFragment. This method will only be triggered once the
* user has installed Google Play services and returned to the app.
*/
val medallo = LatLng(6.2428525, -75.5835155)
googleMap.addMarker(
MarkerOptions()
.position(medallo)
.title("Aqui vive Superman")
.snippet("Medellin"))
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(medallo,15F))
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_maps, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
mapFragment?.getMapAsync(callback)
}
}
| 0
|
Kotlin
|
1
| 1
|
5966f252450af93ef4499d182a8952f4f9aa9848
| 1,972
|
Team-111
|
MIT License
|
app/src/main/java/pl/jitsolutions/agile/presentation/MainActivity.kt
|
jit-team
| 190,179,705
| false
|
{"Kotlin": 210569}
|
package pl.jitsolutions.agile.presentation
import pl.jitsolutions.agile.R
import pl.jitsolutions.agile.presentation.common.BaseActivity
class MainActivity : BaseActivity() {
override val navigationGraphResId = R.navigation.nav_graph
}
| 0
|
Kotlin
|
0
| 0
|
636d750aff6e10bb879ac08fdef162a62e35df9e
| 240
|
jit-agile-android
|
MIT License
|
composeApp/src/commonMain/kotlin/ui/Components/HomeContent.kt
|
Orisu179
| 734,403,072
| false
|
{"Kotlin": 32869, "Swift": 594}
|
package ui.Components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import com.arkivanov.decompose.extensions.compose.jetbrains.subscribeAsState
import domain.SimpleAnime
import navigation.HomeScreenComponent
@Composable
internal fun HomeContent(component: HomeScreenComponent, modifier: Modifier = Modifier) {
val sampleText: State<String> = component.text.subscribeAsState()
val sampleAnime = component.state.collectAsState()
Column(
modifier = modifier,
horizontalAlignment = Alignment.CenterHorizontally
) {
Box(
modifier = Modifier.background(color = MaterialTheme.colorScheme.secondary)
) {
Text(
text = sampleText.value,
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
4a3c86976adafc21f31a94fe51b3f570dfb1d123
| 1,136
|
Unofficial-Anilist-App
|
MIT License
|
src/main/kotlin/no/nav/syfo/web/api/InntektsmeldingRequest.kt
|
navikt
| 121,716,621
| false
|
{"Kotlin": 368783, "Dockerfile": 440}
|
package no.nav.syfo.web.api
import no.nav.syfo.domain.inntektsmelding.Inntektsmelding
data class InntektsmeldingRequest(
val inntektsmelding: Inntektsmelding
)
| 9
|
Kotlin
|
3
| 4
|
f50563ea7d1a57279788d354ab28ea1406813702
| 166
|
syfoinntektsmelding
|
MIT License
|
app/common/src/main/kotlin/me/zhanghai/android/files/compat/ResourcesCompat.kt
|
overphoenix
| 621,371,055
| false
| null |
/*
* Copyright (c) 2020 Hai Zhang <dreaming.in.code.zh@gmail.com>
* All Rights Reserved.
*/
package me.zhanghai.android.files.compat
import android.content.res.Resources
import androidx.annotation.DimenRes
import androidx.core.content.res.ResourcesCompat
fun Resources.getFloatCompat(@DimenRes id: Int) = ResourcesCompat.getFloat(this, id)
| 0
|
Kotlin
|
0
| 0
|
64264f261c2138d5f1932789702661917bbfae28
| 346
|
phoenix-android
|
Apache License 2.0
|
app/src/main/java/com/kiprosh/optimizeprime/view/activity/AboutCelebratlyActivity.kt
|
amangarg95
| 354,863,116
| false
|
{"Kotlin": 79256, "Java": 5838, "PureBasic": 3565}
|
package com.kiprosh.optimizeprime.view.activity
import android.os.Bundle
import android.view.Window
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.kiprosh.optimizeprime.R
class AboutCelebratlyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_about_celebratly)
updateStatusBarColour()
}
private fun updateStatusBarColour() {
val window: Window = window
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.statusBarColor = ContextCompat.getColor(this, R.color.lavender)
}
}
| 0
|
Kotlin
|
0
| 0
|
d68553632c642bbadc554bcd750ffb2d292ee51f
| 842
|
celebratly
|
MIT License
|
app/src/main/java/com/vivek/eton/feature_note/data/data_source/NoteDatabase.kt
|
V9vek
| 450,054,297
| false
|
{"Kotlin": 49875}
|
package com.vivek.eton.feature_note.data.data_source
import androidx.room.Database
import androidx.room.RoomDatabase
import com.vivek.eton.feature_note.domain.model.Note
@Database(
entities = [Note::class],
version = 1
)
abstract class NoteDatabase : RoomDatabase() {
abstract val noteDao: NoteDao
companion object {
val DATABASE_NAME = "notes_db"
}
}
| 0
|
Kotlin
|
0
| 3
|
3f598e2e4c74bf77e303afaf423cd93e1414dfc8
| 383
|
Eton
|
Apache License 2.0
|
core/utils/kotlin/src/main/java/com/core/utils/logger/AppLogger.kt
|
LStudioO
| 653,597,932
| false
| null |
package com.core.utils.logger
import org.jetbrains.annotations.NonNls
interface AppLogger {
/** Set a one-time tag for use on the next logging call. */
fun tag(@NonNls tag: String)
/** Log a verbose message. */
fun v(@NonNls message: String?)
/** Log a verbose exception and a message. */
fun v(t: Throwable?, @NonNls message: String?)
/** Log a verbose exception. */
fun v(t: Throwable?)
/** Log a debug message. */
fun d(@NonNls message: String?)
/** Log a debug exception and a message. */
fun d(t: Throwable?, @NonNls message: String?)
/** Log a debug exception. */
fun d(t: Throwable?)
/** Log an info message. */
fun i(@NonNls message: String?)
/** Log an info exception and a message. */
fun i(t: Throwable?, @NonNls message: String?)
/** Log an info exception. */
fun i(t: Throwable?)
/** Log a warning message. */
fun w(@NonNls message: String?)
/** Log a warning exception and a message. */
fun w(t: Throwable?, @NonNls message: String?)
/** Log a warning exception. */
fun w(t: Throwable?)
/** Log an error message. */
fun e(@NonNls message: String?)
/** Log an error exception and a message. */
fun e(t: Throwable?, @NonNls message: String?)
/** Log an error exception. */
fun e(t: Throwable?)
/** Log an assert message. */
fun wtf(@NonNls message: String?)
/** Log an assert exception and a message. */
fun wtf(t: Throwable?, @NonNls message: String?)
/** Log an assert exception. */
fun wtf(t: Throwable?)
/** Log at `priority` a message. */
fun log(priority: Int, @NonNls message: String?)
/** Log at `priority` an exception and a message. */
fun log(priority: Int, t: Throwable?, @NonNls message: String?)
/** Log at `priority` an exception. */
fun log(priority: Int, t: Throwable?)
}
| 0
|
Kotlin
|
0
| 2
|
4b7ad630dbd4838b66e560f463b025e79327bebd
| 1,922
|
CodeWarsChallengeViewer
|
Apache License 2.0
|
ocgena-domain/src/main/kotlin/ru/misterpotz/ocgena/simulation_old/stepexecutor/StepExecutor.kt
|
MisterPotz
| 605,293,662
| false
|
{"Kotlin": 749008, "TypeScript": 495751, "JavaScript": 36713, "CSS": 14489, "Python": 8026, "HTML": 3173, "Ruby": 285, "EJS": 274, "Java": 140}
|
package ru.misterpotz.ocgena.simulation_old.stepexecutor
import ru.misterpotz.ocgena.simulation_old.continuation.ExecutionContinuation
interface StepExecutor {
suspend fun executeStep(executionContinuation: ExecutionContinuation)
}
| 0
|
Kotlin
|
0
| 1
|
32a25441882c4780ed6b964a24430ef086222b76
| 237
|
ocgena
|
MIT License
|
backend/domain/src/main/kotlin/com/enjoycode/hexagonal/domain/Employee.kt
|
s-petit
| 398,474,879
| false
|
{"HTML": 24912, "Kotlin": 16976, "TypeScript": 5835, "Shell": 452, "JavaScript": 419, "SCSS": 80}
|
package com.enjoycode.hexagonal.domain
data class Employee(
val id: String,
val name: String
)
| 0
|
HTML
|
0
| 0
|
d0f172432672c578c7252a95b0ab681f9a99f884
| 104
|
ddd-hexagonal-template
|
MIT License
|
app/src/test/java/io/github/wulkanowy/data/repositories/student/StudentRemoteTest.kt
|
dominik-korsa
| 162,416,621
| true
|
{"Kotlin": 668158, "Shell": 220, "IDL": 131}
|
package io.github.wulkanowy.data.repositories.student
import io.github.wulkanowy.api.Api
import io.github.wulkanowy.api.register.Student
import io.reactivex.Single
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito.doReturn
import org.mockito.MockitoAnnotations
class StudentRemoteTest {
@Mock
private lateinit var mockApi: Api
@Before
fun initApi() {
MockitoAnnotations.initMocks(this)
}
@Test
fun testRemoteAll() {
doReturn(Single.just(listOf(Student("", "", 1, "test", "", "", "", 1, Api.LoginType.AUTO))))
.`when`(mockApi).getStudents()
val students = StudentRemote(mockApi).getStudents("", "", "").blockingGet()
assertEquals(1, students.size)
assertEquals("test", students.first().studentName)
}
}
| 0
|
Kotlin
|
0
| 0
|
ba84f2be6ea7f4722560d7323a0c314f88614b75
| 876
|
wulkanowy
|
Apache License 2.0
|
app/src/main/kotlin/util/ZipFlowExtensions.kt
|
amandeepg
| 487,098,236
| false
|
{"Kotlin": 200351, "Shell": 5920, "Python": 1095}
|
package ca.amandeep.path.util
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.zip
/**
* Combines the given flows into a single flow that emits a list of values.
*/
fun <T, R> zip(
vararg flows: Flow<T>,
transform: suspend (List<T>) -> R,
): Flow<R> = zip(flows.toList(), transform)
/**
* Combines the given flows into a single flow that emits a list of values.
*/
fun <T, R> zip(
flows: List<Flow<T>>,
transform: suspend (List<T>) -> R,
): Flow<R> = when (flows.size) {
0 -> emptyFlow()
1 -> flows[0].map { transform(listOf(it)) }
2 -> flows[0].zip(flows[1]) { a, b -> transform(listOf(a, b)) }
else -> {
var accFlow: Flow<List<T>> = flows[0].zip(flows[1]) { a, b -> listOf(a, b) }
for (i in 2 until flows.size) {
accFlow = accFlow.zip(flows[i]) { list, it ->
list + it
}
}
accFlow.map(transform)
}
}
/**
* Combines the given flows into a single flow that emits a list of values.
*/
@JvmName("zipExtension")
fun <T, R> List<Flow<T>>.zip(
transform: suspend (List<T>) -> R,
): Flow<R> = zip(this, transform)
| 0
|
Kotlin
|
0
| 3
|
9decf523468ea3567544e3974acdfab383d0528e
| 1,224
|
PathTimes
|
Apache License 2.0
|
src/main/kotlin/uk/gov/justice/digital/hmpps/arnscoordinatorapi/oasys/associations/repository/OasysAssociation.kt
|
ministryofjustice
| 858,719,887
| false
|
{"Kotlin": 270210, "Makefile": 2528, "Dockerfile": 1185}
|
package uk.gov.justice.digital.hmpps.arnscoordinatorapi.oasys.associations.repository
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.EnumType
import jakarta.persistence.Enumerated
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.Table
import org.hibernate.annotations.SQLRestriction
import java.time.LocalDateTime
import java.util.UUID
enum class EntityType {
ASSESSMENT,
PLAN,
}
@Entity
@Table(name = "oasys_associations", schema = "coordinator")
@SQLRestriction("deleted IS FALSE")
data class OasysAssociation(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long? = null,
@Column(nullable = false)
val uuid: UUID? = UUID.randomUUID(),
@Column(name = "created_at", nullable = false)
val createdAt: LocalDateTime = LocalDateTime.now(),
@Enumerated(EnumType.STRING)
@Column(name = "entity_type", nullable = false)
var entityType: EntityType? = null,
@Column(name = "entity_uuid", nullable = false)
var entityUuid: UUID = UUID.randomUUID(),
@Column(name = "oasys_assessment_pk", length = 64, nullable = false)
val oasysAssessmentPk: String? = null,
@Column(name = "region_prison_code", length = 64)
val regionPrisonCode: String? = null,
@Column(nullable = false)
var deleted: Boolean = false,
@Column(nullable = false)
var baseVersion: Long = 0,
) {
fun clone(oasysAssessmentPk: String?): OasysAssociation {
return OasysAssociation(
oasysAssessmentPk = oasysAssessmentPk,
entityType = entityType,
entityUuid = entityUuid,
regionPrisonCode = regionPrisonCode,
)
}
}
| 2
|
Kotlin
|
0
| 0
|
c7ce9fdb04301a23268b4c1713e2d7bcb24a83d4
| 1,711
|
hmpps-assess-risks-and-needs-coordinator-api
|
MIT License
|
app/src/main/java/com/example/hospitalfinder/PlaceJSONParser.kt
|
aalshawa97
| 274,258,169
| false
| null |
package com.example.hospitalfinder
import java.util.HashMap;
import org.json.JSONObject;
class PlaceJSONParser {
//JSONArray jPlaces = null;
val jsonObject = JSONObject(strJson)
private fun JSONObject(strJson: strJson): Any {
return JSONObject()
}
val JSONArray = "Employee"
var hashMap: HashMap<String, Int> = HashMap<String, Int>()
}
public class PlaceDetailsJSONParser{
}
object strJson {
}
| 0
|
Kotlin
|
0
| 0
|
8c2967cd9ccf9bb08a8553dbdcecb6eaf543b91f
| 429
|
HosiptalLocator
|
MIT License
|
src/main/kotlin/dev/austinzhu/algods/containers/util/Operation.kt
|
AustinZhu
| 287,033,539
| false
| null |
package dev.austinzhu.algods.containers.util
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class Operation(val description: String = "")
| 0
|
Kotlin
|
0
| 0
|
e0188bad8a6519e571bdc3ee21c41764c1271f10
| 178
|
AlgoDS
|
MIT License
|
lib/src/main/java/com/sd/lib/compose/gesture/FPointerChange.kt
|
zj565061763
| 519,831,774
| false
| null |
package com.sd.lib.compose.gesture
import androidx.compose.foundation.gestures.calculatePan
import androidx.compose.foundation.gestures.forEachGesture
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.PointerId
import androidx.compose.ui.input.pointer.PointerInputChange
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.util.VelocityTracker
import androidx.compose.ui.unit.Velocity
fun Modifier.fPointerChange(
requireUnconsumedDown: Boolean = false,
requireUnconsumedUp: Boolean = false,
requireUnconsumedMove: Boolean = false,
pass: PointerEventPass = PointerEventPass.Main,
onStart: (FPointerChangeScope.() -> Unit)? = null,
onDown: (FPointerChangeScope.(PointerInputChange) -> Unit)? = null,
onUp: (FPointerChangeScope.(PointerInputChange) -> Unit)? = null,
onMove: (FPointerChangeScope.(PointerInputChange) -> Unit)? = null,
onFinish: (FPointerChangeScope.() -> Unit)? = null,
) = composed {
val scopeImpl = remember { FPointerChangeScopeImpl() }
pointerInput(Unit) {
forEachGesture {
awaitPointerEventScope {
scopeImpl.reset()
val touchSlop = viewConfiguration.touchSlop
var pastTouchSlop = false
var pan = Offset.Zero
do {
val event = awaitPointerEvent(pass)
scopeImpl.setCurrentEvent(event)
val hasDown = event.fHasDownPointer()
for (input in event.changes) {
when {
input.fChangedToDown(requireUnconsumedDown) -> {
if (scopeImpl.maxPointerCount == 0) {
onStart?.invoke(scopeImpl)
if (scopeImpl.isGestureCanceled) break
}
scopeImpl.onDown(input)
onDown?.invoke(scopeImpl, input)
}
input.fChangedToUp(requireUnconsumedUp) -> {
onUp?.invoke(scopeImpl, input)
scopeImpl.onUpAfter(input)
}
input.fPositionChanged(requireUnconsumedMove) -> {
if (hasDown) {
if (!pastTouchSlop) {
pan += event.calculatePan()
if (pan.getDistance() > touchSlop) {
pastTouchSlop = true
}
}
if (pastTouchSlop) {
scopeImpl.onMove(input)
onMove?.invoke(scopeImpl, input)
}
}
}
}
}
if (scopeImpl.isGestureCanceled) break
} while (hasDown)
onFinish?.invoke(scopeImpl)
}
}
}
}
interface FPointerChangeScope : FGestureScope {
val pointerCount: Int
val maxPointerCount: Int
var enableVelocity: Boolean
fun getPointerVelocity(pointerId: PointerId): Velocity
}
private class FPointerChangeScopeImpl : BaseGestureScope(), FPointerChangeScope {
private var _maxPointerCount = 0
private val _pointerHolder = mutableMapOf<PointerId, PointerInfo>()
override val pointerCount: Int
get() = _pointerHolder.size
override val maxPointerCount: Int
get() = _maxPointerCount
override var enableVelocity: Boolean = false
override fun getPointerVelocity(pointerId: PointerId): Velocity {
return _pointerHolder[pointerId]?.velocityTracker?.calculateVelocity() ?: Velocity.Zero
}
fun onDown(input: PointerInputChange) {
if (_pointerHolder.containsKey(input.id)) return
val velocityTracker = if (enableVelocity) {
VelocityTracker().apply { this.addPosition(input.uptimeMillis, input.position) }
} else null
_pointerHolder[input.id] = PointerInfo(input, velocityTracker)
_maxPointerCount++
}
fun onUpAfter(input: PointerInputChange) {
_pointerHolder.remove(input.id)
}
fun onMove(input: PointerInputChange) {
if (enableVelocity) {
_pointerHolder[input.id]?.velocityTracker?.addPosition(input.uptimeMillis, input.position)
}
}
override fun reset() {
super.reset()
_maxPointerCount = 0
_pointerHolder.clear()
enableVelocity = false
}
private data class PointerInfo(
val change: PointerInputChange,
val velocityTracker: VelocityTracker?,
)
}
| 0
|
Kotlin
|
0
| 0
|
3232d9f27decc8497103086f95a5f0625835e4a8
| 5,166
|
compose-gesture
|
MIT License
|
app/src/main/java/info/penadidik/p2pmobile/MainActivity.kt
|
penadidik
| 511,021,144
| false
| null |
package info.penadidik.p2pmobile
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat
import androidx.navigation.ui.AppBarConfiguration
import info.penadidik.couchbase.ClientPeerActivity
import info.penadidik.couchbase.ServerPeerActivity
import info.penadidik.p2pmobile.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setContent()
}
private fun setContent() {
binding.btnServer.setOnClickListener {
startActivity(Intent(this, ServerPeerActivity::class.java))
}
binding.btnClient.setOnClickListener {
startActivity(Intent(this, ClientPeerActivity::class.java))
}
}
}
| 0
|
Kotlin
|
0
| 0
|
723741ec32ff9adf14571c979b2c8988d62c0a0f
| 1,080
|
p2pMobile
|
MIT License
|
app/src/main/java/com/yasinkacmaz/jetflix/ui/moviedetail/person/PeopleGridScreen.kt
|
yasinkacmaz
| 223,481,763
| false
| null |
package com.yasinkacmaz.jetflix.ui.moviedetail.person
import androidx.compose.animation.core.Easing
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyGridScope
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.yasinkacmaz.jetflix.ui.moviedetail.credits.Person
import com.yasinkacmaz.jetflix.util.animation.ItemAnimationArgs
import com.yasinkacmaz.jetflix.util.animation.animateItem
import com.yasinkacmaz.jetflix.util.toDp
@Composable
fun PeopleGridScreen(people: List<Person>) {
val statusBarPadding = WindowInsets.statusBars.getBottom(LocalDensity.current).toDp().dp
val navigationBarPadding = WindowInsets.navigationBars.getBottom(LocalDensity.current).toDp().dp
val horizontalPadding = 4.dp
val columnCount = 3
val state = rememberLazyGridState()
LazyVerticalGrid(
columns = GridCells.Fixed(columnCount),
modifier = Modifier.background(MaterialTheme.colors.surface),
contentPadding = PaddingValues(
start = horizontalPadding,
end = horizontalPadding,
top = statusBarPadding,
bottom = navigationBarPadding
),
state = state,
content = { peopleGridContent(people, columnCount, state, horizontalPadding) }
)
}
private fun LazyGridScope.peopleGridContent(
people: List<Person>,
columnCount: Int,
state: LazyGridState,
horizontalPadding: Dp
) {
items(people.count()) { index ->
val (delay, easing) = state.calculateDelayAndEasing(index, columnCount)
val args = ItemAnimationArgs(
scaleRange = 0f..1f,
alphaRange = 0f..1f,
delay = delay,
easing = easing
)
val animationData = animateItem(args)
Person(
person = people[index],
modifier = Modifier
.padding(horizontal = horizontalPadding, vertical = 8.dp)
.graphicsLayer(
alpha = animationData.alpha,
scaleX = animationData.scale,
scaleY = animationData.scale
)
)
}
}
@Composable
private fun LazyGridState.calculateDelayAndEasing(index: Int, columnCount: Int): Pair<Int, Easing> {
val rowIndex = index / columnCount
val visibleRows = layoutInfo.visibleItemsInfo.count()
val firstVisibleRowIndex = firstVisibleItemIndex
val firstVisibleRow = firstVisibleRowIndex + 1
val scrollingToBottom = firstVisibleRowIndex <= rowIndex
val isFirstLoad = visibleRows == 0
val rowMultiplier = when {
isFirstLoad -> rowIndex
scrollingToBottom -> firstVisibleRowIndex + visibleRows - rowIndex
else -> firstVisibleRow - rowIndex // scrolling to top
}
val rowDelay = 200 * rowMultiplier
val scrollDirectionMultiplier = if (isFirstLoad || scrollingToBottom) 1 else -1
val column = (index % columnCount) + 1
val columnDelay = column * 150 * scrollDirectionMultiplier
val easing = if (isFirstLoad || scrollingToBottom) LinearOutSlowInEasing else FastOutSlowInEasing
return rowDelay + columnDelay to easing
}
| 1
|
Kotlin
|
27
| 256
|
1c17321bd154586b35f55cb764c73f5febeea872
| 4,026
|
jetflix
|
MIT License
|
ktaf/src/test/kotlin/com/github/benpollarduk/ktaf/command/global/AboutTest.kt
|
benpollarduk
| 696,256,399
| false
|
{"Kotlin": 531898, "JavaScript": 486, "HTML": 346, "CSS": 343}
|
package com.github.benpollarduk.ktaf.command.global
import com.github.benpollarduk.ktaf.assets.interaction.ReactionResult
import com.github.benpollarduk.ktaf.commands.global.About
import com.github.benpollarduk.ktaf.logic.GameTestHelper
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
class AboutTest {
@Test
fun `given valid game when invoke then return internal`() {
// Given
val command = About()
// When
val result = command.invoke(GameTestHelper.getBlankGame())
// Then
Assertions.assertEquals(ReactionResult.INTERNAL, result.result)
}
}
| 1
|
Kotlin
|
0
| 9
|
1b865af8f8d207c3c4505647e88cca0d281869b0
| 633
|
ktaf
|
MIT License
|
app/src/main/java/com/autosec/pie/viewModels/ShareReceiverViewModel.kt
|
cryptrr
| 850,497,911
| false
|
{"Kotlin": 334195, "Shell": 1942}
|
package com.autosec.pie.viewModels
import android.app.Application
import android.content.Intent
import android.os.Environment
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.core.content.ContextCompat.startForegroundService
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.autosec.pie.data.CommandExtra
import com.autosec.pie.data.CommandExtraInput
import com.autosec.pie.data.CommandModel
import com.autosec.pie.data.CommandType
import com.autosec.pie.data.ShareInputs
import com.autosec.pie.domain.ViewModelEvent
import com.autosec.pie.notifications.AutoPieNotification
import com.autosec.pie.services.ForegroundService
import com.autosec.pie.services.ProcessManagerService
import com.autosec.pie.utils.Utils
import com.autosec.pie.utils.isValidUrl
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.JsonParseException
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.koin.java.KoinJavaComponent.inject
import timber.log.Timber
import java.io.File
import java.io.FileInputStream
class ShareReceiverViewModel(val application1: Application) : AndroidViewModel(application1) {
val main: MainViewModel by inject(MainViewModel::class.java)
var shareItemsResult by mutableStateOf<List<CommandModel>>(emptyList())
var filteredShareItemsResult by mutableStateOf<List<CommandModel>>(emptyList())
private val autoPieNotification: AutoPieNotification by inject(
AutoPieNotification::class.java)
var searchQuery = mutableStateOf("")
val currentExtrasDetails = mutableStateOf<Triple<Boolean, CommandModel, ShareInputs>?>(null)
init {
try {
viewModelScope.launch {
getSharesConfig()
main.eventFlow.collect{
when(it){
is ViewModelEvent.SharesConfigChanged -> {
Timber.d("Share config changed: Restarting")
getSharesConfig()
}
else -> {}
}
}
}
}catch (e:Exception){
Timber.e(e)
}
}
fun search(query: String) {
filteredShareItemsResult = shareItemsResult.filter {
it.name.contains(
query,
ignoreCase = true
) || it.command.contains(query, ignoreCase = true) || it.exec.contains(
query,
ignoreCase = true
)
}
}
fun getSharesConfig() {
val observerConfig = readSharesConfig()
if (observerConfig == null) {
Timber.d("Observers file not available")
main.sharesConfigAvailable = false
return
} else {
main.schedulerConfigAvailable = true
}
val tempList = mutableListOf<CommandModel>()
//TODO: Need to do some refactoring
for (entry in observerConfig.entrySet()) {
val key = entry.key
val value = entry.value.asJsonObject
// Process the key-value pair
val directoryPath = value.get("path").asString
val exec = value.get("exec").asString
val command = value.get("command").asString
val deleteSource = value.get("deleteSourceFile").asBoolean
val extrasJsonArray = value.getAsJsonArray("extras")
val extrasListType = object : TypeToken<List<CommandExtra>>() {}.type
val extras: List<CommandExtra> = try{
Gson().fromJson(extrasJsonArray, extrasListType)
}catch(e: Exception){
emptyList()
}
val shareObject = CommandModel(
type = CommandType.SHARE,
name = key,
path = directoryPath,
command = command,
exec = exec,
deleteSourceFile = deleteSource,
extras = extras
)
tempList.add(shareObject)
}
shareItemsResult = tempList
filteredShareItemsResult = tempList
}
private fun readSharesConfig(): JsonObject? {
val sharesFilePath =
Environment.getExternalStorageDirectory().absolutePath + "/AutoSec/shares.json"
try {
val file = File(sharesFilePath)
val inputStream = FileInputStream(file)
val size = inputStream.available()
val buffer = ByteArray(size)
inputStream.read(buffer)
inputStream.close()
val jsonString = String(buffer)
//Timber.d(jsonString)
// Parse the JSON string
val gson = Gson()
val dataObject = gson.fromJson(jsonString, JsonElement::class.java)
if (!dataObject.isJsonObject) {
Timber.d("Share Sheet config is not valid json")
throw JsonParseException("Config not valid")
}
return dataObject.asJsonObject
} catch (e: Exception) {
Timber.e(e)
return null
}
}
fun runShareCommand(item: CommandModel, currentLink: String?, fileUris: List<String>, commandExtraInputs: List<CommandExtraInput> = emptyList()) {
Timber.d(item.toString())
Timber.d(currentLink.toString())
val inputDir = fileUris.firstOrNull()?.let { File(it) }
when {
inputDir?.isDirectory == true -> {
runShareCommandForDirectory(item,inputDir, commandExtraInputs)
}
fileUris.isNotEmpty() -> {
runShareCommandForFiles(item, currentLink, fileUris, commandExtraInputs)
}
currentLink.isValidUrl() -> {
runShareCommandForUrl(item, currentLink!!, fileUris, commandExtraInputs)
}
!currentLink.isNullOrBlank() -> {
}
else -> {}
}
}
private fun runShareCommandForUrl(
item: CommandModel,
currentLink: String,
fileUris: List<String>,
commandExtraInputs: List<CommandExtraInput> = emptyList()
) {
Timber.d("runShareCommandForUrl")
var resultString = "\"${item.command.replace("{INPUT_FILE}", "'$currentLink'")}\""
if(commandExtraInputs.isEmpty()){
for(extra in item.extras ?: emptyList()){
resultString = resultString.replace("{${extra.name}}", "'${extra.default}'")
}
}else{
for(extra in commandExtraInputs){
resultString = resultString.replace("{${extra.name}}", "'${extra.value}'")
}
}
val execFilePath =
Environment.getExternalStorageDirectory().absolutePath + "/AutoSec/bin/" + item.exec
val fullExecPath = when{
File(item.exec).isAbsolute -> {
item.exec
}
File(execFilePath).exists() -> {
//For packages installed inside autosec/bin
execFilePath
}
else -> {
//Base case fallback to terminal installed packages such as busybox packages.
item.exec
}
}
val usePython = !Utils.isShellScript(File(fullExecPath))
Timber.d("Command to run: ${item.exec} $resultString")
viewModelScope.launch(Dispatchers.IO) {
try {
val success = ProcessManagerService.runCommandForShare(fullExecPath, resultString, item.path, usePython)
if (success) {
Timber.d("Process Success".uppercase())
autoPieNotification.sendNotification("Command Success", "${item.name} $currentLink")
} else {
Timber.d("Process FAILED".uppercase())
autoPieNotification.sendNotification("Command Failed", "${item.name} $currentLink")
}
main.dispatchEvent(ViewModelEvent.CommandCompleted)
}catch (e: Exception){
main.dispatchEvent(ViewModelEvent.CommandCompleted)
Timber.e(e)
}
//main.dispatchEvent(ViewModelEvent.CloseShareReceiverSheet)
}
}
private fun runShareCommandForFiles(
item: CommandModel,
currentLink: String?,
fileUris: List<String>,
commandExtraInputs: List<CommandExtraInput> = emptyList()
) {
Timber.d("runShareCommandForFiles")
val currentItems = fileUris
viewModelScope.launch(Dispatchers.IO) {
try {
if (item.command.contains("{INPUT_FILES}")) {
Timber.d("Multiple Input files detected")
var replacedString = item.command
.replace("{INPUT_FILES}", currentItems.joinToString(" "){ "\'$it\'" })
.replace("''", "'")
.replace("{INPUT_FILE}", "'${currentItems.firstOrNull() ?: ""}'")
//Handling extras
if(commandExtraInputs.isEmpty()){
for(extra in item.extras ?: emptyList()){
replacedString = replacedString.replace("{${extra.name}}", "'${extra.default}'")
}
}else{
for(extra in commandExtraInputs){
replacedString = replacedString.replace("{${extra.name}}", "'${extra.value}'")
}
}
Timber.d("Replaced String $replacedString")
val resultString = "\"${replacedString}\""
val execFilePath =
Environment.getExternalStorageDirectory().absolutePath + "/AutoSec/bin/" + item.exec
val fullExecPath = when{
File(item.exec).isAbsolute -> {
item.exec
}
File(execFilePath).exists() -> {
//For packages installed inside autosec/bin
execFilePath
}
else -> {
//Base case fallback to terminal installed packages such as busybox packages.
item.exec
}
}
val usePython = !Utils.isShellScript(File(fullExecPath))
val success = ProcessManagerService.runCommandForShare(fullExecPath, resultString, item.path, usePython)
if (success) {
Timber.d("Process Success".uppercase())
autoPieNotification.sendNotification("Command Success", "${item.name} $fileUris")
} else {
Timber.d("Process FAILED".uppercase())
autoPieNotification.sendNotification("Command Failed", "${item.name} $fileUris")
}
main.dispatchEvent(ViewModelEvent.CommandCompleted)
//main.dispatchEvent(ViewModelEvent.CloseShareReceiverSheet)
} else {
Timber.d("Single input file")
currentItems.map { path ->
var resultString = "\"${item.command.replace("{INPUT_FILE}", "'$path'")}\""
if(commandExtraInputs.isEmpty()){
for(extra in item.extras ?: emptyList()){
resultString = resultString.replace("{${extra.name}}", "'${extra.default}'")
}
}else{
for(extra in commandExtraInputs){
resultString = resultString.replace("{${extra.name}}", "'${extra.value}'")
}
}
Timber.d("Replaced String $resultString")
val execFilePath =
Environment.getExternalStorageDirectory().absolutePath + "/AutoSec/bin/" + item.exec
val fullExecPath = when{
File(item.exec).isAbsolute -> {
item.exec
}
File(execFilePath).exists() -> {
//For packages installed inside autosec/bin
execFilePath
}
else -> {
//Base case fallback to terminal installed packages such as busybox packages.
item.exec
}
}
val usePython = !Utils.isShellScript(File(fullExecPath))
val success = ProcessManagerService.runCommandForShare(fullExecPath, resultString, item.path, usePython)
if (success) {
Timber.d("Process Success".uppercase())
autoPieNotification.sendNotification("Command Success", "${item.name} $fileUris")
} else {
Timber.d("Process FAILED".uppercase())
autoPieNotification.sendNotification("Command Failed", "${item.name} $fileUris")
}
}
main.dispatchEvent(ViewModelEvent.CommandCompleted)
//main.dispatchEvent(ViewModelEvent.CloseShareReceiverSheet)
}
}catch (e: Exception){
main.dispatchEvent(ViewModelEvent.CommandCompleted)
Timber.e(e)
}
}
}
private fun runShareCommandForDirectory(
item: CommandModel,
inputDir: File,
commandExtraInputs: List<CommandExtraInput> = emptyList()
) {
Timber.d("runShareCommandForDirectory")
val currentItems = inputDir.listFiles()!!
viewModelScope.launch(Dispatchers.IO) {
try {
val startTime = System.currentTimeMillis()
currentItems.map { path ->
var resultString = "\"${item.command.replace("{INPUT_FILE}", path.absolutePath)}\""
if(commandExtraInputs.isEmpty()){
for(extra in item.extras ?: emptyList()){
resultString = resultString.replace("{${extra.name}}", "'${extra.default}'")
}
}else{
for(extra in commandExtraInputs){
resultString = resultString.replace("{${extra.name}}", "'${extra.value}'")
}
}
val execFilePath =
Environment.getExternalStorageDirectory().absolutePath + "/AutoSec/bin/" + item.exec
val fullExecPath = when{
File(item.exec).isAbsolute -> {
item.exec
}
File(execFilePath).exists() -> {
//For packages installed inside autosec/bin
execFilePath
}
else -> {
//Base case fallback to terminal installed packages such as busybox packages.
item.exec
}
}
val usePython = !Utils.isShellScript(File(fullExecPath))
val success = ProcessManagerService.runCommandForShare(fullExecPath, resultString, item.path, usePython)
if (success) {
Timber.d("Process Success".uppercase())
//autoPieNotification.sendNotification("Command Success", "${item.name} $inputDir")
if (item.deleteSourceFile == true) {
ProcessManagerService.deleteFile(path.absolutePath)
}
} else {
Timber.d("Process FAILED".uppercase())
//autoPieNotification.sendNotification("Command Failed", "${item.name} $inputDir")
}
}
main.dispatchEvent(ViewModelEvent.CommandCompleted)
val endTime = System.currentTimeMillis()
Timber.d("Time Elapsed: ${endTime - startTime}")
}catch (e:Exception){
main.dispatchEvent(ViewModelEvent.CommandCompleted)
Timber.e(e)
}
}
}
fun onCommandClick(card: CommandModel, fileUris: List<String>, currentLink: String?, onComplete: () -> Unit){
viewModelScope.launch {
try {
val commandJson = Gson().toJson(card)
val fileUrisJson = Gson().toJson(fileUris)
val intent = Intent(application1, ForegroundService::class.java).apply {
putExtra("command", commandJson)
putExtra("currentLink", currentLink)
putExtra("fileUris", fileUrisJson)
}
startForegroundService(application1, intent)
onComplete()
}catch (e: Exception){
Timber.e(e)
}
}
}
}
| 2
|
Kotlin
|
0
| 2
|
5dc9ce2a1a0950e2e6db0c85a0927b2b5e9e16f0
| 17,814
|
AutoPie
|
Apache License 2.0
|
app/src/main/java/fnsb/macstransit/routematch/Route.kt
|
yeSpud
| 214,586,881
| false
|
{"Kotlin": 170540, "Java": 2845}
|
package fnsb.macstransit.routematch
import android.graphics.Color
import android.util.Log
import androidx.annotation.UiThread
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.model.LatLng
import com.google.maps.android.ktx.addPolyline
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.io.UnsupportedEncodingException
/**
* Created by Spud on 2019-10-12 for the project: MACS Transit.
* For the license, view the file titled LICENSE at the root of the project.
*
* @version 3.2.
* @since Beta 3.
*/
class Route {
/**
* The name of the route.
*/
val name: String
/**
* The color of the route.
*/
var color: Int = 0
/**
* The name of the route formatted to be parsed as a URL.
*/
val urlFormattedName: String
/**
* All the stops in the route.
*/
val stops: HashMap<String, Stop> = HashMap()
/**
* All the shared stops in the route.
*/
val sharedStops: HashMap<String, SharedStop> = HashMap()
/**
* Whether or not the route is enabled or disabled (to be shown or hidden).
* Default is false (disabled).
*/
var enabled = false
/**
* The polyline that corresponds to this route.
*/
private var polyline: com.google.android.gms.maps.model.Polyline? = null
/**
* Constructor for a new Route object with only a name.
*
* @param routeName The name of the route. This cannot contain any whitespace characters.
* @throws UnsupportedEncodingException Thrown if the route name cannot be formatted to a URL.
*/
@Throws(UnsupportedEncodingException::class)
constructor(routeName: String) : this(routeName, 0)
/**
* Creates a new Route object.
*
* @param name The name of the route. This cannot contain any whitespace characters.
* @param color The route color.
* @throws UnsupportedEncodingException Thrown if the route name contains whitespace.
*/
@Throws(UnsupportedEncodingException::class)
constructor(name: String, color: Int) {
// Make sure the route name does not contain any whitespace characters.
if (name.contains(Regex("\\s"))) {
throw UnsupportedEncodingException("Route name contains whitespace!")
}
// Set the route name and color.
this.name = name
this.color = color
// Set the urlFormattedName from the name.
urlFormattedName = java.util.regex.Pattern.compile("\\+")
.matcher(java.net.URLEncoder.encode(name, "UTF-8")).replaceAll("%20")
}
/**
* Creates and sets the polyline for the route.
*
* This must be run on the UI Thread.
*
* @param coordinates The coordinates of the polyline.
* @param map The map to add the polyline to.
*/
@UiThread
fun createPolyline(coordinates: Array<LatLng>, map: GoogleMap) {
Log.v("createPolyline", "Creating route polyline")
// Add the polyline to the map with the following options:
polyline = map.addPolyline {
// Create new polyline options from the array of polyline coordinates stored for the route.
add(*coordinates)
// Make sure its not clickable.
clickable(false)
// Set the color of the polylines based on the route color.
color(this@Route.color)
// Set the polyline visibility to whether or not the route is enabled.
visible(enabled)
}
}
/**
* Removes stops that have shared stops.
*/
fun purgeStops() {
for (stopName: String in sharedStops.keys) {
// Try to remove stops by shared stop name.
if (stops.remove(stopName) != null) {
// If the value for removed wasn't null then log the stop for debugging.
Log.d("purgeStops", "Stop removed: $stopName")
}
}
}
/**
* Sets the polylines visibly to whether or not the route is enabled or not.
* If the polyline didn't previously exist it will be created in this method.
*
* This must be run on the UI Thread.
*
* @param routeMatch The RouteMatch object to use if the polyline coordinates need to be retrieved.
* @param map The map to add the polyline to.
*/
@UiThread
fun togglePolylineVisibility(routeMatch: RouteMatch, map: GoogleMap) {
if (polyline != null) {
Log.d("togglePolyline", "Setting route $name to visible: $enabled")
polyline!!.isVisible = enabled
return
}
// We know the polyline is null here...
// Get the polyline coordinates for the route from the RouteMatch server.
routeMatch.callLandRoute(this, {
// Get the data from all the stops and store it in a JSONArray.
val data: JSONArray = RouteMatch.parseData(it)
// Get the land route points object from the land route data array.
val landRoutePoints: JSONObject = data.getJSONObject(0)
// Get the land route points array from the land route points object.
val landRoutePointsArray: JSONArray = landRoutePoints.getJSONArray("points")
// Get the number of points in the array.
val count: Int = landRoutePointsArray.length()
// Create a new LatLng array to store all the coordinates.
val coordinates = arrayOfNulls<LatLng>(count)
// Initialize the array of coordinates by iterating through the land route points array.
for (i in 0 until count) {
// Get the land route point object from the land route points array.
val landRoutePoint = landRoutePointsArray.getJSONObject(i)
// Get the latitude and longitude from the land route point.
val latitude: Double = landRoutePoint.getDouble("latitude")
val longitude: Double = landRoutePoint.getDouble("longitude")
// Add the newly created LatLng object to the LatLng array.
coordinates[i] = LatLng(latitude, longitude)
}
// Create a new polyline for the route since it didn't have one before.
@Suppress("UNCHECKED_CAST") // Suppressed because we are asserting that none of the coordinates are null
createPolyline(coordinates as Array<LatLng>, map)
// Log if there was any error getting the polyline coordinates.
} , { error: com.android.volley.VolleyError -> Log.e("togglePolylineVisible",
"Unable to get polyline coordinates",
error) }, this)
}
/**
* Removes the routes polyline from the map, and sets it to null.
*
* This must be run on the UI thread.
*/
@UiThread
fun removePolyline() {
if (polyline != null) {
polyline!!.remove()
polyline = null
}
}
companion object {
/**
* Creates a new route object from the provided json object.
* If the json object is null then a RouteException will be thrown.
*
* @param jsonObject The json object contain the data to create a new route object.
* @return The newly created route object.
* @throws JSONException Thrown if the json object is null,
* or if the route name is unable to be parsed.
* @throws UnsupportedEncodingException Thrown if the route name cannot be formatted to a URL.
*/
@JvmStatic
@Throws(JSONException::class, UnsupportedEncodingException::class)
fun generateRoute(jsonObject: JSONObject): Route {
// First, parse the name.
val name = jsonObject.getString("routeId")
return try {
// Now try to parse the route color.
val colorName = jsonObject.getString("routeColor")
val color = if (name == "Yellow") {
Log.i("generateRoute", "Hardcoding yellow route color")
0xFFD5B60A.toInt()
} else {
Color.parseColor(colorName)
}
// Return our newly created route with color!
Route(name, color)
} catch (exception: Exception) {
Log.w("generateRoute", "Unable to parse color", exception)
// Since there was an issue parsing the color,
// and we have the name at this point simply create the route without a color.
Route(name)
}
}
/**
* Iterates though all the provided routes and enables those that have been marked favorited.
*
* @param routes All the routes that can be tracked.
* @param favoriteRouteNames The names of the favorite routes.
*/
@JvmStatic
fun enableFavoriteRoutes(routes: HashMap<String, Route>, favoriteRouteNames: Array<String>) {
for (routeName: String in favoriteRouteNames) {
try {
routes[routeName]!!.enabled = true
} catch (nullPointerException: NullPointerException) {
// If the route was not found log it as an error.
Log.w("enableFavoriteRoutes", "$routeName route is not running today", nullPointerException)
}
}
}
}
}
| 6
|
Kotlin
|
2
| 9
|
3562922b39aad52a2010de4c0aed15521bc220c0
| 8,392
|
MACSTransitApp
|
The Unlicense
|
08-build-common-ui-components-part-3/final/app/src/main/java/com/raywenderlich/android/librarian/ui/addBook/AddBookView.kt
|
kodecocodes
| 300,386,927
| false
| null |
package com.raywenderlich.android.librarian.ui.addBook
interface AddBookView {
fun onBookAdded()
}
| 4
|
Kotlin
|
21
| 34
|
b93afbacc1e903b7b3332cd2c687ed54a703c89c
| 102
|
video-jcomp-materials
|
Apache License 2.0
|
android-app/app/src/main/java/arun/com/chromer/util/animations/SpringUtils.kt
|
Efreak
| 435,082,649
| true
|
{"Java": 572028, "Kotlin": 472360, "HTML": 15099, "AIDL": 11594}
|
package arun.com.chromer.util.animations
import android.os.Build.VERSION.SDK_INT
import android.os.Build.VERSION_CODES.LOLLIPOP
import android.view.View
import android.view.View.*
import androidx.dynamicanimation.animation.DynamicAnimation
import androidx.dynamicanimation.animation.SpringAnimation
import androidx.dynamicanimation.animation.SpringForce
private fun getKey(property: DynamicAnimation.ViewProperty) = when (property) {
SpringAnimation.TRANSLATION_X -> TRANSLATION_X.name
SpringAnimation.TRANSLATION_Y -> TRANSLATION_Y.name
SpringAnimation.TRANSLATION_Z -> TRANSLATION_Z.name
SpringAnimation.SCALE_X -> SCALE_X.name
SpringAnimation.SCALE_Y -> SCALE_Y.name
SpringAnimation.ROTATION -> ROTATION.name
SpringAnimation.ROTATION_X -> ROTATION_X.name
SpringAnimation.ROTATION_Y -> ROTATION_Y.name
SpringAnimation.X -> X.name
SpringAnimation.Y -> Y.name
SpringAnimation.Z -> Z.name
SpringAnimation.ALPHA -> ALPHA.name
SpringAnimation.SCROLL_X -> "SCROLL_X"
SpringAnimation.SCROLL_Y -> "SCROLL_Y"
else -> throw IllegalAccessException("Unknown ViewProperty: $property")
}.hashCode()
fun View.spring(
property: DynamicAnimation.ViewProperty,
stiffness: Float = SpringForce.STIFFNESS_MEDIUM,
damping: Float = SpringForce.DAMPING_RATIO_NO_BOUNCY,
startVelocity: Float? = null
): SpringAnimation {
val key = getKey(property)
var springAnim = getTag(key) as? SpringAnimation?
if (springAnim == null) {
springAnim = SpringAnimation(this, property).apply {
spring = SpringForce().apply {
this.dampingRatio = damping
this.stiffness = stiffness
startVelocity?.let(::setStartVelocity)
}
}
setTag(key, springAnim)
}
return springAnim
}
| 0
|
Java
|
0
| 1
|
8ae744e51849a961059517fa50f6c5fd5e580fd9
| 1,729
|
lynket-browser
|
Condor Public License v1.1
|
algorithms-kotlin/src/main/kotlin/io/github/brunogabriel/math/Factorial.kt
|
brunogabriel
| 294,995,479
| false
| null |
package io.github.brunogabriel.math
fun factorial(number: Long): Long {
if (number < 0L) {
return Long.MIN_VALUE
}
var result = 1L
(2L..number).forEach {
result *= it
}
return result
}
fun factorialRecursive(number: Long): Long {
return when {
number < 0L -> return Long.MIN_VALUE
number <= 1L -> 1L
else -> number * factorialRecursive(number - 1)
}
}
| 0
|
Kotlin
|
0
| 3
|
050a7093c0f2cf3864157c74adb84a969dea8882
| 429
|
algorithms
|
MIT License
|
src/test/kotlin/uk/gov/justice/digital/hmpps/personrecord/message/listeners/OffenderDomainEventsListenerIntTest.kt
|
ministryofjustice
| 608,040,205
| false
|
{"Kotlin": 213786, "PLpgSQL": 15020, "Shell": 2601, "Dockerfile": 1145, "Makefile": 214}
|
package uk.gov.justice.digital.hmpps.personrecord.message.listeners
import org.assertj.core.api.Assertions.assertThat
import org.awaitility.kotlin.await
import org.awaitility.kotlin.matches
import org.awaitility.kotlin.untilCallTo
import org.awaitility.kotlin.untilNotNull
import org.junit.jupiter.api.Test
import uk.gov.justice.digital.hmpps.personrecord.integration.MessagingMultiNodeTestBase
import uk.gov.justice.digital.hmpps.personrecord.message.processors.delius.NEW_OFFENDER_CREATED
import uk.gov.justice.digital.hmpps.personrecord.model.DomainEvent
import uk.gov.justice.digital.hmpps.personrecord.model.PersonIdentifier
import uk.gov.justice.digital.hmpps.personrecord.model.PersonReference
import uk.gov.justice.digital.hmpps.personrecord.model.identifiers.PNCIdentifier
import uk.gov.justice.digital.hmpps.personrecord.service.type.TelemetryEventType.CPR_RECORD_CREATED
import uk.gov.justice.digital.hmpps.personrecord.service.type.TelemetryEventType.DELIUS_RECORD_CREATION_RECEIVED
import uk.gov.justice.digital.hmpps.personrecord.test.messages.newProbationRecord
import uk.gov.justice.digital.hmpps.personrecord.test.messages.notFoundResponse
import uk.gov.justice.digital.hmpps.personrecord.test.messages.nullPnc
import uk.gov.justice.hmpps.sqs.countAllMessagesOnQueue
import java.time.Duration
import java.util.UUID
import java.util.concurrent.TimeUnit.SECONDS
class OffenderDomainEventsListenerIntTest : MessagingMultiNodeTestBase() {
private fun probationDomainCreatedEventUrl(crn: String) = "/probation-case.engagement.created/$crn"
@Test
fun `should receive the message successfully when new offender event published`() {
// Given
val crn = UUID.randomUUID().toString()
val pnc = "2020/0476873U"
patchRequest(probationDomainCreatedEventUrl(crn), newProbationRecord(crn, pnc))
val expectedPncNumber = PNCIdentifier.from(pnc)
val crnType = PersonIdentifier("CRN", crn)
val personReference = PersonReference(listOf(crnType))
val domainEvent = DomainEvent(eventType = NEW_OFFENDER_CREATED, detailUrl = createDeliusDetailUrl(crn), personReference = personReference, additionalInformation = null)
publishDomainEvent(NEW_OFFENDER_CREATED, domainEvent)
val personEntity = await.atMost(10, SECONDS) untilNotNull { personRepository.findByCrn(crn) }
assertThat(personEntity.pnc).isEqualTo(expectedPncNumber)
assertThat(personEntity.crn).isEqualTo(crn)
checkTelemetry(DELIUS_RECORD_CREATION_RECEIVED, mapOf("CRN" to crn))
checkTelemetry(CPR_RECORD_CREATED, mapOf("SourceSystem" to "DELIUS", "CRN" to crn))
}
@Test
fun `should write offender without PNC if PNC is missing`() {
val crn = UUID.randomUUID().toString()
patchRequest(probationDomainCreatedEventUrl(crn), newProbationRecord(crn, pnc = null))
val crnType = PersonIdentifier("CRN", crn)
val personReference = PersonReference(listOf(crnType))
val domainEvent = DomainEvent(eventType = NEW_OFFENDER_CREATED, detailUrl = createDeliusDetailUrl(crn), personReference = personReference, additionalInformation = null)
publishDomainEvent(NEW_OFFENDER_CREATED, domainEvent)
val personEntity = await.atMost(10, SECONDS) untilNotNull { personRepository.findByCrn(crn) }
assertThat(personEntity.pnc?.pncId).isEqualTo("")
assertThat(personEntity.crn).isEqualTo(crn)
checkTelemetry(DELIUS_RECORD_CREATION_RECEIVED, mapOf("CRN" to crn))
checkTelemetry(CPR_RECORD_CREATED, mapOf("SourceSystem" to "DELIUS", "CRN" to crn))
}
@Test
fun `should handle new offender details with null pnc`() {
val crn = UUID.randomUUID().toString()
patchRequest(probationDomainCreatedEventUrl(crn), nullPnc(crn))
val crnType = PersonIdentifier("CRN", crn)
val personReference = PersonReference(listOf(crnType))
val domainEvent = DomainEvent(eventType = NEW_OFFENDER_CREATED, detailUrl = createDeliusDetailUrl(crn), personReference = personReference, additionalInformation = null)
publishDomainEvent(NEW_OFFENDER_CREATED, domainEvent)
val personEntity = await.atMost(10, SECONDS) untilNotNull { personRepository.findByCrn(crn) }
checkTelemetry(DELIUS_RECORD_CREATION_RECEIVED, mapOf("CRN" to crn))
checkTelemetry(CPR_RECORD_CREATED, mapOf("SourceSystem" to "DELIUS", "CRN" to crn))
assertThat(personEntity.pnc?.pncId).isEqualTo("")
assertThat(personEntity.crn).isEqualTo(crn)
}
@Test
fun `should handle new offender details with an empty pnc`() {
val crn = UUID.randomUUID().toString()
patchRequest(probationDomainCreatedEventUrl(crn), newProbationRecord(crn, pnc = ""))
val crnType = PersonIdentifier("CRN", crn)
val personReference = PersonReference(listOf(crnType))
val domainEvent = DomainEvent(eventType = NEW_OFFENDER_CREATED, detailUrl = createDeliusDetailUrl(crn), personReference = personReference, additionalInformation = null)
publishDomainEvent(NEW_OFFENDER_CREATED, domainEvent)
val personEntity = await.atMost(10, SECONDS) untilNotNull { personRepository.findByCrn(crn) }
assertThat(personEntity.pnc?.pncId).isEqualTo("")
assertThat(personEntity.crn).isEqualTo(crn)
checkTelemetry(DELIUS_RECORD_CREATION_RECEIVED, mapOf("CRN" to crn))
checkTelemetry(CPR_RECORD_CREATED, mapOf("SourceSystem" to "DELIUS", "CRN" to crn))
}
@Test
fun `should not push 404 to dead letter queue`() {
// Given
val crn = UUID.randomUUID().toString()
patchRequest(probationDomainCreatedEventUrl(crn), notFoundResponse(), 404)
val crnType = PersonIdentifier("CRN", crn)
val personReference = PersonReference(listOf(crnType))
val domainEvent = DomainEvent(eventType = NEW_OFFENDER_CREATED, detailUrl = createDeliusDetailUrl(crn), personReference = personReference, additionalInformation = null)
publishDomainEvent(NEW_OFFENDER_CREATED, domainEvent)
await.atMost(Duration.ofSeconds(5)) untilCallTo {
offenderEventsQueue?.sqsClient?.countAllMessagesOnQueue(offenderEventsQueue!!.queueUrl)?.get()
} matches { it == 0 }
await.atMost(Duration.ofSeconds(5)) untilCallTo {
offenderEventsQueue?.sqsDlqClient?.countAllMessagesOnQueue(offenderEventsQueue!!.dlqUrl!!)?.get()
} matches { it == 0 }
checkTelemetry(DELIUS_RECORD_CREATION_RECEIVED, mapOf("CRN" to crn))
}
}
| 8
|
Kotlin
|
2
| 1
|
0403e4eae7fd4191d10adcb7838c055a3fe680a0
| 6,279
|
hmpps-person-record
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.