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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sickcore-api/fabric/src/main/kotlin/net/sickmc/sickcore/api/fabric/commands/InventorySeeCommand.kt | SickMC | 450,823,022 | false | {"Kotlin": 48786, "Java": 14148} | package net.sickmc.sickcore.api.fabric.commands
import net.minecraft.commands.CommandSourceStack
import net.minecraft.commands.arguments.GameProfileArgument
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.SimpleMenuProvider
import net.minecraft.world.inventory.AbstractContainerMenu
import net.minecraft.world.inventory.ChestMenu
import net.minecraft.world.inventory.ContainerListener
import net.minecraft.world.inventory.MenuType
import net.minecraft.world.item.ItemStack
import net.sickmc.sickcore.api.fabric.server
import net.silkmc.silk.commands.LiteralCommandBuilder
import net.silkmc.silk.commands.PermissionLevel
import net.silkmc.silk.commands.command
val invSeeCommand = command("invsee") {
invCommand(false)
}
val enderChestSeeCommand = command("enderchestsee") {
alias("ecsee")
invCommand(true)
}
private fun LiteralCommandBuilder<CommandSourceStack>.invCommand(ec: Boolean) {
requiresPermissionLevel(PermissionLevel.BAN_RIGHTS)
argument("target", GameProfileArgument.gameProfile()) { targetPl ->
runs {
val player = source.playerOrException
val targetProfile = targetPl().getNames(source).first()
var offline = false
val target = server.playerList.getPlayer(targetProfile.id) ?: ServerPlayer(
server, server.overworld(), targetProfile, null
).also {
server.playerList.load(it)
offline = true
}
player.openMenu(SimpleMenuProvider({ i: Int, playerInventory, _ ->
ChestMenu(
if (ec) MenuType.GENERIC_9x3 else MenuType.GENERIC_9x4,
i,
playerInventory,
if (ec) target.enderChestInventory else target.inventory,
if (ec) 3 else 4
).apply {
addSlotListener(object : ContainerListener {
override fun slotChanged(
abstractContainerMenu: AbstractContainerMenu, i: Int, itemStack: ItemStack
) {
if (offline) {
server.playerList.players.add(target)
server.playerList.saveAll()
server.playerList.players.remove(target)
}
}
override fun dataChanged(abstractContainerMenu: AbstractContainerMenu, i: Int, j: Int) {}
})
}
}, target.name))
}
}
} | 2 | Kotlin | 0 | 2 | f09ecb79c38bab89fa435061a4b3810ccef9e70d | 2,618 | SickCore | MIT License |
app/src/main/java/com/unixtrong/salarybox/home/HomeViewModel.kt | Unixtrong | 117,833,226 | false | null | package com.unixtrong.salarybox.home
import android.app.Application
import android.arch.lifecycle.AndroidViewModel
import com.unixtrong.salarybox.arch.SingleLiveEvent
import com.unixtrong.salarybox.data.source.SalaryRepo
/**
* danyun
* 2018/1/22
*/
class HomeViewModel(app: Application, salaryRepo: SalaryRepo) : AndroidViewModel(app) {
val openDetailsEvent = SingleLiveEvent<String>()
} | 0 | Kotlin | 0 | 0 | 98c7236c917885bf135f57f9e35578e25af6afbb | 396 | salary-box | Apache License 2.0 |
app/src/main/java/es/voghdev/playbattlegrounds/features/season/model/PlayerSeasonGameModeStats.kt | JcMinarro | 132,865,433 | true | {"Kotlin": 162816} | /*
* Copyright (C) 2018 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package es.voghdev.playbattlegrounds.features.season.model
data class PlayerSeasonGameModeStats(
val killPoints: Float = 0f,
val kills: Int = 0,
val top10s: Int = 0,
val winPoints: Float = 0f,
val roundsPlayed: Int = 0,
val wins: Int = 0
)
| 0 | Kotlin | 0 | 0 | dc17db29406aff4c5cfe1d3eda463697c88837ea | 880 | PlayBattlegrounds | Apache License 2.0 |
hive-connector/src/main/kotlin/io/pivotal/cloud/hive/HiveDriverAdapter.kt | pivotal-legacy | 76,569,067 | false | null | /*
* Copyright (C) 2016-Present Pivotal Software, Inc. All rights reserved.
*
* This program and the accompanying materials are made available under
*
* the terms of the 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.pivotal.cloud.hive
import org.apache.hive.jdbc.HiveDriver
import java.sql.Connection
import java.sql.Driver
import java.sql.DriverManager
import java.sql.SQLException
import java.util.*
/**
* Since Hive jdbc driver {@code org.apache.hive.jdbc.HiveDriver} is not able to extract the username and password from jdbc URL,
* this class acts as adapter to extract those information and provide them explicitly.
*/
class HiveDriverAdapter : Driver by driver {
companion object {
init {
try {
DriverManager.registerDriver(HiveDriverAdapter())
} catch (e: SQLException) {
e.printStackTrace()
}
}
val driver: HiveDriver = HiveDriver()
}
override fun connect(url: String, info: Properties): Connection {
val connectionInfo = ConnectionAdapter().adapt(url)
info.setProperty("user", connectionInfo.username)
info.setProperty("password", connectionInfo.password)
return driver.connect(connectionInfo.uri, info)
}
}
class ConnectionAdapter {
fun adapt(url: String): ConnectionInfo {
val startOfQuery = url.indexOf('?')
if (startOfQuery == -1) return ConnectionInfo(url, "", "")
val queryParams = url.substring(startOfQuery + 1).split('&').map {
val (name, value) = it.split("=")
Pair(name, value)
}
val user = queryParams.find { it.first == "user" }?.second ?: ""
val password = queryParams.find { it.first == "password" }?.second ?: ""
val newQueryParams = queryParams
.filter { it.first !in listOf("user", "password") }
.map { "${it.first}=${it.second}" }
.joinToString("&")
val urlBase = url.substring(0, startOfQuery)
val newUrl = if (newQueryParams.isBlank()) urlBase else "$urlBase?$newQueryParams"
return ConnectionInfo(newUrl, user, password)
}
}
data class ConnectionInfo(val uri: String,
val username: String,
val password: String)
| 2 | Kotlin | 3 | 5 | 66c68f3e3781dde22523d33b087768c5bd6bc678 | 2,847 | simple-hive | Apache License 2.0 |
src/test/kotlin/algorithms/AlgorithmsTest.kt | Jordan396 | 723,897,827 | false | {"Kotlin": 11260} | package utils
import objects.ProcessedWordMap
import org.junit.jupiter.api.Test
class AlgorithmsTest {
@Test
fun `findLongestWord should find the longest word`() {
// val processedWordMap = mockk<ProcessedWordMap>
}
} | 0 | Kotlin | 0 | 0 | c75b5ec1bc3f0eb580d64d5c3d1bc31981f9b71a | 238 | bananagrams-solver | MIT License |
app/src/main/kotlin/com/ivanovsky/passnotes/presentation/setupOneTimePassword/SetupOneTimePasswordInteractor.kt | aivanovski | 95,774,290 | false | {"Kotlin": 1570745, "Java": 110321, "Ruby": 2731} | package com.ivanovsky.passnotes.presentation.setupOneTimePassword
import com.ivanovsky.passnotes.domain.otp.OtpParametersValidator
import com.ivanovsky.passnotes.domain.otp.OtpUriFactory
import com.ivanovsky.passnotes.util.StringUtils.EMPTY
class SetupOneTimePasswordInteractor {
fun isPeriodValid(period: Int?): Boolean {
return OtpParametersValidator.isPeriodValid(period)
}
fun isCounterValid(counter: Long?): Boolean {
return OtpParametersValidator.isCounterValid(counter)
}
fun isDigitsValid(digits: Int?): Boolean {
return OtpParametersValidator.isDigitsValid(digits)
}
fun isSecretValid(secret: String?): Boolean {
return OtpParametersValidator.isSecretValid(secret)
}
fun isUrlValid(url: String?): Boolean {
return OtpUriFactory.parseUri(url ?: EMPTY) != null
}
} | 6 | Kotlin | 4 | 53 | 83605c13c7f13e1f484aa00f6b3e9af622880888 | 858 | keepassvault | Apache License 2.0 |
shared/src/commonMain/kotlin/account/presentation/ProfileSheet.kt | FelixHennerich | 674,391,173 | false | {"Kotlin": 157194, "Swift": 718, "Shell": 228, "Ruby": 101} | package account.presentation
import account.RESTfulUserManager
import account.manager.FollowManagerClass
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowBack
import androidx.compose.material.icons.rounded.Person
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import event.TrendWaveEvent
import event.TrendWaveState
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import managers.DataStorageManager
import post.Post
import post.RESTfulPostManager
import post.presentation.PostDisplay
import utilities.presentation.BottomSheet
@Composable
fun ProfileSheet(
isOpen: Boolean,
localDataSource: DataStorageManager,
onEvent: (TrendWaveEvent) -> Unit,
state: TrendWaveState,
pageOwner: RESTfulUserManager.User,
) {
BottomSheet(
visible = isOpen,
modifier = Modifier.fillMaxSize(),
backgroundcolor = Color.White,
padding = 0.dp
) {
var posts by remember { mutableStateOf<List<Post>>(emptyList()) }
GlobalScope.launch {
val restapi = RESTfulPostManager(state)
posts = restapi.getUserPosts(pageOwner.uuid)
}
Scaffold(
modifier = Modifier.offset(y = 25.dp).fillMaxWidth()
) {
Row(
modifier = Modifier
.height(60.dp)
.fillMaxWidth()
.background(Color(230, 255, 255)),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
IconButton(onClick = {onEvent(TrendWaveEvent.ClickCloseProfileScreen)}) {
Icon(
imageVector = Icons.Rounded.ArrowBack,
contentDescription = "",
)
}
Text(
text = "@",
fontSize = 20.sp,
fontWeight = FontWeight.SemiBold,
)
Text(
text = pageOwner.username,
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(end = 260.dp)
)
}
Box(
modifier = Modifier.fillMaxWidth().offset(y = 90.dp),
contentAlignment = Alignment.Center
) {
Row(
modifier = Modifier
.background(Color(255, 204, 204), RoundedCornerShape(30.dp))
.padding(50.dp),
horizontalArrangement = Arrangement.Center
) {
Icon(
imageVector = Icons.Rounded.Person,
contentDescription = "",
modifier = Modifier.scale(3f),
)
}
}
Row (
modifier = Modifier.offset(y = 160.dp).fillMaxWidth().padding(50.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
){
Text(
text = "Follower: ${pageOwner.follower}",
fontWeight = FontWeight.SemiBold,
fontSize = 15.sp,
modifier = Modifier.padding(15.dp)
)
Text(
text = "Following: ${pageOwner.following}",
fontWeight = FontWeight.SemiBold,
fontSize = 15.sp,
modifier = Modifier.padding(15.dp)
)
}
var color by remember { mutableStateOf(Color.Transparent) }
if (state.user?.followed?.contains(pageOwner.uuid) == false) {
color = Color.Red
}else {
color = Color.LightGray
}
Column(
modifier = Modifier.fillMaxWidth().offset(y = 265.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Box(
modifier = Modifier
.background(color, RoundedCornerShape(20))
.clickable {
GlobalScope.launch {
val followManager = FollowManagerClass(state, onEvent)
if (state.user?.followed?.contains(pageOwner.uuid) == false) {
state.user?.let { it1 ->
followManager.followUser(
it1.uuid,
pageOwner.uuid
)
onEvent(TrendWaveEvent.FollowUser(
pageOwner.uuid,
state.user!!
))
}
onEvent(TrendWaveEvent.ClickCloseProfileScreen)
}else {
state.user?.let { it1 ->
followManager.unfollowUser(
it1.uuid,
pageOwner.uuid
)
onEvent(TrendWaveEvent.UnfollowUser(
pageOwner.uuid,
state.user!!
))
}
onEvent(TrendWaveEvent.ClickCloseProfileScreen)
}
}
}
) {
if (state.user?.followed?.contains(pageOwner.uuid) == false) {
if (pageOwner.uuid != state.user?.uuid) {
Text(
text = "Subscribe",
fontWeight = FontWeight.ExtraBold,
color = Color.White,
modifier = Modifier.padding(10.dp)
)
}
}else {
if (pageOwner.uuid != state.user?.uuid) {
Text(
text = "Subscribed",
fontWeight = FontWeight.ExtraBold,
color = Color.White,
modifier = Modifier.padding(10.dp)
)
}
}
}
}
Column(
verticalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.offset(y = 320.dp)
) {
Text(
text = "${pageOwner.username}'s activity",
modifier = Modifier.offset(x = 20.dp),
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
for (post in posts) {
PostDisplay(
modifier = Modifier.fillMaxWidth(),
posttext = post.text,
postuser = post.username,
postuuid = post.uuid,
postdate = post.date,
postid = post.id,
localDataStorageManager = localDataSource,
onEvent = onEvent,
state = state
)
}
}
}
}
} | 8 | Kotlin | 2 | 3 | 1c8c9720c60ea89e382fc6a730ed2e3024eafaab | 9,116 | TrendWave-App | Apache License 2.0 |
vknews/src/main/java/com/stacktivity/vknews/model/NewsItemSourceInfo.kt | FireTiger33 | 386,420,851 | false | {"Java": 51616, "Kotlin": 40245} | package com.stacktivity.vknews.model
data class NewsItemSourceInfo(
val name: String,
val avatarUrl: String?
) | 1 | null | 1 | 1 | 1a1677790fab113fb00c314b5a46f96bae1542ab | 119 | VkCup_2021_android | Apache License 2.0 |
magellan-sample-advanced/src/main/java/com/wealthfront/magellan/sample/advanced/suggestexhibit/SuggestConfirmationStep.kt | wealthfront | 82,854,849 | false | null | package com.wealthfront.magellan.sample.advanced.suggestexhibit
import android.content.Context
import com.wealthfront.magellan.core.Step
import com.wealthfront.magellan.sample.advanced.SampleApplication.Companion.app
import com.wealthfront.magellan.sample.advanced.ToolbarHelper
import com.wealthfront.magellan.sample.advanced.databinding.SuggestExhibitConfirmationBinding
import javax.inject.Inject
class SuggestConfirmationStep(
private val finishFlow: () -> Unit
) : Step<SuggestExhibitConfirmationBinding>(SuggestExhibitConfirmationBinding::inflate) {
@Inject lateinit var toolbarHelper: ToolbarHelper
override fun onCreate(context: Context) {
app(context).injector().inject(this)
}
override fun onShow(context: Context, binding: SuggestExhibitConfirmationBinding) {
binding.acknowledgeSubmitted.setOnClickListener { finishFlow() }
toolbarHelper.setTitle("Thank you")
}
}
| 35 | Kotlin | 66 | 684 | de2f7a90da9f696b1e7d55550208b668c1a3eccc | 905 | magellan | Apache License 2.0 |
client/src/commonMain/kotlin/com/algolia/search/configuration/Region.kt | algolia | 153,273,215 | false | {"Kotlin": 1346247, "Dockerfile": 163} | package com.algolia.search.configuration
import com.algolia.search.model.internal.Raw
import com.algolia.search.serialize.internal.Key
/**
* Region configuration, used in some [Configuration] implementations.
*/
public sealed class Region {
/**
* Available analytics' regions, used in [ConfigurationAnalytics].
*/
public sealed class Analytics(override val raw: String) : Raw<String> {
public object EU : Analytics(Key.DE)
public object US : Analytics(Key.US)
public class Other(override val raw: String) : Analytics(raw)
override fun toString(): String = raw
}
/**
* Available regions, used in [ConfigurationPersonalization].
*/
public sealed class Personalization(override val raw: String) : Raw<String> {
public object EU : Personalization(Key.EU)
public object US : Personalization(Key.US)
public class Other(override val raw: String) : Personalization(raw)
override fun toString(): String = raw
}
}
| 14 | Kotlin | 23 | 59 | 21f0c6bd3c6c69387d1dd4ea09f69a220c5eaff4 | 1,022 | algoliasearch-client-kotlin | MIT License |
common/src/commonMain/kotlin/entity/DiscordRole.kt | kordlib | 202,856,399 | false | null | package dev.kord.common.entity
import dev.kord.common.entity.optional.Optional
import dev.kord.common.entity.optional.OptionalBoolean
import dev.kord.common.entity.optional.OptionalInt
import dev.kord.common.entity.optional.OptionalSnowflake
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
public data class DiscordRole(
val id: Snowflake,
val name: String,
val color: Int,
val hoist: Boolean,
val icon: Optional<String?> = Optional.Missing(),
@SerialName("unicode_emoji")
val unicodeEmoji: Optional<String?> = Optional.Missing(),
val position: Int,
val permissions: Permissions,
val managed: Boolean,
val mentionable: Boolean,
val tags: Optional<DiscordRoleTags> = Optional.Missing(),
)
@Serializable
public data class DiscordRoleTags(
@SerialName("bot_id")
val botId: OptionalSnowflake = OptionalSnowflake.Missing,
@SerialName("integration_id")
val integrationId: OptionalSnowflake = OptionalSnowflake.Missing,
@SerialName("premium_subscriber")
val premiumSubscriber: Optional<Nothing?> = Optional.Missing(),
@SerialName("subscription_listing_id")
val subscriptionListingId: OptionalSnowflake = OptionalSnowflake.Missing,
@SerialName("available_for_purchase")
val availableForPurchase: Optional<Nothing?> = Optional.Missing(),
@SerialName("guild_connections")
val guildConnections: Optional<Nothing?> = Optional.Missing(),
)
@Serializable
public data class DiscordPartialRole(
val id: Snowflake,
val name: Optional<String> = Optional.Missing(),
val color: OptionalInt = OptionalInt.Missing,
val hoist: OptionalBoolean = OptionalBoolean.Missing,
val icon: Optional<String?> = Optional.Missing(),
@SerialName("unicode_emoji")
val unicodeEmoji: Optional<String?> = Optional.Missing(),
val position: OptionalInt = OptionalInt.Missing,
val permissions: Optional<Permissions> = Optional.Missing(),
val managed: OptionalBoolean = OptionalBoolean.Missing,
val mentionable: OptionalBoolean = OptionalBoolean.Missing,
val tags: Optional<DiscordRoleTags> = Optional.Missing(),
)
@Serializable
public data class DiscordAuditLogRoleChange(
val id: String,
val name: String? = null,
val color: Int? = null,
val hoist: Boolean? = null,
val position: Int? = null,
val permissions: Permissions? = null,
val managed: Boolean? = null,
val mentionable: Boolean? = null,
)
@Serializable
public data class DiscordGuildRole(
@SerialName("guild_id")
val guildId: Snowflake,
val role: DiscordRole,
)
@Serializable
public data class DiscordDeletedGuildRole(
@SerialName("guild_id")
val guildId: Snowflake,
@SerialName("role_id")
val id: Snowflake,
)
| 43 | Kotlin | 67 | 754 | 59d83d9d35e84180d7ccb9e676769d89b28f7eea | 2,785 | kord | MIT License |
src/main/kotlin/org/bibletranslationtools/scriptureburrito/flavor/scripture/text/TextTranslationSchema.kt | Bible-Translation-Tools | 804,953,693 | false | {"Kotlin": 157326} | package org.bibletranslationtools.scriptureburrito.flavor.scripture.text
import com.fasterxml.jackson.annotation.*
import com.fasterxml.jackson.databind.JsonNode
import org.bibletranslationtools.scriptureburrito.flavor.FlavorSchema
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder(
"name", "projectType", "translationType", "audience", "usfmVersion", "conventions"
)
class TextTranslationSchema: FlavorSchema() {
@get:JsonProperty("name")
@set:JsonProperty("name")
@JsonProperty("name")
override lateinit var name: String
@get:JsonProperty("projectType")
@set:JsonProperty("projectType")
@JsonProperty("projectType")
var projectType: ProjectType? = null
@get:JsonProperty("translationType")
@set:JsonProperty("translationType")
@JsonProperty("translationType")
var translationType: TranslationType? = null
@get:JsonProperty("audience")
@set:JsonProperty("audience")
@JsonProperty("audience")
var audience: Audience? = null
@get:JsonProperty("usfmVersion")
@set:JsonProperty("usfmVersion")
@JsonProperty("usfmVersion")
var usfmVersion: String? = null
@JsonProperty("conventions")
private var conventions: JsonNode? = null
@JsonProperty("conventions")
fun getConventions(): JsonNode? {
return conventions
}
@JsonProperty("conventions")
fun setConventions(conventions: JsonNode?) {
this.conventions = conventions
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is TextTranslationSchema) return false
if (name != other.name) return false
if (projectType != other.projectType) return false
if (translationType != other.translationType) return false
if (audience != other.audience) return false
if (usfmVersion != other.usfmVersion) return false
if (conventions != other.conventions) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + (projectType?.hashCode() ?: 0)
result = 31 * result + (translationType?.hashCode() ?: 0)
result = 31 * result + (audience?.hashCode() ?: 0)
result = 31 * result + (usfmVersion?.hashCode() ?: 0)
result = 31 * result + (conventions?.hashCode() ?: 0)
return result
}
override fun toString(): String {
return "TextTranslationSchema(name=$name, projectType=$projectType, translationType=$translationType, audience=$audience, usfmVersion=$usfmVersion, conventions=$conventions)"
}
enum class Audience(private val value: String) {
BASIC("basic"),
COMMON("common"),
COMMON_LITERARY("common-literary"),
LITERARY("literary"),
LITURGICAL("liturgical"),
CHILDREN("children");
override fun toString(): String {
return this.value
}
@JsonValue
fun value(): String {
return this.value
}
companion object {
private val CONSTANTS: MutableMap<String, Audience> = HashMap()
init {
for (c in values()) {
CONSTANTS[c.value] = c
}
}
@JsonCreator
fun fromValue(value: String): Audience {
val constant = CONSTANTS[value]
requireNotNull(constant) { value }
return constant
}
}
}
enum class ProjectType(private val value: String) {
STANDARD("standard"),
DAUGHTER("daughter"),
STUDY_BIBLE("studyBible"),
STUDY_BIBLE_ADDITIONS("studyBibleAdditions"),
BACK_TRANSLATION("backTranslation"),
AUXILIARY("auxiliary"),
TRANSLITERATION_MANUAL("transliterationManual"),
TRANSLITERATION_WITH_ENCODER("transliterationWithEncoder");
override fun toString(): String {
return this.value
}
@JsonValue
fun value(): String {
return this.value
}
companion object {
private val CONSTANTS: MutableMap<String, ProjectType> = HashMap()
init {
for (c in values()) {
CONSTANTS[c.value] = c
}
}
@JsonCreator
fun fromValue(value: String): ProjectType {
val constant = CONSTANTS[value]
requireNotNull(constant) { value }
return constant
}
}
}
enum class TranslationType(private val value: String) {
FIRST_TRANSLATION("firstTranslation"),
NEW_TRANSLATION("newTranslation"),
REVISION("revision"),
STUDY_OR_HELP_MATERIAL("studyOrHelpMaterial");
override fun toString(): String {
return this.value
}
@JsonValue
fun value(): String {
return this.value
}
companion object {
private val CONSTANTS: MutableMap<String, TranslationType> = HashMap()
init {
for (c in values()) {
CONSTANTS[c.value] = c
}
}
@JsonCreator
fun fromValue(value: String): TranslationType {
val constant = CONSTANTS[value]
requireNotNull(constant) { value }
return constant
}
}
}
}
| 0 | Kotlin | 0 | 1 | 71170bc16a35ba4e5a69f80f1a68dc162260ad48 | 5,486 | kotlin-scripture-burrito | MIT License |
implementation/src/test/kotlin/com/aoc/intcode/droid/spring/HullDamageReportTest.kt | TomPlum | 227,887,094 | false | null | package com.aoc.intcode.droid.spring
import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.isNotEqualTo
import org.junit.jupiter.api.Test
class HullDamageReportTest {
@Test
fun toStringTest() {
assertThat(HullDamageReport(1223234234).toString()).isEqualTo("1223234234")
}
@Test
fun equalityPositive() {
assertThat(HullDamageReport(345345234)).isEqualTo(HullDamageReport(345345234))
}
@Test
fun equalityNegative() {
assertThat(HullDamageReport(8345234234)).isNotEqualTo(HullDamageReport(345345234))
}
} | 7 | null | 1 | 2 | 12d47cc9c50aeb9e20bcf110f53d097d8dc3762f | 599 | advent-of-code-2019 | Apache License 2.0 |
Megazord_Poke_KMM/module/src/commonMain/kotlin/br/com/manobray/megazordpokeappp/PokemonFacade.kt | 1ucas | 380,384,065 | false | null | import br.com.manobray.megazordpokeappp.network.Pokemon
import br.com.manobray.megazordpokeappp.network.PokemonApi
class PokemonFacade {
private val api = PokemonApi()
@Throws(Exception::class) suspend fun getPokemonTop() : Pokemon {
return api.getCharmander()
}
@Throws(Exception::class) suspend fun listPokemons() : List<String> {
return api.listPokemons().results.map { it.name }
}
} | 0 | Kotlin | 0 | 9 | 3816e7fd4fad791f2e17f90cb83ac6ee1688a96e | 426 | megazord-pokemon-mobile | The Unlicense |
app/src/main/java/com/shurikus/boostnoteandroid/ui/storage/storageactivity/StorageActivity.kt | ShurikuS57 | 147,323,031 | false | null | package com.shurikus.boostnoteandroid.ui.storage.storageactivity
import android.os.Bundle
import com.arellomobile.mvp.presenter.InjectPresenter
import com.shurikus.boostnoteandroid.R
import com.shurikus.boostnoteandroid.di.DI
import com.shurikus.boostnoteandroid.presentation.storage.activity.StoragePresenter
import com.shurikus.boostnoteandroid.presentation.storage.activity.StorageView
import com.shurikus.boostnoteandroid.ui.base.BaseActivity
import toothpick.Toothpick
class StorageActivity : BaseActivity(), StorageView {
override val layoutRes = R.layout.activity_storage
@InjectPresenter
lateinit var presenter: StoragePresenter
override fun onCreate(savedInstanceState: Bundle?) {
Toothpick.inject(this, Toothpick.openScope(DI.APP_SCOPE))
super.onCreate(savedInstanceState)
}
} | 0 | Kotlin | 0 | 0 | 35b0ba0000811cc7bdbe7178a1811bb9bfce938a | 827 | BoostNoteAndroid | Apache License 2.0 |
profilers/src/com/android/tools/profilers/tasks/taskhandlers/singleartifact/SingleArtifactTaskHandler.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.profilers.tasks.taskhandlers.singleartifact
import com.android.tools.profilers.InterimStage
import com.android.tools.profilers.sessions.SessionArtifact
import com.android.tools.profilers.sessions.SessionsManager
import com.android.tools.profilers.tasks.args.TaskArgs
import com.android.tools.profilers.tasks.taskhandlers.ProfilerTaskHandler
import com.android.tools.profilers.tasks.taskhandlers.TaskHandlerUtils
import com.google.common.annotations.VisibleForTesting
/**
* Building on/extending the ProfilerTaskHandler, this abstract class adds and enforces additional functionality catered towards tasks
* backed by a single artifact. It augments the behavior of the ProfilerTaskHandler by introducing and enforcing the use of an InterimStage
* to facilitate the capture of the artifact.
*/
abstract class SingleArtifactTaskHandler<T : InterimStage>(sessionsManager: SessionsManager) : ProfilerTaskHandler(sessionsManager) {
/**
* To collect the single artifact, an interim stage instance is utilized.
*
* For example, to perform a heap dump capture (and thus receive a heap dump artifact), the MainMemoryProfilerStage's
* startHeapDumpCapture method can be invoked.
*/
var stage: T? = null
protected set
/**
* This method sets up the respective stage which translates into (1) creating the instance of the stage and (2) setting the newly created
* stage as the current one.
*
* To be called before invoking the super class' enter method as the stage being prepared is a pre-requisite to start and load a task.
*/
@VisibleForTesting
abstract fun setupStage()
/**
* Builds upon the ProfilerTaskHandler enter method by setting up the respective stage first to enable starting and loading a task.
*/
override fun enter(args: TaskArgs): Boolean {
setupStage()
return super.enter(args)
}
/**
* SingleArtifactTaskHandlers create and store a stage to perform starting, stopping, and loading of the tasks. Yet, when this type of
* task handler is not in use, it is unnecessary to hold onto the instance of the stage. Thus, on exit of the task handler, we null it
* out to prevent a memory leak.
*/
override fun exit() {
stage = null
}
/**
* For a single artifact task handler, starting the task functionally is equivalent to starting the capture of the artifact.
*/
override fun startTask(args: TaskArgs) {
if (stage == null) {
handleError("Cannot start the task as the InterimStage was null")
return
}
// Prevent redundant capture initiation from AndroidProfilerLaunchTaskContributor if the task has already started from startup,
// avoiding potential issues caused by initiating multiple captures in succession.
if (args.isFromStartup) {
return
}
TaskHandlerUtils.executeTaskAction(action = { startCapture(stage!!) }, errorHandler = ::handleError)
}
/**
* For a single artifact task handler, stopping the task functionally is equivalent to stopping the capture of the artifact.
*/
override fun stopTask() {
if (stage == null) {
handleError("Cannot stop the task as the InterimStage was null")
return
}
TaskHandlerUtils.executeTaskAction(action = { stopCapture(stage!!) }, errorHandler = ::handleError)
}
/**
* For a single artifact task handler, loading the task functionally is equivalent to invoke the doSelect method on an artifact.
* This will effectively create and set the capture stage required to display the artifact. To prepare for this doSelect behavior, the
* only pre-requisite is being in the correct InterimStage, which is why we invoke setupStage before entering the task for single
* artifact task handlers.
*/
protected fun loadCapture(artifact: SessionArtifact<*>) {
TaskHandlerUtils.executeTaskAction(action = { artifact.doSelect() }, errorHandler = ::handleError)
}
/**
* Utilizing the parametrized InterimStage, implementations invoke the start of a capture for their respective tasks.
*/
protected abstract fun startCapture(stage: T)
/**
* Utilizing the parametrized InterimStage, implementations invoke the stop of a capture for their respective tasks.
*/
protected abstract fun stopCapture(stage: T)
} | 5 | null | 227 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 4,909 | android | Apache License 2.0 |
app/src/main/java/com/example/bmicalculator/MainActivity.kt | mansoorulhaq166 | 583,747,023 | false | {"Kotlin": 5256} | package com.example.bmicalculator
import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
import androidx.lifecycle.ViewModelProvider
import com.example.bmicalculator.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var viewModel: BMICalculatorViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
ViewCompat.setOnApplyWindowInsetsListener(binding.root) { root, windowInsets ->
val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())
root.updatePadding(bottom = insets.bottom)
windowInsets
}
viewModel = ViewModelProvider(this)[BMICalculatorViewModel::class.java]
binding.buttonCalculate.setOnClickListener {
val weight = binding.editWeight.text.toString().toDoubleOrNull()
val heightFeet = binding.editHeightFeet.text.toString().toDoubleOrNull()
val heightInches = binding.editHeightInches.text.toString().toDoubleOrNull()
var isValid = true
if (weight == null) {
binding.editWeightLayout.error = "Please enter a valid weight"
isValid = false
} else {
binding.editWeightLayout.error = null
}
if (heightFeet == null) {
binding.editHeightFeetLayout.error = "Please enter a valid height (feet)"
isValid = false
} else {
binding.editHeightFeetLayout.error = null
}
if (heightInches == null) {
binding.editHeightInchesLayout.error = "Please enter a valid height (inches)"
isValid = false
} else {
binding.editHeightInchesLayout.error = null
}
if (isValid) {
viewModel.calculateBMI(weight!!, heightFeet!!, heightInches!!)
}
}
viewModel.bmiResult.observe(this) { result ->
binding.textResult.text = result
}
viewModel.bmiCategory.observe(this) { category ->
binding.textMsg.visibility = View.VISIBLE
binding.textMsg.text = category
}
viewModel.backgroundColor.observe(this) { colorResId ->
binding.mainLnrLayout.setBackgroundColor(ContextCompat.getColor(this, colorResId))
}
}
} | 0 | Kotlin | 0 | 0 | 1929e2c71c24a1b40078788010074c026c78e16f | 2,852 | SimpleBmiCalculator | Apache License 2.0 |
src/main/kotlin/com/ingbyr/vdm/views/MainView.kt | vaginessa | 812,440,857 | true | {"Kotlin": 118939, "Shell": 129} | package com.ingbyr.vdm.views
import com.ingbyr.vdm.controllers.MainController
import com.ingbyr.vdm.controllers.ThemeController
import com.ingbyr.vdm.models.DownloadTaskModel
import com.ingbyr.vdm.models.DownloadTaskStatus
import com.ingbyr.vdm.utils.Attributes
import com.ingbyr.vdm.utils.ConfigUtils
import com.ingbyr.vdm.utils.OSUtils
import com.jfoenix.controls.JFXButton
import com.jfoenix.controls.JFXProgressBar
import javafx.scene.control.*
import javafx.scene.layout.ColumnConstraints
import javafx.scene.layout.GridPane
import javafx.scene.layout.VBox
import tornadofx.*
import java.text.DecimalFormat
import java.util.*
class MainView : View() {
init {
messages = ResourceBundle.getBundle("i18n/MainView")
title = messages["ui.vdm"]
}
private val vdmVersion = "0.4.0"
override val root: VBox by fxml("/fxml/MainView.fxml")
private val controller: MainController by inject()
private val themeController: ThemeController by inject()
private val btnNew: JFXButton by fxid()
private val btnStart: JFXButton by fxid()
private val btnStop: JFXButton by fxid()
private val btnDelete: JFXButton by fxid()
private val btnOpenFile: JFXButton by fxid()
private val btnSearch: JFXButton by fxid()
private val btnPreferences: JFXButton by fxid()
private val btnMenu: JFXButton by fxid()
private val contextMenu: ContextMenu = ContextMenu()
private var menuNew: MenuItem
private var menuOpenDir: MenuItem
private var menuStartAllTask: MenuItem
private var menuStopAllTask: MenuItem
private var menuPreferences: MenuItem
private var menuAbout: MenuItem
private var menuQuit: MenuItem
private var menuDonate: MenuItem
private var selectedTaskModel: DownloadTaskModel? = null
private var downloadTaskTableView: TableView<DownloadTaskModel>
init {
themeController.initTheme()
downloadTaskTableView = tableview(controller.downloadTaskModelList) {
fitToParentSize()
columnResizePolicy = SmartResize.POLICY
column(messages["ui.title"], DownloadTaskModel::titleProperty).remainingWidth()
column(messages["ui.size"], DownloadTaskModel::sizeProperty)
column(messages["ui.status"], DownloadTaskModel::statusProperty).cellFormat {
val labelStatus = Label()
when (it!!) {
DownloadTaskStatus.COMPLETED -> labelStatus.text = messages["ui.completed"]
DownloadTaskStatus.STOPPED -> labelStatus.text = messages["ui.stopped"]
DownloadTaskStatus.MERGING -> labelStatus.text = messages["ui.merging"]
DownloadTaskStatus.ANALYZING -> labelStatus.text = messages["ui.analyzing"]
DownloadTaskStatus.DOWNLOADING -> labelStatus.text = messages["ui.downloading"]
DownloadTaskStatus.FAILED -> labelStatus.text = messages["ui.failed"]
}
graphic = labelStatus
}
column(messages["ui.progress"], DownloadTaskModel::progressProperty).pctWidth(20).cellFormat {
val progressFormat = DecimalFormat("#.##")
val progressPane = GridPane()
val progressBar = JFXProgressBar(it.toDouble())
val progressLabel = Label(progressFormat.format(it.toDouble() * 100) + "%")
progressPane.useMaxSize = true
progressPane.add(progressBar, 0, 0)
progressPane.add(progressLabel, 1, 0)
val columnBar = ColumnConstraints()
columnBar.percentWidth = 75.0
val columnLabel = ColumnConstraints()
columnLabel.percentWidth = 25.0
progressPane.columnConstraints.addAll(columnBar, columnLabel)
progressPane.hgap = 10.0
progressBar.useMaxSize = true
progressLabel.useMaxWidth = true
graphic = progressPane
}
column(messages["ui.createdAt"], DownloadTaskModel::createdAtProperty)
contextmenu {
item(messages["ui.stopTask"]).action {
selectedTaskModel?.run { controller.stopTask(this) }
}
item(messages["ui.startTask"]).action {
selectedTaskModel?.run { controller.startTask(this) }
}
item(messages["ui.deleteTask"]).action {
selectedTaskModel?.run { controller.deleteTask(this) }
}
}
}
root += downloadTaskTableView
downloadTaskTableView.placeholder = Label(messages["ui.noTaskInList"])
// init context menu
menuNew = MenuItem(messages["ui.new"])
menuOpenDir = MenuItem(messages["ui.openDirectory"])
menuStartAllTask = MenuItem(messages["ui.startAllTask"])
menuStopAllTask = MenuItem(messages["ui.stopAllTask"])
menuPreferences = MenuItem(messages["ui.preferences"])
menuAbout = MenuItem(messages["ui.about"])
menuQuit = MenuItem(messages["ui.quit"])
menuDonate = MenuItem(messages["ui.donate"])
contextMenu.items.addAll(
menuNew,
menuOpenDir,
menuStartAllTask,
menuStopAllTask,
SeparatorMenuItem(),
menuPreferences,
menuAbout,
menuDonate,
SeparatorMenuItem(),
menuQuit
)
loadVDMConfig()
initListeners()
controller.loadTaskFromDB()
}
private fun loadVDMConfig() {
// create the config file when first time use VDM
val firstTimeUse = ConfigUtils.safeLoad(Attributes.FIRST_TIME_USE, "true").toBoolean()
if (firstTimeUse) {
// init config file
ConfigUtils.update(Attributes.VDM_VERSION, vdmVersion)
find(PreferencesView::class).openWindow()?.hide()
// find(WizardView::class).openWindow(stageStyle = StageStyle.UNDECORATED)?.isAlwaysOnTop = true // todo use this
find(WizardView::class).openWindow()?.isAlwaysOnTop = true // make sure wizard is always on top
// ConfigUtils.update(Attributes.FIRST_TIME_USE, "false") // TODO uncomment this
} else {
ConfigUtils.update(Attributes.VDM_VERSION, vdmVersion)
}
}
private fun initListeners() {
// models list view
downloadTaskTableView.selectionModel.selectedItemProperty().addListener { _, _, selectedItem ->
selectedTaskModel = selectedItem
}
// shortcut buttons
// start models
btnStart.setOnMouseClicked { _ ->
selectedTaskModel?.let { controller.startTask(it) }
}
// preferences view
btnPreferences.setOnMouseClicked {
find(PreferencesView::class).openWindow()
}
// create models
btnNew.setOnMouseClicked {
find(CreateDownloadTaskView::class).openWindow()
}
// delete models
btnDelete.setOnMouseClicked {
selectedTaskModel?.run { controller.deleteTask(this) }
}
// stop models
btnStop.setOnMouseClicked {
selectedTaskModel?.run { controller.stopTask(this) }
}
// open dir
btnOpenFile.setOnMouseClicked {
if (selectedTaskModel != null) {
OSUtils.openDir(selectedTaskModel!!.taskConfig.storagePath)
} else {
OSUtils.openDir(ConfigUtils.load(Attributes.STORAGE_PATH))
}
}
// TODO search models
btnSearch.isVisible = false
btnSearch.setOnMouseClicked {
}
// menus
btnMenu.setOnMouseClicked {
contextMenu.show(primaryStage, it.screenX, it.screenY)
}
menuNew.action {
find(CreateDownloadTaskView::class).openWindow()
}
menuOpenDir.action {
if (selectedTaskModel != null) {
OSUtils.openDir(selectedTaskModel!!.taskConfig.storagePath)
} else {
OSUtils.openDir(ConfigUtils.load(Attributes.STORAGE_PATH))
}
}
menuStartAllTask.action {
controller.startAllTask()
}
menuStopAllTask.action {
controller.stopAllTask()
}
menuPreferences.action {
find(PreferencesView::class).openWindow()
}
menuAbout.action {
find(AboutView::class).openWindow()
}
menuQuit.action {
this.close()
}
menuDonate.action {
openInternalWindow(DonationView::class)
}
}
override fun onUndock() {
super.onUndock()
controller.clear()
selectedTaskModel = null
}
} | 1 | Kotlin | 0 | 0 | d4301c475988232c4fd4c0756ef2f295308b2215 | 8,871 | ingbyr-vdm | MIT License |
src/main/kotlin/codes/som/koffee/insns/sugar/IntConstants.kt | char | 184,816,641 | false | {"Kotlin": 88664} | package codes.som.koffee.insns.sugar
import codes.som.koffee.insns.InstructionAssembly
import codes.som.koffee.insns.jvm.*
/**
* Push an arbitrary integer constant onto the stack.
* It will use the appropriate instruction depending on the value.
*/
public fun InstructionAssembly.push_int(i: Int) {
when (i) {
-1 -> iconst_m1
0 -> iconst_0
1 -> iconst_1
2 -> iconst_2
3 -> iconst_3
4 -> iconst_4
5 -> iconst_5
in Byte.MIN_VALUE .. Byte.MAX_VALUE -> bipush(i)
in Short.MIN_VALUE .. Short.MAX_VALUE -> sipush(i)
else -> ldc(i)
}
}
| 1 | Kotlin | 7 | 76 | 3a78d8a43776bec026a8f3f64cec15c4d76505ce | 624 | Koffee | MIT License |
server/src/main/kotlin/com/joshmlwood/crudadmindemo/service/dto/AdminRoomDTO.kt | jmlw | 260,100,893 | false | null | package com.joshmlwood.crudadmindemo.service.dto
import com.joshmlwood.crudadmindemo.admin.Cardinality
import com.joshmlwood.crudadmindemo.admin.PrimaryKey
import com.joshmlwood.crudadmindemo.admin.Relation
data class AdminRoomDTO(
@PrimaryKey
var id: Long = 0L,
var floor: Int = 1,
var occupancy: Int = 1,
var description: String = "",
@Relation("features", Cardinality.TO_MANY)
var features: Set<AdminAutocompleteDTO> = emptySet()
)
| 1 | Kotlin | 0 | 1 | a7776a625769182ab3deb4adc54c023ad685cd8a | 465 | crud-admin-demo | MIT License |
feature/theme-picker/core/src/main/kotlin/ru/maksonic/beresta/feature/theme_picker/core/ui/widget/palette_picker/PickerRowContainer.kt | maksonic | 580,058,579 | false | null | package ru.maksonic.beresta.feature.theme_picker.core.ui.widget.palette_picker
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import ru.maksonic.beresta.feature.theme_picker.api.ThemeUiModel
import ru.maksonic.beresta.ui.theme.Theme
import ru.maksonic.beresta.ui.theme.color.AppThemePalette
import ru.maksonic.beresta.ui.theme.component.dp6
/**
* @Author maksonic on 26.02.2023
*/
@Composable
internal fun PickerRowContainer(
isFilledPalette: Boolean,
palettes: Array<ThemeUiModel.Palette>,
colors: Array<Color>,
onChangePalette: (AppThemePalette) -> Unit,
modifier: Modifier = Modifier
) {
Row(
modifier
.fillMaxWidth()
.height(Theme.widgetSize.minimumTouchTargetSize)
.padding(dp6),
horizontalArrangement = Arrangement.SpaceBetween
) {
palettes.forEach { item ->
CirclePickerItemWidget(
item = item,
isFilledPalette = isFilledPalette,
selectColor = { onChangePalette(item.palette) },
pickColor = { colors[item.id] },
modifier = modifier.weight(1f)
)
}
}
} | 0 | Kotlin | 0 | 0 | 450010eb1bfd6536222100e659596cf98b3a7d8c | 1,493 | Beresta | MIT License |
src/main/kotlin/todolist/test.kt | tenkuuBin | 522,364,049 | false | null | package todolist
import androidx.compose.desktop.ui.tooling.preview.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.*
import androidx.compose.ui.draw.*
import androidx.compose.ui.platform.*
import androidx.compose.ui.unit.*
@Preview
@Composable
fun test() {
Row(
Modifier.fillMaxWidth().height(IntrinsicSize.Min)
) {
var text1 = if (LocalInspectionMode.current) "test" else text
val isBlank = text1.isBlank()
TextField(
value = text1,
onValueChange = {
text1 = it
},
modifier = Modifier.fillMaxWidth(),
isError = isBlank,
trailingIcon = {
Button(
onClick = {
textList.add(text1)
},
modifier = Modifier
.clip(RoundedCornerShape(10))
.padding(5.dp),
enabled = !isBlank
) {
Text("I18n.add")
}
},
singleLine = false,
)
}
}
| 0 | Kotlin | 0 | 0 | ad9b67685aed0dbfc613b5d3edcec6d27e853d49 | 954 | ComposeTest | Apache License 2.0 |
roboto-library/src/main/java/com/lockwood/multispan/roboto/delegate/SpanStyleDelegate.kt | ScornfulBirch | 261,485,816 | false | null | package com.lockwood.multispan.roboto.delegate
import com.lockwood.multispan.delegate.base.SpanDelegate
import com.lockwood.multispan.item.SpanItem
import com.lockwood.multispan.roboto.item.RobotoSpanItem
import kotlin.reflect.KProperty
class SpanStyleDelegate(
spanItem: SpanItem,
override val onSet: () -> Unit
) : SpanDelegate<Int>(spanItem) {
override fun getValue(thisRef: Any, property: KProperty<*>): Int {
return (spanItem as RobotoSpanItem).style
}
override fun setValue(thisRef: Any, property: KProperty<*>, value: Int) {
(spanItem as RobotoSpanItem).style = value
onSet()
}
} | 0 | Kotlin | 0 | 0 | 1e47b2d46b715d719c4acc3a75d75872ae833273 | 639 | roboto-span-view | Apache License 2.0 |
app/src/main/java/com/sundayweather/android/activity/WeatherActivity.kt | Xiedejin1024 | 664,577,404 | false | {"Kotlin": 38128} | package com.sundayweather.android.activity
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout.DrawerListener
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.sundayweather.android.MyApplication
import com.sundayweather.android.R
import com.sundayweather.android.databinding.ActivityWeatherBinding
import com.sundayweather.android.logic.model.HourWeather
import com.sundayweather.android.logic.model.Weather
import com.sundayweather.android.logic.model.getSky
import com.sundayweather.android.ui.weather.HourlyAdapter
import com.sundayweather.android.ui.weather.WeatherViewModel
import com.sundayweather.android.utils.ToastUtil
import com.sundayweather.android.utils.showToast
import com.tencent.bugly.crashreport.CrashReport
import java.text.SimpleDateFormat
import java.util.*
class WeatherActivity : AppCompatActivity() {
val viewModel by lazy { ViewModelProvider(this).get(WeatherViewModel::class.java) }
lateinit var binding: ActivityWeatherBinding
lateinit var adapter: HourlyAdapter
private val hourlyWeatherList = ArrayList<HourWeather>()
@RequiresApi(Build.VERSION_CODES.R)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//沉浸式状态
val decorView = window.decorView
decorView.systemUiVisibility =
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
window.statusBarColor = Color.TRANSPARENT
window.navigationBarColor = Color.TRANSPARENT
binding = ActivityWeatherBinding.inflate(layoutInflater)
setContentView(binding.root)
if (viewModel.locationLng.isEmpty()) viewModel.locationLng =
intent.getStringExtra("location_lng") ?: ""
if (viewModel.locationLat.isEmpty()) viewModel.locationLat =
intent.getStringExtra("location_lat") ?: ""
if (viewModel.placeName.isEmpty()) viewModel.placeName =
intent.getStringExtra("place_name") ?: ""
viewModel.weatherLiveData.observe(this, Observer { result ->
val weather = result.getOrNull()
if (weather != null) {
viewModel.saveWeather(weather)
showWeatherInfo(weather)
} else {
if (viewModel.placeName.isNotEmpty()
&& viewModel.locationLng.isNotEmpty()
&& viewModel.locationLat.isNotEmpty()
&& viewModel.isWeatherSaved()
) {
val saveWeather = viewModel.getSaveWeather()
showWeatherInfo(saveWeather)
}
"无法成功获取天气信息".showToast(MyApplication.context)
result.exceptionOrNull()?.printStackTrace()
}
binding.swipeRefreshLayout.isRefreshing = false
})
//该方法取消了下滑刷新功能,不在需求该功能,但recycleView 的划动不会受影响
binding.includeHour.hourRecycleView.viewTreeObserver.addOnScrollChangedListener {
if (binding.swipeRefreshLayout != null) {
binding.swipeRefreshLayout.isEnabled = false
}
}
binding.scrollViewLayout.viewTreeObserver.addOnScrollChangedListener {
if (binding.swipeRefreshLayout != null) {
binding.swipeRefreshLayout.isEnabled = binding.scrollViewLayout.scrollY == 0
}
}
binding.swipeRefreshLayout.setColorSchemeResources(R.color.gray_p30)
refreshWeather()
binding.swipeRefreshLayout.setOnRefreshListener { refreshWeather() }
binding.switchover.setOnClickListener { binding.drawerLayout.openDrawer(GravityCompat.START) }
binding.drawerLayout.addDrawerListener(object : DrawerListener {
override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}
override fun onDrawerOpened(drawerView: View) {}
override fun onDrawerStateChanged(newState: Int) {}
override fun onDrawerClosed(drawerView: View) {
val manager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
manager.hideSoftInputFromWindow(
decorView.windowToken,
InputMethodManager.HIDE_NOT_ALWAYS
)
}
})
binding.refresh.setOnClickListener { refreshWeather() }
//设置24小时预报的RecyclerView
val layoutManager = LinearLayoutManager(this)
layoutManager.orientation = LinearLayoutManager.HORIZONTAL
binding.includeHour.hourRecycleView.layoutManager = layoutManager
adapter = HourlyAdapter(hourlyWeatherList)
binding.includeHour.hourRecycleView.adapter = adapter
}
fun refreshWeather() {
viewModel.refreshWeather(viewModel.locationLng, viewModel.locationLat)
binding.swipeRefreshLayout.isRefreshing = true
}
private fun showWeatherInfo(weather: Weather) {
binding.placeName.text = viewModel.placeName
val realtime = weather.realtime
val daily = weather.daily
val hourly = weather.hourly
//填充now.xml的数据
binding.includeNow.currentTemp.text = "${realtime.temperature.toInt()} ℃"
binding.includeNow.currentSky.text = getSky(realtime.skycon).info
binding.includeNow.currentAQI.text = "空气指数${realtime.air_quality.aqi.chn.toInt()}"
//binding.includeNow.nowLayout.setBackgroundResource(getSky(realtime.skycon).bg)
//hour.xml的数据
hourlyWeatherList.clear()
val hours = hourly.skycon.size
for (i in 0 until hours) {
val temVal = hourly.temperature[i].value
val skyVal = hourly.skycon[i].value
val datetime = hourly.skycon[i].datetime
hourlyWeatherList.add(HourWeather(datetime, skyVal, temVal))
}
binding.includeHour.hourRecycleView.adapter?.notifyDataSetChanged()
//填充forcast.xml的数据
binding.includeForecast.forecastLayout.removeAllViews()
val days = daily.skycon.size
for (i in 0 until days) {
val skycon = daily.skycon[i]
val temperature = daily.temperature[i]
val view =
LayoutInflater.from(this)
.inflate(R.layout.forecast_item, binding.includeForecast.forecastLayout, false)
val dataInfo = view.findViewById<TextView>(R.id.dateInfo)
val skyIcon = view.findViewById<ImageView>(R.id.skyIcon)
val skyInfo = view.findViewById<TextView>(R.id.skyInfo)
val temperatureInfo = view.findViewById<TextView>(R.id.temperatureInfo)
dataInfo.text = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(skycon.date)
val sky = getSky(skycon.value)
skyIcon.setImageResource(sky.icon)
skyInfo.text = sky.info
val tempText = "${temperature.min.toInt()}~${temperature.max.toInt()}℃"
temperatureInfo.text = tempText
binding.includeForecast.forecastLayout.addView(view)
}
//填充life_index.xml的数据
val lifeIndex = daily.lifeIndex
binding.includeLifeIndex.coldRiskText.text = lifeIndex.coldRisk[0].desc
binding.includeLifeIndex.dressingText.text = lifeIndex.dressing[0].desc
binding.includeLifeIndex.ultravioletText.text = lifeIndex.ultraviolet[0].desc
binding.includeLifeIndex.carWashingText.text = lifeIndex.carWashing[0].desc
binding.weatherLayout.setBackgroundResource(getSky(realtime.skycon).bg)
binding.weatherLayout.visibility = View.VISIBLE
}
} | 0 | Kotlin | 0 | 0 | 469cd0a1278a393788e0c1f292e6c3f31e690d54 | 8,132 | SundayWeather | Apache License 2.0 |
ui-kit-lib/src/main/kotlin/com/linkedplanet/uikit/wrapper/ajs/Imports.kt | linked-planet | 427,161,616 | false | {"Kotlin": 317837, "JavaScript": 1646, "HTML": 940, "SCSS": 653} | /**
* Copyright 2022 linked-planet GmbH.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.linkedplanet.uikit.wrapper.ajs
object AJS {
fun getCurrentUserFullname(): String =
js("AJS.Meta.get('current-user-fullname')").toString()
fun getCurrentUsername(): String =
js("AJS.Meta.get('remote-user')").toString()
fun getCurrentUserId(): String =
js("AJS.Meta.get('remote-user-key')").toString()
fun getUserLocale(): String =
js("AJS.Meta.get('user-locale')").toString()
}
| 0 | Kotlin | 0 | 2 | 9328c3032a8eff76767e19bb28e9b71973f49125 | 1,045 | ui-kit | Apache License 2.0 |
examples/virtual-device-app/android/App/core/matter/src/main/java/com/matter/virtual/device/app/core/matter/MatterApi.kt | project-chip | 244,694,174 | false | null | package com.matter.virtual.device.app.core.matter
import com.matter.virtual.device.app.core.matter.model.asSetupPayload
import com.matter.virtual.device.app.core.model.Payload
import javax.inject.Inject
import javax.inject.Singleton
import matter.onboardingpayload.OnboardingPayloadException
import matter.onboardingpayload.OnboardingPayloadParser
import timber.log.Timber
@Singleton
class MatterApi @Inject constructor() {
fun getQrcodeString(payload: Payload): String {
val onboardingPayloadParser = OnboardingPayloadParser()
var qrcode = ""
try {
qrcode = onboardingPayloadParser.getQrCodeFromPayload(payload.asSetupPayload())
} catch (e: OnboardingPayloadException) {
e.printStackTrace()
}
Timber.d("qrcode:$qrcode")
return qrcode
}
fun getManualPairingCodeString(payload: Payload): String {
val onboardingPayloadParser = OnboardingPayloadParser()
var manualPairingCode = ""
try {
manualPairingCode =
onboardingPayloadParser.getManualPairingCodeFromPayload(payload.asSetupPayload())
} catch (e: OnboardingPayloadException) {
e.printStackTrace()
}
Timber.d("manualPairingCode:$manualPairingCode")
return manualPairingCode
}
}
| 1,443 | null | 1769 | 6,671 | 420e6d424c00aed3ead4015eafd71a1632c5e540 | 1,231 | connectedhomeip | Apache License 2.0 |
app/src/main/java/com/anbui/recipely/presentation/recipe/recipe_detail/components/OverviewSection.kt | AnBuiii | 667,858,307 | false | null | package com.anbui.recipely.presentation.recipe.recipe_detail.components
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import com.anbui.recipely.R
import com.anbui.recipely.domain.models.Recipe
import com.anbui.recipely.presentation.ui.theme.SpaceMedium
import kotlin.math.roundToInt
fun LazyListScope.overviewSection(
recipe: Recipe
) {
item {
Row(
modifier = Modifier.fillMaxWidth()
) {
NutritionItem(
icon = R.drawable.ic_carb,
text = stringResource(R.string.carbs, recipe.totalCarb.roundToInt()),
modifier = Modifier.weight(1f)
)
NutritionItem(
icon = R.drawable.ic_protein,
text = stringResource(
R.string.proteins,
recipe.totalProtein.roundToInt()
),
modifier = Modifier.weight(1f)
)
}
Spacer(modifier = Modifier.height(SpaceMedium))
Row(
modifier = Modifier.fillMaxWidth()
) {
NutritionItem(
icon = R.drawable.ic_calories,
text = stringResource(R.string.kcal, recipe.totalCalories.roundToInt()),
modifier = Modifier.weight(1f)
)
NutritionItem(
icon = R.drawable.ic_fat,
text = stringResource(R.string.fats, recipe.totalFat.roundToInt()),
modifier = Modifier.weight(1f)
)
}
Spacer(modifier = Modifier.height(SpaceMedium))
}
}
| 0 | null | 1 | 4 | 42dbe9feecf9bf0d071e6d69e7d4c8fac20372f3 | 1,867 | Recipely | Apache License 2.0 |
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/DefaultBaseStyle.kt | Danilo-Araujo-Silva | 271,904,885 | false | null | package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: DefaultBaseStyle
*
* Full name: System`DefaultBaseStyle
*
* Usage: DefaultBaseStyle is a low-level option for formatting and related constructs that specifies a default base style to use before BaseStyle.
*
* Options: None
*
* Attributes: Protected
*
* local: paclet:ref/DefaultBaseStyle
* Documentation: web: http://reference.wolfram.com/language/ref/DefaultBaseStyle.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun defaultBaseStyle(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("DefaultBaseStyle", arguments.toMutableList(), options)
}
| 2 | Kotlin | 0 | 3 | 4fcf68af14f55b8634132d34f61dae8bb2ee2942 | 1,056 | mathemagika | Apache License 2.0 |
app/src/main/java/org/softeg/slartus/forpdaplus/classes/QmsHtmlBuilder.kt | slartus | 21,554,455 | false | null | package org.softeg.slartus.forpdaplus.classes
import org.softeg.slartus.forpdaplus.emotic.Smiles
import org.softeg.slartus.forpdaplus.prefs.HtmlPreferences
import org.softeg.slartus.forpdaplus.prefs.Preferences
class QmsHtmlBuilder : HtmlBuilder() {
override fun addScripts() {
super.addScripts()
m_Body.append("<script type=\"text/javascript\" src=\"file:///android_asset/qms.js\"></script>\n")
}
fun buildBody(loadMore: Boolean, chatBody: String, htmlPreferences: HtmlPreferences?) {
var chatBodyLocal = chatBody
beginHtml("QMS")
beginBody("qms${if (loadMore) "_more" else ""}", "", Preferences.Topic.isShowAvatars)
// htmlBuilder.beginBody("qms", "onload=\"scrollToElement('bottom_element')\"", Preferences.Topic.isShowAvatars());
if (!Preferences.Topic.isShowAvatars)
chatBodyLocal = chatBodyLocal.replace("<img[^>]*?class=\"avatar\"[^>]*>".toRegex(), "")
if (htmlPreferences?.isSpoilerByButton == true)
chatBodyLocal = HtmlPreferences.modifySpoiler(chatBodyLocal)
chatBodyLocal = HtmlPreferences.modifyBody(chatBodyLocal, Smiles.getSmilesDict())
chatBodyLocal = chatBodyLocal.replace("(<a[^>]*?href=\"([^\"]*?savepice[^\"]*-)[\\w]*(\\.[^\"]*)\"[^>]*?>)[^<]*?(</a>)".toRegex(), "$1<img src=\"$2prev$3\">$4")
append(chatBodyLocal)
append("<div id=\"bottom_element\" name=\"bottom_element\"></div>")
//m_Body.append("<script>jsEmoticons.parseAll('").append("file:///android_asset/forum/style_emoticons/default/").append("');initPostBlock();</script>");
append("<script>jsEmoticons.parseAll('").append("file:///android_asset/forum/style_emoticons/default/").append("');</script>")
endBody()
endHtml()
}
} | 2 | null | 17 | 86 | 03dfdb68c1ade272cf84ff1c89dc182f7fe69c39 | 1,784 | 4pdaClient-plus | Apache License 2.0 |
samples/ktor/src/application.kt | mirromutth | 176,066,212 | false | null | package com.oshai
import com.github.jasync.sql.db.Connection
import com.github.jasync.sql.db.QueryResult
import com.github.jasync.sql.db.mysql.MySQLConnectionBuilder
import io.ktor.application.ApplicationCall
import io.ktor.application.call
import io.ktor.application.install
import io.ktor.features.ContentNegotiation
import io.ktor.gson.gson
import io.ktor.response.respond
import io.ktor.routing.get
import io.ktor.routing.routing
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.util.pipeline.PipelineContext
import kotlinx.coroutines.future.await
import mu.KotlinLogging
import java.util.concurrent.TimeUnit
fun main() {
val server = embeddedServer(Netty, port = 8080) {
install(ContentNegotiation) {
gson {
setPrettyPrinting()
}
routing {
get("/") {
logger.info { "handling mysql request" }
handleMysqlRequest("select 0")
}
}
}
}
println("STARTING")
connectionPool.connect().get()
try {
server.start(wait = true)
} finally {
println("DISCO")
connectionPool.disconnect().get()
}
}
private val logger = KotlinLogging.logger {}
val connectionPool = MySQLConnectionBuilder.createConnectionPool {
username = "test"
host = "localhost"
port = 3306
password = "123456"
database = "test"
maxActiveConnections = 100
maxIdleTime = TimeUnit.MINUTES.toMillis(15)
maxPendingQueries = 10_000
connectionValidationInterval = TimeUnit.SECONDS.toMillis(30)
}
private suspend fun PipelineContext<Unit, ApplicationCall>.handleMysqlRequest(query: String) {
val queryResult = connectionPool.sendPreparedStatementAwait(query = query)
call.respond(queryResult.rows[0][0].toString())
}
private suspend fun Connection.sendPreparedStatementAwait(query: String, values: List<Any> = emptyList()): QueryResult =
this.sendPreparedStatement(query, values).await()
| 9 | null | 136 | 2 | 76854b2df7ba39c4843d8c372343403721c4c8b7 | 2,043 | jasync-sql | Apache License 2.0 |
idea/testData/refactoring/safeDeleteMultiModule/byImplClassSecondaryConstructor/after/Common/src/test/test.kt | dgrachev28 | 101,798,165 | true | {"Java": 26358285, "Kotlin": 24866412, "JavaScript": 144710, "Protocol Buffer": 57164, "HTML": 55011, "Lex": 18174, "Groovy": 14228, "ANTLR": 9797, "IDL": 8350, "Shell": 5436, "CSS": 4679, "Batchfile": 4437} | package test
header open class Foo {
constructor(n: Int)
}
fun test() = Foo(1) | 0 | Java | 0 | 1 | 4ada69242104c8ce265383400797ed37d74c7fe9 | 84 | kotlin | Apache License 2.0 |
app/src/test/java/com/hieuwu/groceriesstore/domain/usecases/impl/GetProductsListUseCaseImplTest.kt | hieuwu | 360,573,503 | false | {"Kotlin": 373053} | package com.hieuwu.groceriesstore.domain.usecases.impl
import com.hieuwu.groceriesstore.data.repository.ProductRepository
import com.hieuwu.groceriesstore.domain.models.ProductModel
import com.hieuwu.groceriesstore.domain.usecases.GetProductsListUseCase
import junit.framework.TestCase.assertEquals
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.runBlocking
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.kotlin.whenever
@RunWith(MockitoJUnitRunner::class)
class GetProductsListUseCaseImplTest {
@Mock
lateinit var mockedProductsRepository: ProductRepository
private lateinit var testee: GetProductsListUseCase
@Before
fun setUp() {
testee = GetProductsListUseCaseImpl(
productRepository = mockedProductsRepository
)
}
@Test
fun givenProductsAvailable_whenExecute_thenReturnCorrectValue() {
val mockedProducts = listOf(
ProductModel(id = "1", name = "Apple", price = 1.0, image = "image1.jpg", description = "Fruit", nutrition = "Healthy"),
ProductModel(id = "2", name = "Fries", price = 5.0, image = "image2.jpg", description = "Junk food", nutrition = "Unhealthy"),
ProductModel(id = "3", name = "Potato", price = 10.0, image = "image3.jpg", description = "Vegetable", nutrition = "Healthy"),
)
whenever(mockedProductsRepository.products).thenReturn(flow {
emit(mockedProducts)
})
runBlocking {
val result = testee.execute(GetProductsListUseCase.Input())
result.result.collect { products ->
assertEquals(mockedProducts[0], products[0])
assertEquals(mockedProducts[1], products[1])
assertEquals(mockedProducts[2], products[2])
assertEquals(mockedProducts[1].name, "Fries")
}
}
}
@Test
fun givenProductsUnavailable_whenExecute_thenReturnCorrectValue() {
whenever(mockedProductsRepository.products).thenReturn(flow {
emit(listOf())
})
runBlocking {
val result = testee.execute(GetProductsListUseCase.Input())
result.result.collect {
assertEquals(it.isEmpty(), true)
}
}
}
} | 29 | Kotlin | 56 | 224 | f6f2e2b3e0e7550d5f6a1d1acc64ca5adb03e3b2 | 2,384 | android-groceries-store | MIT License |
tmp/arrays/youTrackTests/10221.kt | DaniilStepanov | 228,623,440 | false | null | // Original bug: KT-8148
fun main(args: Array<String>) {
try {
try {
return
} finally {
println("1")
}
} finally {
throw RuntimeException("fail")
}
}
| 1 | null | 8 | 1 | 602285ec60b01eee473dcb0b08ce497b1c254983 | 220 | bbfgradle | Apache License 2.0 |
app/src/main/java/com/example/viacep/presenter/list/adapter/AddressAdapter.kt | kelvingcr | 628,608,775 | false | null | package com.example.viacep.presenter.list.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.viacep.databinding.ItemAddressBinding
import com.example.viacep.domain.model.Address
class AddressAdapter: ListAdapter<Address, AddressAdapter.ViewHolder>(DIFF_CALLBACK) {
companion object {
private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Address>() {
override fun areItemsTheSame(oldItem: Address, newItem: Address): Boolean {
return oldItem.cep == newItem.cep
}
override fun areContentsTheSame(oldItem: Address, newItem: Address): Boolean {
return newItem.cep == oldItem.cep
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
ItemAddressBinding.inflate(LayoutInflater.from(parent.context), parent, false)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val address = getItem(position)
holder.binding.textAddress.text = address.getFullAddress()
holder.binding.viewFlipper.displayedChild = 1
}
inner class ViewHolder(val binding: ItemAddressBinding) : RecyclerView.ViewHolder(binding.root)
} | 0 | Kotlin | 0 | 0 | 81cd27d31198a4e0f29ce11ad2c21b3bc57565cf | 1,441 | viacep | Apache License 2.0 |
src/main/kotlin/io/lunarchain/lunarcoin/vm/DataWord.kt | lunarchain | 121,196,186 | false | null | package lunar.vm
import io.lunarchain.lunarcoin.util.ByteUtil
import io.lunarchain.lunarcoin.util.FastByteComparisons
import org.spongycastle.util.Arrays
import org.spongycastle.util.encoders.Hex
import java.math.BigInteger
import java.nio.ByteBuffer
class DataWord(): Comparable<DataWord> {
private var data: ByteArray = ByteArray(32)
companion object {
val _2_256: BigInteger = BigInteger.valueOf(2).pow(256)
val ZERO = DataWord(ByteArray(32)) // don't push it in to the stack
val MAX_VALUE: BigInteger = _2_256.subtract(BigInteger.ONE)
}
constructor(data: ByteArray?): this() {
if(data == null) return
if (data.size <= 32)
System.arraycopy(data, 0, this.data, 32 - data.size, data.size)
else
throw RuntimeException("Data word can't exceed 32 bytes: " + data)
}
constructor(buffer: ByteBuffer): this(){
val data = ByteBuffer.allocate(32)
val array = buffer.array()
System.arraycopy(array, 0, data.array(), 32 - array.size, array.size)
this.data = data.array()
}
constructor(num: Int): this(ByteBuffer.allocate(4).putInt(num))
constructor(num: Long): this(ByteBuffer.allocate(8).putLong(num))
constructor(data: String): this(Hex.decode(data))
fun getData(): ByteArray {
return this.data
}
fun isZero(): Boolean {
for (tmp in data) {
if (tmp.toInt() != 0) return false
}
return true
}
override fun compareTo(other: DataWord): Int {
val result = FastByteComparisons.compareTo(
data, 0, data.size,
other.getData(), 0, other.getData().size)
// Convert result into -1, 0 or 1 as is the convention
return Math.signum(result.toFloat()).toInt()
}
/**
* Converts this DataWord to an int, checking for lost information.
* If this DataWord is out of the possible range for an int result
* then an ArithmeticException is thrown.
*
* @return this DataWord converted to an int.
* @throws ArithmeticException - if this will not fit in an int.
*/
fun intValue(): Int {
var intVal = 0
for (aData in data) {
intVal = (intVal shl 8) + (aData.toInt() and 0xff)
}
return intVal
}
fun value(): BigInteger {
return BigInteger(1, data)
}
fun getLast20Bytes(): ByteArray {
return Arrays.copyOfRange(data, 12, data.size)
}
fun clone(): DataWord {
return DataWord(Arrays.clone(data))
}
/**
* In case of long overflow returns Long.MAX_VALUE
* otherwise works as #longValue()
*/
fun longValueSafe(): Long {
val bytesOccupied = bytesOccupied()
val longValue = longValue()
return if (bytesOccupied > 8 || longValue < 0) java.lang.Long.MAX_VALUE else longValue
}
fun bytesOccupied(): Int {
val firstNonZero = ByteUtil.firstNonZeroByte(data)
return if (firstNonZero == -1) 0 else 31 - firstNonZero + 1
}
/**
* Converts this DataWord to a long, checking for lost information.
* If this DataWord is out of the possible range for a long result
* then an ArithmeticException is thrown.
*
* @return this DataWord converted to a long.
* @throws ArithmeticException - if this will not fit in a long.
*/
fun longValue(): Long {
var longVal: Long = 0
for (aData in data) {
longVal = (longVal shl 8) + (aData.toInt() and 0xff)
}
return longVal
}
fun sub(word: DataWord) {
val result = value().subtract(word.value())
this.data = ByteUtil.copyToArray(result.and(MAX_VALUE))
}
fun and(w2: DataWord): DataWord {
for (i in this.data.indices) {
this.data[i] = (this.data[i].toInt() and w2.data[i].toInt()).toByte()
}
return this
}
fun add(word: DataWord) {
val result = ByteArray(32)
var i = 31
var overflow = 0
while (i >= 0) {
val v = (this.data[i].toInt() and 0xff) + (word.data[i].toInt() and 0xff) + overflow
result[i] = v.toByte()
overflow = v.ushr(8)
i--
}
this.data = result
}
// old add-method with BigInteger quick hack
fun add2(word: DataWord) {
val result = value().add(word.value())
this.data = ByteUtil.copyToArray(result.and(MAX_VALUE))
}
// TODO: mul can be done in more efficient way
// TODO: with shift left shift right trick
// TODO without BigInteger quick hack
fun mul(word: DataWord) {
val result = value().multiply(word.value())
this.data = ByteUtil.copyToArray(result.and(MAX_VALUE))
}
operator fun div(word: DataWord) {
if (word.isZero()) {
this.and(ZERO)
return
}
val result = value().divide(word.value())
this.data = ByteUtil.copyToArray(result.and(MAX_VALUE))
}
fun sValue(): BigInteger {
return BigInteger(data)
}
// TODO: improve with no BigInteger
fun sDiv(word: DataWord) {
if (word.isZero()) {
this.and(ZERO)
return
}
val result = sValue().divide(word.sValue())
this.data = ByteUtil.copyToArray(result.and(MAX_VALUE))
}
// TODO: improve with no BigInteger
operator fun mod(word: DataWord) {
if (word.isZero()) {
this.and(ZERO)
return
}
val result = value().mod(word.value())
this.data = ByteUtil.copyToArray(result.and(MAX_VALUE))
}
fun sMod(word: DataWord) {
if (word.isZero()) {
this.and(ZERO)
return
}
var result = sValue().abs().mod(word.sValue().abs())
result = if (sValue().signum() == -1) result.negate() else result
this.data = ByteUtil.copyToArray(result.and(MAX_VALUE))
}
fun addmod(word1: DataWord, word2: DataWord) {
if (word2.isZero()) {
this.data = ByteArray(32)
return
}
val result = value().add(word1.value()).mod(word2.value())
this.data = ByteUtil.copyToArray(result.and(MAX_VALUE))
}
fun mulmod(word1: DataWord, word2: DataWord) {
if (this.isZero() || word1.isZero() || word2.isZero()) {
this.data = ByteArray(32)
return
}
val result = value().multiply(word1.value()).mod(word2.value())
this.data = ByteUtil.copyToArray(result.and(MAX_VALUE))
}
// TODO: improve with no BigInteger
fun exp(word: DataWord) {
val result = value().modPow(word.value(), _2_256)
this.data = ByteUtil.copyToArray(result)
}
fun signExtend(k: Byte) {
if (0 > k || k > 31)
throw IndexOutOfBoundsException()
val mask = if (this.sValue().testBit(k * 8 + 7)) 0xff.toByte() else 0
for (i in 31 downTo k + 1) {
this.data[31 - i] = mask
}
}
fun bnot() {
if (this.isZero()) {
this.data = ByteUtil.copyToArray(MAX_VALUE)
return
}
this.data = ByteUtil.copyToArray(MAX_VALUE.subtract(this.value()))
}
fun xor(w2: DataWord): DataWord {
for (i in this.data.indices) {
this.data[i] = (this.data[i].toInt() xor w2.data[i].toInt()).toByte()
}
return this
}
fun or(w2: DataWord): DataWord {
for (i in this.data.indices) {
this.data[i] = (this.data[i].toInt() or w2.data[i].toInt()).toByte()
}
return this
}
fun getNoLeadZeroesData(): ByteArray {
return ByteUtil.stripLeadingZeroes(data)!!
}
override fun toString(): String {
return Hex.toHexString(data)
}
fun toPrefixString(): String {
val pref = getNoLeadZeroesData()
if (pref == null || pref.isEmpty()) return ""
return if (pref.size < 7) Hex.toHexString(pref) else Hex.toHexString(pref).substring(0, 6)
}
fun shortHex(): String {
val hexValue = Hex.toHexString(getNoLeadZeroesData()).toUpperCase()
return "0x" + hexValue.replaceFirst("^0+(?!$)".toRegex(), "")
}
/**
* In case of int overflow returns Integer.MAX_VALUE
* otherwise works as #intValue()
*/
fun intValueSafe(): Int {
val bytesOccupied = bytesOccupied()
val intValue = intValue()
return if (bytesOccupied > 4 || intValue < 0) Integer.MAX_VALUE else intValue
}
override fun equals(o: Any?): Boolean {
if (this === o) return true
if (o == null || javaClass != o.javaClass) return false
val dataWord = o as DataWord?
return java.util.Arrays.equals(data, dataWord!!.data)
}
override fun hashCode(): Int {
return java.util.Arrays.hashCode(data)
}
} | 1 | Kotlin | 2 | 2 | 4f43e5965fb32ee451260d8b1ddef7ae41b684fb | 8,964 | lunarcoin-core | Apache License 2.0 |
base/src/main/java/smart/base/BFragment.kt | eastar-dev | 188,695,253 | false | null | package smart.base
import android.base.CFragment
import android.log.Log
import dev.eastar.operaxinterceptor.event.OperaXEventObserver
import java.util.*
abstract class BFragment : CFragment(), OperaXEventObserver {
override fun update(observable: Observable?, data: Any?) {
Log.e(observable, data)
}
} | 0 | Kotlin | 0 | 1 | 100cf219787346561cc9af83db555f3f363cd0c7 | 319 | _EastarStudyLogForAndroid | Apache License 2.0 |
stacks/src/commonMain/kotlin/kollections/Stack.kt | aSoft-Ltd | 537,964,662 | false | {"Kotlin": 132802} | @file:JsExport
package kollections
import kotlinx.JsExport
interface Stack<E> : kotlin.collections.Collection<E> {
fun top(): E?
fun push(element: E)
fun pop(): E?
fun canPop(): Boolean
fun toList(): List<E>
} | 0 | Kotlin | 1 | 9 | 8887905f6bd7c0984f6cb95b1f23db4038785bdd | 233 | kollections | MIT License |
AlivcUgsvDemo/AUIVideoEditor/AUIEditorEffect/src/main/java/com/aliyun/svideo/editor/filter/VideoFilterEntryViewModel.kt | aliyunvideo | 554,213,214 | false | {"Java": 6071582, "Kotlin": 665216, "GLSL": 3598, "HTML": 1810} | package com.aliyun.svideo.editor.filter
import android.view.View
import androidx.lifecycle.LifecycleOwner
import com.aliyun.svideo.editor.common.panel.OnItemClickListener
import com.aliyun.svideo.editor.common.panel.viewmodel.ActionBarViewModel
import com.aliyun.svideo.editor.common.panel.viewmodel.BaseViewModel
import com.aliyun.svideo.editor.common.panel.viewmodel.PanelItemId
import com.aliyun.svideo.editor.effect.R
import com.aliyun.svideo.track.bean.BaseClipInfo
import com.aliyun.svideo.track.bean.ClipType
import com.aliyun.svideo.track.inc.MultiTrackListener
import com.aliyun.svideosdk.common.struct.effect.TrackEffectFilter
import com.aliyun.svideosdk.editor.AliyunIEditor
import com.aliyun.svideosdk.editor.impl.AliyunPasterControllerCompoundCaption
class VideoFilterEntryViewModel() : BaseViewModel() {
val actionBarViewModel = ActionBarViewModel(
cancelVisible = false,
confirmVisible = false,
titleResId = R.string.ugsv_editor_filter_title
)
private lateinit var mEditor: AliyunIEditor
fun bind(lifecycleOwner: LifecycleOwner, editor : AliyunIEditor) {
this.mEditor = editor
}
fun unBind() {
onCleared()
}
fun addVideoEffect(view: View) {
mOnItemClickListener?.onItemClick(view, PanelItemId.ITEM_ID_ADD)
}
fun deleteVideoEffect(view: View) {
}
override fun setOnItemClickListener(onItemClickListener: OnItemClickListener?) {
super.setOnItemClickListener(onItemClickListener)
actionBarViewModel.setOnItemClickListener(onItemClickListener)
}
} | 5 | Java | 5 | 17 | 1bc1becec5f41681a2a04cc2f8fc1e5899de3fec | 1,585 | MONE_demo_opensource_android | MIT License |
app/src/main/java/com/mitteloupe/loader/MainActivity.kt | EranBoudjnah | 739,791,962 | false | {"Kotlin": 130319} | package com.mitteloupe.loader
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.mitteloupe.loader.gears.Gears
import com.mitteloupe.loader.home.Home
import com.mitteloupe.loader.jigsaw.Jigsaw
import com.mitteloupe.loader.ui.theme.LoadersTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
LoadersTheme {
MainNavHost()
}
}
}
}
@Composable
fun MainNavHost(
modifier: Modifier = Modifier,
navController: NavHostController = rememberNavController(),
startDestination: String = "home"
) {
NavHost(navController, startDestination = startDestination, modifier = modifier) {
composable("home") {
Home(
onNavigateToGears = { navController.navigate("gears") },
onNavigateToJigsaw = { navController.navigate("jigsaw") }
)
}
composable("gears") { Gears(navController) }
composable("jigsaw") { Jigsaw(navController) }
}
}
@Preview
@Composable
fun Preview() {
LoadersTheme {
MainNavHost()
}
}
| 0 | Kotlin | 1 | 8 | d98f2f3fca9ad1e003c761e8e6e3f7c986e76e55 | 1,571 | Loaders | MIT License |
app/src/main/java/com/mitteloupe/loader/MainActivity.kt | EranBoudjnah | 739,791,962 | false | {"Kotlin": 130319} | package com.mitteloupe.loader
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.mitteloupe.loader.gears.Gears
import com.mitteloupe.loader.home.Home
import com.mitteloupe.loader.jigsaw.Jigsaw
import com.mitteloupe.loader.ui.theme.LoadersTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
LoadersTheme {
MainNavHost()
}
}
}
}
@Composable
fun MainNavHost(
modifier: Modifier = Modifier,
navController: NavHostController = rememberNavController(),
startDestination: String = "home"
) {
NavHost(navController, startDestination = startDestination, modifier = modifier) {
composable("home") {
Home(
onNavigateToGears = { navController.navigate("gears") },
onNavigateToJigsaw = { navController.navigate("jigsaw") }
)
}
composable("gears") { Gears(navController) }
composable("jigsaw") { Jigsaw(navController) }
}
}
@Preview
@Composable
fun Preview() {
LoadersTheme {
MainNavHost()
}
}
| 0 | Kotlin | 1 | 8 | d98f2f3fca9ad1e003c761e8e6e3f7c986e76e55 | 1,571 | Loaders | MIT License |
common/navigation/src/main/kotlin/com/festivalfellow/mobile/navigation/start/StartNavigation.kt | stupacki | 597,824,235 | false | null | package com.festivalfellow.mobile.navigation.start
import androidx.navigation.NavController
import com.festivalfellow.mobile.navigation.start.StartScreenStep.Companion.DEST_ID_START_SCREEN
class StartNavigation(private val navController: NavController) {
fun entry() {
navController.navigate(DEST_ID_START_SCREEN)
}
} | 0 | Kotlin | 0 | 0 | 11750fbcddd27a045eff7c6eaea6e28dfd93de76 | 336 | PocModularization2023 | Apache License 2.0 |
api/src/main/kotlin/org/jetbrains/kotlinx/dl/api/inference/keras/config/LayerConfig.kt | SebastianAigner | 330,901,129 | false | null | /*
* Copyright 2020 JetBrains s.r.o. and Kotlin Deep Learning project contributors. All Rights Reserved.
* Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file.
*/
package org.jetbrains.kotlinx.dl.api.inference.keras.config
internal data class LayerConfig(
val activation: String? = null,
val activity_regularizer: ActivityRegularizer? = null,
var batch_input_shape: List<Int?>? = null,
val bias_constraint: Any? = null,
val bias_initializer: KerasInitializer? = null,
val bias_regularizer: KerasRegularizer? = null,
val data_format: String? = null,
val dilation_rate: List<Int>? = null,
val dtype: String? = null,
val filters: Int? = null,
val kernel_constraint: Any? = null,
val kernel_initializer: KerasInitializer? = null,
val kernel_regularizer: KerasRegularizer? = null,
val kernel_size: List<Int>? = null,
val name: String? = null,
val padding: String? = null,
val pool_size: List<Int>? = null,
val strides: List<Int>? = null,
val trainable: Boolean? = true,
val units: Int? = null,
val use_bias: Boolean? = null
) | 0 | null | 0 | 1 | 41ab1cd89c27507db9a22d029f9690cfe2b0f825 | 1,161 | KotlinDL | Apache License 2.0 |
Comman/app/src/main/java/org/appjam/comman/ui/card/CardActivity.kt | seoyeonkk | 144,235,253 | true | {"Kotlin": 227033} | package org.appjam.comman.ui.card
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentStatePagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.activity_card.*
import org.appjam.comman.R
import org.appjam.comman.network.APIClient
import org.appjam.comman.network.data.CardData
import org.appjam.comman.network.data.CoursesData
import org.appjam.comman.network.data.LectureData
import org.appjam.comman.util.PrefUtils
import org.appjam.comman.util.SetColorUtils
import org.appjam.comman.util.setDefaultThreads
/**
* Created by KSY on 2017-12-31.
*/
@Suppress("UNREACHABLE_CODE")
class CardActivity : AppCompatActivity() {
companion object {
const val TAG = "CardActivity"
}
private val disposables = CompositeDisposable()
private var cardInfoList: List<CardData.CardInfo> = listOf()
private var lectureID: Int = 0
private var courseID: Int = 0
private var pageCount: Int = 0
private var lectureTitle: String = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_card)
// secondString=getIntent().getStringExtra("firstData")
// getText=findViewById(R.id.main2_get_text) as TextView
// getText!!.text=secondString
card_back_btn.setOnClickListener {
finish()
}
courseID = intent.getIntExtra("courseID",0)
lectureID = intent.getIntExtra("lectureID", 0)
var current_page : Int = 1
PrefUtils.putCurrentLectureID(this, lectureID)
PrefUtils.putLectureOfCourseID(this, lectureID, courseID)
card_view_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
}
@SuppressLint("ResourceAsColor")
override fun onPageSelected(position: Int) {
PrefUtils.putLectureOfCoursePosition(this@CardActivity, position, courseID)
when (position) {
card_view_pager.adapter.count - 1 -> {
card_prev_tv.setTextColor(SetColorUtils.get(this@CardActivity, R.color.mainTextColor))
card_next_tv.setTextColor(SetColorUtils.get(this@CardActivity, R.color.grayMainTextColor))
card_prev_btn.setBackgroundResource(R.drawable.view_pager_prev_btn)
card_next_btn.setBackgroundResource(R.drawable.unclickable_view_pager_next_btn)
card_question_btn.visibility = View.VISIBLE
}
0 -> {
card_prev_tv.setTextColor(SetColorUtils.get(this@CardActivity, R.color.grayMainTextColor))
card_prev_btn.setBackgroundResource(R.drawable.unclickable_view_pager_prev_btn)
card_next_tv.setTextColor(SetColorUtils.get(this@CardActivity, R.color.mainTextColor))
card_next_btn.setBackgroundResource(R.drawable.view_pager_next_btn)
card_question_btn.visibility = View.GONE
}
else -> {
card_prev_tv.setTextColor(SetColorUtils.get(this@CardActivity, R.color.mainTextColor))
card_next_tv.setTextColor(SetColorUtils.get(this@CardActivity, R.color.mainTextColor))
card_prev_btn.setBackgroundResource(R.drawable.view_pager_prev_btn)
card_next_btn.setBackgroundResource(R.drawable.view_pager_next_btn)
card_question_btn.visibility = View.GONE
}
}
card_count_tv.text = "${position + 1} / $pageCount"
}
})
card_prev_layout.setOnClickListener {
card_view_pager.currentItem = card_view_pager.currentItem - 1
}
card_next_layout.setOnClickListener {
card_view_pager.currentItem = card_view_pager.currentItem + 1
}
card_question_btn.setOnClickListener {
val intent = Intent(this@CardActivity, QuestionActivity::class.java)
intent.putExtra("lectureID", lectureID)
intent.putExtra("lectureTitle", lectureTitle)
startActivity(intent)
}
disposables.add(APIClient.apiService.getLectureInfo(
PrefUtils.getUserToken(this), lectureID)
.setDefaultThreads()
.subscribe({ response ->
lectureTitle = response.data.title
if(response.data.priority < 10)
card_lecture_name_tv.text = "0${response.data.priority}. ${response.data.title}"
else
card_lecture_name_tv.text = "${response.data.priority}. ${response.data.title}"
lectureTitle = card_lecture_name_tv.text.toString()
}, { failure ->
Log.i(CardActivity.TAG, "on Failure ${failure.message}")
}))
disposables.add(APIClient.apiService.getLectureCards(
PrefUtils.getUserToken(this), lectureID)
.setDefaultThreads()
.subscribe({ response ->
cardInfoList = response.result
pageCount = cardInfoList.size + 1
card_count_tv.text = "$current_page / $pageCount"
card_view_pager.adapter = CardPagerAdapter(supportFragmentManager)
if(lectureID == PrefUtils.getRecentLectureOfCourseID(this, courseID)) {
card_view_pager.currentItem = PrefUtils.getRecentLectureOfCoursePosition(this, courseID)
current_page = card_view_pager.currentItem + 1
}
}, { failure ->
Log.i(CardActivity.TAG, "on Failure ${failure.message}")
}))
}
inner class CardPagerAdapter(fm: FragmentManager): FragmentStatePagerAdapter(fm){
override fun getItem(position:Int): Fragment {
return if (position < count - 1) {
val cardFragment = CardFragment()
val bundle = Bundle()
bundle.putString("image_url", cardInfoList[position].image_path)
cardFragment.arguments = bundle
cardFragment
} else {
val cardLastFragment = CardLastFragment()
val bundle = Bundle()
bundle.putInt(CoursesData.COURSE_ID_KEY,courseID)
bundle.putInt(LectureData.LECTURE_ID_KEY, lectureID)
cardLastFragment.arguments = bundle
cardLastFragment
}
}
override fun getCount(): Int= pageCount
}
override fun onDestroy() {
disposables.clear()
super.onDestroy()
}
}
| 0 | Kotlin | 0 | 0 | f60496af8aba71a8b3dfa70223ea6725d7c49f47 | 7,385 | CommanTeam-android | MIT License |
multiplatform/features/src/commonMain/kotlin/multiplatform/features/screens/home/tabs/settings/SettingsTabState.kt | Alaksion | 743,354,018 | false | {"Kotlin": 122689} | package multiplatform.features.screens.home.tabs.settings
internal data class SettingsTabState(
val showLogoutButton: Boolean = false
)
internal sealed interface SettingsTabEvents {
data object Logout : SettingsTabEvents
} | 0 | Kotlin | 0 | 0 | c486e238d42734a84606c4377b91409e9b929960 | 232 | ImagefyAndroid | MIT License |
build-attribution/src/com/android/build/attribution/ui/data/builder/AnnotationProcessorsReportBuilder.kt | JetBrains | 60,701,247 | false | {"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19} | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.build.attribution.ui.data.builder
import com.android.build.attribution.analyzers.BuildEventsAnalysisResult
import com.android.build.attribution.ui.data.AnnotationProcessorUiData
import com.android.build.attribution.ui.data.AnnotationProcessorsReport
class AnnotationProcessorsReportBuilder(
val analyzersResultsProvider: BuildEventsAnalysisResult
) {
fun build(): AnnotationProcessorsReport = object : AnnotationProcessorsReport {
override val nonIncrementalProcessors: List<AnnotationProcessorUiData> = analyzersResultsProvider
.getNonIncrementalAnnotationProcessorsData()
.map {
object : AnnotationProcessorUiData {
override val className = it.className
override val compilationTimeMs = it.compilationDuration.toMillis()
}
}
.sortedByDescending { it.compilationTimeMs }
}
}
| 5 | Kotlin | 227 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 1,490 | android | Apache License 2.0 |
domain/src/commonMain/kotlin/app/tivi/domain/interactors/UpdateEpisodeDetails.kt | chrisbanes | 100,624,553 | false | {"Kotlin": 912114, "Swift": 8717, "Shell": 3317, "Ruby": 3139, "Python": 1228} | // Copyright 2019, Google LLC, <NAME> and the Tivi project contributors
// SPDX-License-Identifier: Apache-2.0
package app.tivi.domain.interactors
import app.tivi.data.episodes.SeasonsEpisodesRepository
import app.tivi.domain.Interactor
import app.tivi.util.AppCoroutineDispatchers
import kotlinx.coroutines.withContext
import me.tatarka.inject.annotations.Inject
@Inject
class UpdateEpisodeDetails(
private val seasonsEpisodesRepository: SeasonsEpisodesRepository,
private val dispatchers: AppCoroutineDispatchers,
) : Interactor<UpdateEpisodeDetails.Params, Unit>() {
override suspend fun doWork(params: Params) {
withContext(dispatchers.io) {
if (params.forceLoad || seasonsEpisodesRepository.needEpisodeUpdate(params.episodeId)) {
seasonsEpisodesRepository.updateEpisode(params.episodeId)
}
}
}
data class Params(val episodeId: Long, val forceLoad: Boolean)
}
| 20 | Kotlin | 868 | 6,469 | e1fee556dffc326ef0457f08b3729772c30e446b | 907 | tivi | Apache License 2.0 |
src/main/kotlin/gg/ingot/iron/transformer/ValueTransformer.kt | IngotGG | 809,438,131 | false | {"Kotlin": 63153} | package gg.ingot.iron.transformer
import gg.ingot.iron.representation.EntityField
import gg.ingot.iron.serialization.ColumnDeserializer
import gg.ingot.iron.serialization.SerializationAdapter
import java.sql.ResultSet
import kotlin.reflect.KClass
/**
* Transforms a value from a [ResultSet] into its corresponding type.
* @author DebitCardz
* @since 1.2
*/
internal class ValueTransformer(
private val serializationAdapter: SerializationAdapter?
) {
private val arrayTransformations: Map<KClass<*>, (Array<*>) -> Collection<*>> = mapOf(
List::class to { it.toList() },
Set::class to { it.toSet() }
)
/**
* Retrieve the value from the result set for the given field.
* Will automatically convert an [Array] into a given [Collection] type if the field is said [Collection].
* @param resultSet The result set to retrieve the value from.
* @param field The field to retrieve the value for.
* @return The value from the result set.
*/
fun convert(resultSet: ResultSet, field: EntityField): Any? {
val type = field.javaField.type
return when {
field.deserializer != null -> toCustomDeserializedObj(resultSet, field)
field.isJson -> toJsonObject(resultSet, field)
type.isArray -> toArray(resultSet, field.columnName)
Collection::class.java.isAssignableFrom(type) -> toCollection(resultSet, field.columnName, type)
else -> return toObject(resultSet, field.columnName)
}
}
/**
* Retrieve the value as an [Array] from the result set.
* @param resultSet The result set to retrieve the value from.
* @param columnName The column name to retrieve the value for.
*/
private fun toArray(resultSet: ResultSet, columnName: String): Any? {
return resultSet.getArray(columnName)
?.array
}
/**
* Retrieve the value as a [Collection] from the result set.
* @param resultSet The result set to retrieve the value from.
* @param columnName The column name to retrieve the value for.
* @param type The type of the collection.
*/
private fun toCollection(resultSet: ResultSet, columnName: String, type: Class<*>): Collection<*> {
val arr = toArray(resultSet, columnName) as Array<*>
val transformation = arrayTransformations.entries
// retrieve the first transformation that matches the type
.firstOrNull { it.key.java.isAssignableFrom(type) }
?.value
?: error("Unsupported collection type: $type")
return transformation(arr)
}
/**
* Retrieve the value as an object from the result set.
* @param resultSet The result set to retrieve the value from.
* @param columnName The column name to retrieve the value for.
* @return The value from the result set.
*/
private fun toObject(resultSet: ResultSet, columnName: String): Any? {
return resultSet.getObject(columnName)
}
/**
* Retrieve the value as a deserialized JSON object from the result set.
* @param resultSet The result set to retrieve the value from.
* @param field The field to retrieve the value for.
* @return The value from the result set.
*/
private fun toJsonObject(resultSet: ResultSet, field: EntityField): Any? {
checkNotNull(serializationAdapter) {
"A serializer adapter has not been passed through IronSettings, you will not be able to automatically deserialize JSON."
}
val obj = toObject(resultSet, field.columnName)
?: return null
return serializationAdapter.deserialize(obj, field.javaField.type)
}
/**
* Retrieve the value as a deserialized object from the provided
* [ColumnDeserializer].
* @param resultSet The result set to retrieve the value from.
* @param field The field to retrieve the value for.
* @return The value from the result set.
*/
private fun toCustomDeserializedObj(resultSet: ResultSet, field: EntityField): Any? {
val obj = toObject(resultSet, field.columnName)
?: return null
val deserializer = field.deserializer as? ColumnDeserializer<Any, *>
?: error("Deserializer is null, but it should not be.")
return deserializer.deserialize(obj)
}
} | 1 | Kotlin | 0 | 3 | b0fe2af1cf0abb9b046b66ad5cd98248ae3d64c0 | 4,369 | iron | Apache License 2.0 |
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsaccreditedprogrammesapi/service/OasysApiServiceTest.kt | ministryofjustice | 615,402,552 | false | {"Kotlin": 395666, "Shell": 9504, "Dockerfile": 1391} | package uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.service
import io.mockk.every
import io.mockk.mockk
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.springframework.http.HttpStatus
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.client.ClientResult
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.client.oasysApi.OasysApiClient
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.client.oasysApi.model.OasysAssessmentTimeline
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.client.oasysApi.model.OasysAttitude
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.client.oasysApi.model.OasysBehaviour
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.client.oasysApi.model.OasysHealth
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.client.oasysApi.model.OasysOffenceDetail
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.client.oasysApi.model.OasysPsychiatric
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.client.oasysApi.model.OasysRelationships
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.client.oasysApi.model.OasysRoshFull
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.client.oasysApi.model.Timeline
import java.time.LocalDateTime
class OasysApiServiceTest {
private val oasysApiClient = mockk<OasysApiClient>()
val service = OasysService(oasysApiClient)
@Test
fun `should return assessmentId`() {
val assessment1 =
Timeline(123123, "COMPLETE", "LAYER3", LocalDateTime.now())
val assessment2 = Timeline(
999999,
"COMPLETE",
"LAYER3",
LocalDateTime.now().minusDays(1),
)
val assessment3 = Timeline(111111, "STARTED", "LAYER3", null)
val oasysAssessmentTimeline = OasysAssessmentTimeline("A9999BB", null, listOf(assessment1, assessment2, assessment3))
every { oasysApiClient.getAssessments(any()) } returns ClientResult.Success(HttpStatus.OK, oasysAssessmentTimeline)
val result = service.getAssessmentId("A9999BB")
assertEquals(assessment1.id, result)
}
@Test
fun `should return offence detail`() {
val offenceDetail = OasysOffenceDetail(
"offence analysis",
listOf("Stalking"),
"Yes",
0,
"No",
"influences",
"motivation",
"Yes",
"fully",
"pattern",
)
every { oasysApiClient.getOffenceDetail(any()) } returns ClientResult.Success(
HttpStatus.OK,
offenceDetail,
)
val result = service.getOffenceDetail(123123)
assertEquals(offenceDetail, result)
}
@Test
fun `should return relationships`() {
val oasysRelationships = OasysRelationships(
"Yes",
"Yes",
"Yes",
"Yes",
"Yes",
"Free text",
)
every { oasysApiClient.getRelationships(any()) } returns ClientResult.Success(
HttpStatus.OK,
oasysRelationships,
)
val result = service.getRelationships(123123)
assertEquals(oasysRelationships, result)
}
@Test
fun `should return Rosh Analysis`() {
val oasysRoshFull = OasysRoshFull(
"Offence detail",
"where when",
"how done",
"who were victims",
"Any one else involved",
"motivation",
"source",
)
every { oasysApiClient.getRoshFull(any()) } returns ClientResult.Success(
HttpStatus.OK,
oasysRoshFull,
)
val result = service.getRoshFull(123123)
assertEquals(oasysRoshFull, result)
}
@Test
fun `should return psychiatric details`() {
val psychiatric = OasysPsychiatric(
"0 - no problems",
)
every { oasysApiClient.getPsychiatric(any()) } returns ClientResult.Success(
HttpStatus.OK,
psychiatric,
)
val result = service.getPsychiatric(123123)
assertEquals(psychiatric, result)
}
@Test
fun `should return behaviour details`() {
val behaviour = OasysBehaviour(
"1",
"2",
"3",
"4",
"5",
"6",
)
every { oasysApiClient.getBehaviour(any()) } returns ClientResult.Success(
HttpStatus.OK,
behaviour,
)
val result = service.getBehaviour(123123)
assertEquals(behaviour, result)
}
@Test
fun `should return health details`() {
val health = OasysHealth(
"Yes",
"blind",
)
every { oasysApiClient.getHealth(any()) } returns ClientResult.Success(
HttpStatus.OK,
health,
)
val result = service.getHealth(123123)
assertEquals(health, result)
}
@Test
fun `should return attitude details`() {
val attitude = OasysAttitude(
"0-no problems",
"1-some problems",
)
every { oasysApiClient.getAttitude(any()) } returns ClientResult.Success(
HttpStatus.OK,
attitude,
)
val result = service.getAttitude(123123)
assertEquals(attitude, result)
}
}
| 2 | Kotlin | 0 | 0 | b1f6a5805a8c63e31d22f48ce7051a7dc4c1c8b3 | 4,962 | hmpps-accredited-programmes-api | MIT License |
src/main/kotlin/io/thelandscape/krawler/crawler/KrawlConfig.kt | brianmadden | 71,804,596 | false | null | /**
* Created by <EMAIL> on 10/31/16.
*
* Copyright (c) <2016> <H, 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 io.thelandscape.krawler.crawler
class KrawlConfig(
// Size of crawler threadpool
// Default: -1 (unlimited)
val numThreads: Int = 1,
// Maximum crawl depth
// Default: -1 (unlimited)
val maxDepth: Int = -1,
// Global crawl limit -- if this is reached, shutdown
// Default: -1 (unlimited)
val totalPages: Int = -1,
// Politeness delay (in ms) to wait between requests
// Default: 200ms
val politenessDelay: Long = 200,
// User agent string
val userAgent: String = "io.thelandscape.Krawler Web Crawler Framework",
// Directory where KrawlQueue will be persisted
val crawlDirectory: String = ".krawl",
// Should the Krawl progress persist?
val persistentCrawl: Boolean = false,
// Maximum number of queued URLs - when this value is exceeded
// additional crawl requests are rejected until the queue has drained
val maximumQueueSize: Int = 1000000,
// Length of time (in seconds) to wait before giving up and calling it quits
emptyQueueWaitTime: Long = 10,
// The timeout in milliseconds used when requesting a connection. 0 = infinite, -1 = system default
// Default: -1
val connectionRequestTimeout: Int = -1,
// Maximum period inactivity between two consecutive data packets. 0 = infinite, -1 = system default
// Default: -1
val socketTimeout: Int = -1,
// Connect timeout in milliseconds until a connection is established. 0 = infinite, -1 = system default
val connectTimeout: Int = -1,
// Should we respect robots.txt
val respectRobotsTxt: Boolean = true,
// Should we follow redirects
val followRedirects: Boolean = true,
// Use fast redirect strategy, or slow
// Slow redirect strategy inserts the target URL of the redirect back to the queue rather than auto following
val useFastRedirectStrategy: Boolean = true,
// Should we use content compression
val allowContentCompression: Boolean = true) {
// Length of time to sleep when queue becomes empty
var emptyQueueWaitTime: Long = emptyQueueWaitTime
private set(value) { field = if (value <= 0) 1 else value }
} | 6 | null | 17 | 128 | d58e901e427a52874c164111db6c4013e71ffec3 | 3,447 | krawler | MIT License |
tokisaki-api/src/main/kotlin/io/micro/api/function/converter/FunctionConverter.kt | spcookie | 730,690,607 | false | {"Kotlin": 168133, "Java": 13136} | package io.micro.api.function.converter
import io.micro.api.function.dto.QueryFunctionDTO
import io.micro.server.function.domain.model.entity.FunctionDO
import org.mapstruct.Mapper
import org.mapstruct.MappingConstants.ComponentModel
@Mapper(componentModel = ComponentModel.CDI)
interface FunctionConverter {
fun functionDO2functionDTO(functionDO: FunctionDO): QueryFunctionDTO
} | 0 | Kotlin | 0 | 0 | 63cd90108a0215a42b916fcc15281c658019d357 | 385 | Tokisaki | Apache License 2.0 |
src/test/kotlin/testsupport/VcsTestCase.kt | carlrobertoh | 602,041,947 | false | {"Java": 574564, "Kotlin": 336851} | package testsupport
import com.intellij.openapi.components.service
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsDirectoryMapping
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.testFramework.HeavyPlatformTestCase
import git4idea.GitVcs
import git4idea.commands.Git
import git4idea.commands.GitCommand
import git4idea.commands.GitLineHandler
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import org.assertj.core.api.Assertions.assertThat
import org.junit.Assert
import java.nio.file.Files
import java.nio.file.Path
open class VcsTestCase : HeavyPlatformTestCase() {
private lateinit var projectDir: Path
@Throws(Exception::class)
override fun setUp() {
super.setUp()
projectDir = tempDir.createDir()
}
fun git(command: GitCommand, parameters: List<String> = emptyList()) {
val checkoutHandler = GitLineHandler(project, projectDir.toFile(), command)
checkoutHandler.addParameters(parameters)
service<Git>().runCommand(checkoutHandler).throwOnError()
}
fun registerRepository(): GitRepository =
ProjectLevelVcsManager.getInstance(project).run {
directoryMappings = listOf(VcsDirectoryMapping(projectDir.toString(), GitVcs.NAME))
Files.createDirectories(projectDir)
Assert.assertFalse(
"There are no VCS roots. Active VCSs: $allActiveVcss",
allVcsRoots.isEmpty()
)
val file = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(projectDir)
runBlocking(Dispatchers.IO) {
val repository = project.service<GitRepositoryManager>().getRepositoryForRoot(file)
assertThat(repository).describedAs("Couldn't find repository for root $projectDir")
.isNotNull()
repository!!
}
}
} | 96 | Java | 194 | 955 | 7ae66e04cac6bff592709267990e4194f1a67858 | 2,018 | CodeGPT | Apache License 2.0 |
p2m-core/src/main/java/com/p2m/core/internal/event/InternalMediatorBackgroundLiveEvent.kt | wangdaqi77 | 367,279,479 | false | null | package com.p2m.core.internal.event
import androidx.annotation.MainThread
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import com.p2m.core.event.*
internal class InternalMediatorBackgroundLiveEvent<T>() : wang.lifecycle.MediatorBackgroundLiveEvent<T>(),
MediatorBackgroundLiveEvent<T>,
MediatorEvent {
@Suppress("UNCHECKED_CAST")
override fun <S> addSource(source: BackgroundLiveEvent<S>, onChanged: BackgroundObserver<in S>) {
super.addSource(source as wang.lifecycle.BackgroundLiveEvent<S>, onChanged)
}
@Suppress("UNCHECKED_CAST")
override fun <S> removeSource(toRemote: BackgroundLiveEvent<S>) {
super.removeSource(toRemote as wang.lifecycle.BackgroundLiveEvent<S>,)
}
@MainThread
@Suppress("UNCHECKED_CAST")
override fun <S> addSource(source: LiveEvent<S>, onChanged: Observer<in S>) {
super.addSource(source as wang.lifecycle.LiveEvent<S>, onChanged)
}
@MainThread
@Suppress("UNCHECKED_CAST")
override fun <S> removeSource(toRemote: LiveEvent<S>) {
super.removeSource(toRemote as wang.lifecycle.LiveEvent<S>)
}
@MainThread
override fun <S> addLiveDataSource(source: LiveData<S>, onChanged: Observer<in S>) {
super.addSource(source, onChanged)
}
@MainThread
override fun <S> removeLiveDataSource(toRemote: LiveData<S>) {
super.removeSource(toRemote)
}
override fun observe(owner: LifecycleOwner, observer: BackgroundObserver<in T>) {
super.observe(owner, observer)
}
override fun observeForever(observer: BackgroundObserver<in T>) {
super.observeForever(observer)
}
override fun observeNoSticky(owner: LifecycleOwner, observer: BackgroundObserver<in T>) {
super.observeNoSticky(owner, observer)
}
override fun observeForeverNoSticky(observer: BackgroundObserver<in T>) {
super.observeForeverNoSticky(observer)
}
override fun observeNoLoss(owner: LifecycleOwner, observer: BackgroundObserver<in T>) {
super.observeNoLoss(owner, observer)
}
override fun observeForeverNoLoss(observer: BackgroundObserver<in T>) {
super.observeForeverNoLoss(observer)
}
override fun observeNoStickyNoLoss(owner: LifecycleOwner, observer: BackgroundObserver<in T>) {
super.observeNoStickyNoLoss(owner, observer)
}
override fun observeForeverNoStickyNoLoss(observer: BackgroundObserver<in T>) {
super.observeForeverNoStickyNoLoss(observer)
}
override fun removeObserver(observer: BackgroundObserver<in T>) {
super.removeObserver(observer)
}
} | 0 | Kotlin | 6 | 34 | 6263c1c5a2dedda773eb7c6745b86ac2ff8f00d9 | 2,689 | P2M | Apache License 2.0 |
dmn-test-cases/signavio/dmn/dmn2java/expected/proto/proto3/kotlin/dmn/date-time-proto/Date.kt | goldmansachs | 118,478,361 | false | {"Java": 10066454, "Kotlin": 1014324, "Python": 419543, "FreeMarker": 229361, "ANTLR": 100720, "Batchfile": 1400, "Shell": 980} |
import java.util.*
import java.util.stream.Collectors
@javax.annotation.Generated(value = ["signavio-decision.ftl", "Date"])
@com.gs.dmn.runtime.annotation.DRGElement(
namespace = "",
name = "Date",
label = "",
elementKind = com.gs.dmn.runtime.annotation.DRGElementKind.DECISION,
expressionKind = com.gs.dmn.runtime.annotation.ExpressionKind.LITERAL_EXPRESSION,
hitPolicy = com.gs.dmn.runtime.annotation.HitPolicy.UNKNOWN,
rulesCount = -1
)
class Date() : com.gs.dmn.signavio.runtime.JavaTimeSignavioBaseDecision() {
override fun applyMap(input_: MutableMap<String, String>, context_: com.gs.dmn.runtime.ExecutionContext): java.time.LocalDate? {
try {
return apply(input_.get("CompositeInputDateTime")?.let({ com.gs.dmn.serialization.JsonSerializer.OBJECT_MAPPER.readValue(it, object : com.fasterxml.jackson.core.type.TypeReference<type.TCompositeDateTimeImpl>() {}) }), input_.get("InputDate")?.let({ date(it) }), input_.get("InputDateTime")?.let({ dateAndTime(it) }), input_.get("InputTime")?.let({ time(it) }), context_)
} catch (e: Exception) {
logError("Cannot apply decision 'Date'", e)
return null
}
}
fun apply(compositeInputDateTime: type.TCompositeDateTime?, inputDate: java.time.LocalDate?, inputDateTime: java.time.temporal.TemporalAccessor?, inputTime: java.time.temporal.TemporalAccessor?, context_: com.gs.dmn.runtime.ExecutionContext): java.time.LocalDate? {
try {
// Start decision 'Date'
var annotationSet_: com.gs.dmn.runtime.annotation.AnnotationSet = context_.getAnnotations()
var eventListener_: com.gs.dmn.runtime.listener.EventListener = context_.getEventListener()
var externalExecutor_: com.gs.dmn.runtime.external.ExternalFunctionExecutor = context_.getExternalFunctionExecutor()
var cache_: com.gs.dmn.runtime.cache.Cache = context_.getCache()
val dateStartTime_ = System.currentTimeMillis()
val dateArguments_ = com.gs.dmn.runtime.listener.Arguments()
dateArguments_.put("CompositeInputDateTime", compositeInputDateTime)
dateArguments_.put("InputDate", inputDate)
dateArguments_.put("InputDateTime", inputDateTime)
dateArguments_.put("InputTime", inputTime)
eventListener_.startDRGElement(DRG_ELEMENT_METADATA, dateArguments_)
// Evaluate decision 'Date'
val output_: java.time.LocalDate? = evaluate(compositeInputDateTime, inputDate, inputDateTime, inputTime, context_)
// End decision 'Date'
eventListener_.endDRGElement(DRG_ELEMENT_METADATA, dateArguments_, output_, (System.currentTimeMillis() - dateStartTime_))
return output_
} catch (e: Exception) {
logError("Exception caught in 'Date' evaluation", e)
return null
}
}
fun applyProto(dateRequest_: proto.DateRequest, context_: com.gs.dmn.runtime.ExecutionContext): proto.DateResponse {
// Create arguments from Request Message
val compositeInputDateTime: type.TCompositeDateTime? = type.TCompositeDateTime.toTCompositeDateTime(dateRequest_.getCompositeInputDateTime())
val inputDate: java.time.LocalDate? = date(dateRequest_.getInputDate())
val inputDateTime: java.time.temporal.TemporalAccessor? = dateAndTime(dateRequest_.getInputDateTime())
val inputTime: java.time.temporal.TemporalAccessor? = time(dateRequest_.getInputTime())
// Invoke apply method
val output_: java.time.LocalDate? = apply(compositeInputDateTime, inputDate, inputDateTime, inputTime, context_)
// Convert output to Response Message
val builder_: proto.DateResponse.Builder = proto.DateResponse.newBuilder()
val outputProto_ = string(output_)
builder_.setDate(outputProto_)
return builder_.build()
}
private inline fun evaluate(compositeInputDateTime: type.TCompositeDateTime?, inputDate: java.time.LocalDate?, inputDateTime: java.time.temporal.TemporalAccessor?, inputTime: java.time.temporal.TemporalAccessor?, context_: com.gs.dmn.runtime.ExecutionContext): java.time.LocalDate? {
var annotationSet_: com.gs.dmn.runtime.annotation.AnnotationSet = context_.getAnnotations()
var eventListener_: com.gs.dmn.runtime.listener.EventListener = context_.getEventListener()
var externalExecutor_: com.gs.dmn.runtime.external.ExternalFunctionExecutor = context_.getExternalFunctionExecutor()
var cache_: com.gs.dmn.runtime.cache.Cache = context_.getCache()
return inputDate as java.time.LocalDate?
}
companion object {
val DRG_ELEMENT_METADATA : com.gs.dmn.runtime.listener.DRGElement = com.gs.dmn.runtime.listener.DRGElement(
"",
"Date",
"",
com.gs.dmn.runtime.annotation.DRGElementKind.DECISION,
com.gs.dmn.runtime.annotation.ExpressionKind.LITERAL_EXPRESSION,
com.gs.dmn.runtime.annotation.HitPolicy.UNKNOWN,
-1
)
@JvmStatic
fun requestToMap(dateRequest_: proto.DateRequest): kotlin.collections.Map<String, Any?> {
// Create arguments from Request Message
val compositeInputDateTime: type.TCompositeDateTime? = type.TCompositeDateTime.toTCompositeDateTime(dateRequest_.getCompositeInputDateTime())
val inputDate: java.time.LocalDate? = com.gs.dmn.signavio.feel.lib.JavaTimeSignavioLib.INSTANCE.date(dateRequest_.getInputDate())
val inputDateTime: java.time.temporal.TemporalAccessor? = com.gs.dmn.signavio.feel.lib.JavaTimeSignavioLib.INSTANCE.dateAndTime(dateRequest_.getInputDateTime())
val inputTime: java.time.temporal.TemporalAccessor? = com.gs.dmn.signavio.feel.lib.JavaTimeSignavioLib.INSTANCE.time(dateRequest_.getInputTime())
// Create map
val map_: kotlin.collections.MutableMap<String, Any?> = mutableMapOf()
map_.put("CompositeInputDateTime", compositeInputDateTime)
map_.put("InputDate", inputDate)
map_.put("InputDateTime", inputDateTime)
map_.put("InputTime", inputTime)
return map_
}
@JvmStatic
fun responseToOutput(dateResponse_: proto.DateResponse): java.time.LocalDate? {
// Extract and convert output
return com.gs.dmn.signavio.feel.lib.JavaTimeSignavioLib.INSTANCE.date(dateResponse_.getDate())
}
}
}
| 9 | Java | 43 | 149 | 1e252d7dcfb0e2da0816304ea6456f10734ac2f4 | 6,523 | jdmn | Apache License 2.0 |
app-core/src/main/kotlin/com/flab/hsw/core/domain/content/ContentRecommendation.kt | f-lab-edu | 545,756,758 | false | {"Kotlin": 249863, "Vim Snippet": 765} | package com.flab.hsw.core.domain.content
import com.flab.hsw.core.domain.content.aggregate.ContentRecommendationModel
import java.time.Instant
import java.util.*
interface ContentRecommendation {
val recommenderUserId: UUID
val contentId: Long
val registeredAt: Instant
companion object {
fun create(
userId : UUID,
contentId: Long
) : ContentRecommendation = ContentRecommendationModel.create(
recommenderUserId = userId,
contentId = contentId
)
}
}
| 2 | Kotlin | 4 | 5 | 90dd69cbef256eff7cb852abfc2573719a1fb5f1 | 548 | hello-study-world | MIT License |
app-core/src/main/kotlin/com/flab/hsw/core/domain/content/ContentRecommendation.kt | f-lab-edu | 545,756,758 | false | {"Kotlin": 249863, "Vim Snippet": 765} | package com.flab.hsw.core.domain.content
import com.flab.hsw.core.domain.content.aggregate.ContentRecommendationModel
import java.time.Instant
import java.util.*
interface ContentRecommendation {
val recommenderUserId: UUID
val contentId: Long
val registeredAt: Instant
companion object {
fun create(
userId : UUID,
contentId: Long
) : ContentRecommendation = ContentRecommendationModel.create(
recommenderUserId = userId,
contentId = contentId
)
}
}
| 2 | Kotlin | 4 | 5 | 90dd69cbef256eff7cb852abfc2573719a1fb5f1 | 548 | hello-study-world | MIT License |
app/src/main/java/com/example/beersguide/viewModel/MealViewModel.kt | Tanujain0811 | 606,802,916 | false | null | package com.example.beersguide.viewModel
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.beersguide.db.MealDb
import com.example.beersguide.pojo.Meal
import com.example.beersguide.pojo.MealInfo
import com.example.beersguide.retrofit.RetrofitInstance
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class MealViewModel(val mealDb: MealDb):ViewModel() {
private var mealDetailLiveData=MutableLiveData<Meal>()
fun getMealDetail(id:String){
RetrofitInstance.api.getMealDetail(id).enqueue(object :Callback<MealInfo>{
override fun onResponse(call: Call<MealInfo>, response: Response<MealInfo>) {
if(response.body()!=null){
mealDetailLiveData.value=response.body()!!.meals[0]
}
else{
return
}
}
override fun onFailure(call: Call<MealInfo>, t: Throwable) {
t.message?.let { Log.d("ERROR", it) }
}
})
}
fun observeMealDetails():LiveData<Meal>{
return mealDetailLiveData
}
fun insertMeal(meal: Meal){
viewModelScope.launch {
mealDb.mealDao().insertMeal(meal)
}
}
fun deleteMeal(meal: Meal){
viewModelScope.launch {
mealDb.mealDao().deleteMeal(meal)
}
}
} | 0 | Kotlin | 0 | 0 | a5faf05ebe9afae6940a33858d29e6e2e73dd97a | 1,542 | Application | MIT License |
src/main/kotlin/uk/gov/justice/digital/hmpps/incidentreporting/jpa/Question.kt | ministryofjustice | 725,638,590 | false | {"Kotlin": 239888, "Dockerfile": 1365} | package uk.gov.justice.digital.hmpps.incidentreporting.jpa
import jakarta.persistence.CascadeType
import jakarta.persistence.Entity
import jakarta.persistence.FetchType
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.ManyToOne
import jakarta.persistence.OneToMany
import jakarta.persistence.OrderColumn
import org.hibernate.Hibernate
import java.time.LocalDateTime
import uk.gov.justice.digital.hmpps.incidentreporting.dto.Question as QuestionDto
@Entity
class Question(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long? = null,
@ManyToOne(fetch = FetchType.LAZY)
private val report: Report,
val code: String,
val question: String,
val additionalInformation: String? = null,
@OneToMany(mappedBy = "question", fetch = FetchType.LAZY, cascade = [CascadeType.ALL], orphanRemoval = true)
@OrderColumn(name = "sequence")
private val responses: MutableList<Response> = mutableListOf(),
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || Hibernate.getClass(this) != Hibernate.getClass(other)) return false
other as Question
return id == other.id
}
override fun hashCode(): Int {
return id?.hashCode() ?: 0
}
override fun toString(): String {
return "Question(id=$id)"
}
fun getReport() = report
fun getResponses(): List<Response> = responses
fun addResponse(
response: String,
additionalInformation: String?,
recordedBy: String,
recordedOn: LocalDateTime,
): Question {
responses.add(
Response(
question = this,
response = response,
recordedBy = recordedBy,
recordedOn = recordedOn,
additionalInformation = additionalInformation,
),
)
return this
}
fun toDto() = QuestionDto(
code = code,
question = question,
additionalInformation = additionalInformation,
responses = responses.map { it.toDto() },
)
}
| 2 | Kotlin | 0 | 0 | c424db6080838a9ad133a983146f4f35e7ebdf5f | 2,041 | hmpps-incident-reporting-api | MIT License |
browser-kotlin/src/jsMain/kotlin/web/authn/AttestationConveyancePreference.kt | karakum-team | 393,199,102 | false | null | // Automatically generated - do not modify!
@file:Suppress(
"NAME_CONTAINS_ILLEGAL_CHARS",
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
package web.authentication
// language=JavaScript
@JsName("""(/*union*/{direct: 'direct', enterprise: 'enterprise', indirect: 'indirect', none: 'none'}/*union*/)""")
sealed external interface AttestationConveyancePreference {
companion object {
val direct: AttestationConveyancePreference
val enterprise: AttestationConveyancePreference
val indirect: AttestationConveyancePreference
val none: AttestationConveyancePreference
}
}
| 0 | null | 6 | 26 | 3fcfd2c61da8774151cf121596e656cc123b37db | 611 | types-kotlin | Apache License 2.0 |
shared/src/commonMain/kotlin/org/mixdrinks/ui/list/main/ListComponent.kt | MixDrinks | 614,917,688 | false | {"Kotlin": 196307, "Swift": 10681, "Ruby": 277, "Shell": 228} | package org.mixdrinks.ui.list.main
import com.arkivanov.decompose.ComponentContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combineTransform
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import org.mixdrinks.data.CocktailsProvider
import org.mixdrinks.ui.filters.FilterItemUiModel
import org.mixdrinks.ui.list.CocktailListMapper
import org.mixdrinks.ui.list.CocktailsListState
import org.mixdrinks.ui.list.SelectedFilterProvider
import org.mixdrinks.ui.navigation.INavigator
import org.mixdrinks.ui.navigation.MainTabNavigator
import org.mixdrinks.ui.widgets.undomain.UiState
import org.mixdrinks.ui.widgets.undomain.launch
@Suppress("LongParameterList")
internal class ListComponent(
private val componentContext: ComponentContext,
private val cocktailsProvider: CocktailsProvider,
private val selectedFilterProvider: SelectedFilterProvider,
private val mainTabNavigator: MainTabNavigator,
private val mutableFilterStorage: MutableFilterStorage,
private val cocktailListMapper: CocktailListMapper,
) : ComponentContext by componentContext,
INavigator by mainTabNavigator {
private val _state = MutableStateFlow<UiState<CocktailsListState>>(UiState.Loading)
val state: StateFlow<UiState<CocktailsListState>> = _state
private val _searchQuery: MutableStateFlow<String> = MutableStateFlow("")
val searchQuery: StateFlow<String> = _searchQuery
private val _isSearchActive = MutableStateFlow(false)
val isSearchActive: StateFlow<Boolean> = _isSearchActive
init {
launch {
cocktailsProvider.getCocktails()
.map { cocktails -> map(cocktails) }
.combineTransform(isSearchActive) { cocktails, isSearchActive ->
if (!isSearchActive) {
emit(cocktails)
}
}
.collect(_state)
}
launch {
searchQuery
.map { query ->
cocktailsProvider.getAllCocktails()
.filter { cocktail ->
cocktail.name.contains(query, ignoreCase = true)
}
.sortedBy { it.name }
}
.map { cocktails -> map(cocktails) }
.combineTransform(isSearchActive) { cocktails, isSearchActive ->
if (isSearchActive) {
emit(cocktails)
}
}
.collect(_state)
}
}
val filterCountState: StateFlow<Int?> = mutableFilterStorage.selected
.map { filterGroups ->
filterGroups.flatMap { it.value }.count().takeIf { it > 0 }
}
.stateIn(
CoroutineScope(Dispatchers.Main), SharingStarted.WhileSubscribed(), null
)
fun openSearch() = launch {
_isSearchActive.emit(true)
}
fun closeSearch() = launch {
_searchQuery.emit("")
_isSearchActive.emit(false)
}
fun onSearchQueryChange(query: String) = launch {
println("onSearchQueryChange: $query")
_searchQuery.emit(query)
}
private suspend fun map(cocktails: List<CocktailsProvider.Cocktail>): UiState.Data<CocktailsListState> {
return UiState.Data(
if (cocktails.isEmpty()) {
CocktailsListState.PlaceHolder(selectedFilterProvider.getSelectedFiltersWithData())
} else {
CocktailsListState.Cocktails(cocktailListMapper.map(cocktails))
}
)
}
fun onFilterStateChange(
filterGroupId: FilterItemUiModel,
isSelect: Boolean,
) {
mutableFilterStorage.onFilterStateChange(filterGroupId, isSelect)
}
}
| 14 | Kotlin | 1 | 9 | 182933ab91b766def2d6dfd67f63c7e4ef008ee8 | 3,982 | Mobile | Apache License 2.0 |
app/src/main/java/com/zhuravlev/stockobserverapp/model/moex/ResponseMarketData.kt | YuriZhuravlev | 339,771,129 | false | null | package com.zhuravlev.stockobserverapp.model.moex
import com.google.gson.annotations.SerializedName
data class ResponseMarketData(
@field:SerializedName("marketdata")
val marketdata: List<MarketDataItem?>? = null
)
data class MarketDataItem(
@field:SerializedName("OPENPERIODPRICE")
val openPeriodPrice: String? = null,
@field:SerializedName("HIGH")
val high: String? = null,
@field:SerializedName("BOARDID")
val boardId: String? = null,
@field:SerializedName("OFFERDEPTHT")
val offerDepthT: String? = null,
@field:SerializedName("VALUE")
val value: String? = null,
@field:SerializedName("LASTOFFER")
val lASTOFFER: Any? = null,
@field:SerializedName("QTY")
val qty: String? = null,
@field:SerializedName("WAPTOPREVWAPRICE")
val wapToPrevWaPrice: String? = null,
@field:SerializedName("MARKETPRICETODAY")
val marketPriceToday: String? = null,
@field:SerializedName("MARKETPRICE2")
val marketPrice2: String? = null,
@field:SerializedName("CLOSINGAUCTIONVOLUME")
val closingAuctionVolume: String? = null,
@field:SerializedName("ETFSETTLEPRICE")
val etfSetTlePrice: Any? = null,
@field:SerializedName("NUMTRADES")
val numTrades: String? = null,
@field:SerializedName("CLOSEPRICE")
val closePrice: Any? = null,
@field:SerializedName("TRADINGSESSION")
val tradingSession: Any? = null,
@field:SerializedName("HIGHBID")
val highBid: Any? = null,
@field:SerializedName("MARKETPRICE")
val marketPrice: String? = null,
@field:SerializedName("LASTTOPREVPRICE")
val lastToPrevPrice: String? = null,
@field:SerializedName("WAPRICE")
val waPrice: String? = null,
@field:SerializedName("OFFERDEPTH")
val offerDepth: Any? = null,
@field:SerializedName("ISSUECAPITALIZATION")
val issueCapitalization: String? = null,
@field:SerializedName("LOW")
val low: String? = null,
@field:SerializedName("LAST")
val last: String? = null,
@field:SerializedName("LCURRENTPRICE")
val lCurrentPrice: String? = null,
@field:SerializedName("SECID")
val secId: String? = null,
@field:SerializedName("LCLOSEPRICE")
val lClosePrice: String? = null,
@field:SerializedName("UPDATETIME")
val updateTime: String? = null,
@field:SerializedName("CLOSINGAUCTIONPRICE")
val closingAuctionPrice: String? = null,
@field:SerializedName("VALTODAY_USD")
val valTodayUsd: String? = null,
@field:SerializedName("ADMITTEDQUOTE")
val admitTedQuote: String? = null,
@field:SerializedName("OFFER")
val offer: Any? = null,
@field:SerializedName("SYSTIME")
val sysTime: String? = null,
@field:SerializedName("LASTCNGTOLASTWAPRICE")
val lastCngToLastWapPrice: String? = null,
@field:SerializedName("VALTODAY")
val valToday: String? = null,
@field:SerializedName("BIDDEPTHT")
val bidDepthT: String? = null,
@field:SerializedName("SEQNUM")
val seqNum: String? = null,
@field:SerializedName("VALTODAY_RUR")
val valTodayRur: String? = null,
@field:SerializedName("NUMOFFERS")
val numOffers: Any? = null,
@field:SerializedName("CHANGE")
val change: String? = null,
@field:SerializedName("BID")
val bId: Any? = null,
@field:SerializedName("SPREAD")
val spread: String? = null,
@field:SerializedName("LOWOFFER")
val lowOffer: Any? = null,
@field:SerializedName("LASTCHANGEPRCNT")
val lastChangePrcnt: String? = null,
@field:SerializedName("TRADINGSTATUS")
val tradingStatus: String? = null,
@field:SerializedName("LASTCHANGE")
val lastChange: String? = null,
@field:SerializedName("VOLTODAY")
val volToday: String? = null,
@field:SerializedName("WAPTOPREVWAPRICEPRCNT")
val wapToPrevWaPricePrcnt: String? = null,
@field:SerializedName("TIME")
val time: String? = null,
@field:SerializedName("ISSUECAPITALIZATION_UPDATETIME")
val issueCapitalizationUpdateTime: String? = null,
@field:SerializedName("OPEN")
val open: String? = null,
@field:SerializedName("VALUE_USD")
val valueUsd: String? = null,
@field:SerializedName("NUMBIDS")
val numBIds: Any? = null,
@field:SerializedName("ETFSETTLECURRENCY")
val etfSetTleCurrency: Any? = null,
@field:SerializedName("BIDDEPTH")
val bIdDepth: Any? = null,
@field:SerializedName("LASTBID")
val lastBId: Any? = null,
@field:SerializedName("PRICEMINUSPREVWAPRICE")
val priceMinusPrevWaPrice: String? = null
)
| 0 | Kotlin | 0 | 0 | 74b5e761e09c3b8262d1d2a3fb40e318f39d501c | 4,596 | StockObserverApp | Apache License 2.0 |
data/src/main/kotlin/data/network/OfflineEnabledRequestFacade.kt | anirudh8860 | 144,851,679 | false | null | package data.network
import data.ObjectMapper
/**
* Defines how a typical request looks.
*/
internal abstract class OfflineEnabledRequestFacade<
in RequestModel, MappedRequestModel, ResponseModel, MappedModel>(
source: RequestSource<MappedRequestModel, ResponseModel>,
requestMapper: ObjectMapper<RequestModel, MappedRequestModel>,
responseMapper: ObjectMapper<ResponseModel, MappedModel>)
: Gettable<RequestModel, MappedModel>,
RequestFacade<RequestModel, MappedRequestModel, ResponseModel, MappedModel>(
source, requestMapper, responseMapper) {
override fun get(parameters: RequestModel) = map(source.get(requestMapper.from(parameters)))
}
| 0 | null | 0 | 1 | ba8ead38f5bcefc857a6dc9cc344cd030ca5b22d | 678 | dinger | MIT License |
render/jpql/src/test/kotlin/com/linecorp/kotlinjdsl/render/jpql/serializer/impl/JpqlLeftFetchJoinSerializerTest.kt | line | 442,633,985 | false | null | package com.linecorp.kotlinjdsl.render.jpql.serializer.impl
import com.linecorp.kotlinjdsl.querymodel.jpql.entity.Entities
import com.linecorp.kotlinjdsl.querymodel.jpql.join.Joins
import com.linecorp.kotlinjdsl.querymodel.jpql.join.impl.JpqlLeftFetchJoin
import com.linecorp.kotlinjdsl.querymodel.jpql.path.Paths
import com.linecorp.kotlinjdsl.querymodel.jpql.predicate.Predicates
import com.linecorp.kotlinjdsl.render.TestRenderContext
import com.linecorp.kotlinjdsl.render.jpql.entity.author.Author
import com.linecorp.kotlinjdsl.render.jpql.entity.book.BookAuthor
import com.linecorp.kotlinjdsl.render.jpql.serializer.JpqlRenderClause
import com.linecorp.kotlinjdsl.render.jpql.serializer.JpqlRenderSerializer
import com.linecorp.kotlinjdsl.render.jpql.serializer.JpqlSerializerTest
import com.linecorp.kotlinjdsl.render.jpql.writer.JpqlWriter
import io.mockk.impl.annotations.MockK
import io.mockk.verifySequence
import org.assertj.core.api.WithAssertions
import org.junit.jupiter.api.Test
@JpqlSerializerTest
class JpqlLeftFetchJoinSerializerTest : WithAssertions {
private val sut = JpqlLeftFetchJoinSerializer()
@MockK
private lateinit var writer: JpqlWriter
@MockK
private lateinit var serializer: JpqlRenderSerializer
private val entity1 = Entities.entity(Author::class, "author01")
private val predicate1 = Predicates.equal(
Paths.path(entity1, Author::authorId),
Paths.path(BookAuthor::authorId),
)
@Test
fun handledType() {
// when
val actual = sut.handledType()
// then
assertThat(actual).isEqualTo(JpqlLeftFetchJoin::class)
}
@Test
fun serialize() {
// given
val part = Joins.leftFetchJoin(
entity1,
predicate1,
)
val context = TestRenderContext(serializer)
// when
sut.serialize(part as JpqlLeftFetchJoin<*>, writer, context)
// then
verifySequence {
writer.write("LEFT JOIN FETCH")
writer.write(" ")
serializer.serialize(entity1, writer, context + JpqlRenderClause.Join)
writer.write(" ")
writer.write("ON")
writer.write(" ")
serializer.serialize(predicate1, writer, context + JpqlRenderClause.On)
}
}
}
| 4 | null | 86 | 705 | 3a58ff84b1c91bbefd428634f74a94a18c9b76fd | 2,316 | kotlin-jdsl | Apache License 2.0 |
data/src/main/java/com/movies/data/RetrofitRunner.kt | chenshige | 152,017,908 | false | null | package com.movies.data
import com.movies.data.entities.Failure
import com.movies.data.entities.Result
import com.movies.data.entities.Success
import com.movies.data.mappers.Mapper
import com.movies.extensions.bodyOrThrow
import com.movies.extensions.toException
import retrofit2.Response
import javax.inject.Inject
import javax.inject.Singleton
/**
* @author donnieSky
* @created_at 2018/8/22.
* @description
* @version
*/
@Singleton
class RetrofitRunner @Inject constructor() {
suspend fun <T, E> executeForResponse(mapper: Mapper<T, E>, request: suspend () -> Response<T>): Result<E> {
return try {
val response = request()
if (response.isSuccessful) {
val okHttpNetworkResponse = response.raw().networkResponse()
val notModified = okHttpNetworkResponse == null || okHttpNetworkResponse.code() == 304
Success(data = mapper.map(response.bodyOrThrow()), responseModified = !notModified)
} else {
Failure(response.toException())
}
} catch (e: Exception) {
Failure(e)
}
}
suspend fun <T> executeForResponse(request: suspend () -> Response<T>): Result<T> {
val unitMapper = object : Mapper<T, T> {
override fun map(from: T) = from
}
return executeForResponse(unitMapper, request)
}
suspend fun <T, E> mapperForResponse(mapper: Mapper<T, E>, request: suspend () -> T?): Result<E> {
return try {
val response = request()
if (response != null) {
Success(data = mapper.map(response))
} else {
Failure(Exception("result is null"))
}
} catch (e: Exception) {
Failure(e)
}
}
} | 0 | Kotlin | 1 | 0 | d4d4d898b334aa29a1943728673e5549ddc58766 | 1,800 | Digging | MIT License |
src/main/generated/io/guthix/oldscape/server/template/SpotAnimTemplates.kt | BarRescue | 305,352,660 | true | {"Kotlin": 5361134} | /*
* Copyright 2018-2020 Guthix
*
* 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.
*/
/* Dont EDIT! This file is automatically generated by io.guthix.oldscape.server.template.TemplateGenerator. */
@file:Suppress("PropertyName", "ObjectPropertyName")
package io.guthix.oldscape.server.template
object SpotAnimTemplates : TemplateLoader<SpotAnimTemplate>() {
val SPLASH_H123_85: PhysicalSpotAnimTemplate get() = PhysicalSpotAnimTemplate(get(85), 123)
val WIND_STRIKE_CAST_H92_90: PhysicalSpotAnimTemplate get() = PhysicalSpotAnimTemplate(get(90), 92)
val WIND_STRIKE_HIT_H124_92: PhysicalSpotAnimTemplate get() = PhysicalSpotAnimTemplate(get(92), 124)
}
| 0 | null | 0 | 0 | 1e5971d19c0bc6b986d48ea76f379b59f5e57b2e | 1,171 | OldScape-Server | Apache License 2.0 |
app/src/main/java/dev/thiaago/finn/core/ui/components/BottomSheetHeader.kt | thiaagodev | 683,539,394 | false | {"Kotlin": 81852} | package dev.thiaago.finn.core.ui.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun BottomSheetHeader(title: String, onClose: () -> Unit) {
Row(
Modifier
.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = title,
style = TextStyle(
fontSize = 24.sp,
fontWeight = FontWeight.Bold,
)
)
IconButton(
modifier = Modifier.size(32.dp),
onClick = onClose
) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Fechar Modal",
Modifier.size(32.dp)
)
}
}
}
@Preview(showBackground = true, showSystemUi = true)
@Composable
private fun BottomSheetHeaderPreview() {
BottomSheetHeader(
title = "Teste BottomSheet Header",
onClose = {
}
)
} | 0 | Kotlin | 0 | 2 | b5e8d1a6e75093867ad18ac5e0989a7d23e41871 | 1,730 | Finn | Creative Commons Attribution 4.0 International |
src/commonTest/kotlin/com.d10ng.common.test/CoordinateTest.kt | D10NGYANG | 675,554,851 | false | {"Kotlin": 515315, "Java": 173} | package com.d10ng.common.test
import com.d10ng.common.coordinate.*
import kotlin.math.absoluteValue
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class CoordinateTest {
@Test
fun testConvert() {
val doubleEqual:(Double, Double) -> Unit = { a, b -> assertTrue { (a - b).absoluteValue < 0.0000001 } }
val point = Coordinate(39.908720, 116.397500)
val wgs84ToWgs84 = point.convert(CoordinateSystemType.WGS84, CoordinateSystemType.WGS84)
doubleEqual(wgs84ToWgs84.lat, point.lat)
doubleEqual(wgs84ToWgs84.lng, point.lng)
val wgs84ToGcj02Base = Coordinate(39.91012350021168, 116.40374357520177)
val wgs84ToGcj02 = point.convert(CoordinateSystemType.WGS84, CoordinateSystemType.GCJ02)
doubleEqual(wgs84ToGcj02.lat, wgs84ToGcj02Base.lat)
doubleEqual(wgs84ToGcj02.lng, wgs84ToGcj02Base.lng)
val wgs84ToBd09Base = Coordinate(39.91646274462449, 116.41011657186905)
val wgs84ToBd09 = point.convert(CoordinateSystemType.WGS84, CoordinateSystemType.BD09)
doubleEqual(wgs84ToBd09.lat, wgs84ToBd09Base.lat)
doubleEqual(wgs84ToBd09.lng, wgs84ToBd09Base.lng)
val gcj02ToGcj02 = point.convert(CoordinateSystemType.GCJ02, CoordinateSystemType.GCJ02)
doubleEqual(gcj02ToGcj02.lat, point.lat)
doubleEqual(gcj02ToGcj02.lng, point.lng)
val gcj02ToWgs84Base = Coordinate(39.90731649978832, 116.39125642479821)
val gcj02ToWgs84 = point.convert(CoordinateSystemType.GCJ02, CoordinateSystemType.WGS84)
doubleEqual(gcj02ToWgs84.lat, gcj02ToWgs84Base.lat)
doubleEqual(gcj02ToWgs84.lng, gcj02ToWgs84Base.lng)
val gcj02ToBd09Base = Coordinate(39.91506334508605, 116.40387295666915)
val gcj02ToBd09 = point.convert(CoordinateSystemType.GCJ02, CoordinateSystemType.BD09)
doubleEqual(gcj02ToBd09.lat, gcj02ToBd09Base.lat)
doubleEqual(gcj02ToBd09.lng, gcj02ToBd09Base.lng)
val bd09ToBd09 = point.convert(CoordinateSystemType.BD09, CoordinateSystemType.BD09)
doubleEqual(bd09ToBd09.lat, point.lat)
doubleEqual(bd09ToBd09.lng, point.lng)
val bd09ToWgs84Base = Coordinate(39.90100884486498, 116.38486891344253)
val bd09ToWgs84 = point.convert(CoordinateSystemType.BD09, CoordinateSystemType.WGS84)
doubleEqual(bd09ToWgs84.lat, bd09ToWgs84Base.lat)
doubleEqual(bd09ToWgs84.lng, bd09ToWgs84Base.lng)
val bd09ToGcj02Base = Coordinate(39.902409805050404, 116.39110934566948)
val bd09ToGcj02 = point.convert(CoordinateSystemType.BD09, CoordinateSystemType.GCJ02)
doubleEqual(bd09ToGcj02.lat, bd09ToGcj02Base.lat)
doubleEqual(bd09ToGcj02.lng, bd09ToGcj02Base.lng)
}
@Test
fun testIsEastLongitude() {
assertEquals(0.0.isEastLongitude(), true)
assertEquals(180.0.isEastLongitude(), true)
assertEquals(360.0.isEastLongitude(), false)
assertEquals(90.0.isEastLongitude(), true)
assertEquals(270.0.isEastLongitude(), false)
assertEquals((-45.0).isEastLongitude(), false)
}
@Test
fun testIsNorthLatitude() {
assertEquals(0.0.isNorthLatitude(), true)
assertEquals(90.0.isNorthLatitude(), true)
assertEquals(180.0.isNorthLatitude(), false)
assertEquals(360.0.isNorthLatitude(), false)
assertEquals(270.0.isNorthLatitude(), false)
assertEquals((-45.0).isNorthLatitude(), false)
}
@Test
fun testToLongitudeNoPre() {
assertEquals(0.0.toLongitudeNoPre(), 0.0)
assertEquals(180.0.toLongitudeNoPre(), 180.0)
assertEquals(360.0.toLongitudeNoPre(), 0.0)
assertEquals(90.0.toLongitudeNoPre(), 90.0)
assertEquals(270.0.toLongitudeNoPre(), 90.0)
assertEquals((-45.0).toLongitudeNoPre(), 45.0)
}
@Test
fun testToLatitudeNoPre() {
assertEquals(0.0.toLatitudeNoPre(), 0.0)
assertEquals(180.0.toLatitudeNoPre(), 0.0)
assertEquals(135.0.toLatitudeNoPre(), 45.0)
assertEquals(90.0.toLatitudeNoPre(), 90.0)
assertEquals((-45.0).toLatitudeNoPre(), 45.0)
}
@Test
fun testToFullLongitude() {
assertEquals(0.0.toFullLongitude(true), 0.0)
assertEquals(180.0.toFullLongitude(true), 180.0)
assertEquals(113.1.toFullLongitude(true), 113.1)
assertEquals(113.1.toFullLongitude(false), 246.9)
assertEquals(113.1.toFullLongitude(false, isPositive = false), -113.1)
}
@Test
fun testToDMS() {
assertEquals(0.0.toDMS(true).toString(), "0°0′0.0″")
assertEquals(180.0.toDMS(true).toString(), "180°0′0.0″")
assertEquals(118.234123.toDMS(true).toString(), "118°14′2.84″")
assertEquals(45.234.toDMS(false).toString(), "45°14′2.4″")
}
@Test
fun testToLatLng() {
assertEquals(DMS(0, 0, 0.0f).toLatLng(), 0.0)
assertEquals(DMS(180, 0, 0.0f).toLatLng(), 180.0)
assertTrue { DMS(118, 14, 2.8428f).toLatLng() in 118.234122 .. 118.234124 }
assertTrue { DMS(45, 14, 2.4f).toLatLng() in 45.233999 .. 45.234001}
}
@Test
fun testToLatLngString() {
assertEquals(118.234123.toLatLngString(true), "东经E118°14′2.84″")
assertEquals(45.234.toLatLngString(false), "北纬N45°14′2.40″")
assertEquals(118.234123.toLatLngString(true, "d°m′S.ss″"), "118°14′2.84″")
assertEquals(45.234.toLatLngString(false, "d°m′S.ss″"), "45°14′2.40″")
assertEquals(118.234123.toLatLngString(true, "Fd°m′S.ss″"), "E118°14′2.84″")
assertEquals(45.234.toLatLngString(false, "Fd°m′S.ss″"), "N45°14′2.40″")
assertEquals(118.234123.toLatLngString(true, "CHd°m′S.ss″"), "东经118°14′2.84″")
assertEquals(45.234.toLatLngString(false, "CHd°m′S.ss″"), "北纬45°14′2.40″")
}
@Test
fun testToLongitudeString() {
assertEquals(118.234123.toLongitudeString(), "东经E118°14′2.84″")
}
@Test
fun testToLatitudeString() {
assertEquals(45.234.toLatitudeString(), "北纬N45°14′2.40″")
}
@Test
fun testToLatLngByString() {
assertEquals("东经E118°14′2.84″".toLatLng("CHFd°m′S.ss″"), 118.23412222222223)
assertEquals("北纬N45°14′2.40″".toLatLng("CHFd°m′S.ss″"), 45.234)
assertEquals("东经118°14′2.84″".toLatLng("CHd°m′S.ss″"), 118.23412222222223)
assertEquals("北纬45°14′2.40″".toLatLng("CHd°m′S.ss″"), 45.234)
}
@Test
fun testToLongitude() {
assertEquals("东经E118°14′2.84″".toLongitude("CHFd°m′S.ss″"), 118.23412222222223)
assertEquals("东经118°14′2.84″".toLongitude("CHd°m′S.ss″"), 118.23412222222223)
assertEquals("118°14′2.84″".toLongitude("d°m′S.ss″"), 118.23412222222223)
}
@Test
fun testToLatitude() {
assertEquals("北纬N45°14′2.40″".toLatitude("CHFd°m′S.ss″"), 45.234)
assertEquals("北纬45°14′2.40″".toLatitude("CHd°m′S.ss″"), 45.234)
assertEquals("45°14′2.40″".toLatitude("d°m′S.ss″"), 45.234)
}
@Test
fun testddmmpmmmm2LatLng() {
assertEquals(11301.8789.ddmmpmmmm2LatLng(), 113.03131499999999)
}
@Test
fun testlatLng2ddmmpmmmm() {
assertEquals(113.03131499999999.latLng2ddmmpmmmm(), 11301.8789)
}
} | 0 | Kotlin | 0 | 1 | c91abb67843c000b0634afc5a0ce53ffe449e6ee | 7,218 | DLCommonUtil | MIT License |
src/test/kotlin/no/nav/helsearbeidsgiver/bro/sykepenger/LagreKomplettForespoerselRiverTest.kt | navikt | 545,996,420 | false | {"Kotlin": 188375, "PLpgSQL": 153, "Dockerfile": 68} | package no.nav.helsearbeidsgiver.bro.sykepenger
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.equality.shouldBeEqualToIgnoringFields
import io.kotest.matchers.shouldBe
import io.mockk.clearAllMocks
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkStatic
import io.mockk.verify
import io.mockk.verifySequence
import kotlinx.serialization.builtins.MapSerializer
import no.nav.helse.rapids_rivers.testsupport.TestRapid
import no.nav.helsearbeidsgiver.bro.sykepenger.db.ForespoerselDao
import no.nav.helsearbeidsgiver.bro.sykepenger.domene.ForespoerselDto
import no.nav.helsearbeidsgiver.bro.sykepenger.domene.ForespoerselMottatt
import no.nav.helsearbeidsgiver.bro.sykepenger.domene.Orgnr
import no.nav.helsearbeidsgiver.bro.sykepenger.domene.Periode
import no.nav.helsearbeidsgiver.bro.sykepenger.domene.SpleisForespurtDataDto
import no.nav.helsearbeidsgiver.bro.sykepenger.kafkatopic.pri.PriProducer
import no.nav.helsearbeidsgiver.bro.sykepenger.kafkatopic.spleis.Spleis
import no.nav.helsearbeidsgiver.bro.sykepenger.testutils.mockForespoerselDto
import no.nav.helsearbeidsgiver.bro.sykepenger.testutils.sendJson
import no.nav.helsearbeidsgiver.bro.sykepenger.testutils.toKeyMap
import no.nav.helsearbeidsgiver.bro.sykepenger.utils.randomUuid
import no.nav.helsearbeidsgiver.utils.json.serializer.LocalDateSerializer
import no.nav.helsearbeidsgiver.utils.json.serializer.list
import no.nav.helsearbeidsgiver.utils.json.toJson
import no.nav.helsearbeidsgiver.utils.test.date.januar
import no.nav.helsearbeidsgiver.utils.test.date.mars
import java.time.LocalDate
class LagreKomplettForespoerselRiverTest : FunSpec({
val testRapid = TestRapid()
val mockForespoerselDao = mockk<ForespoerselDao>(relaxed = true)
val mockPriProducer = mockk<PriProducer>(relaxed = true)
LagreKomplettForespoerselRiver(
rapid = testRapid,
forespoerselDao = mockForespoerselDao,
priProducer = mockPriProducer,
)
fun mockInnkommendeMelding(
forespoersel: ForespoerselDto,
bestemmendeFravaersdager: Map<Orgnr, LocalDate> = emptyMap(),
) {
testRapid.sendJson(
Spleis.Key.TYPE to Spleis.Event.TRENGER_OPPLYSNINGER_FRA_ARBEIDSGIVER_KOMPLETT.toJson(Spleis.Event.serializer()),
Spleis.Key.ORGANISASJONSNUMMER to forespoersel.orgnr.toJson(Orgnr.serializer()),
Spleis.Key.FØDSELSNUMMER to forespoersel.fnr.toJson(),
Spleis.Key.VEDTAKSPERIODE_ID to forespoersel.vedtaksperiodeId.toJson(),
Spleis.Key.BESTEMMENDE_FRAVÆRSDAGER to
bestemmendeFravaersdager.toJson(
MapSerializer(
Orgnr.serializer(),
LocalDateSerializer,
),
),
Spleis.Key.SYKMELDINGSPERIODER to forespoersel.sykmeldingsperioder.toJson(Periode.serializer().list()),
Spleis.Key.EGENMELDINGSPERIODER to forespoersel.egenmeldingsperioder.toJson(Periode.serializer().list()),
Spleis.Key.FORESPURT_DATA to forespoersel.forespurtData.toJson(SpleisForespurtDataDto.serializer().list()),
)
}
beforeEach {
testRapid.reset()
clearAllMocks()
}
test("Forespørsel blir lagret og sender notifikasjon") {
val forespoersel = mockForespoerselDto()
every { mockForespoerselDao.hentAktivForespoerselForVedtaksperiodeId(forespoersel.vedtaksperiodeId) } returns null
mockkStatic(::randomUuid) {
every { randomUuid() } returns forespoersel.forespoerselId
mockInnkommendeMelding(forespoersel)
}
val expectedPublished =
ForespoerselMottatt(
forespoerselId = forespoersel.forespoerselId,
orgnr = forespoersel.orgnr,
fnr = forespoersel.fnr,
)
verifySequence {
mockForespoerselDao.hentAktivForespoerselForVedtaksperiodeId(forespoersel.vedtaksperiodeId)
mockForespoerselDao.lagre(
withArg {
it.shouldBeEqualToIgnoringFields(forespoersel, forespoersel::oppdatert, forespoersel::opprettet)
},
)
mockPriProducer.send(
*expectedPublished.toKeyMap().toList().toTypedArray(),
)
mockForespoerselDao.hentForespoerslerForVedtaksperiodeId(forespoersel.vedtaksperiodeId, any())
}
}
test("Oppdatert forespørsel (ubesvart) blir lagret uten notifikasjon") {
val forespoersel = mockForespoerselDto()
every {
mockForespoerselDao.hentAktivForespoerselForVedtaksperiodeId(forespoersel.vedtaksperiodeId)
} returns
forespoersel.copy(
egenmeldingsperioder =
listOf(
Periode(13.mars(1812), 14.mars(1812)),
),
)
mockkStatic(::randomUuid) {
every { randomUuid() } returns forespoersel.forespoerselId
mockInnkommendeMelding(forespoersel)
}
verifySequence {
mockForespoerselDao.hentAktivForespoerselForVedtaksperiodeId(forespoersel.vedtaksperiodeId)
mockForespoerselDao.lagre(
withArg {
it.shouldBeEqualToIgnoringFields(forespoersel, forespoersel::oppdatert, forespoersel::opprettet)
},
)
mockForespoerselDao.hentForespoerslerForVedtaksperiodeId(forespoersel.vedtaksperiodeId, any())
}
verify(exactly = 0) {
mockPriProducer.send(any())
}
}
test("Duplisert forespørsel blir hverken lagret eller sender notifikasjon") {
val forespoersel = mockForespoerselDto()
every {
mockForespoerselDao.hentAktivForespoerselForVedtaksperiodeId(forespoersel.vedtaksperiodeId)
} returns forespoersel
mockkStatic(::randomUuid) {
every { randomUuid() } returns forespoersel.forespoerselId
mockInnkommendeMelding(forespoersel)
}
verifySequence {
mockForespoerselDao.hentAktivForespoerselForVedtaksperiodeId(forespoersel.vedtaksperiodeId)
mockForespoerselDao.hentForespoerslerForVedtaksperiodeId(forespoersel.vedtaksperiodeId, any())
}
verify(exactly = 0) {
mockForespoerselDao.lagre(any())
mockPriProducer.send(any())
}
}
test("Skjæringstidspunkt blir satt til minste bestemmende fraværsdag blant andre arbeidsgivere.") {
val forespoersel = mockForespoerselDto()
every { mockForespoerselDao.hentAktivForespoerselForVedtaksperiodeId(forespoersel.vedtaksperiodeId) } returns null
mockkStatic(::randomUuid) {
every { randomUuid() } returns forespoersel.forespoerselId
mockInnkommendeMelding(
forespoersel,
mapOf(
forespoersel.orgnr to 15.januar,
"234234234".let(::Orgnr) to 17.januar,
"678678678".let(::Orgnr) to 19.januar,
),
)
}
verifySequence {
mockForespoerselDao.hentAktivForespoerselForVedtaksperiodeId(forespoersel.vedtaksperiodeId)
mockForespoerselDao.lagre(
withArg {
it.shouldBeEqualToIgnoringFields(
forespoersel,
forespoersel::skjaeringstidspunkt,
forespoersel::oppdatert,
forespoersel::opprettet,
)
it.skjaeringstidspunkt shouldBe 17.januar
},
)
mockForespoerselDao.hentForespoerslerForVedtaksperiodeId(forespoersel.vedtaksperiodeId, any())
}
}
})
| 0 | Kotlin | 0 | 0 | ff796561e7cb382c50e4faabf60d978fbe4b11cf | 7,840 | helsearbeidsgiver-bro-sykepenger | MIT License |
apiTester/src/commonMain/kotlin/com/revenuecat/purchases/kmp/apitester/BillingFeatureAPI.kt | RevenueCat | 758,647,648 | false | {"Kotlin": 391318, "Ruby": 17650, "Swift": 594} | package com.revenuecat.purchases.kmp.apitester
import com.revenuecat.purchases.kmp.models.BillingFeature
@Suppress("unused")
private class BillingFeatureAPI {
fun check(billingFeature: BillingFeature) {
when (billingFeature) {
BillingFeature.PRICE_CHANGE_CONFIRMATION,
BillingFeature.SUBSCRIPTIONS,
BillingFeature.SUBSCRIPTIONS_UPDATE,
-> {
}
}.exhaustive
}
}
| 6 | Kotlin | 3 | 88 | af9d4f70c0af9a7a346f56dcf34d1ca621c41297 | 446 | purchases-kmp | MIT License |
ese-core/src/jvmMain/kotlin/me/naotiki/ese/core/vfs/PlatformCommands.kt | naotiki | 585,808,592 | false | null | package me.naotiki.ese.core.vfs
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import me.naotiki.ese.core.EseSystem
import me.naotiki.ese.core.EseSystem.IO
import me.naotiki.ese.core.appName
import me.naotiki.ese.core.commands.parser.ArgType
import me.naotiki.ese.core.commands.parser.Executable
import me.naotiki.ese.core.secure.PluginLoader
import me.naotiki.ese.core.user.User
import me.naotiki.ese.core.utils.normalizeYesNoAnswer
import java.io.File
import java.util.jar.JarFile
actual val platformCommands: List<Executable<*>> =
listOf(Udon())
actual val platformDevCommands: List<Executable<*>> =
listOf(Status())
class Status : Executable<Unit>(
"stat", """
Print JRE Status
開発用 / For development
""".trimIndent()
) {
override suspend fun execute(user: User, rawArgs: List<String>) {
out.println(
"""
$appName MemoryInfo
Free : ${"%,6d MB".format((Runtime.getRuntime().freeMemory() / (1024 * 1024)))}
Total: ${"%,6d MB".format((Runtime.getRuntime().totalMemory() / (1024 * 1024)))}
Max : ${"%,6d MB".format((Runtime.getRuntime().maxMemory() / (1024 * 1024)))}
""".trimIndent()
)
}
}
//Pluginsフォルダなど
val dataDir = File(System.getProperty("compose.application.resources.dir") ?: "client-gui/resources/common/")
class Udon : Executable<Unit>("udon", "UDON is a Downloader Of Noodles") {
var agree = false
override val subCommands: List<SubCommand<*>>
= listOf(Install(),LocalInstall())
//さぶこまんど
inner class Install : SubCommand<Unit>("world", "世界中からインストールします。") {
val pkgName by argument(ArgType.String, "packageName", "パッケージ名")
override suspend fun execute(user: User, rawArgs: List<String>) {
out.println("[DEMO]Installing $pkgName ")
}
}
inner class LocalInstall : SubCommand<Unit>("local", "ローカルファイルからインストールします。") {
val pkgName by argument(ArgType.String, "packageName", "パッケージ名")
override suspend fun execute(user: User, rawArgs: List<String>) {
val pluginDir = File(dataDir, "plugins")
if (!pluginDir.exists()) {
out.println("pluginフォルダーが見つかりませんでした。\n${pluginDir.absolutePath}に作成してください。")
}
val file = pluginDir.listFiles { dir, name -> name.endsWith(".$fileExtension") }.orEmpty().singleOrNull {
it.nameWithoutExtension == pkgName
} ?: return
val jarFile = withContext(Dispatchers.IO) {
JarFile(file)
}
val targetClassName = jarFile.manifest.mainAttributes.getValue("Plugin-Class")
var ans: Boolean?
do {
ans = normalizeYesNoAnswer(
IO.newPrompt(client, "プラグイン ${file.nameWithoutExtension} を本当にインストールしますか?(yes/no)")
)
} while (ans == null)
if (ans != true) {
return
}
val plugin = PluginLoader.loadPluginFromFile(file)
plugin?.init(user)
}
}
override suspend fun execute(user: User, rawArgs: List<String>) {
out.println(
"""
Udon は $appName のプラグインマネージャーです。
""".trimIndent()
)
}
companion object {
const val fileExtension = "ndl"
}
}
| 0 | Kotlin | 0 | 4 | c785de56fcf948a428c9d97a12d312af1beac9d7 | 3,364 | Ese | MIT License |
ese-core/src/jvmMain/kotlin/me/naotiki/ese/core/vfs/PlatformCommands.kt | naotiki | 585,808,592 | false | null | package me.naotiki.ese.core.vfs
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import me.naotiki.ese.core.EseSystem
import me.naotiki.ese.core.EseSystem.IO
import me.naotiki.ese.core.appName
import me.naotiki.ese.core.commands.parser.ArgType
import me.naotiki.ese.core.commands.parser.Executable
import me.naotiki.ese.core.secure.PluginLoader
import me.naotiki.ese.core.user.User
import me.naotiki.ese.core.utils.normalizeYesNoAnswer
import java.io.File
import java.util.jar.JarFile
actual val platformCommands: List<Executable<*>> =
listOf(Udon())
actual val platformDevCommands: List<Executable<*>> =
listOf(Status())
class Status : Executable<Unit>(
"stat", """
Print JRE Status
開発用 / For development
""".trimIndent()
) {
override suspend fun execute(user: User, rawArgs: List<String>) {
out.println(
"""
$appName MemoryInfo
Free : ${"%,6d MB".format((Runtime.getRuntime().freeMemory() / (1024 * 1024)))}
Total: ${"%,6d MB".format((Runtime.getRuntime().totalMemory() / (1024 * 1024)))}
Max : ${"%,6d MB".format((Runtime.getRuntime().maxMemory() / (1024 * 1024)))}
""".trimIndent()
)
}
}
//Pluginsフォルダなど
val dataDir = File(System.getProperty("compose.application.resources.dir") ?: "client-gui/resources/common/")
class Udon : Executable<Unit>("udon", "UDON is a Downloader Of Noodles") {
var agree = false
override val subCommands: List<SubCommand<*>>
= listOf(Install(),LocalInstall())
//さぶこまんど
inner class Install : SubCommand<Unit>("world", "世界中からインストールします。") {
val pkgName by argument(ArgType.String, "packageName", "パッケージ名")
override suspend fun execute(user: User, rawArgs: List<String>) {
out.println("[DEMO]Installing $pkgName ")
}
}
inner class LocalInstall : SubCommand<Unit>("local", "ローカルファイルからインストールします。") {
val pkgName by argument(ArgType.String, "packageName", "パッケージ名")
override suspend fun execute(user: User, rawArgs: List<String>) {
val pluginDir = File(dataDir, "plugins")
if (!pluginDir.exists()) {
out.println("pluginフォルダーが見つかりませんでした。\n${pluginDir.absolutePath}に作成してください。")
}
val file = pluginDir.listFiles { dir, name -> name.endsWith(".$fileExtension") }.orEmpty().singleOrNull {
it.nameWithoutExtension == pkgName
} ?: return
val jarFile = withContext(Dispatchers.IO) {
JarFile(file)
}
val targetClassName = jarFile.manifest.mainAttributes.getValue("Plugin-Class")
var ans: Boolean?
do {
ans = normalizeYesNoAnswer(
IO.newPrompt(client, "プラグイン ${file.nameWithoutExtension} を本当にインストールしますか?(yes/no)")
)
} while (ans == null)
if (ans != true) {
return
}
val plugin = PluginLoader.loadPluginFromFile(file)
plugin?.init(user)
}
}
override suspend fun execute(user: User, rawArgs: List<String>) {
out.println(
"""
Udon は $appName のプラグインマネージャーです。
""".trimIndent()
)
}
companion object {
const val fileExtension = "ndl"
}
}
| 0 | Kotlin | 0 | 4 | c785de56fcf948a428c9d97a12d312af1beac9d7 | 3,364 | Ese | MIT License |
src/main/kotlin/org/unbrokendome/gradle/plugins/testsets/internal/TestTaskSystemPropertiesObserver.kt | unbroken-dome | 31,334,105 | false | null | package org.unbrokendome.gradle.plugins.testsets.internal
import org.gradle.api.tasks.TaskContainer
import org.gradle.api.tasks.testing.Test
import org.unbrokendome.gradle.plugins.testsets.dsl.TestSet
import org.unbrokendome.gradle.plugins.testsets.dsl.TestSetBase
import org.unbrokendome.gradle.plugins.testsets.dsl.TestSetObserver
internal class TestTaskSystemPropertiesObserver(
private val tasks: TaskContainer
) : TestSetObserver {
override fun systemPropertiesChanged(testSet: TestSetBase, newProperties: Map<String, Any?>) {
val testTaskName = (testSet as TestSet).testTaskName
(tasks.findByName(testTaskName) as? Test?)?.let { task ->
task.systemProperties = newProperties
}
}
}
| 18 | Kotlin | 49 | 227 | 228a44b73ac1ffd8def2411ee2526902fe712fe0 | 739 | gradle-testsets-plugin | MIT License |
fundamentals/android/auth-email-password/Notes/app/src/main/java/com/notes/app/NotesApp.kt | FirebaseExtended | 467,490,083 | false | {"Swift": 584690, "Kotlin": 163332, "JavaScript": 48493, "CSS": 41317, "Vue": 5664, "HTML": 3230} | package com.notes.app
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.navigation.compose.NavHost
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.notes.app.screens.account_center.AccountCenterScreen
import com.notes.app.screens.note.NoteScreen
import com.notes.app.screens.notes_list.NotesListScreen
import com.notes.app.screens.sign_in.SignInScreen
import com.notes.app.screens.sign_up.SignUpScreen
import com.notes.app.screens.splash.SplashScreen
import com.notes.app.ui.theme.NotesTheme
@Composable
@OptIn(ExperimentalMaterial3Api::class)
fun NotesApp() {
NotesTheme {
Surface(color = MaterialTheme.colorScheme.background) {
val appState = rememberAppState()
Scaffold { innerPaddingModifier ->
NavHost(
navController = appState.navController,
startDestination = SPLASH_SCREEN,
modifier = Modifier.padding(innerPaddingModifier)
) {
notesGraph(appState)
}
}
}
}
}
@Composable
fun rememberAppState(navController: NavHostController = rememberNavController()) =
remember(navController) {
NotesAppState(navController)
}
fun NavGraphBuilder.notesGraph(appState: NotesAppState) {
composable(NOTES_LIST_SCREEN) {
NotesListScreen(
restartApp = { route -> appState.clearAndNavigate(route) },
openScreen = { route -> appState.navigate(route) }
)
}
composable(
route = "$NOTE_SCREEN$NOTE_ID_ARG",
arguments = listOf(navArgument(NOTE_ID) { defaultValue = NOTE_DEFAULT_ID })
) {
NoteScreen(
noteId = it.arguments?.getString(NOTE_ID) ?: NOTE_DEFAULT_ID,
popUpScreen = { appState.popUp() },
restartApp = { route -> appState.clearAndNavigate(route) }
)
}
composable(SIGN_IN_SCREEN) {
SignInScreen(openAndPopUp = { route, popUp -> appState.navigateAndPopUp(route, popUp) })
}
composable(SIGN_UP_SCREEN) {
SignUpScreen(openAndPopUp = { route, popUp -> appState.navigateAndPopUp(route, popUp) })
}
composable(SPLASH_SCREEN) {
SplashScreen(openAndPopUp = { route, popUp -> appState.navigateAndPopUp(route, popUp) })
}
composable(ACCOUNT_CENTER_SCREEN) {
AccountCenterScreen(restartApp = { route -> appState.clearAndNavigate(route) })
}
}
| 23 | Swift | 114 | 98 | 8e0e8bc0d62924c8f9176a7036f58d92572f6f54 | 2,951 | firebase-video-samples | Apache License 2.0 |
app/src/main/kotlin/com/ivanovsky/passnotes/data/entity/TestAutofillData.kt | aivanovski | 95,774,290 | false | {"Kotlin": 1570745, "Java": 110321, "Ruby": 2731} | package com.ivanovsky.passnotes.data.entity
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class TestAutofillData(
val filenamePatterns: List<String>,
val passwords: List<String>,
val webdavUrl: String,
val webdavUsername: String,
val webdavPassword: String,
val gitUrl: String,
val fakeFsUrl: String,
val fakeFsUsername: String,
val fakeFsPassword: String
) : Parcelable | 6 | Kotlin | 4 | 53 | 83605c13c7f13e1f484aa00f6b3e9af622880888 | 442 | keepassvault | Apache License 2.0 |
swr/src/main/java/com/kazakago/swr/compose/internal/NetworkCallbackManager.kt | KazaKago | 566,693,483 | false | {"Kotlin": 276405} | package com.kazakago.swr.compose.internal
import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
internal class NetworkCallbackManager private constructor(
private val context: Context,
) {
companion object {
@SuppressLint("StaticFieldLeak")
private var instance: NetworkCallbackManager? = null
fun getInstance(context: Context): NetworkCallbackManager {
var instance = instance
return if (instance != null && instance.context == context.applicationContext) {
instance
} else {
instance = NetworkCallbackManager(context.applicationContext)
this.instance = instance
instance
}
}
}
private var isFirstTime = true
private val _onAvailable = MutableSharedFlow<Network>(extraBufferCapacity = 1)
val onAvailable = _onAvailable.asSharedFlow()
init {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val request = NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
.build()
val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
if (isFirstTime) {
isFirstTime = false
return
}
_onAvailable.tryEmit(network)
}
}
connectivityManager.registerNetworkCallback(request, networkCallback)
}
}
| 4 | Kotlin | 0 | 37 | 4bf1f41816c02c59524dc741f0bdfd9d1b195756 | 1,905 | swr-compose | Apache License 2.0 |
src/test/kotlin/io/github/cdimascio/essence/StopWordsSpec.kt | cdimascio | 158,731,101 | false | null | package io.github.cdimascio.essence
import io.github.cdimascio.essence.words.StopWords
import org.junit.Test
import kotlin.test.assertEquals
class StopWordsSpec {
@Test
fun countStopwords() {
val stopwords = StopWords.load(Language.en)
val stats = stopwords.statistics("this is silly")
assertEquals(3, stats.wordCount)
assertEquals(2, stats.stopWords.size)
stats.stopWords.containsAll(listOf("this", "is"))
}
@Test
fun stripsPunctuation() {
val stopwords = StopWords.load(Language.en)
val stats = stopwords.statistics("this! is?? silly....")
assertEquals(3, stats.wordCount)
assertEquals(2, stats.stopWords.size)
stats.stopWords.containsAll(listOf("this", "is"))
}
@Test
fun defaultsToEnglish() {
val stopwords = StopWords.load(Language.en)
val stats = stopwords.statistics("this is fun")
assertEquals(3, stats.wordCount)
assertEquals(2, stats.stopWords.size)
stats.stopWords.containsAll(listOf("this", "is"))
}
@Test
fun handlesSpanish() {
val stopwords = StopWords.load(Language.es)
val stats = stopwords.statistics("este es rico")
assertEquals(3, stats.wordCount)
assertEquals(2, stats.stopWords.size)
stats.stopWords.containsAll(listOf("este", "es"))
}
}
| 6 | null | 14 | 96 | ebe2a0cb889db9cd2e324579432a856453f7bbb6 | 1,374 | essence | Apache License 2.0 |
app/shared/sqldelight/impl/src/iosMain/kotlin/build/wallet/sqldelight/DatabaseIntegrityCheckerImpl.kt | proto-at-block | 761,306,853 | false | {"C": 10474259, "Kotlin": 8243078, "Rust": 2779264, "Swift": 893661, "HCL": 349246, "Python": 338898, "Shell": 136508, "TypeScript": 118945, "C++": 69203, "Meson": 64811, "JavaScript": 36398, "Just": 32977, "Ruby": 13559, "Dockerfile": 5934, "Makefile": 3915, "Open Policy Agent": 1552, "Procfile": 80} | package build.wallet.sqldelight
import build.wallet.logging.LogLevel
import build.wallet.logging.log
import build.wallet.platform.data.FileDirectoryProvider
import platform.Foundation.NSFileManager
actual class DatabaseIntegrityCheckerImpl actual constructor(
private val fileDirectoryProvider: FileDirectoryProvider,
) : DatabaseIntegrityChecker {
override suspend fun purgeDatabaseStateIfInvalid(databaseEncryptionKey: String?): Boolean {
val dbDirectory = fileDirectoryProvider.databasesDir()
val nsFileManager = NSFileManager.defaultManager()
if (nsFileManager.fileExistsAtPath(dbDirectory) && databaseEncryptionKey == null) {
// If the database key is null AND the .db file has already been created, purge the database since
// we have no way to decrypt it. This can happen if the .db file was backed up to e.g. iCloud
// and then restored to another device, which would not have the encryption key.
val success = nsFileManager.removeItemAtPath(path = dbDirectory, error = null)
if (!success) {
log(LogLevel.Error) { "DatabaseIntegrityChecker failed to remove database directory." }
}
return false
}
return true
}
}
| 3 | C | 16 | 113 | 694c152387c1fdb2b6be01ba35e0a9c092a81879 | 1,203 | bitkey | MIT License |
app/src/main/java/com/example/newsapp/db/ArticleDAO.kt | fahaddhabib | 737,397,532 | false | {"Kotlin": 33526} | package com.example.newsapp.db
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.example.newsapp.models.Article
import retrofit2.http.DELETE
@Dao
interface ArticleDAO {
@Insert(
onConflict = OnConflictStrategy.REPLACE)
suspend fun upsert(article: Article): Long
@Query("SELECT * FROM articles")
fun getAllArticles(): LiveData<List<Article>>
@Delete
suspend fun deleteArticle(article: Article)
}
| 0 | Kotlin | 2 | 3 | a34239271735080f38cbc4b2a19c741707e58ea6 | 575 | news-app | MIT License |
app/src/main/java/com/privategallery/akscorp/privategalleryandroid/Widgets/AnimatingProgressBar.kt | vovaksenov99 | 127,191,777 | false | {"Gradle": 3, "CODEOWNERS": 1, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "JSON": 1, "Kotlin": 47, "XML": 78, "Java": 4} | package com.privategallery.akscorp.privategalleryandroid.Widgets
import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.ProgressBar
class AnimatingProgressBar : ProgressBar {
private var animator: ValueAnimator? = null
private var animatorSecondary: ValueAnimator? = null
var isAnimate = true
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(
context,
attrs,
defStyle
) {
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}
constructor(context: Context) : super(context) {}
@Synchronized
override fun setProgress(progress: Int) {
if (!isAnimate) {
super.setProgress(progress)
return
}
if (animator != null)
animator!!.cancel()
if (animator == null) {
animator = ValueAnimator.ofInt(getProgress(), progress)
animator!!.interpolator = DEFAULT_INTERPOLATER
animator!!.addUpdateListener { animation ->
[email protected](
animation.animatedValue as Int
)
}
} else
animator!!.setIntValues(getProgress(), progress)
animator!!.start()
}
@Synchronized
override fun setSecondaryProgress(secondaryProgress: Int) {
if (!isAnimate) {
super.setSecondaryProgress(secondaryProgress)
return
}
if (animatorSecondary != null)
animatorSecondary!!.cancel()
if (animatorSecondary == null) {
animatorSecondary = ValueAnimator.ofInt(progress, secondaryProgress)
animatorSecondary!!.interpolator = DEFAULT_INTERPOLATER
animatorSecondary!!.addUpdateListener { animation ->
[email protected](
animation.animatedValue as Int
)
}
} else
animatorSecondary!!.setIntValues(progress, secondaryProgress)
animatorSecondary!!.start()
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
if (animator != null)
animator!!.cancel()
if (animatorSecondary != null)
animatorSecondary!!.cancel()
}
companion object {
private val DEFAULT_INTERPOLATER = AccelerateDecelerateInterpolator()
}
}
| 0 | Kotlin | 0 | 0 | b2a45191158984359e570e0f474b9ca55b2ff2fd | 2,578 | Private.Gallery.Android | Apache License 2.0 |
app/src/main/java/com/privategallery/akscorp/privategalleryandroid/Widgets/AnimatingProgressBar.kt | vovaksenov99 | 127,191,777 | false | {"Gradle": 3, "CODEOWNERS": 1, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "JSON": 1, "Kotlin": 47, "XML": 78, "Java": 4} | package com.privategallery.akscorp.privategalleryandroid.Widgets
import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.ProgressBar
class AnimatingProgressBar : ProgressBar {
private var animator: ValueAnimator? = null
private var animatorSecondary: ValueAnimator? = null
var isAnimate = true
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(
context,
attrs,
defStyle
) {
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}
constructor(context: Context) : super(context) {}
@Synchronized
override fun setProgress(progress: Int) {
if (!isAnimate) {
super.setProgress(progress)
return
}
if (animator != null)
animator!!.cancel()
if (animator == null) {
animator = ValueAnimator.ofInt(getProgress(), progress)
animator!!.interpolator = DEFAULT_INTERPOLATER
animator!!.addUpdateListener { animation ->
[email protected](
animation.animatedValue as Int
)
}
} else
animator!!.setIntValues(getProgress(), progress)
animator!!.start()
}
@Synchronized
override fun setSecondaryProgress(secondaryProgress: Int) {
if (!isAnimate) {
super.setSecondaryProgress(secondaryProgress)
return
}
if (animatorSecondary != null)
animatorSecondary!!.cancel()
if (animatorSecondary == null) {
animatorSecondary = ValueAnimator.ofInt(progress, secondaryProgress)
animatorSecondary!!.interpolator = DEFAULT_INTERPOLATER
animatorSecondary!!.addUpdateListener { animation ->
[email protected](
animation.animatedValue as Int
)
}
} else
animatorSecondary!!.setIntValues(progress, secondaryProgress)
animatorSecondary!!.start()
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
if (animator != null)
animator!!.cancel()
if (animatorSecondary != null)
animatorSecondary!!.cancel()
}
companion object {
private val DEFAULT_INTERPOLATER = AccelerateDecelerateInterpolator()
}
}
| 0 | Kotlin | 0 | 0 | b2a45191158984359e570e0f474b9ca55b2ff2fd | 2,578 | Private.Gallery.Android | Apache License 2.0 |
server/src/main/kotlin/fi/vauhtijuoksu/vauhtijuoksuapi/server/impl/timers/TimerRouter.kt | Vauhtijuoksu | 394,707,727 | false | null | package fi.vauhtijuoksu.vauhtijuoksuapi.server.impl.timers
import fi.vauhtijuoksu.vauhtijuoksuapi.server.impl.base.BaseRouter
import jakarta.inject.Inject
class TimerRouter
@Inject
constructor(
getRouter: TimerGetRouter,
postRouter: TimerPostRouter,
patchRouter: TimerPatchRouter,
deleteRouter: TimerDeleteRouter,
) : BaseRouter(
"/timers",
listOf(
getRouter,
postRouter,
patchRouter,
deleteRouter,
),
)
| 5 | null | 0 | 3 | eecb46dfb04de9e590f507bc2fcf07b83c324325 | 466 | vauhtijuoksu-api | MIT License |
sykepenger-model/src/main/kotlin/no/nav/helse/person/inntekt/Infotrygd.kt | navikt | 193,907,367 | false | {"Kotlin": 6612297, "PLpgSQL": 2738, "Dockerfile": 168} | package no.nav.helse.person.inntekt
import java.time.LocalDate
import java.time.LocalDateTime
import java.util.UUID
import no.nav.helse.dto.InntektsopplysningDto
import no.nav.helse.økonomi.Inntekt
internal class Infotrygd(
id: UUID,
dato: LocalDate,
hendelseId: UUID,
beløp: Inntekt,
tidsstempel: LocalDateTime
) : Inntektsopplysning(id, hendelseId, dato, beløp, tidsstempel) {
override fun accept(visitor: InntektsopplysningVisitor) {
visitor.visitInfotrygd(this, id, dato, hendelseId, beløp, tidsstempel)
}
override fun kanOverstyresAv(ny: Inntektsopplysning) = false
override fun blirOverstyrtAv(ny: Inntektsopplysning): Inntektsopplysning {
throw IllegalStateException("Infotrygd kan ikke bli overstyrt")
}
override fun erSamme(other: Inntektsopplysning): Boolean {
if (other !is Infotrygd) return false
return this.dato == other.dato && this.beløp == other.beløp
}
override fun dto() =
InntektsopplysningDto.InfotrygdDto(id, hendelseId, dato, beløp.dtoMånedligDouble(), tidsstempel)
internal companion object {
fun gjenopprett(dto: InntektsopplysningDto.InfotrygdDto) =
Infotrygd(
id = dto.id,
hendelseId = dto.hendelseId,
dato = dto.dato,
beløp = Inntekt.gjenopprett(dto.beløp),
tidsstempel = dto.tidsstempel
)
}
} | 2 | Kotlin | 6 | 3 | 6ac7b807befc905f9cc00dd1d6ad5b0f8bc079ed | 1,439 | helse-spleis | MIT License |
shared/src/commonMain/kotlin/com/hoppers/birdsafari/network/KtorClient.kt | jk2pr | 701,754,785 | false | {"Kotlin": 12183, "Swift": 3634} | package com.hoppers.birdsafari.network
import io.github.aakira.napier.Napier
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.logging.LogLevel
import io.ktor.client.plugins.logging.Logger
import io.ktor.client.plugins.logging.Logging
import io.ktor.client.plugins.observer.ResponseObserver
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.json.Json
object KtorClient {
fun getKtorClient(): HttpClient = HttpClient {
install(ContentNegotiation) {
json(Json {
prettyPrint = true
isLenient = true
})
}
install(Logging) {
logger = object : Logger {
override fun log(message: String) {
println("Message $message")
// Napier.d("Logger Ktor =>, $message", tag = "KTOR")
}
}
level = LogLevel.ALL
}
install(ResponseObserver) {
onResponse { response ->
Napier.d(message = "HTTP status:, $response", tag = "KTOR")
}
}
}
} | 1 | Kotlin | 0 | 0 | cee29c314b22b584f78d6704e20122cec98fe805 | 1,214 | BirdSafari | MIT License |
blog/api/model/src/main/kotlin/com/excref/kotblog/blog/api/model/common/ResultResponse.kt | excref | 93,243,887 | false | null | package com.excref.kotblog.blog.api.model.common
import com.fasterxml.jackson.annotation.JsonProperty
/**
* @author <NAME>
* @since 6/15/17 12:04 AM
*/
data class ResultResponse<out T : ResponseModel>(
@JsonProperty("response")
val response: T? = null,
@JsonProperty("success")
val success: Boolean = true,
@JsonProperty("errors")
val errors: Set<ErrorResponseModel> = setOf()
) {
fun hasErrors(): Boolean = !errors.isEmpty()
} | 16 | Kotlin | 4 | 5 | 50bc2bd840b1074eb50e9c0d0e87aac6060c7fce | 484 | kotblog | Apache License 2.0 |
app/src/main/java/vn/nms/sample/data/extensions/ViewExtensions.kt | minhnn2607 | 417,355,816 | false | {"Kotlin": 220688, "Java": 5735} | package vn.nms.sample.data.extensions
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.PointF
import android.graphics.drawable.ColorDrawable
import android.view.View
import android.view.ViewTreeObserver
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jakewharton.rxbinding4.widget.textChangeEvents
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import vn.nms.sample.R
import java.util.concurrent.TimeUnit
fun Context.showDialog(
title: String? = null,
message: String,
isCancelable: Boolean = true,
positiveText: String? = getString(R.string.ok),
onClickPositive: (() -> Unit)? = null,
negativeText: String? = getString(R.string.cancel),
onClickNegative: (() -> Unit)? = null
) {
val builder = AlertDialog.Builder(this).apply {
if (!title.isNullOrEmpty()) {
setTitle(title)
}
setMessage(message)
if (positiveText != null) {
setPositiveButton(positiveText) { _, _ -> onClickPositive?.invoke() }
}
if (negativeText != null) {
setNegativeButton(negativeText) { _, _ -> onClickNegative?.invoke() }
}
}
builder.setCancelable(isCancelable)
val dialog: AlertDialog = builder.create()
dialog.show()
// val buttonNegative: Button = dialog.getButton(DialogInterface.BUTTON_NEGATIVE)
// buttonNegative.setTextColor(ContextCompat.getColor(this, R.color.colorGrayHard))
}
fun Context.showToast(message: String?) {
if (!message.isNullOrEmpty()) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
}
fun Context.showToast(messageIds: Int?) {
if (messageIds != null) {
Toast.makeText(this, getString(messageIds), Toast.LENGTH_SHORT).show()
}
}
fun Activity.hideKeyboard() {
if (currentFocus == null) View(this) else currentFocus?.let { hideKeyboard(it) }
}
fun Context.hideKeyboard(view: View) {
val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}
fun EditText.hideKeyboard() {
val inputMethodManager =
context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}
fun Activity.createLoadingDialog(): Dialog {
val progressDialog = Dialog(this)
progressDialog.let {
it.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
it.setContentView(R.layout.dialog_progress)
it.setCancelable(false)
it.setCanceledOnTouchOutside(false)
return it
}
}
fun EditText.textChanges(timeout: Long = 500, onTextChangeListener: (String) -> Unit) {
this.textChangeEvents().debounce(timeout, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
.subscribe { charSequence -> onTextChangeListener.invoke(charSequence.text.toString()) }
}
fun View.afterLayout(what: () -> Unit) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
viewTreeObserver.removeOnGlobalLayoutListener(this)
what.invoke()
}
})
}
fun EditText.focus() {
requestFocus()
setSelection(length())
}
fun RecyclerView.addScrollListener(
onLoadMore: () -> Unit,
onIdle: ((isIdle: Boolean) -> Unit)? = null
) {
val layoutManager = layoutManager as LinearLayoutManager
addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val totalItemCount = layoutManager.itemCount
val lastVisibleItem = layoutManager.findLastVisibleItemPosition()
if (totalItemCount <= (lastVisibleItem + 5)) {
onLoadMore.invoke()
}
}
override fun onScrollStateChanged(
recyclerView: RecyclerView,
newState: Int
) {
if (newState != RecyclerView.SCROLL_STATE_IDLE) {
onIdle?.invoke(false)
} else {
onIdle?.invoke(true)
}
}
})
}
fun View.getLocationOnScreen(): PointF {
val location = IntArray(2)
this.getLocationOnScreen(location)
return PointF(location[0].toFloat(), location[1].toFloat())
}
fun View.getParentWithTag(tag: String): View? {
val parent = this.parent
return if (parent is View) {
if (parent.tag == tag) parent
else parent.getParentWithTag(tag)
} else {
null
}
}
| 0 | Kotlin | 0 | 3 | 59d92211b072e1fbafe3a904883b343554127713 | 5,009 | SampleDataList | Apache License 2.0 |
src/main/kotlin/ph/mcmod/csd/rei/SingleCatagory.kt | Phoupraw | 523,310,408 | false | null | package ph.mcmod.csd.rei
import com.google.common.collect.Lists
import com.simibubi.create.AllBlocks
import com.simibubi.create.compat.rei.DoubleItemIcon
import me.shedaniel.math.Point
import me.shedaniel.math.Rectangle
import me.shedaniel.rei.api.client.gui.Renderer
import me.shedaniel.rei.api.client.gui.widgets.Widget
import me.shedaniel.rei.api.client.gui.widgets.Widgets
import me.shedaniel.rei.api.client.registry.display.DisplayCategory
import me.shedaniel.rei.api.common.category.CategoryIdentifier
import me.shedaniel.rei.api.common.util.EntryStacks
import net.minecraft.fluid.Fluids
import net.minecraft.item.Items
import net.minecraft.text.Text
import net.minecraft.text.TranslatableText
import ph.mcmod.csd.MyRegistries
import java.text.DecimalFormat
abstract class SingleCatagory<T : SingleDisplay> : DisplayCategory<T> {
override fun setupDisplay(display: T, bounds: Rectangle): MutableList<Widget> {
val startPoint = Point(bounds.x + 7, bounds.y + 9)
val duration: Double = display.duration
val df = DecimalFormat("###.##")
val widgets: MutableList<Widget> = Lists.newArrayList()
widgets.add(Widgets.createRecipeBase(bounds))
widgets.add(Widgets.createResultSlotBackground(Point(startPoint.x + 61, startPoint.y + 0)))
widgets.add(Widgets.createLabel(Point(bounds.x + bounds.width - 5, bounds.y + 5), TranslatableText("category.rei.campfire.time", df.format(duration / 20.0)))
.noShadow()
.rightAligned()
.color(-0xbfbfc0, -0x444445))
widgets.add(Widgets.createArrow(Point(startPoint.x + 24, startPoint.y + 0))
.animationDurationTicks(duration))
widgets.add(Widgets.createSlot(Point(startPoint.x + 61, startPoint.y + 0))
.entries(display.outputEntries[0])
.disableBackground()
.markOutput())
widgets.add(Widgets.createSlot(Point(startPoint.x + 1, startPoint.y + 0))
.entries(display.inputEntries[0])
.markInput())
return widgets
}
override fun getDisplayHeight(): Int {
return 34
}
override fun getDisplayWidth(display: T): Int {
return 130
}
} | 1 | Kotlin | 2 | 4 | 3d6870faea3f44d97523431fc6b7ee0b371c67fb | 2,189 | CreateSDelight | The Unlicense |
data-android/model/src/main/java/dev/shuanghua/weather/data/android/model/params/ShenZhenParams.kt | shuanghua | 479,336,029 | false | {"Kotlin": 303212} | package dev.shuanghua.weather.data.android.model.params
import dev.shuanghua.weather.data.android.model.Config
/**
* Bean -> Map -> JsonString
* 此请求参数模型类,综合了所有页面的参数
* 并不是根据每个链接生成对应的模型
* 本项目中链接对应的模型使用了 Map (因为 url 中的 jsonBody 有嵌套类型,还有重复类型,使用 Bean to Json 很麻烦),
*/
open class ShenZhenParams {
// 因为自用,所以就不获取真实的设备信息
val uid: String = Config.uid
val uname: String = Config.uname
val token: String = Config.token
val os: String = Config.os
val type: String = Config.type
val version: String = Config.version
val rever: String = Config.rever
val net: String = Config.net
val gif: String = Config.gif
val w: String = Config.width
val h: String = Config.height
open var cityName: String = ""
open var district: String = ""
open var lon: String = ""
open var lat: String = ""
}
| 0 | Kotlin | 2 | 5 | 218cd475728687ed3c6bf63df793577ea7087bc7 | 842 | jianmoweather | Apache License 2.0 |
app/src/main/java/com/example/helloworld/MainActivity.kt | TitoMuller | 596,319,848 | false | null | package com.example.helloworld
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import org.w3c.dom.Text
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btnCalculate: Button = findViewById<Button>(R.id.btnCalculate)
val weightInput: EditText = findViewById<EditText>(R.id.weight)
val heightInput: EditText = findViewById<EditText>(R.id.height)
btnCalculate.setOnClickListener {
val weightStr = weightInput.text.toString()
val heightStr = heightInput.text.toString()
if (weightStr.isNotEmpty() && heightStr.isNotEmpty()) {
val weight: Float = weightStr.toFloat()
val height: Float = heightStr.toFloat()
val result = weight / (height * height)
val intent = Intent(this, ResultActivity::class.java)
.apply {
putExtra("EXTRA_RESULT", result)
}
startActivity(intent)
} else {
Toast.makeText(this, "Preencha todos os campos", Toast.LENGTH_LONG).show()
}
}
}
} | 0 | Kotlin | 0 | 0 | 2d0b4f3a654d436c61d3a5ff733e91fea40943db | 1,442 | CalculadoraIMC | MIT License |
shared/src/commonMain/kotlin/tech/alexib/yaba/kmm/data/api/ApolloResponse.kt | LouisCAD | 380,833,587 | true | {"Kotlin": 184981, "Ruby": 2062, "Swift": 344, "Shell": 306} | package tech.alexib.yaba.kmm.data.api
import com.apollographql.apollo.api.Response
import com.apollographql.apollo.api.Error as ApolloError
sealed class ApolloResponse<out T> {
data class Success<T>(val data: T) : ApolloResponse<T>()
data class Error(val errors: List<String>) :
ApolloResponse<Nothing>() {
val message = errors.first()
}
companion object {
fun <T> success(data: T) = Success(data)
fun error(errors: List<String>) = Error(errors)
operator fun <T> invoke(response: Response<T>): ApolloResponse<T> {
return if (response.hasErrors()) {
error(response.errors!!)
} else {
success(response.data!!)
}
}
operator fun <T, R> invoke(
response: Response<T>,
mapper: (T) -> R
): ApolloResponse<R> {
return if (response.hasErrors()) {
error(response.errorMessages())
} else {
success(mapper(response.data!!))
}
}
}
}
private fun List<ApolloError>.messages(): List<String> = this.map { it.message }
fun <T> Response<T>.errorMessages(): List<String> =
this.errors?.map { it.message } ?: emptyList() | 0 | null | 0 | 0 | f46020f59be5f1603ee00d7540d83bf7d6840a1c | 1,264 | yaba-kmm | Apache License 2.0 |
shared/src/commonMain/kotlin/com/example/multiplatform/koru/shared/viewmodel/CountdownViewModel.kt | FutureMind | 334,913,136 | false | null | package com.example.multiplatform.koru.shared.viewmodel
import com.futuremind.koru.ToNativeClass
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import com.example.multiplatform.koru.shared.scope.MainScopeProvider
@ToNativeClass(
name = "CountdownViewModelIos",
launchOnScope = MainScopeProvider::class
)
class CountdownViewModel : ViewModel() {
val countdown: MutableStateFlow<String> = MutableStateFlow("")
init {
viewModelScope.launch {
(100 downTo 1).forEach {
countdown.value = "...$it..."
delay(1000)
}
countdown.value = "Finished countdown"
}
}
override protected fun onCleared() {
println("onCleared")
}
} | 0 | Kotlin | 1 | 17 | 95a6a29d1acf3afc410ca61fbd8a18e92d862e45 | 804 | koru-example | MIT License |
kompendium-core/src/main/kotlin/io/bkbn/kompendium/models/oas/OpenApiSpecServerVariable.kt | bkbnio | 356,919,425 | false | null | package org.leafygreens.kompendium.models.oas
data class OpenApiSpecServerVariable(
val `enum`: Set<String>, // todo enforce not empty
val default: String,
val description: String?
)
| 22 | Kotlin | 7 | 31 | d66880f9b28193d0cd033ba1bc3969f20f1e34e4 | 190 | kompendium | MIT License |
app2/src/main/java/net/yslibrary/monotweety/ui/login/LoginFragmentComponent.kt | yshrsmz | 69,078,478 | false | {"Kotlin": 444779} | package net.yslibrary.monotweety.ui.login
import dagger.Subcomponent
import net.yslibrary.monotweety.di.FragmentScope
@FragmentScope
@Subcomponent
interface LoginFragmentComponent {
fun inject(fragment: LoginFragment)
@Subcomponent.Factory
interface Factory {
fun build(): LoginFragmentComponent
}
interface ComponentProvider {
fun loginFragmentComponent(): Factory
}
}
| 10 | Kotlin | 25 | 113 | 7b5b5fe9e0b1dd4667a024d5e22947132b01c426 | 415 | monotweety | Apache License 2.0 |
app/src/main/java/com/hadi/minimalnotes/util/Constants.kt | unaisulhadi | 435,369,043 | false | {"Kotlin": 49830} | package com.hadi.minimalnotes.util
object Constants {
const val SPLASH_DURATION = 1000L
} | 0 | Kotlin | 2 | 22 | 3c60aac740c9643fefd624b0e214e47b882752c4 | 95 | MinimalNotes | MIT License |
app/src/main/java/cz/nestresuju/model/entities/api/auth/LoginChecklistResponse.kt | johnondrej | 371,166,772 | false | null | package cz.nestresuju.model.entities.api.auth
import com.squareup.moshi.JsonClass
/**
* API response with information about completion of necessary after-login steps.
*/
@JsonClass(generateAdapter = true)
class LoginChecklistResponse(
val consentGiven: Boolean,
val inputTestSubmitted: Boolean,
val screeningTestSubmitted: Boolean,
val finalTestFirstSubmitted: Boolean,
val finalTestSecondSubmitted: Boolean
) | 0 | Kotlin | 0 | 0 | 8d7c54c00c865a370ed24a356abd2bfeeef4ed4b | 433 | nestresuju-android | Apache License 2.0 |
Repairs/app/src/test/java/com/rooio/repairs/StatusTypeTest.kt | roopairs | 212,211,326 | false | {"XML": 431086, "Kotlin": 299391, "Java": 26386} | package com.rooio.repairs
import org.junit.Assert.assertEquals
import org.junit.Test
class StatusTypeTest {
@Test
fun testPendingStatusType() {
assertEquals(StatusType.PENDING.toString(), "Pending")
assertEquals(StatusType.PENDING.getInt(), 0)
}
@Test
fun testDeclinedStatusType() {
assertEquals(StatusType.DECLINED.toString(), "Declined")
assertEquals(StatusType.DECLINED.getInt(), 1)
}
@Test
fun testAcceptedStatusType() {
assertEquals(StatusType.ACCEPTED.toString(), "Accepted")
assertEquals(StatusType.ACCEPTED.getInt(), 2)
}
@Test
fun testCompletedStatusType() {
assertEquals(StatusType.COMPLETED.toString(), "Completed")
assertEquals(StatusType.COMPLETED.getInt(), 3)
}
@Test
fun testCancelledStatusType() {
assertEquals(StatusType.CANCELLED.toString(), "Cancelled")
assertEquals(StatusType.CANCELLED.getInt(), 4)
}
@Test
fun testStartedStatusType() {
assertEquals(StatusType.STARTED.toString(), "Started")
assertEquals(StatusType.STARTED.getInt(), 5)
}
@Test
fun testPausedStatusType() {
assertEquals(StatusType.PAUSED.toString(), "Paused")
assertEquals(StatusType.PAUSED.getInt(), 6)
}
} | 0 | XML | 0 | 0 | e81487aba0a997812769e893dc8e34d21935647f | 1,301 | Rooio | MIT License |
backend.native/tests/external/stdlib/collections/MapTest/filter.kt | pedromassango | 109,945,056 | true | {"Kotlin": 3706234, "C++": 727837, "C": 135283, "Groovy": 47410, "JavaScript": 7780, "Shell": 6563, "Batchfile": 6379, "Objective-C++": 5203, "Objective-C": 1891, "Python": 1844, "Pascal": 1698, "Makefile": 1341, "Java": 782, "HTML": 185} | import kotlin.test.*
fun box() {
val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2))
val filteredByKey = map.filter { it.key[0] == 'b' }
assertEquals(mapOf("b" to 3), filteredByKey)
val filteredByKey2 = map.filterKeys { it[0] == 'b' }
assertEquals(mapOf("b" to 3), filteredByKey2)
val filteredByValue = map.filter { it.value == 2 }
assertEquals(mapOf("a" to 2, "c" to 2), filteredByValue)
val filteredByValue2 = map.filterValues { it % 2 == 0 }
assertEquals(mapOf("a" to 2, "c" to 2), filteredByValue2)
}
| 0 | Kotlin | 0 | 1 | 5d514e3ede6c70ad144ceaf3a5aac065c74e09eb | 552 | kotlin-native | Apache License 2.0 |
moove/application/src/main/kotlin/io/charlescd/moove/application/user/impl/FindUserByIdInteractorImpl.kt | lucassaleszup | 357,264,743 | true | {"TypeScript": 3202507, "Kotlin": 1558911, "Groovy": 981904, "HTML": 887133, "JavaScript": 696262, "Java": 490542, "Go": 460052, "FreeMarker": 130951, "AMPL": 26291, "Shell": 16488, "Mustache": 13220, "C#": 9630, "Dockerfile": 3861, "Ruby": 2632, "CSS": 2547, "Makefile": 2491} | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.charlescd.moove.application.user.impl
import io.charlescd.moove.application.UserService
import io.charlescd.moove.application.user.FindUserByIdInteractor
import io.charlescd.moove.application.user.response.UserResponse
import io.charlescd.moove.domain.MooveErrorCode
import io.charlescd.moove.domain.User
import io.charlescd.moove.domain.exceptions.BusinessException
import io.charlescd.moove.domain.service.KeycloakService
import java.util.UUID
import javax.inject.Named
@Named
class FindUserByIdInteractorImpl(private val userService: UserService, private val keycloakService: KeycloakService) : FindUserByIdInteractor {
override fun execute(authorization: String, id: UUID): UserResponse {
val user = userService.find(id.toString())
validateUser(authorization, user)
return UserResponse.from(user)
}
private fun validateUser(authorization: String, user: User) {
val parsedEmail = keycloakService.getEmailByAccessToken(authorization)
val registeredUser = userService.findByEmail(parsedEmail)
if (registeredUser.email != user.email && !registeredUser.root) {
throw BusinessException.of(MooveErrorCode.FORBIDDEN)
}
}
}
| 1 | null | 1 | 0 | 998f3fe19e39e471f99991bf02a5b017acb9359f | 1,846 | charlescd | Apache License 2.0 |
mobile/src/main/java/com/sebastiansokolowski/healthguard/view/CustomMarkerView.kt | sebastiansokolowski | 125,769,078 | false | {"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "JSON": 1, "Java": 2, "XML": 52, "Kotlin": 121} | package com.sebastiansokolowski.healthguard.view
import android.content.Context
import android.view.View
import com.github.mikephil.charting.components.MarkerView
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.highlight.Highlight
import com.github.mikephil.charting.utils.MPPointF
import com.sebastiansokolowski.healthguard.util.EntryHelper
import com.sebastiansokolowski.healthguard.util.SafeCall
import com.sebastiansokolowski.shared.util.Utils
import kotlinx.android.synthetic.main.custom_marker_view.view.*
/**
* Created by <NAME> on 17.03.19.
*/
class CustomMarkerView : MarkerView {
constructor(context: Context) : super(context, 0)
constructor(context: Context?, layoutResource: Int) : super(context, layoutResource)
var unit: String = ""
override fun refreshContent(e: Entry?, highlight: Highlight?) {
SafeCall.safeLet(e?.x, e?.y) { x, y ->
text.text = "${EntryHelper.getDate(x, true)}\n${Utils.formatValue(y)} $unit"
text.textAlignment = View.TEXT_ALIGNMENT_CENTER
}
super.refreshContent(e, highlight)
}
override fun getOffset(): MPPointF {
return MPPointF((-(width / 2)).toFloat(), (-height).toFloat())
}
} | 1 | null | 1 | 1 | 5c164405abb457b91f04b15ff04ef1702cee6a54 | 1,246 | mHealth-Guard | Apache License 2.0 |
advent-of-code-2020/src/main/kotlin/eu/janvdb/aoc2020/day20/Day20.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2020.day20
import eu.janvdb.aocutil.kotlin.readGroupedLines
val MONSTER = Picture(
listOf(
" # ",
"# ## ## ###",
" # # # # # # "
)
)
fun main() {
val tiles = readGroupedLines(2020, "input20.txt").map(::MapTile)
val topLeftCorner = getTopLeftCorner(tiles)
val fullPicture = buildPictureFromCornerDown(tiles, topLeftCorner)
val occurrences = fullPicture.findImageOccurrences(MONSTER)
val pictureWithoutMonsters = occurrences.fold(fullPicture) { picture, occurrence ->
picture.removeImageOccurrence(occurrence.first, occurrence.second)
}
println(pictureWithoutMonsters.numberOfPixelsSet())
}
private fun getTopLeftCorner(tiles: List<MapTile>): MapTile {
// Corners only attach to two other tiles.
// This means that of their eight border checksums, four will not be found in other tiles
val borderValues = tiles.flatMap { it.borderValues }
val borderValuesOccurringOnce = borderValues.groupBy { it }.filterValues { it.size == 1 }.map { it.key }.toSet()
val corners = tiles.filter { borderValuesOccurringOnce.intersect(it.borderValues).size == 4 }
// Result of part 1: multiply id of corners
val cornerProduct = corners.fold(1L) { temp, corner -> temp * corner.id }
println(cornerProduct)
// Take the first corner and orient it so that its top and left edge don't match any other
return corners[0].getAllTransformations()
.first { it.borderLeft in borderValuesOccurringOnce && it.borderTop in borderValuesOccurringOnce }
}
private fun buildPictureFromCornerDown(allTiles: List<MapTile>, topLeft: MapTile): Picture {
fun findTileMatchingRight(tileToMatch: MapTile): MapTile? {
val tile = allTiles.filter { it.id != tileToMatch.id }.singleOrNull { tileToMatch.borderRight in it.borderValues }
?: return null
return tile.getAllTransformations().single { it.borderLeftFlipped == tileToMatch.borderRight }
}
fun getTileMatchingBottom(tileToMatch: MapTile): MapTile? {
val tile = allTiles.filter { it.id != tileToMatch.id }.singleOrNull { tileToMatch.borderBottom in it.borderValues }
?: return null
return tile.getAllTransformations().single { it.borderTopFlipped == tileToMatch.borderBottom }
}
val tilesOrdered = mutableListOf<MutableList<MapTile>>()
var currentLeft: MapTile? = topLeft
while (currentLeft != null) {
val currentLine = mutableListOf(currentLeft)
tilesOrdered.add(currentLine)
var current = findTileMatchingRight(currentLeft)
while (current != null) {
currentLine.add(current)
current = findTileMatchingRight(current)
}
currentLeft = getTileMatchingBottom(currentLeft)
}
return tilesOrdered.combine()
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 2,650 | advent-of-code | Apache License 2.0 |
app/src/main/java/com/brins/lightmusic/ui/customview/RoundCoverImageView.kt | wyrccx99 | 207,684,464 | true | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 115, "XML": 86, "Java": 16, "JSON": 2} | package com.brins.lightmusic.ui.customview
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.view.animation.LinearInterpolator
import com.makeramen.roundedimageview.RoundedImageView
class RoundCoverImageView @JvmOverloads constructor(context: Context, attrs : AttributeSet? = null): RoundedImageView(context , attrs) {
private var mRotateAnimator: ObjectAnimator
private var mLastAnimationValue: Long = 0
init {
mRotateAnimator = ObjectAnimator.ofFloat(this, "rotation", 0f, 360f)
mRotateAnimator.duration = 7200
mRotateAnimator.interpolator = LinearInterpolator()
mRotateAnimator.repeatMode = ValueAnimator.RESTART
mRotateAnimator.repeatCount = ValueAnimator.INFINITE
}
fun startRotateAnimation() {
mRotateAnimator.cancel()
mRotateAnimator.start()
}
fun cancelRotateAnimation() {
mLastAnimationValue = 0
mRotateAnimator.cancel()
}
fun pauseRotateAnimation() {
mLastAnimationValue = mRotateAnimator.currentPlayTime
mRotateAnimator.cancel()
}
fun resumeRotateAnimation() {
mRotateAnimator.start()
mRotateAnimator.currentPlayTime = mLastAnimationValue
}
} | 0 | null | 0 | 1 | d7bdf517122af29e1c7b67182401df91076d99be | 1,319 | LightMusic | Apache License 2.0 |
kotlin/shrine/app/src/main/java/com/google/codelabs/mdc/kotlin/shrine/ProductGridFragment.kt | ababenko1 | 702,056,826 | false | {"Java": 19044, "Kotlin": 18260, "Shell": 3408} | package com.google.codelabs.mdc.kotlin.shrine
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AccelerateDecelerateInterpolator
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.codelabs.mdc.kotlin.shrine.network.ProductEntry
import com.google.codelabs.mdc.kotlin.shrine.staggeredgridlayout.StaggeredProductCardRecyclerViewAdapter
import kotlinx.android.synthetic.main.shr_product_grid_fragment.view.app_bar
import kotlinx.android.synthetic.main.shr_product_grid_fragment.view.product_grid
import kotlinx.android.synthetic.main.shr_product_grid_fragment.view.recycler_view
class ProductGridFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.shr_product_grid_fragment, container, false)
(activity as MainActivity).setSupportActionBar(view.app_bar)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
view.product_grid.background = ContextCompat.getDrawable(requireContext(), R.drawable.shr_product_grid_background_shape)
}
view.app_bar.setNavigationOnClickListener(NavigationIconClickListener(
requireActivity(), view.product_grid,
AccelerateDecelerateInterpolator(),
ContextCompat.getDrawable(requireContext(), R.drawable.shr_branded_menu),
ContextCompat.getDrawable(requireContext(), R.drawable.shr_close_menu)))
initList(view)
return view
}
private fun initList(view: View) {
view.recycler_view.setHasFixedSize(true)
val gridLayoutManager = GridLayoutManager(context, 2, RecyclerView.HORIZONTAL, false)
gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
return if (position % 3 == 2) 2 else 1
}
}
view.recycler_view.layoutManager = gridLayoutManager
val adapter = StaggeredProductCardRecyclerViewAdapter(ProductEntry.initProductEntryList(resources))
view.recycler_view.adapter = adapter
val largePadding = resources.getDimensionPixelSize(R.dimen.shr_product_grid_spacing)
val smallPadding = resources.getDimensionPixelSize(R.dimen.shr_product_grid_spacing_small)
val itemDecoration = ProductGridItemDecoration(largePadding, smallPadding)
view.recycler_view.addItemDecoration(itemDecoration)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.shr_toolbar_menu, menu)
super.onCreateOptionsMenu(menu, inflater)
}
}
| 1 | null | 1 | 1 | d0558e25226171d310ca1ffdce6fffd41b14ed90 | 3,128 | exam_codelabs_mdc | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.