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
modules/optimization/src/main/kotlin/org/kalasim/examples/coursescheduler/TFUtil.kt
holgerbrandl
299,282,108
false
{"Kotlin": 3670626, "HTML": 818831, "Java": 56143, "R": 12761}
package org.kalasim.examples.coursescheduler import ai.timefold.solver.core.api.domain.variable.VariableListener import ai.timefold.solver.core.api.score.director.ScoreDirector open class BasicVariableListener<S, E>() : VariableListener<S, E> { override fun beforeEntityAdded(scoreDirector: ScoreDirector<S>, entity: E) {} override fun afterEntityAdded(scoreDirector: ScoreDirector<S>, entity: E) {} override fun beforeEntityRemoved(scoreDirector: ScoreDirector<S>, entity: E) {} override fun afterEntityRemoved(scoreDirector: ScoreDirector<S>, entity: E) {} override fun beforeVariableChanged(scoreDirector: ScoreDirector<S>, entity: E) {} override fun afterVariableChanged(scoreDirector: ScoreDirector<S>, entity: E) {} } fun <T, Solution_> ScoreDirector<Solution_>.change(name: String, task: T, block: T.(T) -> Unit) { beforeVariableChanged(task, name) task.block(task) afterVariableChanged(task, name) }
6
Kotlin
10
65
692f30b5154370702e621cfb9e7b5caa2c84b14a
948
kalasim
MIT License
app/src/main/java/com/moneybudget/categories/categoriesList/CategoriesListViewModel.kt
lucadalmedico
468,884,501
false
{"Kotlin": 110571}
package com.moneybudget.categories.categoriesList import androidx.lifecycle.viewModelScope import com.moneybudget.database.Category import com.moneybudget.database.NameAndId import com.moneybudget.repository.Repository import com.moneybudget.utils.viewModels.ListViewModel import kotlinx.coroutines.launch class CategoriesListViewModel: ListViewModel<Category>(Repository.categoriesDataSource) { val categories = Repository .categoriesDataSource .getAllNames() override fun updateDeletedFlag(element : Any, flag : Boolean) { if(element is NameAndId){ viewModelScope.launch { val category = repositoryDataSource.get(element.id) if(category != null){ category.isDeleted = flag repositoryDataSource.update(category) } } } } }
0
Kotlin
0
0
56eb812f82b22c8cae3065ea661feee1415247de
881
MoneyBudget
MIT License
tasks/src/commonMain/kotlin/NewAnswerDrawer.kt
InsanusMokrassar
606,391,766
false
null
package center.sciprog.tasks_bot.tasks import center.sciprog.tasks_bot.common.common_resources import center.sciprog.tasks_bot.common.languagesRepo import center.sciprog.tasks_bot.common.utils.locale import center.sciprog.tasks_bot.tasks.models.DraftInfoPack import center.sciprog.tasks_bot.tasks.models.tasks.AnswerFormat import center.sciprog.tasks_bot.tasks.models.tasks.NewAnswerFormatInfo import center.sciprog.tasks_bot.tasks.models.tasks.TaskDraft import center.sciprog.tasks_bot.teachers.repos.ReadTeachersRepo import center.sciprog.tasks_bot.users.repos.ReadUsersRepo import dev.inmo.micro_utils.coroutines.runCatchingSafely import dev.inmo.micro_utils.fsm.common.State import dev.inmo.micro_utils.koin.singleWithRandomQualifier import dev.inmo.micro_utils.language_codes.IetfLanguageCode import dev.inmo.micro_utils.pagination.Pagination import dev.inmo.micro_utils.pagination.SimplePagination import dev.inmo.micro_utils.pagination.utils.paginate import dev.inmo.micro_utils.repos.set import dev.inmo.plagubot.Plugin import dev.inmo.tgbotapi.extensions.api.edit.edit import dev.inmo.tgbotapi.extensions.api.send.reply import dev.inmo.tgbotapi.extensions.api.send.send import dev.inmo.tgbotapi.extensions.behaviour_builder.* import dev.inmo.tgbotapi.extensions.behaviour_builder.expectations.waitCommandMessage import dev.inmo.tgbotapi.extensions.behaviour_builder.expectations.waitTextMessage import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onMessageDataCallbackQuery import dev.inmo.tgbotapi.extensions.utils.extensions.sameChat import dev.inmo.tgbotapi.extensions.utils.types.buttons.* import dev.inmo.tgbotapi.extensions.utils.updates.hasNoCommands import dev.inmo.tgbotapi.extensions.utils.withContentOrThrow import dev.inmo.tgbotapi.types.MessageId import dev.inmo.tgbotapi.types.UserId import dev.inmo.tgbotapi.types.buttons.InlineKeyboardMarkup import dev.inmo.tgbotapi.utils.buildEntities import dev.inmo.tgbotapi.utils.row import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.first import kotlinx.serialization.Serializable import kotlinx.serialization.json.JsonObject import kotlinx.serialization.modules.SerializersModule import org.jetbrains.exposed.sql.Database import org.koin.core.Koin import org.koin.core.module.Module internal class NewAnswerDrawer( private val changeAnswersButtonData: String, private val backButtonData: String, ) : Plugin { @Serializable private data class OnChangeFileExtensionState( override val context: UserId, val i: Int, val messageId: MessageId ) : State fun newAnswerFormatSmallTitle( newAnswerFormatInfo: NewAnswerFormatInfo, ietfLanguageCode: IetfLanguageCode ): String { val locale = ietfLanguageCode.locale return when (val format = newAnswerFormatInfo.format) { is AnswerFormat.File -> { "${tasks_resources.strings.answerFormatTitleFile.localized(locale)}: .${format.extension ?: "*"}" } is AnswerFormat.Link -> { "${tasks_resources.strings.answerFormatTitleLink.localized(locale)}: ${format.regexString}" } is AnswerFormat.Text -> { "${tasks_resources.strings.answerFormatTitleText.localized(locale)}${format.lengthRange ?.let { ": ${it.first} - ${it.last}" } ?: ""}" } } } private fun createAnswersFormatKeyboardByPage(ietfLanguageCode: IetfLanguageCode, draft: TaskDraft, pagination: Pagination): InlineKeyboardMarkup { return inlineKeyboard { val resultPagination = draft.newAnswersFormats.paginate(pagination) if (resultPagination.size > 1) { row { if (resultPagination.page > 1) { dataButton("<<", newAnswersOpenAnswersList) } if (resultPagination.page > 0) { dataButton("<", "${newAnswersOpenAnswersList}${pagination.page - 1}") } dataButton("\uD83D\uDD04", "${newAnswersOpenAnswersList}${pagination.page}") if (resultPagination.pagesNumber - resultPagination.page > 1) { dataButton(">", "${newAnswersOpenAnswersList}${pagination.page + 1}") } if (resultPagination.pagesNumber - resultPagination.page > 2) { dataButton(">>", "${newAnswersOpenAnswersList}${resultPagination.pagesNumber - 1}") } } } resultPagination.results.withIndex().chunked(2).forEach { row { it.forEach { (i, it) -> dataButton(newAnswerFormatSmallTitle(it, ietfLanguageCode), "${newAnswerOpenIndexAnswerDataPrefix}$i") } } } row { dataButton(common_resources.strings.back.localized(ietfLanguageCode.locale), backButtonData) dataButton( tasks_resources.strings.newAnswersFormatAddBtnText.localized(ietfLanguageCode.locale), newAnswerCreateAnswerData ) } } } private suspend fun BehaviourContext.putAnswerInfo( userId: UserId, messageId: MessageId?, i: Int, draftInfoPack: DraftInfoPack ) { val draft = draftInfoPack.draft ?: return val answerItem = draft.newAnswersFormats.getOrNull(i) ?: return val locale = draftInfoPack.ietfLanguageCode.locale val keyboard = inlineKeyboard { when (val format = answerItem.format) { is AnswerFormat.File -> { row { dataButton( tasks_resources.strings.answerFormatFileChangeExtension.localized(locale), "${newAnswerChangeIndexFileExtensionDataPrefix}$i" ) } } is AnswerFormat.Link -> TODO() is AnswerFormat.Text -> { row { format.lengthRange ?.also { dataButton( it.first.toString(), "${newAnswerChangeIndexTextMinLengthExtensionDataPrefix}$i" ) dataButton( it.last.toString(), "${newAnswerChangeIndexTextMaxLengthExtensionDataPrefix}$i" ) } ?: dataButton( tasks_resources.strings.answerFormatTextSetRangeExtension.localized(locale), "${newAnswerChangeIndexTextSetRangeExtensionDataPrefix}$i" ) } format.lengthRange ?.let { row { dataButton( tasks_resources.strings.answerFormatTextUnsetRangeExtension.localized(locale), "${newAnswerChangeIndexTextUnsetRangeExtensionDataPrefix}$i" ) } } } } row { dataButton(common_resources.strings.back.localized(locale), newAnswersOpenAnswersList) } } val entities = buildEntities { +newAnswerFormatSmallTitle(answerItem, draftInfoPack.ietfLanguageCode) } messageId ?.let { edit( userId, messageId, entities = entities, replyMarkup = keyboard ) } ?: send( userId, entities = entities, replyMarkup = keyboard ) } override fun Module.setupDI(database: Database, params: JsonObject) { singleWithRandomQualifier { SerializersModule { polymorphic(State::class, OnChangeFileExtensionState::class, OnChangeFileExtensionState.serializer()) polymorphic(Any::class, OnChangeFileExtensionState::class, OnChangeFileExtensionState.serializer()) } } } override suspend fun BehaviourContextWithFSM<State>.setupBotPlugin(koin: Koin) { val languagesRepo = koin.languagesRepo val usersRepo = koin.get<ReadUsersRepo>() val teachersRepo = koin.get<ReadTeachersRepo>() val draftsRepo = koin.tasksDraftsRepo onMessageDataCallbackQuery(Regex("(${newAnswersOpenAnswersList}\\d*)|($changeAnswersButtonData)")) { val draftInfoPack = DraftInfoPack( it.user.id, languagesRepo, usersRepo, teachersRepo, draftsRepo ) ?: return@onMessageDataCallbackQuery val draft = draftInfoPack.draft ?: return@onMessageDataCallbackQuery val page = it.data.removePrefix(newAnswersOpenAnswersList).toIntOrNull() ?: 0 val pagination = SimplePagination(page, 6) edit( it.message.withContentOrThrow(), replyMarkup = createAnswersFormatKeyboardByPage( draftInfoPack.ietfLanguageCode, draft, pagination ) ) { +tasks_resources.strings.newAnswersFormatsText.localized(draftInfoPack.ietfLanguageCode.locale) } } onMessageDataCallbackQuery(Regex("${newAnswerOpenIndexAnswerDataPrefix}\\d+")) { val i = it.data.removePrefix(newAnswerOpenIndexAnswerDataPrefix).toIntOrNull() ?: return@onMessageDataCallbackQuery val draftInfoPack = DraftInfoPack( it.user.id, languagesRepo, usersRepo, teachersRepo, draftsRepo ) ?: return@onMessageDataCallbackQuery putAnswerInfo( it.user.id, it.message.messageId, i, draftInfoPack ) } onMessageDataCallbackQuery(Regex("${newAnswerCreateAnswerData}\\w*")) { val draftInfoPack = DraftInfoPack( it.user.id, languagesRepo, usersRepo, teachersRepo, draftsRepo ) ?: return@onMessageDataCallbackQuery val newAnswerFormatTypeInfo = it.data.removePrefix(newAnswerCreateAnswerData) val draft = draftInfoPack.draft ?: return@onMessageDataCallbackQuery val newDraftInfo = when (newAnswerFormatTypeInfo) { textAnswerFormatDataInfo -> draft.copy( newAnswersFormats = draft.newAnswersFormats + NewAnswerFormatInfo( AnswerFormat.Text(), false ) ) fileAnswerFormatDataInfo -> draft.copy( newAnswersFormats = draft.newAnswersFormats + NewAnswerFormatInfo( AnswerFormat.File(), false ) ) linkAnswerFormatDataInfo -> draft.copy( newAnswersFormats = draft.newAnswersFormats + NewAnswerFormatInfo( AnswerFormat.Link(), false ) ) else -> null } if (newDraftInfo != null) { draftsRepo.set(draftInfoPack.teacher.id, newDraftInfo) val newDraftInfoPack = draftInfoPack.copy( draft = newDraftInfo ) putAnswerInfo( it.user.id, it.message.messageId, newDraftInfoPack.draft ?.newAnswersFormats ?.lastIndex ?: return@onMessageDataCallbackQuery, newDraftInfoPack ) } else { edit( it.message, replyMarkup = inlineKeyboard { row { dataButton(tasks_resources.strings.answerFormatTitleFile.localized(draftInfoPack.ietfLanguageCode.locale), "${newAnswerCreateAnswerData}${fileAnswerFormatDataInfo}") dataButton(tasks_resources.strings.answerFormatTitleText.localized(draftInfoPack.ietfLanguageCode.locale), "${newAnswerCreateAnswerData}${textAnswerFormatDataInfo}") dataButton(tasks_resources.strings.answerFormatTitleLink.localized(draftInfoPack.ietfLanguageCode.locale), "${newAnswerCreateAnswerData}${linkAnswerFormatDataInfo}") } row { dataButton(common_resources.strings.back.localized(draftInfoPack.ietfLanguageCode.locale), newAnswersOpenAnswersList) } } ) } } strictlyOn { state: OnChangeFileExtensionState -> val draftInfoPack = DraftInfoPack( state.context, languagesRepo, usersRepo, teachersRepo, draftsRepo ) ?: return@strictlyOn null val format = draftInfoPack.draft ?.newAnswersFormats ?.getOrNull(state.i) ?.format as? AnswerFormat.File ?: return@strictlyOn null runCatchingSafely { send( state.context, replyMarkup = flatReplyKeyboard( oneTimeKeyboard = true, resizeKeyboard = true ) { simpleButton("pdf") simpleButton("txt") simpleButton("docx") } ) { +tasks_resources.strings.answerFormatFileCurrentExtensionTemplate.localized(draftInfoPack.ietfLanguageCode.locale).format(format.extension ?: "*") } } oneOf( parallel { waitCommandMessage("cancel").filter { it.sameChat(state.context) }.first() val freshDraftInfoPack = DraftInfoPack( state.context, languagesRepo, usersRepo, teachersRepo, draftsRepo ) ?: return@parallel putAnswerInfo( state.context, state.messageId, state.i, freshDraftInfoPack ) }, parallel { val newExtension = waitTextMessage().filter { it.sameChat(state.context) && it.hasNoCommands() }.first { val content = it.content.text.split(Regex("\\s")) if (content.size == 1 && content.first().isNotBlank()) { true } else { reply(it) { +tasks_resources.strings.answerFormatFileCurrentWrongNewExtension.localized(draftInfoPack.ietfLanguageCode.locale) } false } }.content.text val freshDraftInfoPack = DraftInfoPack( state.context, languagesRepo, usersRepo, teachersRepo, draftsRepo ) ?: return@parallel val draft = freshDraftInfoPack.draft ?: return@parallel val newDraft = freshDraftInfoPack.draft.copy( newAnswersFormats = draft.newAnswersFormats.let { it.toMutableList().apply { val old = get(state.i) set(state.i, old.copy(format = AnswerFormat.File(newExtension))) }.toList() } ) draftsRepo.set( freshDraftInfoPack.teacher.id, newDraft ) putAnswerInfo( state.context, null, state.i, freshDraftInfoPack.copy( draft = newDraft ) ) } ) null } onMessageDataCallbackQuery(Regex("${newAnswerChangeIndexFileExtensionDataPrefix}\\d+")) { val i = it.data.removePrefix(newAnswerChangeIndexFileExtensionDataPrefix).toIntOrNull() ?: return@onMessageDataCallbackQuery val draftInfoPack = DraftInfoPack( it.user.id, languagesRepo, usersRepo, teachersRepo, draftsRepo ) ?: return@onMessageDataCallbackQuery if (draftInfoPack.draft ?.newAnswersFormats ?.getOrNull(i) ?.format is AnswerFormat.File) { startChain(OnChangeFileExtensionState(it.user.id, i, it.message.messageId)) } } } companion object { const val newAnswersOpenAnswersList = "newAnswersOpenAnswersList" private const val newAnswerOpenIndexAnswerDataPrefix = "nadoa_" private const val newAnswerCreateAnswerData = "newAnswerCreateAnswerData" private const val newAnswerChangeIndexFileExtensionDataPrefix = "nacifedp_" private const val newAnswerChangeIndexTextMinLengthExtensionDataPrefix = "nacitmnledp_" private const val newAnswerChangeIndexTextMaxLengthExtensionDataPrefix = "nacitmxledp_" private const val newAnswerChangeIndexTextUnsetRangeExtensionDataPrefix = "nacitmxluredp_" private const val newAnswerChangeIndexTextSetRangeExtensionDataPrefix = "nacitmxlsredp_" private const val textAnswerFormatDataInfo = "text" private const val fileAnswerFormatDataInfo = "file" private const val linkAnswerFormatDataInfo = "link" } }
1
Kotlin
1
2
98fda0d70b1c0a12475251bb5ad50305e9ad6a66
18,534
SchoolTasksBot
MIT License
common/src/main/kotlin/gg/scala/cgs/common/player/handler/CgsDeathHandler.kt
GrowlyX
462,082,675
false
null
package gg.scala.cgs.common.player.handler import net.evilblock.cubed.util.CC import org.apache.commons.lang.WordUtils import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer import org.bukkit.entity.Entity import org.bukkit.entity.Player import org.bukkit.event.entity.EntityDamageEvent import kotlin.math.ceil /** * @author GrowlyX * @since 12/2/2021 */ object CgsDeathHandler { fun formDeathMessage(entity: Player, killer: Entity?): String { var output = getEntityName(entity, true) + CC.SEC val cause = entity.lastDamageCause if (cause != null) { val killerName = getEntityName(killer) when (cause.cause!!) { Cause.BLOCK_EXPLOSION, Cause.ENTITY_EXPLOSION -> output += " was blown to smithereens" Cause.CONTACT -> output += " was pricked to death" Cause.DROWNING -> output += if (killer != null) { " drowned while fighting $killerName" } else { " drowned" } Cause.ENTITY_ATTACK -> if (killer != null) { output += " was slain by $killerName" if (killer is Player) { val hand = killer.itemInHand val handString = if (hand == null) "their fists" else if (hand.hasItemMeta() && hand.itemMeta .hasDisplayName() ) hand.itemMeta.displayName else WordUtils.capitalizeFully( hand.type.name.replace("_", " ") ) output += CC.SEC + " using " + CC.RED + handString } } Cause.FALL -> output += if (killer != null) { " hit the ground too hard thanks to $killerName" } else { " hit the ground too hard" } Cause.FALLING_BLOCK -> { } Cause.FIRE_TICK, Cause.FIRE -> output += if (killer != null) { " burned to death thanks to $killerName" } else { " burned to death" } Cause.LAVA -> output += if (killer != null) { " tried to swim in lava while fighting $killerName" } else { " tried to swim in lava" } Cause.MAGIC -> output += " died" Cause.MELTING -> output += " died of melting" Cause.POISON -> output += " was poisoned" Cause.LIGHTNING -> output += " was struck by lightning" Cause.PROJECTILE -> if (killer != null) { output += " was shot to death by $killerName" } Cause.STARVATION -> output += " starved to death" Cause.SUFFOCATION -> output += " suffocated in a wall" Cause.SUICIDE -> output += " committed suicide" Cause.THORNS -> output += " died whilst trying to kill $killerName" Cause.VOID -> output += if (killer != null) { " fell into the void thanks to $killerName" } else { " fell into the void" } Cause.WITHER -> output += " withered away" Cause.CUSTOM -> output += " died" } } else { output += " died for unknown reasons" } return "$output${CC.SEC}." } private fun getEntityName(entity: Entity?, doNotAddHealth: Boolean = false): String { entity ?: return "" val output: String = if (entity is Player) { val health = ceil(entity.health) / 2.0 "${entity.displayName}${ if (!doNotAddHealth) " ${CC.D_RED}[${health}❤]" else "" }" } else { val entityName: String = if (entity.customName != null) entity.customName else entity.type.name CC.SEC + "a " + CC.RED + WordUtils.capitalizeFully(entityName.replace("_", "")) } return output } fun getKiller(player: Player): CraftEntity? { val lastAttacker = (player as CraftPlayer).handle.lastDamager return lastAttacker?.bukkitEntity } } typealias Cause = EntityDamageEvent.DamageCause
0
Kotlin
1
9
42c87232c394aaed3eeb5f2c2a175da74662011b
4,843
cgs
MIT License
kotlin/api/src/main/kotlin/org/diffkt/model/SGDOptimizer.kt
facebookresearch
495,505,391
false
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package org.diffkt.model import org.diffkt.* /** * Stochastic gradient descent optimizer with optional weight decay regularization and momentum parameters. * * Default arguments are based on fast.ai's (https://docs.fast.ai/learner#Learner) * * About using default values: * - `SGD()` is "Vanilla SGD", with a default alpha of .001f and no weight decay or momentum. * - `SGD(weightDecay = true, `momentum` = true)` enables weight decay and momentum with default values: * `weightDecay`=.01f, `momentum`=.9f. `alpha` remains .001f by default. */ class SGDOptimizer<T : TrainableComponent<T>>( val initialLearningRate: Float = defaultLearningRate, val weightDecay: Float = 0f, val momentum: Float = 0f, ) : Optimizer<T>() { constructor(initialLearningRate: Float = defaultLearningRate, weightDecay: Boolean, momentum: Boolean): this( initialLearningRate = initialLearningRate, weightDecay = if (weightDecay) .01f else 0f, momentum = if (momentum) .9f else 0f ) private var nextParameter = 0 private var iteration = 0 private var learningRate = initialLearningRate private val velocities = mutableListOf<DTensor>() override fun tensorTrainingStep(tensor: DTensor, gradient: DTensor): DTensor { require(tensor.shape == gradient.shape) val velocity = if (momentum == 0f) { gradient } else if (nextParameter >= velocities.size) { // On the first training round, we don't have any velocity to // work with so we use the gradient as the velocity assert(iteration == 0) assert(nextParameter == velocities.size) velocities.add(gradient) gradient } else { val prevVelocity = velocities[nextParameter] val newVelocity = momentum * prevVelocity + (1 - momentum) * gradient velocities[nextParameter] = newVelocity newVelocity } nextParameter++ return tensor - learningRate * velocity } override fun afterFit() { nextParameter = 0 iteration++ learningRate = initialLearningRate / (1 + weightDecay * iteration) } companion object { private const val defaultLearningRate = .001f } }
62
Jupyter Notebook
3
55
710f403719bb89e3bcf00d72e53313f8571d5230
2,546
diffkt
MIT License
protocol/src/main/kotlin/com/github/traderjoe95/mls/protocol/crypto/impl/SignProvider.kt
Traderjoe95
757,448,383
false
{"Kotlin": 1143520}
package com.github.traderjoe95.mls.protocol.crypto.impl import arrow.core.Either import arrow.core.raise.Raise import arrow.core.raise.catch import arrow.core.raise.either import com.github.traderjoe95.mls.protocol.crypto.Sign import com.github.traderjoe95.mls.protocol.error.CreateSignatureError import com.github.traderjoe95.mls.protocol.error.DecoderError import com.github.traderjoe95.mls.protocol.error.MalformedPrivateKey import com.github.traderjoe95.mls.protocol.error.MalformedPublicKey import com.github.traderjoe95.mls.protocol.error.ReconstructSignaturePublicKeyError import com.github.traderjoe95.mls.protocol.error.VerifySignatureError import com.github.traderjoe95.mls.protocol.types.crypto.Signature import com.github.traderjoe95.mls.protocol.types.crypto.Signature.Companion.asSignature import com.github.traderjoe95.mls.protocol.types.crypto.SignatureKeyPair import com.github.traderjoe95.mls.protocol.types.crypto.SignaturePrivateKey import com.github.traderjoe95.mls.protocol.types.crypto.SignaturePublicKey import com.github.traderjoe95.mls.protocol.util.padStart import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator import org.bouncycastle.crypto.Signer import org.bouncycastle.crypto.generators.ECKeyPairGenerator import org.bouncycastle.crypto.generators.Ed25519KeyPairGenerator import org.bouncycastle.crypto.generators.Ed448KeyPairGenerator import org.bouncycastle.crypto.params.AsymmetricKeyParameter import org.bouncycastle.crypto.params.ECKeyGenerationParameters import org.bouncycastle.crypto.params.ECPrivateKeyParameters import org.bouncycastle.crypto.params.ECPublicKeyParameters import org.bouncycastle.crypto.params.Ed25519KeyGenerationParameters import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters import org.bouncycastle.crypto.params.Ed448KeyGenerationParameters import org.bouncycastle.crypto.params.Ed448PrivateKeyParameters import org.bouncycastle.crypto.params.Ed448PublicKeyParameters import org.bouncycastle.crypto.signers.DSADigestSigner import org.bouncycastle.crypto.signers.ECDSASigner import org.bouncycastle.crypto.signers.Ed25519Signer import org.bouncycastle.crypto.signers.Ed448Signer import java.math.BigInteger import java.security.SecureRandom internal class SignProvider( private val dhKem: DhKem, private val rand: SecureRandom = SecureRandom(), ) : Sign.Provider() { override fun sign( signatureKey: SignaturePrivateKey, content: ByteArray, ): Either<CreateSignatureError, Signature> = either { signer().apply { init(true, signatureKey.asParameter) update(content, 0, content.size) }.generateSignature().asSignature } override fun verify( signaturePublicKey: SignaturePublicKey, content: ByteArray, signature: Signature, ): Either<VerifySignatureError, Unit> = either { val valid = signer().apply { init(false, DecoderError.wrap { signaturePublicKey.asParameter }) update(content, 0, content.size) }.verifySignature(signature.bytes) if (!valid) raise(VerifySignatureError.BadSignature) } override fun generateSignatureKeyPair(): SignatureKeyPair = kpg.generateKeyPair().run { SignatureKeyPair(SignaturePrivateKey(private.bytes), SignaturePublicKey(public.bytes)) } override fun reconstructPublicKey(privateKey: SignaturePrivateKey): Either<ReconstructSignaturePublicKeyError, SignatureKeyPair> = either { SignatureKeyPair( privateKey, when (val p = privateKey.asParameter) { is Ed25519PrivateKeyParameters -> SignaturePublicKey(p.generatePublicKey().bytes) is Ed448PrivateKeyParameters -> SignaturePublicKey(p.generatePublicKey().bytes) is ECPrivateKeyParameters -> SignaturePublicKey( ECPublicKeyParameters(p.parameters.g.multiply(p.d), p.parameters).bytes, ) else -> error("Unsupported") }, ) } private fun signer(): Signer = when (dhKem) { DhKem.X25519_SHA256 -> Ed25519Signer() DhKem.X448_SHA512 -> Ed448Signer(byteArrayOf()) else -> DSADigestSigner(ECDSASigner(), dhKem.hash.createDigest()) } private val kpg: AsymmetricCipherKeyPairGenerator by lazy { when (dhKem) { DhKem.P256_SHA256, DhKem.P384_SHA384, DhKem.P521_SHA512 -> ECKeyPairGenerator().apply { init(ECKeyGenerationParameters(dhKem.domainParams, rand)) } DhKem.X25519_SHA256 -> Ed25519KeyPairGenerator().apply { init(Ed25519KeyGenerationParameters(rand)) } DhKem.X448_SHA512 -> Ed448KeyPairGenerator().apply { init(Ed448KeyGenerationParameters(rand)) } } } private val AsymmetricKeyParameter.bytes: ByteArray get() = when (this) { is ECPublicKeyParameters -> q.getEncoded(false) is ECPrivateKeyParameters -> d.toByteArray().padStart(dhKem.nsk.toUInt()) is Ed25519PublicKeyParameters -> encoded is Ed25519PrivateKeyParameters -> encoded is Ed448PublicKeyParameters -> encoded is Ed448PrivateKeyParameters -> encoded else -> error("Unsupported") } context(Raise<MalformedPublicKey>) private val SignaturePublicKey.asParameter: AsymmetricKeyParameter get() = catch( block = { when (dhKem) { DhKem.P256_SHA256, DhKem.P384_SHA384, DhKem.P521_SHA512 -> ECPublicKeyParameters(dhKem.domainParams.curve.decodePoint(bytes), dhKem.domainParams) DhKem.X25519_SHA256 -> Ed25519PublicKeyParameters(bytes) DhKem.X448_SHA512 -> Ed448PublicKeyParameters(bytes) } }, catch = { raise(MalformedPublicKey(it.message)) }, ) context(Raise<MalformedPrivateKey>) private val SignaturePrivateKey.asParameter: AsymmetricKeyParameter get() = catch( block = { when (dhKem) { DhKem.P256_SHA256, DhKem.P384_SHA384, DhKem.P521_SHA512 -> ECPrivateKeyParameters(BigInteger(1, bytes), dhKem.domainParams) DhKem.X25519_SHA256 -> Ed25519PrivateKeyParameters(bytes) DhKem.X448_SHA512 -> Ed448PrivateKeyParameters(bytes) } }, catch = { raise(MalformedPrivateKey(it.message)) }, ) }
0
Kotlin
0
1
70bd7110b08713ae9425bbad6e6da13fa6fed8f3
6,319
mls-kotlin
MIT License
sample/presentation/src/main/java/com/htecgroup/coresample/presentation/post/edit/EditPostUI.kt
htecgroup
614,231,356
false
null
/* * Copyright 2023 HTEC Group Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.htecgroup.coresample.presentation.post.edit import android.annotation.SuppressLint import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import com.htecgroup.androidcore.presentation.model.DataUiState import com.htecgroup.androidcore.presentation.model.DataUiState.Idle import com.htecgroup.coresample.presentation.R import com.htecgroup.coresample.presentation.post.PostView @OptIn(ExperimentalMaterial3Api::class) @Composable fun EditPostScreen( uiState: DataUiState<PostView>, titleState: MutableState<String>, bodyState: MutableState<String>, onSaveClick: () -> Unit, onSaved: () -> Unit ) { if (uiState.data?.changesSaved == true) { onSaved() } Column( modifier = Modifier .fillMaxSize() .padding(dimensionResource(id = R.dimen.list_item_padding)), ) { TextField( modifier = Modifier.fillMaxWidth(), value = titleState.value, maxLines = 1, onValueChange = { titleState.value = it }, label = { Text(text = stringResource(id = R.string.title)) } ) TextField( modifier = Modifier .fillMaxWidth() .padding(top = dimensionResource(id = R.dimen.margin_default)), value = bodyState.value, onValueChange = { bodyState.value = it }, label = { Text(text = stringResource(id = R.string.body)) } ) Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, ) { Button( modifier = Modifier .padding(top = dimensionResource(id = R.dimen.margin_default)), onClick = { onSaveClick() } ) { Text(text = stringResource(id = R.string.save)) } } } } @SuppressLint("UnrememberedMutableState") @Preview @Composable fun EditPostPreview() { EditPostScreen( uiState = Idle(), titleState = mutableStateOf("Hello"), bodyState = mutableStateOf("There"), onSaveClick = {}, onSaved = {} ) }
0
Kotlin
1
3
f995c32c19b1a794f9b0e841a4d05266e28d9683
3,570
android-core
Apache License 2.0
core/theme/src/jsMain/kotlin/ru.kyamshanov.mission/Theme.kt
KYamshanov
656,042,097
false
{"Kotlin": 424932, "Batchfile": 2703, "HTML": 199}
package ru.kyamshanov.mission import org.jetbrains.compose.web.css.StyleSheet import org.jetbrains.compose.web.css.color import org.jetbrains.compose.web.css.fontSize import org.jetbrains.compose.web.css.maxHeight import org.jetbrains.compose.web.css.maxWidth import org.jetbrains.compose.web.css.percent import org.jetbrains.compose.web.css.px import org.jetbrains.compose.web.css.rgb object TextStyles : StyleSheet() { val titleText by style { color(rgb(23, 24, 28)) fontSize(50.px) property("font-size", 50.px) property("letter-spacing", (-1.5).px) property("font-weight", 900) property("line-height", 58.px) property( "font-family", "Gotham SSm A,Gotham SSm B,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Droid Sans,Helvetica Neue,Arial,sans-serif" ) } val personText by style { color(rgb(23, 24, 28)) fontSize(24.px) property("font-size", 28.px) property("letter-spacing", "normal") property("font-weight", 300) property("line-height", 40.px) property( "font-family", "Gotham SSm A,Gotham SSm B,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Droid Sans,Helvetica Neue,Arial,sans-serif" ) } } object ImageStyles : StyleSheet() { val appIcon by style { maxHeight(10.percent) maxWidth(10.percent) } }
6
Kotlin
0
1
19ba9237ba59a1f52ca54b948647144d9d450902
1,503
Mission-app
Apache License 2.0
app/src/main/java/pl/edu/zut/trackfitnesstraining/ui/options/settings/SettingsViewModel.kt
Dominik-Stasiak
624,498,221
false
null
package pl.edu.zut.trackfitnesstraining.ui.options.settings import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase class SettingsViewModel() : ViewModel() { private val auth = Firebase.auth private val user = auth.currentUser val userEmail = MutableLiveData<String>() val userName = MutableLiveData<String>() val userID = MutableLiveData<String>() fun setData() { if (auth.currentUser != null) { user?.let { val name = it.displayName val email = it.email val uid = it.uid userEmail.value = email.toString() userName.value = name.toString() userID.value = uid } } else { userEmail.value = "" userName.value = "" userID.value = "" } } }
0
Kotlin
0
1
4a6b4661af0190f3c5bed20749f7e96dc89f1c55
952
FitnessTrainingProgressKt
MIT License
chats/src/main/java/com/cyberland/messenger/chats/components/GroupJoiningReviewItem.kt
Era-CyberLabs
576,196,269
false
{"Java": 6276144, "Kotlin": 5427066, "HTML": 92928, "C": 30870, "Groovy": 12495, "C++": 6551, "CMake": 2728, "Python": 1600, "AIDL": 1267, "Makefile": 472}
package com.bcm.messenger.chats.components import android.content.Context import android.util.AttributeSet import android.view.View import com.bcm.messenger.chats.R import com.bcm.messenger.chats.group.logic.GroupLogic import com.bcm.messenger.common.ARouterConstants import com.bcm.messenger.common.AccountContext import com.bcm.messenger.common.core.corebean.BcmGroupJoinRequest import com.bcm.messenger.common.core.corebean.BcmGroupJoinStatus import com.bcm.messenger.common.core.corebean.BcmReviewGroupJoinRequest import com.bcm.messenger.common.provider.AMELogin import com.bcm.messenger.common.provider.AmeModuleCenter import com.bcm.messenger.common.recipients.Recipient import com.bcm.messenger.common.recipients.RecipientModifiedListener import com.bcm.messenger.common.utils.* import com.bcm.messenger.utility.logger.ALog import com.bcm.messenger.utility.setDrawableLeft import com.bcm.route.api.BcmRouter import kotlinx.android.synthetic.main.chats_item_group_joining_check.view.* /** * Created by wjh on 2019/6/4 */ class GroupJoiningReviewItem @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : androidx.constraintlayout.widget.ConstraintLayout(context, attrs, defStyle), RecipientModifiedListener { private val TAG = "GroupJoiningReviewItem" private var mJoiner: Recipient? = null private var mInviter: Recipient? = null private var mRequestData: BcmGroupJoinRequest? = null private var mUnHandleCount: Int = 0 private var mUnReadCount: Int = 0 init { View.inflate(context, R.layout.chats_item_group_joining_check, this) val p = resources.getDimensionPixelSize(R.dimen.common_horizontal_gap) setPadding(p, p, p, p) join_action_accept_iv.setOnClickListener { val data = mRequestData ?: return@setOnClickListener val groupModel = GroupLogic.get(AMELogin.majorContext).getModel(data.gid) ?: return@setOnClickListener AmeAppLifecycle.showLoading() val reviewRequest = BcmReviewGroupJoinRequest(data.uid, data.reqId, true) groupModel.reviewJoinRequests(listOf(reviewRequest)) { succeed, error -> ALog.d(TAG, "reviewJoinRequests success: $succeed, error: $error") AmeAppLifecycle.hideLoading() if (succeed) { AmeAppLifecycle.succeed(getString(R.string.chats_group_join_approve_success), true) } else { AmeAppLifecycle.failure(getString(R.string.chats_group_join_approve_fail), true) } } } join_action_deny_iv.setOnClickListener { val data = mRequestData ?: return@setOnClickListener val groupModel = GroupLogic.get(AMELogin.majorContext).getModel(data.gid) ?: return@setOnClickListener AmeAppLifecycle.showLoading() val reviewRequest = BcmReviewGroupJoinRequest(data.uid, data.reqId, false) groupModel.reviewJoinRequests(listOf(reviewRequest)) { succeed, error -> ALog.d(TAG, "reviewJoinRequests success: $succeed, error: $error") AmeAppLifecycle.hideLoading() if (succeed) { AmeAppLifecycle.succeed(getString(R.string.chats_group_join_reject_success), true) } else { AmeAppLifecycle.failure(getString(R.string.chats_group_join_reject_fail), true) } } } join_member_comment_tv.setOnClickListener { if (mInviter != null) { val address = mInviter?.address ?: return@setOnClickListener AmeModuleCenter.contact(address.context())?.openContactDataActivity(context, address, mRequestData?.gid ?: 0) } } join_member_all_item.setOnClickListener { BcmRouter.getInstance().get(ARouterConstants.Activity.GROUP_JOIN_CHECK).putLong(ARouterConstants.PARAM.PARAM_GROUP_ID, mRequestData?.gid ?: -1).startBcmActivity(AMELogin.majorContext, context) } } override fun onModified(recipient: Recipient) { if (mJoiner == recipient || mInviter == recipient) { bind(recipient.address.context(), mRequestData ?: return, mUnHandleCount, mUnReadCount) } } fun bind(accountContext: AccountContext, data: BcmGroupJoinRequest, unHandleCount: Int, unReadCount: Int) { unbind() mRequestData = data mUnHandleCount = unHandleCount mUnReadCount = unReadCount mJoiner = Recipient.from(accountContext, data.uid, true) mJoiner?.addListener(this) if (data.inviter.isNullOrEmpty()) { mInviter = null if (data.comment.isNullOrEmpty()) { join_member_comment_tv.visibility = View.GONE } else { join_member_comment_tv.visibility = View.VISIBLE join_member_comment_tv.text = data.comment } } else { mInviter = Recipient.from(accountContext, data.inviter!!, true) mInviter?.addListener(this) join_member_comment_tv.visibility = View.VISIBLE join_member_comment_tv.text = context.getString(R.string.chats_group_join_check_invited_comment, mInviter?.name ?: "") } join_member_avatar.setPhoto(mJoiner) join_member_name_tv.text = if (!mJoiner?.localName.isNullOrEmpty()) { mJoiner?.localName } else if (!mJoiner?.bcmName.isNullOrEmpty()) { mJoiner?.bcmName } else { data.name } if (data.read) { join_member_name_tv.setDrawableLeft(0) } else { join_member_name_tv.setDrawableLeft(R.drawable.chats_group_join_new_icon) } when (data.status) { BcmGroupJoinStatus.WAIT_OWNER_REVIEW -> { join_action_status_tv.visibility = View.GONE join_action_accept_iv.visibility = View.VISIBLE join_action_deny_iv.visibility = View.VISIBLE } BcmGroupJoinStatus.OWNER_APPROVED -> { join_action_status_tv.visibility = View.VISIBLE join_action_accept_iv.visibility = View.GONE join_action_deny_iv.visibility = View.GONE join_action_status_tv.text = context.getString(R.string.chats_group_join_approved_state) join_action_status_tv.setTextColor(context.getAttrColor(R.attr.common_text_green_color)) } BcmGroupJoinStatus.OWNER_REJECTED -> { join_action_status_tv.visibility = View.VISIBLE join_action_accept_iv.visibility = View.GONE join_action_deny_iv.visibility = View.GONE join_action_status_tv.text = context.getString(R.string.chats_group_join_rejected_state) join_action_status_tv.setTextColor(context.getAttrColor(R.attr.common_text_warn_color)) } else -> { } } if (mUnHandleCount > 0) { join_member_all_item.visibility = View.VISIBLE join_member_all_item.setTip(mUnHandleCount.toString(), if (mUnReadCount > 0) R.drawable.common_red_dot else 0) } else { join_member_all_item.visibility = View.GONE } } fun unbind() { mJoiner?.removeListener(this) mInviter?.removeListener(this) } }
1
null
1
1
65a11e5f009394897ddc08f4252969458454d052
7,556
cyberland-android
Apache License 2.0
app/src/main/java/com/sliebald/cula/data/database/pojos/StatisticsLibraryWordCount.kt
erkenberg
137,040,385
false
{"Java": 128265, "Kotlin": 46942}
package com.sliebald.cula.data.database.pojos /** * @param level KnowledgeLevel aggregation (0-1 is level 1, 1-2 is level 2,...). * @param count How many LibraryEntries are in that range of the KnowledgeLevel. */ data class StatisticsLibraryWordCount(var level: Double = 0.0, var count: Int = 0)
1
null
1
1
f00ba0b1b5adb915c45cef9b61337348c4689aeb
299
CuLa
Apache License 2.0
app/src/main/java/android/arch/archsample/MainActivity.kt
YvesCheung
124,842,421
false
null
package android.arch.archsample import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.util.Log import io.reactivex.disposables.Disposable class MainActivity : AppCompatActivity() { private val viewModel by lazy { ViewModelProviders.of(this).get(MyViewModel::class.java) } private lateinit var disposable: Disposable override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) viewModel.lifecycleEvent.setValue("onCreate") disposable = viewModel.lifecycleEvent.subscribe({ Log.i("zyclife", "life $it") }) } override fun onStart() { super.onStart() viewModel.lifecycleEvent.setValue("onStart") } override fun onRestart() { super.onRestart() viewModel.lifecycleEvent.setValue("onRestart") } override fun onResume() { super.onResume() viewModel.lifecycleEvent.setValue("onResume") } override fun onPause() { viewModel.lifecycleEvent.setValue("onPause") super.onPause() } override fun onStop() { viewModel.lifecycleEvent.setValue("onStop") super.onStop() } override fun onDestroy() { disposable.dispose() viewModel.lifecycleEvent.setValue("onDestroy") super.onDestroy() } }
1
null
1
2
b00f6a6690a473754af5b671b19733fae4152ec2
1,450
RxArchitectureComponents
Apache License 2.0
src/models/Eztv.kt
remylavergne
275,922,992
false
null
package models import com.squareup.moshi.JsonClass import enums.Category import enums.SubCategory import repositories.EztvRepository import java.util.* @JsonClass(generateAdapter = true) data class Eztv( override val id: String = UUID.randomUUID().toString(), override val category: Category? = null, override val subCategory: SubCategory? = null, override val url: String = "", override val filename: String = "", override val commentsCount: Int = 0, override val elapsedTimestamp: Long = 0, override val size: String = "", override val completions: Int = 0, override val seeders: Int = 0, override val leechers: Int = 0, override val domain: String = "Eztv.io" ) : Torrent() { companion object { fun fromHtml(html: String): Eztv { return Eztv( url = EztvRepository.domain + EztvRegex.URL.regex.find(html)?.groupValues?.last(), filename = EztvRegex.FILENAME.regex.find(html)?.groupValues?.last() ?: "", elapsedTimestamp = System.currentTimeMillis(), seeders = EztvRegex.SEEDERS.regex.find(html)?.groupValues?.last()?.toInt() ?: 0 ) } } } enum class EztvRegex(val regex: Regex) { URL(Regex("<a href=\"(\\/ep\\/.+?)\" title=\"")), FILENAME(Regex(">([A-Z|0-9][\\w -]+\\[eztv\\])<\\/a>")), SEEDERS(Regex("<font color=\"green\">(\\d*)<\\/font>")) }
1
Kotlin
0
0
7469f252dd7bfbd843dc36b9721a5ca94ccc2e24
1,422
torrent-scrapper
MIT License
app/src/main/java/in/sarangal/spannabletextview/KotlinActivity.kt
thesarangal
224,253,604
false
null
package `in`.sarangal.spannabletextview import `in`.sarangal.lib.spantastic.SpanModel import `in`.sarangal.lib.spantastic.Spantastic import android.graphics.Color import android.graphics.Typeface import android.os.Bundle import android.util.TypedValue import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import java.util.* import kotlin.collections.ArrayList class KotlinActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) /* Just Show Underline under specific word */ var sentence = "Spannable with single word underline." val tvOne = findViewById<TextView>(R.id.tv_one) Spantastic.Builder(tvOne, sentence) .setSpan("underline") .showUnderline(true) .apply() /* Show Underline and make Text BOLD for Multiple words */ sentence = "Spannable with underline and bold for multiple words." val strings: ArrayList<String> = ArrayList() strings.add("spannable") strings.add("underline") strings.add("bold") val tvTwo = findViewById<TextView>(R.id.tv_two) Spantastic.Builder(tvTwo, sentence) .setSpanList(strings) .showUnderline(true) .setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD)) .apply() /* Set Click on Multiple Words with Bold Style */ sentence = "Spannable with click, color, underline and bold for multiple words." strings.clear() strings.add("click") strings.add("color") strings.add("underline") strings.add("bold") val tvThree = findViewById<TextView>(R.id.tv_three) Spantastic.Builder(tvThree, sentence) .setSpanList(strings) .showUnderline(true) .setSpanColor(ContextCompat.getColor(this, R.color.colorAccent)) .setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD)) .setClickCallback(object : Spantastic.SpannableCallBack { override fun onSpanClick(spanString: String?, vararg `object`: Any?) { Toast.makeText( this@KotlinActivity, String.format( Locale.ENGLISH, "\"%s\" Word Clicked", spanString ), Toast.LENGTH_SHORT ) .show() } }) .apply() /* Set TextSize */ sentence = "Spantastic with custom text size for words." val tvFour = findViewById<TextView>(R.id.tv_four) Spantastic.Builder(tvFour, sentence) .setSpan("text size") .setTextSize( TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 20f, this.resources.displayMetrics ) ) .apply() /* Set Custom Spannables with unique styling */ sentence = "Spantastic with custom styles for multiple words." val tvFive = findViewById<TextView>(R.id.tv_five) val spanModelList: MutableList<SpanModel> = ArrayList() spanModelList.add( SpanModel( "custom", ContextCompat.getColor(this, R.color.colorPrimary), "custom", true, Typeface.create(Typeface.DEFAULT, Typeface.NORMAL), TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 15f, this.resources.displayMetrics ) ) ) spanModelList.add( SpanModel( "styles", ContextCompat.getColor(this, R.color.colorPrimaryDark), "styles", false, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 10f, this.resources.displayMetrics ) ) ) spanModelList.add( SpanModel( "for", ContextCompat.getColor(this, R.color.colorAccent), "for", true, Typeface.create(Typeface.SERIF, Typeface.ITALIC), TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 18f, this.resources.displayMetrics ) ) ) spanModelList.add( SpanModel( "multiple", Color.parseColor("#FFFF5722"), "multiple", null, Typeface.create(Typeface.MONOSPACE, Typeface.BOLD_ITALIC), TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 13f, this.resources.displayMetrics ) ) ) spanModelList.add( SpanModel( "words", Color.parseColor("#FF9C27B0"), "words", true, Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD), null ) ) Spantastic.Builder(tvFive, sentence) .setCustomSpanModel(spanModelList) .setClickCallback(object : Spantastic.SpannableCallBack { override fun onSpanClick(spanString: String?, vararg `object`: Any?) { Toast.makeText( this@KotlinActivity, String.format( Locale.ENGLISH, "\"%s\" Word Clicked", spanString ), Toast.LENGTH_SHORT ).show() } }) .apply() /* Developed By Sarangal */ sentence = "Developed with ❤ by Sarangal" val tvCredit = findViewById<TextView>(R.id.tv_credit) val creditModelList = ArrayList<SpanModel>() creditModelList.add( SpanModel( "❤", Color.parseColor("#FFFF2F2F"), "Love", null, Typeface.create(Typeface.DEFAULT, Typeface.NORMAL), null ) ) creditModelList.add( SpanModel( "Sarangal", Color.parseColor("#FF00BCD4"), "Sarangal", null, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), null ) ) Spantastic.Builder(tvCredit, sentence) .setCustomSpanModel(creditModelList) .apply() } }
0
Kotlin
0
1
a138ff5e1c419f88bfbf87cde6148a595c559182
6,625
spantasticlibrary
MIT License
src/main/kotlin/com/krossovochkin/json/JsonElements.kt
krossovochkin
295,803,995
false
null
package com.krossovochkin.json sealed class JsonElement class JsonObject : JsonElement() { val children: MutableMap<String, JsonElement> = mutableMapOf() fun add(key: String, element: JsonElement) { children[key] = element } } class JsonArray : JsonElement() { val children: MutableList<JsonElement> = mutableListOf() fun add(element: JsonElement) { children.add(element) } } data class JsonProperty( val value: Any? ) : JsonElement()
0
Kotlin
0
6
3f548b1aac6143de8e9348f95de9869dc99260ac
487
json.kt
Apache License 2.0
src/commonMain/kotlin/maryk/rocksdb/WaitingTransactions.kt
webnah
195,759,908
true
{"Kotlin": 707302}
package maryk.rocksdb expect class WaitingTransactions { /** Get the Column Family ID. */ fun getColumnFamilyId(): Long /** Get the key on which the transactions are waiting. */ fun getKey(): String /** Get the IDs of the waiting transactions. */ fun getTransactionIds(): LongArray }
0
Kotlin
0
0
92ec1677df1646d817abfd434929d27d430ec319
309
rocksdb
Apache License 2.0
src/benchmark/kotlin/com/github/michaelbull/result/BindingBenchmark.kt
jvanderwee
270,019,223
true
{"Kotlin": 87533}
package com.github.michaelbull.result import org.openjdk.jmh.annotations.Benchmark import org.openjdk.jmh.annotations.BenchmarkMode import org.openjdk.jmh.annotations.Mode import org.openjdk.jmh.annotations.OutputTimeUnit import org.openjdk.jmh.annotations.Scope import org.openjdk.jmh.annotations.State import org.openjdk.jmh.infra.Blackhole import java.util.concurrent.TimeUnit @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.MILLISECONDS) class BindingBenchmark { private object Error @Benchmark fun bindingSuccess(blackhole: Blackhole) { val result = binding<Int, Error> { val x = provideX().bind() val y = provideY().bind() x + y } blackhole.consume(result) } @Benchmark fun bindingFailure(blackhole: Blackhole) { val result = binding<Int, Error> { val x = provideX().bind() val z = provideZ().bind() x + z } blackhole.consume(result) } @Benchmark fun andThenSuccess(blackhole: Blackhole) { val result = provideX().andThen { x -> provideY().andThen { y -> Ok(x + y) } } blackhole.consume(result) } @Benchmark fun andThenFailure(blackhole: Blackhole) { val result = provideX().andThen { x -> provideZ().andThen { z -> Ok(x + z) } } blackhole.consume(result) } @State(Scope.Thread) private companion object { private fun provideX(): Result<Int, Error> = Ok(1) private fun provideY(): Result<Int, Error> = Ok(2) private fun provideZ(): Result<Int, Error> = Err(Error) } }
0
null
0
0
32ccaeea16f94162b3adb57871da7a4a623b1d5c
1,731
kotlin-result
ISC License
sink/src/main/kotlin/org/neo4j/connectors/kafka/sink/strategy/cud/CreateNode.kt
neo4j
665,115,793
false
{"Kotlin": 1457236, "JavaScript": 2839, "ANTLR": 2178, "Shell": 591}
/* * Copyright (c) "Neo4j" * Neo4j Sweden AB [https://neo4j.com] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.neo4j.connectors.kafka.sink.strategy.cud import org.neo4j.connectors.kafka.exceptions.InvalidDataException import org.neo4j.connectors.kafka.utils.MapUtils.getIterable import org.neo4j.connectors.kafka.utils.MapUtils.getMap import org.neo4j.cypherdsl.core.Cypher import org.neo4j.cypherdsl.core.renderer.Renderer import org.neo4j.driver.Query data class CreateNode(val labels: Set<String>, val properties: Map<String, Any?>) : Operation { override fun toQuery(renderer: Renderer): Query { val node = buildNode(labels, emptyMap(), Cypher.parameter("keys")).named("n") val stmt = renderer.render(Cypher.create(node).set(node, Cypher.parameter("properties")).build()) return Query(stmt, mapOf("properties" to properties)) } companion object { fun from(values: Map<String, Any?>): CreateNode { return CreateNode( values.getIterable<String>(Keys.LABELS)?.toSet() ?: emptySet(), values.getMap<String, Any?>(Keys.PROPERTIES) ?: throw InvalidDataException("No ${Keys.PROPERTIES} found")) } } }
6
Kotlin
5
4
47f615d59ad6dcf054471aa672499ab6b0fbc38b
1,707
neo4j-kafka-connector
Apache License 2.0
app/src/commonMain/kotlin/com/github/gdgvenezia/domain/Repository.kt
GDG-Venezia
200,714,923
false
null
package com.github.gdgvenezia.domain import com.github.gdgvenezia.com.github.gdgvenezia.domain.entities.SocialLinkModel import com.github.gdgvenezia.domain.entities.PhotoModel import com.github.gdgvenezia.domain.entities.EventModel import com.github.gdgvenezia.domain.entities.TeamMemberModel /** * @author <NAME> */ interface Repository { fun getEventList(): List<EventModel> fun getPastEventList(): List<EventModel> fun getFutureEventList(): List<EventModel> fun getTeamMemeberList(): List<TeamMemberModel> fun getPhotoList(): List<PhotoModel> fun getSocialLinkList(): List<SocialLinkModel> }
1
Kotlin
0
0
686b799b28947818a1c7bf9f06929cb24bcc9735
622
gdg-venezia-showcase-app-old
Apache License 2.0
stripe-ui-core/src/main/java/com/stripe/android/uicore/elements/PhoneNumberState.kt
stripe
6,926,049
false
{"Kotlin": 13814299, "Java": 102588, "Ruby": 45779, "HTML": 42045, "Shell": 23905, "Python": 21891}
package com.stripe.android.uicore.elements import androidx.annotation.RestrictTo import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @Serializable enum class PhoneNumberState { @SerialName("hidden") HIDDEN, @SerialName("optional") OPTIONAL, @SerialName("required") REQUIRED }
88
Kotlin
644
1,277
174b27b5a70f75a7bc66fdcce3142f1e51d809c8
378
stripe-android
MIT License
src/commonMain/kotlin/io/kotest/assertions/arrow/laws/Law.kt
cybernetics
416,432,126
true
{"Kotlin": 70380}
package io.kotest.assertions.arrow.laws import io.kotest.assertions.fail import io.kotest.core.spec.style.scopes.RootContext import io.kotest.core.test.TestContext import io.kotest.core.test.createTestName public data class Law(val name: String, val test: suspend TestContext.() -> Unit) public fun <A> A.equalUnderTheLaw(b: A, f: (A, A) -> Boolean = { a, b -> a == b }): Boolean = if (f(this, b)) true else fail("Found $this but expected: $b") public fun RootContext.testLaws(vararg laws: List<Law>): Unit = laws .flatMap { list: List<Law> -> list.asIterable() } .distinctBy { law: Law -> law.name } .forEach { law -> registration().addTest(createTestName(law.name), xdisabled = false, law.test) } public fun RootContext.testLaws(prefix: String, vararg laws: List<Law>): Unit = laws .flatMap { list: List<Law> -> list.asIterable() } .distinctBy { law: Law -> law.name } .forEach { law: Law -> registration().addTest(createTestName(prefix, law.name, true), xdisabled = false, law.test) }
0
null
0
0
d7ed71013b71ad906ec77af379958a11068d7907
1,043
kotest-extensions-arrow
Apache License 2.0
start-display/start-display-impl/src/main/java/com/samara/start_display_impl/domain/StartDisplayUseCaseImpl.kt
Salieri666
708,944,325
false
{"Kotlin": 40241}
package com.samara.start_display_impl.domain import android.content.Context import com.samara.core.di.modules.IoDispatcher import com.samara.start_display_api.domain.StartDisplayUseCase import kotlinx.coroutines.CoroutineDispatcher import javax.inject.Inject class StartDisplayUseCaseImpl @Inject constructor( private val context: Context, @IoDispatcher private val ioDispatcher: CoroutineDispatcher ) : StartDisplayUseCase { override fun getHelloWorld(): String { return "Hello world" } }
0
Kotlin
0
0
37bbb7d2b593d31f85590677a86958b2aa352230
515
WeatherFlex
Apache License 2.0
jvm/os-android/app/src/main/java/com/actyx/android/AxNodeService.kt
Actyx
393,963,530
false
{"Rust": 1995550, "TypeScript": 589830, "MDX": 351305, "CSS": 136436, "JavaScript": 78104, "Makefile": 22755, "Kotlin": 15138, "Dockerfile": 11429, "Shell": 10050, "HTML": 6858, "Python": 595, "Batchfile": 49}
package com.actyx.android import android.app.* import android.content.Intent import android.graphics.BitmapFactory import android.os.Build import android.os.IBinder import androidx.core.app.NotificationCompat import androidx.core.content.ContextCompat import com.actyx.android.node.AxNode import com.actyx.android.node.AxNodeMessageHandler import com.actyx.android.util.Logger class AxNodeService : Service() { private val log = Logger() private lateinit var axNode: AxNode private var shutdownInitiatedByUser = false private val msgHandler: AxNodeMessageHandler = { code, msg -> log.warn("onAxNodeMessage: $code, $msg") stopForeground(true) stopSelf() Intent(this, MainActivity::class.java).also { val message = when (code) { AxNode.NODE_STOPPED_BY_NODE -> "Code: NODE_STOPPED_BY_NODE\n" + "Message: $msg\n" + "Please contact your IT administrator." AxNode.NODE_STOPPED_BY_NODE_UI -> "" // stopped by the user AxNode.NODE_STOPPED_BY_HOST -> "Code: NODE_STOPPED_BY_HOST\n" + "Message: $msg\n" + "Please contact your IT administrator." AxNode.FAILED_TO_START_NODE -> "Code: FAILED_TO_START_NODE\n" + "Message: $msg\n" + "Please contact your IT administrator." AxNode.ERR_PORT_COLLISION -> "Code: ERR_PORT_COLLISION\n" + "Message: $msg\n" + "Please contact your IT administrator." else -> "Code: $code\n" + "Message: $msg\n" + "Please contact your IT administrator." } it.putExtra(AXNODE_MESSAGE, message) it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(it) } } override fun onCreate() { axNode = AxNode(this, msgHandler) log.info("Initialization of native platform lib done") } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { log.info("onStartCommand, intent: $intent") if (intent?.action.equals(STOPFOREGROUND_ACTION)) { log.info("Received Stop Foreground Intent") axNode.shutdownByUser() shutdownInitiatedByUser = true } startForeground(ONGOING_NOTIFICATION_ID, setupNotification()) return START_STICKY } override fun onBind(intent: Intent?): IBinder? { return null } override fun onLowMemory() { log.warn("onLowMemory") super.onLowMemory() } override fun onDestroy() { log.info("onDestroy") if (!shutdownInitiatedByUser) { // Try to shutdown gracefully ax node axNode.shutdownBySystem() } super.onDestroy() } private fun setupNotification(): Notification { val intent = Intent(this, MainActivity::class.java) val pendingIntent = PendingIntent.getActivity(this, 0, intent, 0) val contextText = getString(R.string.actyx_is_running) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel( NOTIFICATION_CHANNEL_ID, getString(R.string.background_services_channel_name), NotificationManager.IMPORTANCE_LOW ) channel.description = getString(R.string.background_services_channel_description) getSystemService(NotificationManager::class.java)?.createNotificationChannel(channel) } val requestQuitIntent = Intent(this, MainActivity::class.java).apply { action = REQUEST_QUIT } return NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID) .setOngoing(true) .setContentTitle(contextText) .setSmallIcon(R.drawable.actyx_icon) .setColor(ContextCompat.getColor(this, R.color.colorPrimary)) .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.actyx_icon)) .setCategory(Notification.CATEGORY_SERVICE) .setContentIntent(pendingIntent) .setPriority(NotificationCompat.PRIORITY_LOW) .addAction( 0, getString(R.string.quit), PendingIntent.getActivity(this, 0, requestQuitIntent, 0) ) .build() } companion object { const val NOTIFICATION_CHANNEL_ID = "com.actyx.android" const val ONGOING_NOTIFICATION_ID = 7 const val STOPFOREGROUND_ACTION = "com.actyx.android.STOPFOREGROUND_ACTION" const val AXNODE_MESSAGE = "com.actyx.android.AXNODE_MESSAGE" const val REQUEST_QUIT = "com.actyx.android.REQUEST_QUIT" } }
62
Rust
7
241
1f4bd6699a9345bde630248294b10bbc902d7230
4,299
Actyx
Apache License 2.0
service-scheduling/src/test/kotlin/djei/clockpanda/scheduling/optimization/constraint/OptimizationConstraintsProviderTest.kt
Djei
676,192,849
false
null
package djei.clockpanda.scheduling.optimization.constraint import ai.timefold.solver.test.api.score.stream.ConstraintVerifier import djei.clockpanda.model.LocalTimeSpan import djei.clockpanda.model.fixtures.UserFixtures import djei.clockpanda.scheduling.model.CalendarEventType import djei.clockpanda.scheduling.model.fixtures.CalendarEventFixtures import djei.clockpanda.scheduling.optimization.model.Event import djei.clockpanda.scheduling.optimization.model.OptimizationProblem import djei.clockpanda.scheduling.optimization.model.TimeGrain import kotlinx.datetime.DayOfWeek import kotlinx.datetime.Instant import kotlinx.datetime.LocalTime import kotlinx.datetime.TimeZone import org.junit.jupiter.api.Test class OptimizationConstraintsProviderTest { private val constraintVerifier = ConstraintVerifier.build( OptimizationConstraintsProvider(), OptimizationProblem::class.java, Event::class.java ) @Test fun `penalize if focus time event overlaps with other events`() { val focusTime1 = Event( id = "focus-time-1", type = CalendarEventType.FOCUS_TIME, startTimeGrain = TimeGrain( start = Instant.parse("2021-01-01T00:00:00Z") ), durationInTimeGrains = 8, // End time: 2021-01-01T02:00:00Z originalCalendarEvent = null, owner = UserFixtures.userWithPreferences.email ) val focusTime2 = Event( id = "focus-time-2", type = CalendarEventType.FOCUS_TIME, startTimeGrain = TimeGrain( start = Instant.parse("2021-01-01T01:45:00Z") ), durationInTimeGrains = 8, // End time: 2021-01-01T03:45:00Z originalCalendarEvent = null, owner = UserFixtures.userWithPreferences.email ) // External event 1 partially overlaps with focus time val externalEvent1 = Event( id = "6fpknj2tjkc2ee2v32q7ve8t04", type = CalendarEventType.EXTERNAL_EVENT, startTimeGrain = TimeGrain( start = Instant.parse("2021-01-01T03:00:00Z") ), durationInTimeGrains = 8, // End time: 2021-01-01T05:00:00Z originalCalendarEvent = CalendarEventFixtures.externalTypeCalendarEvent, owner = UserFixtures.userWithPreferences.email ) // External event 2 does not overlap with focus time but with external event 1 (which should not be penalized) val externalEvent2 = Event( id = "bpokgerzlkc2ee2v32asdlklw", type = CalendarEventType.EXTERNAL_EVENT, startTimeGrain = TimeGrain( start = Instant.parse("2021-01-01T04:45:00Z") ), durationInTimeGrains = 8, // End time: 2021-01-01T06:45:00Z originalCalendarEvent = CalendarEventFixtures.externalTypeCalendarEvent, owner = UserFixtures.userWithPreferences.email ) // External event 3 is completely contained within focus time val externalEvent3 = Event( id = "asdqwejkasdjo9i3jodas236", type = CalendarEventType.EXTERNAL_EVENT, startTimeGrain = TimeGrain( start = Instant.parse("2021-01-01T02:00:00Z") ), durationInTimeGrains = 4, // End time: 2021-01-01T03:00:00Z originalCalendarEvent = CalendarEventFixtures.externalTypeCalendarEvent, owner = UserFixtures.userWithPreferences.email ) // External event 4 completely contains focus time val externalEvent4 = Event( id = "asdjoilkjio3940dsfoj312", type = CalendarEventType.EXTERNAL_EVENT, startTimeGrain = TimeGrain( start = Instant.parse("2021-01-01T01:30:00Z") ), durationInTimeGrains = 24, // End time: 2021-01-01T07:30:00Z originalCalendarEvent = CalendarEventFixtures.externalTypeCalendarEvent, owner = UserFixtures.userWithPreferences.email ) val solution = OptimizationProblem( parameters = OptimizationProblem.OptimizationProblemParameters( optimizationReferenceInstant = Instant.parse("2021-01-01T00:00:00Z"), optimizationMaxRangeInWeeks = 2, weekStartDayOfWeek = DayOfWeek.MONDAY ), schedule = listOf( focusTime1, focusTime2, externalEvent1, externalEvent2, externalEvent3, externalEvent4 ), users = listOf(UserFixtures.userWithPreferences) ) // Following overlaps are penalized: // - focusTime1 partially overlaps with focusTime2 - 15 mins // - externalEvent1 partially overlaps with focusTime2 - 45 mins // - externalEvent3 is fully contained within focusTime2 - 60 mins // - externalEvent4 fully contains focusTime2 - 120 mins // - externalEvent4 partially overlaps with focusTime1 - 30 mins constraintVerifier.verifyThat(OptimizationConstraintsProvider::clockPandaEventsShouldNotOverlapWithOtherEvents) .givenSolution(solution) .penalizesBy(270) } @Test fun `penalize if focus time is outside of user preferences working hours`() { val focusTimeOutsideWorkingHours = Event( id = "1", type = CalendarEventType.FOCUS_TIME, startTimeGrain = TimeGrain( start = Instant.parse("2021-01-01T08:00:00Z") ), durationInTimeGrains = 8, originalCalendarEvent = null, owner = UserFixtures.userWithPreferences.email ) val focusTimeInsideWorkingHours = Event( id = "2", type = CalendarEventType.FOCUS_TIME, startTimeGrain = TimeGrain( start = Instant.parse("2021-01-01T14:00:00Z") ), durationInTimeGrains = 8, originalCalendarEvent = null, owner = UserFixtures.userWithPreferences.email ) val solution = OptimizationProblem( parameters = OptimizationProblem.OptimizationProblemParameters( optimizationReferenceInstant = Instant.parse("2021-01-01T00:00:00Z"), optimizationMaxRangeInWeeks = 2, weekStartDayOfWeek = DayOfWeek.MONDAY ), schedule = listOf(focusTimeOutsideWorkingHours, focusTimeInsideWorkingHours), users = listOf(UserFixtures.userWithPreferences) ) // Focus time 1 is outside of working hours and penalized for 60 minutes // Focus time 2 is inside of working hours and not penalized constraintVerifier.verifyThat(OptimizationConstraintsProvider::clockPandaEventsShouldNotBeOutsideOfWorkingHours) .givenSolution(solution) .penalizesBy(60) } @Test fun `penalize if focus time start and end are not on the same day (in user preferred timezone)`() { val userPreferenceWithEuropeLondonPreferredTimezone = UserFixtures.userPreferences.copy( preferredTimeZone = TimeZone.of("Europe/London") ) val user = UserFixtures.userWithPreferences.copy( preferences = userPreferenceWithEuropeLondonPreferredTimezone ) val focusTimeWithStartAndEndDateNotSameDay = Event( id = "1", type = CalendarEventType.FOCUS_TIME, startTimeGrain = TimeGrain( start = Instant.parse("2021-01-01T23:00:00Z") ), durationInTimeGrains = 24, originalCalendarEvent = null, owner = user.email ) val focusTimeNotPassingInUserTimeZone = Event( id = "2", type = CalendarEventType.FOCUS_TIME, startTimeGrain = TimeGrain( start = Instant.parse("2021-07-07T23:45:00Z") ), durationInTimeGrains = 2, originalCalendarEvent = null, owner = user.email ) val externalEventDoesNotCount = Event( id = "3", type = CalendarEventType.EXTERNAL_EVENT, startTimeGrain = TimeGrain( start = Instant.parse("2021-01-01T23:00:00Z") ), durationInTimeGrains = 24, originalCalendarEvent = CalendarEventFixtures.externalTypeCalendarEvent, owner = user.email ) val solution = OptimizationProblem( parameters = OptimizationProblem.OptimizationProblemParameters( optimizationReferenceInstant = Instant.parse("2021-01-01T00:00:00Z"), optimizationMaxRangeInWeeks = 2, weekStartDayOfWeek = DayOfWeek.MONDAY ), schedule = listOf( focusTimeWithStartAndEndDateNotSameDay, focusTimeNotPassingInUserTimeZone, externalEventDoesNotCount ), users = listOf(user) ) constraintVerifier.verifyThat(OptimizationConstraintsProvider::clockPandaEventsShouldStartAndEndOnTheSameDay) .givenSolution(solution) .penalizesBy(1) } @Test fun `penalize if total focus time does not meet user target`() { // userPreferences is set to preferred focus time range 14:00 - 17:00 val userPreferences = UserFixtures.userPreferences.copy( targetFocusTimeHoursPerWeek = 20 ) val user = UserFixtures.userWithPreferences.copy( preferences = userPreferences ) val threeHoursOfFocusTime = Event( id = "1", type = CalendarEventType.FOCUS_TIME, startTimeGrain = TimeGrain( start = Instant.parse("2021-01-01T00:00:00Z") ), durationInTimeGrains = 12, originalCalendarEvent = null, owner = user.email ) val fourHoursOfFocusTime = Event( id = "2", type = CalendarEventType.FOCUS_TIME, startTimeGrain = TimeGrain( start = Instant.parse("2021-01-02T00:00:00Z") ), durationInTimeGrains = 16, originalCalendarEvent = null, owner = user.email ) val externalEvent1 = Event( id = "3", type = CalendarEventType.EXTERNAL_EVENT, startTimeGrain = TimeGrain( start = Instant.parse("2021-01-03T00:00:00Z") ), durationInTimeGrains = 8, originalCalendarEvent = CalendarEventFixtures.externalTypeCalendarEvent, owner = user.email ) val solution = OptimizationProblem( parameters = OptimizationProblem.OptimizationProblemParameters( optimizationReferenceInstant = Instant.parse("2021-01-01T00:00:00Z"), optimizationMaxRangeInWeeks = 2, weekStartDayOfWeek = DayOfWeek.MONDAY ), schedule = listOf(threeHoursOfFocusTime, fourHoursOfFocusTime, externalEvent1), users = listOf(UserFixtures.userWithPreferences) ) // User preference wants 20 hours of focus time per week // Week 1 from 2020-12-28T00:00:00Z to 2021-01-04T00:00:00Z // Week 2 from 2021-01-04T00:00:00Z to 2021-01-11T00:00:00Z // Week 3 from 2021-01-11T00:00:00Z to 2021-01-18T00:00:00Z // Week 1 has 2 focus times of 7 hours in it // Week 2 and 3 have 0 focus times in them constraintVerifier.verifyThat(OptimizationConstraintsProvider::focusTimeTotalAmountPartiallyMeetingUserWeeklyTarget) .givenSolution(solution) .penalizesBy(13 * 60) constraintVerifier.verifyThat(OptimizationConstraintsProvider::focusTimeTotalAmountIsZeroInAWeekForGivenUser) .givenSolution(solution) .penalizesBy(2 * 20 * 60) } @Test fun `penalize if existing focus time is moved`() { val existingFocusTimeThatHasNotMoved = Event( id = "1", type = CalendarEventType.FOCUS_TIME, startTimeGrain = TimeGrain( start = Instant.parse("2021-01-01T00:00:00Z") ), durationInTimeGrains = 12, originalCalendarEvent = CalendarEventFixtures.focusTimeCalendarEvent1, owner = UserFixtures.userWithPreferences.email ) val existingFocusTimeThatHasMoved = Event( id = "2", type = CalendarEventType.FOCUS_TIME, startTimeGrain = TimeGrain( start = Instant.parse("2021-01-12T00:00:00Z") ), durationInTimeGrains = 4, originalCalendarEvent = CalendarEventFixtures.focusTimeCalendarEvent2, owner = UserFixtures.userWithPreferences.email ) val externalEvent1 = Event( id = "3", type = CalendarEventType.EXTERNAL_EVENT, startTimeGrain = TimeGrain( start = Instant.parse("2021-01-03T00:00:00Z") ), durationInTimeGrains = 8, originalCalendarEvent = CalendarEventFixtures.externalTypeCalendarEvent, owner = UserFixtures.userWithPreferences.email ) val solution = OptimizationProblem( parameters = OptimizationProblem.OptimizationProblemParameters( optimizationReferenceInstant = Instant.parse("2021-01-01T00:00:00Z"), optimizationMaxRangeInWeeks = 2, weekStartDayOfWeek = DayOfWeek.MONDAY ), schedule = listOf(existingFocusTimeThatHasNotMoved, existingFocusTimeThatHasMoved, externalEvent1), users = listOf(UserFixtures.userWithPreferences) ) constraintVerifier.verifyThat(OptimizationConstraintsProvider::existingFocusTimeShouldOnlyBeMovedIfTheyGiveMoreFocusTime) .givenSolution(solution) .penalizesBy(30) } @Test fun `penalize if focus time is not within preferred focus time range`() { // userPreferences is set to preferred focus time range 14:00 - 17:00 val userPreferences = UserFixtures.userPreferences.copy( preferredTimeZone = TimeZone.of("Europe/London"), preferredFocusTimeRange = LocalTimeSpan(LocalTime(14, 0), LocalTime(17, 0)) ) val user = UserFixtures.userWithPreferences.copy( preferences = userPreferences ) val focusTimeOutsidePreferredRange = Event( id = "1", type = CalendarEventType.FOCUS_TIME, startTimeGrain = TimeGrain( start = Instant.parse("2021-03-24T07:00:00Z") ), durationInTimeGrains = 12, originalCalendarEvent = null, owner = user.email ) val focusTimeWithinPreferredRange = Event( id = "2", type = CalendarEventType.FOCUS_TIME, startTimeGrain = TimeGrain( start = Instant.parse("2021-03-25T16:00:00Z") ), durationInTimeGrains = 4, originalCalendarEvent = null, owner = user.email ) val externalEvent1OutsidePreferredRange = Event( id = "3", type = CalendarEventType.EXTERNAL_EVENT, startTimeGrain = TimeGrain( start = Instant.parse("2021-03-26T07:00:00Z") ), durationInTimeGrains = 8, originalCalendarEvent = CalendarEventFixtures.externalTypeCalendarEvent, owner = user.email ) val solution = OptimizationProblem( parameters = OptimizationProblem.OptimizationProblemParameters( optimizationReferenceInstant = Instant.parse("2021-01-01T00:00:00Z"), optimizationMaxRangeInWeeks = 2, weekStartDayOfWeek = DayOfWeek.MONDAY ), schedule = listOf( focusTimeOutsidePreferredRange, focusTimeWithinPreferredRange, externalEvent1OutsidePreferredRange ), users = listOf(user) ) constraintVerifier.verifyThat(OptimizationConstraintsProvider::focusTimeShouldBeWithinPreferredFocusTimeRange) .givenSolution(solution) .penalizesBy(12 * 15) } @Test fun `penalize if focus time is not scheduled on the hour or half hour`() { val userPreferences = UserFixtures.userPreferences.copy( preferredTimeZone = TimeZone.of("Europe/London") ) val user = UserFixtures.userWithPreferences.copy( preferences = userPreferences ) val onTheHour = Event( id = "1", type = CalendarEventType.FOCUS_TIME, startTimeGrain = TimeGrain( start = Instant.parse("2021-03-24T07:00:00Z") ), durationInTimeGrains = 12, originalCalendarEvent = null, owner = user.email ) val onTheHalfHour = Event( id = "2", type = CalendarEventType.FOCUS_TIME, startTimeGrain = TimeGrain( start = Instant.parse("2021-03-25T16:00:00Z") ), durationInTimeGrains = 4, originalCalendarEvent = null, owner = user.email ) val at15Minutes = Event( id = "3", type = CalendarEventType.FOCUS_TIME, startTimeGrain = TimeGrain( start = Instant.parse("2021-03-26T16:15:00Z") ), durationInTimeGrains = 4, originalCalendarEvent = null, owner = user.email ) val at45Minutes = Event( id = "4", type = CalendarEventType.FOCUS_TIME, startTimeGrain = TimeGrain( start = Instant.parse("2021-03-27T16:45:00Z") ), durationInTimeGrains = 4, originalCalendarEvent = null, owner = user.email ) val externalEvent = Event( id = "5", type = CalendarEventType.EXTERNAL_EVENT, startTimeGrain = TimeGrain( start = Instant.parse("2021-03-26T07:15:00Z") ), durationInTimeGrains = 8, originalCalendarEvent = CalendarEventFixtures.externalTypeCalendarEvent, owner = user.email ) val solution = OptimizationProblem( parameters = OptimizationProblem.OptimizationProblemParameters( optimizationReferenceInstant = Instant.parse("2021-01-01T00:00:00Z"), optimizationMaxRangeInWeeks = 2, weekStartDayOfWeek = DayOfWeek.MONDAY ), schedule = listOf( onTheHour, onTheHalfHour, at15Minutes, at45Minutes, externalEvent ), users = listOf(user) ) constraintVerifier.verifyThat(OptimizationConstraintsProvider::focusTimesShouldBeScheduledOnTheHourOrHalfHour) .givenSolution(solution) .penalizesBy(2) } }
0
Kotlin
0
2
e6869ca9a7edb0dcaa3cfe41eb62c7946bb04769
19,343
clockpanda
Apache License 2.0
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/dotnet/coverage/serviceMessage/DotnetCoverageParametersBase.kt
JetBrains
49,584,664
false
null
package jetbrains.buildServer.dotnet.coverage.serviceMessage import jetbrains.buildServer.agent.AgentRunningBuild import jetbrains.buildServer.agent.BuildProgressLogger import jetbrains.buildServer.dotnet.CoverageConstants import jetbrains.buildServer.dotnet.coverage.utils.PathUtil import java.io.File abstract class DotnetCoverageParametersBase(protected val runningBuild: AgentRunningBuild) : DotnetCoverageParameters { abstract override fun getRunnerParameter(key: String): String? override fun getConfigurationParameter(key: String): String? { return runningBuild.sharedConfigParameters[key] } override fun getConfigurationParameters(): Map<String, String> { return runningBuild.sharedConfigParameters } override fun getBuildEnvironmentVariables(): Map<String, String> { return runningBuild.sharedBuildParameters.environmentVariables } override fun getCoverageToolName(): String? { return getRunnerParameter(CoverageConstants.PARAM_TYPE) } override fun getCheckoutDirectory(): File { return runningBuild.checkoutDirectory } override fun getBuildName(): String { return runningBuild.projectName + " / " + runningBuild.buildTypeName } override fun getTempDirectory(): File { val temDirectory = File(runningBuild.agentTempDirectory, "dotNetCoverageResults") if (temDirectory.exists() && temDirectory.isFile) { temDirectory.delete() } if (!temDirectory.exists()) { temDirectory.mkdirs() } return temDirectory } override fun resolvePath(path: String): File? { return PathUtil.resolvePath(runningBuild, path) } override fun resolvePathToTool(path: String, toolName: String): File? { return PathUtil.resolvePathToTool(runningBuild, path, toolName) } override fun getBuildLogger(): BuildProgressLogger { return runningBuild.buildLogger } }
3
null
25
94
5f444c22b3354955d1060e08478d543d2b0b99b0
1,978
teamcity-dotnet-plugin
Apache License 2.0
slicing-android/app/src/main/java/com/crescentflare/slicinggame/infrastructure/coreextensions/StringSHA256.kt
crescentflare
242,400,251
false
null
package com.crescentflare.slicinggame.infrastructure.coreextensions import java.security.MessageDigest /** * Core extension: extends string to calculate an SHA256 hash */ fun String.sha256(): String { // Try decoding try { // Obtain digest val messageDigest = MessageDigest.getInstance("SHA256") val digest = messageDigest.digest(this.toByteArray()) // Convert to hex and return val hexArray = "0123456789abcdef".toCharArray() val hexChars = CharArray(digest.size * 2) for (j in digest.indices) { val v = digest[j].toInt() and 0xFF hexChars[j * 2] = hexArray[v.ushr(4)] hexChars[j * 2 + 1] = hexArray[v and 0x0F] } return String(hexChars) } catch (ignored: Exception) { } // Return recognizable error when failed return "#error" }
0
Kotlin
0
1
8afa882f046e43e373af15e60244225720019ca3
869
SlicingGame
MIT License
app/src/main/java/com/example/mylotteryapp/screens/firstScreen/TopBar.kt
petyo-petkov
766,056,034
false
{"Kotlin": 67814}
package com.example.mylotteryapp.screens.firstScreen import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column 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.Delete import androidx.compose.material3.Card import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ShapeDefaults import androidx.compose.material3.Text 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.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.mylotteryapp.viewModels.RealmViewModel import kotlin.text.Typography.euro @Composable fun TopBar(realmViewModel: RealmViewModel) { var showDialog by remember { mutableStateOf(false) } val selected = realmViewModel.selectedCard val boleto = realmViewModel.boleto val gastado = realmViewModel.gastado val ganado = realmViewModel.ganado val balance = ganado - gastado Card( modifier = Modifier .fillMaxWidth(), shape = ShapeDefaults.ExtraSmall, ) { // Nah Row( modifier = Modifier .fillMaxWidth() .size(50.dp) .background(color = MaterialTheme.colorScheme.primaryContainer), ) { // Vacio } // Info Row( modifier = Modifier .fillMaxWidth() .size(64.dp) .background(color = MaterialTheme.colorScheme.secondaryContainer), horizontalArrangement = Arrangement.SpaceAround, verticalAlignment = Alignment.CenterVertically ) { InfoColumn(text1 = "Gastado", text2 = "$gastado $euro") InfoColumn(text1 = "Ganado", text2 = "$ganado $euro") InfoColumn(text1 = "Balance", text2 = "$balance $euro") } HorizontalDivider(color = Color.Black, thickness = 0.4.dp) if (selected) { Row( modifier = Modifier .background(MaterialTheme.colorScheme.errorContainer) .fillMaxWidth(), horizontalArrangement = Arrangement.Center ) { IconButton(onClick = { showDialog = true } ) { Icon( imageVector = Icons.Default.Delete, contentDescription = null, tint = Color.Red ) } } DialogoBorrar( show = showDialog, onDismiss = { showDialog = false }, onConfirm = { realmViewModel.deleteBoleto(boleto!!._id) realmViewModel.boleto = null realmViewModel.selectedCard = false }, mensaje = "Borrar boleto seleccionado ?" ) } } } @Composable fun InfoColumn( text1: String, text2: String ) { Column( modifier = Modifier, verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text(text1, fontSize = 16.sp, fontWeight = FontWeight.Medium) Text(text2, fontSize = 16.sp, fontWeight = FontWeight.Medium) } }
0
Kotlin
0
0
9a5e07a1136546c77b776253e4575ad5019cf74e
3,968
MyLotteryApp
MIT License
idea/testData/intentions/branched/ifThenToElvis/notApplicableForSimpleKotlinNPE.kt
JakeWharton
99,388,807
true
null
// IS_APPLICABLE: false // WITH_RUNTIME fun main(args: Array<String>) { val t: String? = "abc" if (t != null<caret>) t else throw KotlinNullPointerException() }
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
169
kotlin
Apache License 2.0
app/src/main/java/com/norm/firebasedemo/MainActivity.kt
mixin27
242,341,015
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "JSON": 1, "Proguard": 1, "Kotlin": 6, "XML": 14, "Java": 1}
package com.norm.firebasedemo import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val auth = FirebaseAuth.getInstance() val db = FirebaseFirestore.getInstance() db.collection("users") .addSnapshotListener { snapshot, exception -> if (exception != null) { Log.w(TAG, "Listen failed.", exception) return@addSnapshotListener } val users = ArrayList<User>() for (doc in snapshot!!) { val user = doc.toObject(User::class.java).withId<User>(doc.id) users.add(user) } Log.d(TAG, "Current users: $users") var msg = "" for (user in users) { msg = "${user.email}\n${user.name}\n${user.bio}" } textView.text = msg } btnLogOut.setOnClickListener { if (auth.currentUser != null) { auth.signOut() startActivity(Intent(this, AuthActivity::class.java)) finish() } } } companion object { private var TAG = MainActivity::class.java.simpleName } }
0
Kotlin
0
0
cb021f200b9e9b482ca1492a8a69afd45b00b1de
1,680
firebase-demo
MIT License
crouter-api/src/main/java/me/wcy/router/starter/RouterStarterFactory.kt
wangchenyan
207,708,657
false
null
package me.wcy.router.starter import android.annotation.SuppressLint import android.app.Activity import android.app.Fragment import android.content.Context import android.os.Build import android.util.Log import androidx.fragment.app.FragmentActivity import androidx.fragment.app.FragmentManager import me.wcy.router.CRouter import me.wcy.router.RouterUtils /** * Created by wcy on 2020/12/30. */ object RouterStarterFactory { private const val FRAGMENT_TAG = "crouter_fragment_tag" fun create(context: Context): RouterStarter? { if (context is FragmentActivity) { if (RouterUtils.isActivityAlive(context).not()) { Log.w( CRouter.TAG, "RouterStarterFactory.create, context is FragmentActivity, but is not alive" ) return null } val supportFragmentManager = getSupportFragmentManager(context) var permissionSupportFragment = supportFragmentManager.findFragmentByTag(FRAGMENT_TAG) as FragmentXStarter? if (permissionSupportFragment == null) { permissionSupportFragment = FragmentXStarter() supportFragmentManager.beginTransaction() .add(permissionSupportFragment, FRAGMENT_TAG) .commitNowAllowingStateLoss() } return permissionSupportFragment } else if (context is Activity) { if (RouterUtils.isActivityAlive(context).not()) { Log.w( CRouter.TAG, "RouterStarterFactory.create, context is Activity, but is not alive" ) return null } val fragmentManager = getFragmentManager(context) var permissionFragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG) as FragmentStarter? if (permissionFragment == null) { permissionFragment = FragmentStarter() fragmentManager.beginTransaction() .add(permissionFragment, FRAGMENT_TAG) .commitAllowingStateLoss() // make it commit like commitNow fragmentManager.executePendingTransactions() } return permissionFragment } else { return ContextStarter(context) } } private fun getSupportFragmentManager(activity: FragmentActivity): FragmentManager { val fragmentManager = activity.supportFragmentManager // some specific rom will provide a null List val childAvailable = fragmentManager.fragments != null if (childAvailable && fragmentManager.fragments.isNotEmpty() && fragmentManager.fragments[0] != null ) { return fragmentManager.fragments[0].childFragmentManager } else { return fragmentManager } } @SuppressLint("PrivateApi") private fun getFragmentManager(activity: Activity): android.app.FragmentManager { val fragmentManager = activity.fragmentManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (fragmentManager.fragments != null && fragmentManager.fragments.isNotEmpty() && fragmentManager.fragments[0] != null ) { return fragmentManager.fragments[0].childFragmentManager } } else { try { val fragmentsField = Class.forName("android.app.FragmentManagerImpl") .getDeclaredField("mAdded") fragmentsField.isAccessible = true val fragmentList = fragmentsField[fragmentManager] as List<Fragment?> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && fragmentList != null && fragmentList.isNotEmpty() && fragmentList[0] != null ) { Log.d(CRouter.TAG, "reflect get child fragmentManager success") return fragmentList[0]!!.childFragmentManager } } catch (e: Exception) { Log.w(CRouter.TAG, "try to get childFragmentManager failed $e") e.printStackTrace() } } return fragmentManager } }
0
Kotlin
0
8
890fe952d61e721ba03fb3e451bfd7141404991c
4,392
crouter
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/lambda/eventsources/BaseStreamEventSourcePropsDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.lambda.eventsources import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.lambda.eventsources.BaseStreamEventSourceProps @Generated public fun buildBaseStreamEventSourceProps(initializer: @AwsCdkDsl BaseStreamEventSourceProps.Builder.() -> Unit): BaseStreamEventSourceProps = BaseStreamEventSourceProps.Builder().apply(initializer).build()
1
Kotlin
0
0
e08d201715c6bd4914fdc443682badc2ccc74bea
476
aws-cdk-kt
Apache License 2.0
domain/src/main/java/com/mkdev/domain/intractor/ConvertCurrencyUseCase.kt
msddev
469,005,380
false
null
package com.mkdev.domain.intractor import com.mkdev.domain.model.ConvertCurrencyUIModel import com.mkdev.domain.model.ExchangeParams import com.mkdev.domain.repository.BalanceRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flow import javax.inject.Inject class ConvertCurrencyUseCase @Inject constructor( private val balanceRepository: BalanceRepository, ) : BaseUseCase<ExchangeParams, Flow<ConvertCurrencyUIModel>> { override suspend fun invoke(params: ExchangeParams): Flow<ConvertCurrencyUIModel> = flow { if (params.amount <= 0.0) { emit(ConvertCurrencyUIModel.Error("Sell amount is less than zero")) return@flow } val currentSellBalances = balanceRepository.getBalance(params.sellRate.currencyName).first() if (params.amount >= currentSellBalances.balance) { emit(ConvertCurrencyUIModel.Error("Current balance is less than sell amount")) return@flow } val buyCurrency = params.buyRate.rate * params.amount emit(ConvertCurrencyUIModel.Success(buyCurrency)) } }
0
Kotlin
0
0
ca6eacd6b5c6e4e612c766cf9b2df45f6b7ed9d0
1,156
Currency-Exchange
Apache License 2.0
mmdownloader/src/test/java/pl/kwiatekmichal/mkdownloader/util/ExtensionTest.kt
kwiatekM
196,874,772
false
null
package pl.kwiatekmichal.mkdownloader.util import junit.framework.TestCase.assertEquals import org.junit.Test import pl.kwiatekmichal.mkdownloader.Constants class ExtensionTest { @Test fun testValidateUrlTest() { val url = "http://www.orimi.com/pdf-test.pdf" val extension = Constants.FileExtension.PDF val expected = true val actual = url.isValidateUrl(fileExtension = extension) assertEquals("Validate URL string 1", expected, actual) } @Test fun testGetFileExtension() { val url = "http://www.orimi.com/pdf-test.pdf" val expected = Constants.FileExtension.PDF val actual = url.getFileExtension() assertEquals(expected, actual) } }
1
null
1
1
c5e1e032e939c4b4b2940f772b0924c83e3196fd
733
MMDownloader
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem2028/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 826621}
package com.hj.leetcode.kotlin.problem2028 /** * LeetCode page: [2028. Find Missing Observations](https://leetcode.com/problems/find-missing-observations/); */ class Solution { /* Complexity: * Time O(m+n) and Auxiliary Space O(1) where m is the size of rolls. */ fun missingRolls( rolls: IntArray, mean: Int, n: Int, ): IntArray { val m = rolls.size val mRollsSum = rolls.sum() val nRollsSum = mean * (m + n) - mRollsSum if (nRollsSum !in n..(6 * n)) { return IntArray(0) } val (average, shortage) = Pair(nRollsSum / n, nRollsSum % n) return IntArray(n) { i -> if (i < shortage) average + 1 else average } } }
1
Kotlin
0
2
0bb03818f6a55eeedee49114f80fae6b03b304d8
754
hj-leetcode-kotlin
Apache License 2.0
src/test/kotlin/eZmaxApi/models/EzsigndocumentApplyEzsigntemplateglobalV1RequestTest.kt
eZmaxinc
271,950,932
false
{"Kotlin": 6909939}
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package eZmaxApi.models import io.kotlintest.shouldBe import io.kotlintest.specs.ShouldSpec import eZmaxApi.models.EzsigndocumentApplyEzsigntemplateglobalV1Request class EzsigndocumentApplyEzsigntemplateglobalV1RequestTest : ShouldSpec() { init { // uncomment below to create an instance of EzsigndocumentApplyEzsigntemplateglobalV1Request //val modelInstance = EzsigndocumentApplyEzsigntemplateglobalV1Request() // to test the property `fkiEzsigntemplateglobalID` - The unique ID of the Ezsigntemplateglobal should("test fkiEzsigntemplateglobalID") { // uncomment below to test the property //modelInstance.fkiEzsigntemplateglobalID shouldBe ("TODO") } // to test the property `aSEzsigntemplateglobalsigner` should("test aSEzsigntemplateglobalsigner") { // uncomment below to test the property //modelInstance.aSEzsigntemplateglobalsigner shouldBe ("TODO") } // to test the property `aPkiEzsignfoldersignerassociationID` should("test aPkiEzsignfoldersignerassociationID") { // uncomment below to test the property //modelInstance.aPkiEzsignfoldersignerassociationID shouldBe ("TODO") } } }
0
Kotlin
0
0
961c97a9f13f3df7986ea7ba55052874183047ab
1,538
eZmax-SDK-kotlin
MIT License
core/src/main/java/org/futo/circles/core/model/NotificationAction.kt
circles-project
615,347,618
false
{"Kotlin": 1307644, "C": 137821, "C++": 12364, "Shell": 3202, "CMake": 1680, "Ruby": 922}
package org.futo.circles.core.model import org.matrix.android.sdk.api.session.pushrules.Action data class NotificationAction( val shouldNotify: Boolean, val highlight: Boolean, val soundName: String? ) fun List<Action>.toNotificationAction(): NotificationAction { var shouldNotify = false var highlight = false var sound: String? = null forEach { action -> when (action) { is Action.Notify -> shouldNotify = true is Action.Highlight -> highlight = action.highlight is Action.Sound -> sound = action.sound } } return NotificationAction(shouldNotify, highlight, sound) }
8
Kotlin
4
29
7edec708f9c491a7b6f139fc2f2aa3e2b7149112
660
circles-android
Apache License 2.0
core/src/main/kotlin/com/legacycode/cardbox/model/RelativePath.kt
LegacyCodeHQ
381,005,632
false
{"Kotlin": 39663, "Java": 116, "Shell": 94}
package com.legacycode.cardbox.model import java.io.File @JvmInline value class RelativePath(val segment: String) { val parent: RelativePath get() { val parentPath = segment .split(File.separator) .dropLast(1) .joinToString(File.separator) return RelativePath(parentPath) } }
0
Kotlin
0
3
523268fc6ca9a8155b8c1071fb8a24432a34117e
325
cardbox
Apache License 2.0
kmdc/kmdc-data-table/src/jsMain/kotlin/events.kt
mpetuska
430,798,310
false
null
package dev.petuska.kmdc.data.table import dev.petuska.kmdc.core.MDCAttrsDsl /** * [JS API](https://github.com/material-components/material-components-web/tree/v13.0.0/packages/mdc-data-table) */ @MDCAttrsDsl public fun MDCDataTableAttrsScope.onRowSelectionChanged(listener: (event: MDCDataTableModule.MDCRowSelectionChangedEvent) -> Unit) { addEventListener(MDCDataTableModule.events.ROW_SELECTION_CHANGED) { listener(it.nativeEvent.unsafeCast<MDCDataTableModule.MDCRowSelectionChangedEvent>()) } } /** * [JS API](https://github.com/material-components/material-components-web/tree/v13.0.0/packages/mdc-data-table) */ @MDCAttrsDsl public fun MDCDataTableAttrsScope.onRowClick(listener: (event: MDCDataTableModule.MDCRowClickEvent) -> Unit) { addEventListener(MDCDataTableModule.events.ROW_CLICK) { listener(it.nativeEvent.unsafeCast<MDCDataTableModule.MDCRowClickEvent>()) } } /** * [JS API](https://github.com/material-components/material-components-web/tree/v13.0.0/packages/mdc-data-table) */ @MDCAttrsDsl public fun MDCDataTableAttrsScope.onSelectedAll(listener: (event: MDCDataTableModule.MDCSelectedAllEvent) -> Unit) { addEventListener(MDCDataTableModule.events.SELECTED_ALL) { listener(it.nativeEvent.unsafeCast<MDCDataTableModule.MDCSelectedAllEvent>()) } } /** * [JS API](https://github.com/material-components/material-components-web/tree/v13.0.0/packages/mdc-data-table) */ @MDCAttrsDsl public fun MDCDataTableAttrsScope.onUnselectedAll(listener: (event: MDCDataTableModule.MDCSelectedAllEvent) -> Unit) { addEventListener(MDCDataTableModule.events.UNSELECTED_ALL) { listener(it.nativeEvent.unsafeCast<MDCDataTableModule.MDCSelectedAllEvent>()) } } /** * [JS API](https://github.com/material-components/material-components-web/tree/v13.0.0/packages/mdc-data-table) */ @MDCAttrsDsl public fun MDCDataTableAttrsScope.onSorted(listener: (event: MDCDataTableModule.MDCSortedEvent) -> Unit) { addEventListener(MDCDataTableModule.events.SORTED) { listener(it.nativeEvent.unsafeCast<MDCDataTableModule.MDCSortedEvent>()) } }
22
Kotlin
8
29
67b31502b5f76b64f7571821fdd0b78a3df0a68c
2,087
kmdc
Apache License 2.0
app/src/main/java/com/programmergabut/solatkuy/base/BaseRepository.kt
jiwomdf
247,947,112
false
null
package com.programmergabut.solatkuy.base import android.util.Log import com.google.gson.Gson import com.programmergabut.solatkuy.BuildConfig import retrofit2.Call import retrofit2.HttpException abstract class BaseRepository { companion object { private const val TAG = "BaseRepository" fun<T : BaseResponse> execute(call : Call<T>) : T { try{ val response = call.execute() return when(response.isSuccessful){ true -> { if(BuildConfig.BUILD_TYPE == ("debug")) Log.d(TAG, Gson().toJson(response.body()!!)) response.body()!! } false -> { if(BuildConfig.BUILD_TYPE == "debug") Log.d(TAG, response.message()) throw HttpException(response) } } } catch (e : Exception){ if(BuildConfig.BUILD_TYPE == "debug") e.message?.let { Log.d(TAG, it) } throw e } } } }
0
Kotlin
23
35
fc8e239f3cd677470bb5099ab021210db36a18e5
1,211
solat-kuy-android-mvvm-with-coroutine
MIT License
app/src/main/java/com/jodi/cophat/data/local/entity/ApplicationEntity.kt
cophat
241,760,374
false
null
package com.jodi.cophat.data.local.entity import android.os.Parcelable import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey import com.google.firebase.database.Exclude import com.google.firebase.database.IgnoreExtraProperties import com.jodi.cophat.data.presenter.ItemPendingPresenter import kotlinx.android.parcel.Parcelize @Parcelize @IgnoreExtraProperties @Entity(tableName = "application") data class ApplicationEntity( @PrimaryKey(autoGenerate = true) @get:Exclude @set:Exclude var id: Int? = null, var identificationCode: String? = "", var hospital: String? = null, var intervieweeName: String? = null, var gender: String? = null, var relationship: String? = null, var admin: String? = null, var answers: HashMap<String, Answer>? = null, var date: String? = null, var startHour: Long? = null, var endHour: Long? = null, var status: ApplicationStatus = ApplicationStatus.STARTED, @get:Exclude @set:Exclude var keyQuestionnaire: String = "", @get:Exclude @set:Exclude var parentPosition: Int = 0, @get:Exclude @set:Exclude var typeInterviewee: String = "", @get:Exclude @set:Exclude var name: String = "" ) : Parcelable
4
Kotlin
0
0
2272aca57494ef39a09d948549eb9fead5c3f68c
1,227
cophat
Apache License 2.0
rsocket-core/src/commonMain/kotlin/io/rsocket/kotlin/frame/ErrorFrame.kt
yschimke
116,363,172
true
{"Kotlin": 223377, "HTML": 796}
/* * Copyright 2015-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.rsocket.kotlin.frame import io.ktor.utils.io.core.* import io.rsocket.kotlin.error.* class ErrorFrame( override val streamId: Int, val throwable: Throwable, val data: ByteReadPacket? = null ) : Frame(FrameType.Error) { override val flags: Int get() = 0 val errorCode get() = (throwable as? RSocketError)?.errorCode ?: ErrorCode.ApplicationError override fun Output.writeSelf() { writeInt(errorCode) when (data) { null -> writeText(throwable.message ?: "") else -> writePacket(data) } } } fun Input.readError(streamId: Int): ErrorFrame { val errorCode = readInt() val message = readText() return ErrorFrame(streamId, RSocketError(streamId, errorCode, message)) }
0
Kotlin
0
0
696aafee107124663eec92e7614128f196d06efe
1,386
rsocket-kotlin
Apache License 2.0
backend/src/main/kotlin/com/olegknyazev/cloudmessenger/UserPasswordAuthenticationProvider.kt
olegknyazev
785,189,367
false
{"Kotlin": 11485}
package com.olegknyazev.cloudmessenger import io.micronaut.http.HttpRequest import io.micronaut.security.authentication.AuthenticationFailureReason import io.micronaut.security.authentication.AuthenticationRequest import io.micronaut.security.authentication.AuthenticationResponse import io.micronaut.security.authentication.provider.HttpRequestAuthenticationProvider import jakarta.inject.Singleton @Singleton class UserPasswordAuthenticationProvider<T>( private val accountDao: AccountDao, private val passwordEncoder: PasswordEncoder, ) : HttpRequestAuthenticationProvider<T> { override fun authenticate( requestContext: HttpRequest<T>?, authRequest: AuthenticationRequest<String, String> ): AuthenticationResponse { val userName = authRequest.identity val account = accountDao.find(userName) ?: return AuthenticationResponse.failure(AuthenticationFailureReason.USER_NOT_FOUND) if (passwordEncoder.encode(authRequest.secret) != account.encodedPassword) return AuthenticationResponse.failure(AuthenticationFailureReason.CREDENTIALS_DO_NOT_MATCH) return AuthenticationResponse.success(userName) } }
0
Kotlin
0
0
cafb2f5c95980816c7e9519b422c09ee12287316
1,193
cloud-messenger
MIT License
platform/testGuiFramework/src/com/intellij/testGuiFramework/framework/GuiTestSuite.kt
xin497668869
191,014,045
false
null
/* * Copyright 2000-2018 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.testGuiFramework.framework import com.intellij.testGuiFramework.launcher.GuiTestOptions import com.intellij.testGuiFramework.remote.IdeControl import org.junit.AfterClass import org.junit.BeforeClass import java.io.File open class GuiTestSuite { companion object { @BeforeClass @JvmStatic fun setUp() { } @AfterClass @JvmStatic fun tearDown() { IdeControl.closeIde() collectJvmErrors() GuiTestOptions.projectsDir.deleteRecursively() } private fun collectJvmErrors() { GuiTestOptions.projectsDir.walk() .maxDepth(3) .filter { it.name.startsWith("hs_err") } .forEach { it.copyTo(File(GuiTestPaths.failedTestScreenshotDir, it.name)) } } } }
1
null
1
1
a59f605a494dde23f097c9046540bf6a2a3a27d8
1,375
intellij-community
Apache License 2.0
app/src/main/java/com/example/scvmultitest/navigation/AppScreens.kt
scvsoft
546,876,038
false
{"Kotlin": 17534}
package com.example.scvmultitest.navigation sealed class AppScreens(val route: String){ object SplashScreen: AppScreens("splash_screen") object HomeScreen: AppScreens("home_screen") object PreviewUserDataScreen: AppScreens("preview_user_data_screen") object CategoryTestScreen: AppScreens("category_test_screen") object FirstCoupleTestScreen: AppScreens("first_couple_test_screen") }
0
Kotlin
0
0
f537247b72553899cfed107656f4b50d8829f9f5
394
multitest-android-app
MIT License
app/src/main/java/com/peter/landing/ui/home/HomeScreen.kt
peterdevacc
480,611,711
false
{"Kotlin": 362727, "Ruby": 980}
package com.peter.landing.ui.home import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.peter.landing.R import com.peter.landing.data.local.progress.ProgressState import com.peter.landing.data.util.ThemeMode import com.peter.landing.ui.navigation.LandingDestination import com.peter.landing.ui.util.ErrorNotice import com.peter.landing.ui.util.LandingTopBar @Composable fun HomeScreen( isDarkMode: Boolean, viewModel: HomeViewModel, navigateTo: (String) -> Unit, ) { val uiState by viewModel.homeUiState.collectAsStateWithLifecycle() val themeMenuState = remember { mutableStateOf(false) } HomeContent( isDarkMode = isDarkMode, uiState = uiState, themeMenuState = themeMenuState, setTheme = viewModel::setThemeMode, navigateTo = navigateTo, ) } @Composable private fun HomeContent( isDarkMode: Boolean, uiState: HomeUiState, themeMenuState: MutableState<Boolean>, setTheme: (ThemeMode) -> Unit, navigateTo: (String) -> Unit ) { Column( modifier = Modifier .background(MaterialTheme.colorScheme.background) .windowInsetsPadding(insets = WindowInsets.systemBars) .fillMaxSize() ) { LandingTopBar( currentDestination = LandingDestination.Main.Home, navigateTo = navigateTo, actions = { if (uiState is HomeUiState.Success) { Box { IconButton( onClick = { themeMenuState.value = true } ) { Icon( painter = painterResource(R.drawable.ic_theme_24dp), contentDescription = "", tint = MaterialTheme.colorScheme.onBackground ) } DropdownMenu( expanded = themeMenuState.value, onDismissRequest = { themeMenuState.value = false } ) { ThemeMode.values().forEach { DropdownMenuItem( text = { Text(text = it.cnValue) }, onClick = { setTheme(it) themeMenuState.value = false } ) } } } } }, ) Box( contentAlignment = Alignment.Center, modifier = Modifier .padding(16.dp) .weight(1f) .fillMaxWidth() ) { when (uiState) { is HomeUiState.Error -> { ErrorNotice(uiState.code) } is HomeUiState.Loading -> { CircularProgressIndicator( modifier = Modifier.size(24.dp, 24.dp) ) } is HomeUiState.Success -> { Column( modifier = Modifier.fillMaxSize() ) { val stateInfo = getStateActionInfo( uiState.studyState, isDarkMode ) Spacer(modifier = Modifier.weight(1.7f)) Box( modifier = Modifier .weight(3.5f) .fillMaxWidth() ) { Image( painter = painterResource(stateInfo.first), contentDescription = "", contentScale = ContentScale.FillBounds, modifier = Modifier.fillMaxSize() ) } Row( verticalAlignment = Alignment.Bottom, modifier = Modifier .weight(3.8f) .fillMaxWidth() ) { Spacer(modifier = Modifier.weight(1f)) FloatingActionButton( onClick = { navigateTo(stateInfo.third) }, modifier = Modifier.padding(end = 16.dp, bottom = 16.dp) ) { Icon( painter = painterResource(stateInfo.second), contentDescription = "", ) } } } } } } } } fun getStateActionInfo( studyState: StudyState, isDarkMode: Boolean ): Triple<Int, Int, String> { return when (studyState) { is StudyState.Learning -> { val image = if (studyState.progressState == ProgressState.FINISHED) { R.drawable.home_studying } else { if (isDarkMode) { R.drawable.home_learn_dark } else { R.drawable.home_learn_light } } val iconAndRoute = when (studyState.progressState) { ProgressState.LEARN -> { R.drawable.ic_learn_24dp to LandingDestination.General.Learn.route } ProgressState.CHOICE -> { R.drawable.ic_choice_24dp to LandingDestination.General.Choice.route } ProgressState.SPELLING -> { R.drawable.ic_spelling_24dp to LandingDestination.General.Spelling.route } ProgressState.WORD_LIST -> { R.drawable.ic_start_24dp to LandingDestination.General.WordList.route } ProgressState.FINISHED -> { R.drawable.ic_search_24dp to LandingDestination.Main.Search.route } } Triple(image, iconAndRoute.first, iconAndRoute.second) } is StudyState.None, StudyState.PlanFinished -> { val image = if (studyState is StudyState.PlanFinished) { R.drawable.home_finished } else { if (isDarkMode) { R.drawable.home_default_dark } else { R.drawable.home_default_light } } Triple(image, R.drawable.ic_search_24dp, LandingDestination.Main.Search.route) } } }
0
Kotlin
6
18
4efc45d7b27ed881864ff7f3966fb471906c2956
7,341
Landing
Apache License 2.0
platform/build-scripts/groovy/org/jetbrains/intellij/build/projector/projectorPlugin.kt
jwren
31,697,927
true
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.intellij.build.projector import org.jetbrains.intellij.build.ProductProperties private const val projectorPlugin = "intellij.cwm.plugin.projector" private const val projectorJar = "plugins/cwm-plugin-projector/lib/projector/projector.jar" fun configure(productProperties: ProductProperties) { if (productProperties.productLayout.bundledPluginModules.contains(projectorPlugin) && productProperties.versionCheckerConfig?.containsKey(projectorJar) == false) { (productProperties.versionCheckerConfig as? MutableMap)?.put(projectorJar, "17") } }
0
null
0
0
bf2402af3a3443a462b128488b32b5b0130b1534
701
intellij-community
Apache License 2.0
app/src/main/java/com/himanshoe/sample/MainActivity.kt
hi-manshu
448,952,507
false
null
package com.himanshoe.sample import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import com.himanshoe.kalendar.endlos.common.KalendarKonfig import com.himanshoe.kalendar.endlos.common.data.KalendarEvent import com.himanshoe.kalendar.endlos.ui.Kalendar import java.time.LocalDate class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Kalendar( kalendarEvents = listOf(KalendarEvent(LocalDate.now().plusDays(3), "", "")), kalendarKonfig = KalendarKonfig(weekCharacters = 2), onCurrentDayClick = { date, event -> }, errorMessage = {} ) } } }
6
Kotlin
11
236
1cd760985dfcf53ca95383b36c61776583e160cd
827
Kalendar
Apache License 2.0
build-logic/convention/src/main/kotlin/com/oliverspryn/gradle/extension/KotlinAndroidExtension.kt
oliverspryn
446,959,362
false
{"Kotlin": 68312}
package com.oliverspryn.gradle.extension import com.android.build.api.dsl.CommonExtension import com.oliverspryn.gradle.BuildConfig import org.gradle.api.Project import org.gradle.kotlin.dsl.withType import org.jetbrains.kotlin.gradle.tasks.KotlinCompile internal fun Project.configureKotlinAndroid( commonExtension: CommonExtension<*, *, *, *, *> ) { commonExtension.apply { compileOptions { sourceCompatibility = BuildConfig.Jvm.VERSION targetCompatibility = BuildConfig.Jvm.VERSION } } // Use withType to workaround https://youtrack.jetbrains.com/issue/KT-55947 tasks.withType<KotlinCompile>().configureEach { kotlinOptions { allWarningsAsErrors = BuildConfig.Jvm.KOTLIN_WARNINGS_AS_ERRORS jvmTarget = BuildConfig.Jvm.VERSION_STRING } } }
0
Kotlin
0
0
ae82d38f14e16127b93ce5e8415253b9735eb711
849
multimodal-spanner
MIT License
projects/ops/src/fanpoll/ops/OpsRoutes.kt
csieflyman
359,559,498
false
{"Kotlin": 785294, "JavaScript": 17435, "HTML": 6167, "PLpgSQL": 5563, "Dockerfile": 126}
/* * Copyright (c) 2024. fanpoll All rights reserved. */ package fanpoll.ops import fanpoll.infra.base.extension.listProjectAllRoutes import fanpoll.ops.auth.authRoutes import fanpoll.ops.log.logRoutes import fanpoll.ops.monitor.monitorRoutes import fanpoll.ops.notification.notificationRoutes import fanpoll.ops.release.releaseRoutes import fanpoll.ops.report.reportRoutes import fanpoll.ops.user.routes.userRoutes import io.github.oshai.kotlinlogging.KotlinLogging import io.ktor.server.application.Application import io.ktor.server.routing.routing private val logger = KotlinLogging.logger {} fun Application.loadProjectRoutes() { routing { userRoutes() authRoutes() notificationRoutes() reportRoutes() releaseRoutes() monitorRoutes() logRoutes() logger.info { listProjectAllRoutes(OpsConst.projectId, OpsConst.urlRootPath) } } }
1
Kotlin
9
74
1a7d54115dbc42c6a02230f527d9ad56862b4a0b
911
multi-projects-architecture-with-Ktor
MIT License
wear-tile/src/main/java/kndroidx/wear/tile/Modifiers.kt
sky130
711,136,725
false
{"Kotlin": 67315}
package kndroidx.wear.tile import androidx.annotation.OptIn import androidx.wear.protolayout.DimensionBuilders.DpProp import androidx.wear.protolayout.ModifiersBuilders import androidx.wear.protolayout.ModifiersBuilders.AnimatedVisibility import androidx.wear.protolayout.ModifiersBuilders.Background import androidx.wear.protolayout.ModifiersBuilders.Border import androidx.wear.protolayout.ModifiersBuilders.Clickable import androidx.wear.protolayout.ModifiersBuilders.Semantics import androidx.wear.protolayout.TypeBuilders import androidx.wear.protolayout.expression.ProtoLayoutExperimental import androidx.wear.protolayout.ModifiersBuilders.Modifiers.Builder as ModifiersBuilder val Modifier get() = ModifiersBuilder() @OptIn(ProtoLayoutExperimental::class) fun ModifiersBuilder.visible(visible: Boolean) = setVisible(TypeBuilders.BoolProp.Builder().setValue(visible).build()) fun ModifiersBuilder.background(background: Background) = setBackground(background) fun ModifiersBuilder.clickable(clickable: Clickable) = setClickable(clickable) fun ModifiersBuilder.border(border: Border) = setBorder(border) @OptIn(ProtoLayoutExperimental::class) fun ModifiersBuilder.animation(animatedVisibility: AnimatedVisibility) = setContentUpdateAnimation(animatedVisibility) fun ModifiersBuilder.semantics(semantics: Semantics) = setSemantics(semantics) fun ModifiersBuilder.padding( top: DpProp? = null, bottom: DpProp? = null, start: DpProp? = null, end: DpProp? = null, vertical: DpProp? = null, horizontal: DpProp? = null, ) = setPadding(Padding(top, bottom, start, end, vertical, horizontal)) fun Padding( top: DpProp?, bottom: DpProp?, start: DpProp?, end: DpProp?, vertical: DpProp?, horizontal: DpProp?, ) = ModifiersBuilders.Padding.Builder().apply { top?.let { setTop(it) } bottom?.let { setBottom(it) } start?.let { setStart(it) } end?.let { setEnd(it) } vertical?.let { setTop(it) } vertical?.let { setBottom(it) } horizontal?.let { setStart(it) } horizontal?.let { setEnd(it) } }.build()
0
Kotlin
0
1
595f1d685fa216d348154e44edce612923d1a58f
2,127
KndroidX
Apache License 2.0
messaging/src/main/kotlin/studio/lunabee/onesafe/messaging/writemessage/composable/SendResetMessageLayout.kt
LunabeeStudio
624,544,471
false
{"Kotlin": 3315037, "Java": 11987, "Python": 3979}
/* * Copyright (c) 2024 Lunabee Studio * * 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. * * Created by Lunabee Studio / Date - 8/29/2024 - for the oneSafe6 SDK. * Last modified 29/08/2024 15:48 */ package studio.lunabee.onesafe.messaging.writemessage.composable import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import studio.lunabee.compose.core.LbcTextSpec import studio.lunabee.onesafe.atom.button.OSTextButton import studio.lunabee.onesafe.atom.button.defaults.OSTextButtonDefaults import studio.lunabee.onesafe.atom.text.OSText import studio.lunabee.onesafe.commonui.OSString import studio.lunabee.onesafe.model.OSActionState import studio.lunabee.onesafe.ui.res.OSDimens @Composable fun SendResetMessageLayout(contactName: LbcTextSpec, onSendResetClick: () -> Unit) { Column( modifier = Modifier .fillMaxWidth() .background(MaterialTheme.colorScheme.surface) .navigationBarsPadding(), ) { OSText( text = LbcTextSpec.StringResource( OSString.bubbles_writeMessageScreen_reset_description, contactName, ), modifier = Modifier .padding(horizontal = OSDimens.SystemSpacing.ExtraLarge) .padding(top = OSDimens.SystemSpacing.ExtraLarge, bottom = OSDimens.SystemSpacing.Regular), ) OSTextButton( text = LbcTextSpec.StringResource(OSString.bubbles_writeMessageScreen_reset_send), onClick = onSendResetClick, buttonColors = OSTextButtonDefaults.primaryTextButtonColors(state = OSActionState.Enabled), modifier = Modifier .padding(horizontal = OSDimens.SystemSpacing.Large) .padding(bottom = OSDimens.SystemSpacing.ExtraLarge), ) } }
0
Kotlin
1
2
935c5a9fad27406874bc63ec6729fd68269a76ec
2,653
oneSafe6_SDK_Android
Apache License 2.0
app/src/main/java/com/dreamsoftware/fitflextv/data/remote/datasource/ISubscriptionsRemoteDataSource.kt
sergio11
534,529,261
false
{"Kotlin": 615931}
package com.dreamsoftware.fitflextv.data.remote.datasource import com.dreamsoftware.fitflextv.data.remote.dto.response.SubscriptionDTO import com.dreamsoftware.fitflextv.data.remote.exception.FetchSubscriptionsRemoteException interface ISubscriptionsRemoteDataSource { @Throws(FetchSubscriptionsRemoteException::class) suspend fun getSubscriptions(): List<SubscriptionDTO> }
0
Kotlin
3
40
4452dcbcf3d4388144a949c65c216de5547c82a6
385
fitflextv_android
Apache License 2.0
src/test/kotlin/days/Day8Test.kt
minibugdev
322,172,909
true
{"Kotlin": 17258}
package days import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.core.Is.`is` import org.junit.Test class Day8Test { private val aoc = Day8() @Test fun testPartOne() { assertThat(aoc.partOne(), `is`(5)) } @Test fun testPartTwo() { val partTwo = aoc.partTwo() assertThat(partTwo, `is`(8)) } }
0
Kotlin
0
1
572f6b5620c87a41d90f1474b5e89eddb903fd6f
323
aoc-kotlin-starter
Creative Commons Zero v1.0 Universal
GaiaXAndroidJSProxy/src/main/java/com/alibaba/gaiax/js/proxy/modules/GXJSBuildInModule.kt
alibaba
456,772,654
false
{"C": 3164402, "Kotlin": 1594334, "Rust": 1403358, "Objective-C": 927158, "Java": 650057, "C++": 380295, "JavaScript": 260489, "TypeScript": 176298, "CSS": 169253, "HTML": 113541, "MDX": 86833, "Objective-C++": 60140, "Swift": 25151, "Makefile": 12210, "Shell": 10344, "CMake": 9258, "Ruby": 6215, "Batchfile": 3812, "SCSS": 837}
package com.alibaba.gaiax.js.proxy.modules import com.alibaba.fastjson.JSONObject import com.alibaba.gaiax.js.proxy.GXJSRenderProxy import com.alibaba.gaiax.js.api.GXJSBaseModule import com.alibaba.gaiax.js.api.IGXCallback import com.alibaba.gaiax.js.api.annotation.GXAsyncMethod import com.alibaba.gaiax.js.api.annotation.GXSyncMethod import com.alibaba.gaiax.js.utils.Log internal class GXJSBuildInModule : GXJSBaseModule() { override val name: String get() = "BuildIn" @GXAsyncMethod fun setData(data: JSONObject, params: JSONObject, callback: IGXCallback) { if (Log.isLog()) { Log.d("setData() called with: params = $params, callback = $callback") } val templateId = params.getString("templateId") val componentId = params.getLong("instanceId") if (templateId != null && componentId != null) { GXJSRenderProxy.instance.setData( componentId, templateId, data, callback ) } } @GXSyncMethod fun getData(params: JSONObject): JSONObject { if (Log.isLog()) { Log.d("getData() called with: params = $params") } val templateId = params.getString("templateId") val componentId = params.getLong("instanceId") if (templateId != null && componentId != null) { return GXJSRenderProxy.instance.getData(componentId) ?: JSONObject() } return JSONObject() } @GXSyncMethod fun getComponentIndex(params: JSONObject): Int { if (Log.isLog()) { Log.d("getComponentIndex() called with: params = $params") } val templateId = params.getString("templateId") val componentId = params.getLong("instanceId") if (templateId != null && componentId != null) { val data = GXJSRenderProxy.instance.getData(componentId) ?: JSONObject() return data.getInteger("scrollIndex") ?: -1 } return -1 } }
30
C
142
1,201
f169ff56c2cf97b523e8983de2d15f4ef3204c15
1,990
GaiaX
Apache License 2.0
library-network/src/main/java/com/pp/library_network/eyepetizer/bean/Style.kt
PPQingZhao
548,315,946
false
{"Kotlin": 553508, "Java": 1135}
package com.pp.library_network.eyepetizer.bean import com.google.gson.annotations.SerializedName data class Style( @SerializedName("across_column") val acrossColumn: Boolean? = false, @SerializedName("background") val background: Background? = null, @SerializedName("banner_padding") val bannerPadding: Int? = 0, @SerializedName("padding") val padding: Padding? = null, @SerializedName("separator_line") val separatorLine: SeparatorLine? = null, @SerializedName("tpl_label") val tplLabel: String = "" ) { data class Background( @SerializedName("color") val color: String ) data class Padding( @SerializedName("bottom") val bottom: Double, @SerializedName("left") val left: Double, @SerializedName("right") val right: Double, @SerializedName("top") val top: Double ) data class SeparatorLine( @SerializedName("bottom") val bottom: Bottom, @SerializedName("top") val top: Top ) { data class Bottom( @SerializedName("color") val color: String, @SerializedName("height") val height: Double, @SerializedName("margin") val margin: Margin ) data class Top( @SerializedName("color") val color: String, @SerializedName("height") val height: Double, @SerializedName("margin") val margin: Margin ) data class Margin( @SerializedName("bottom") val bottom: Float, @SerializedName("left") val left: Float, @SerializedName("right") val right: Float, @SerializedName("top") val top: Float ) } }
0
Kotlin
0
5
904d9a980811d502f88479cb450c3a6e8d027f09
1,860
Eyepetizer
Apache License 2.0
src/main/kotlin/Mode.kt
counters
429,521,365
false
null
enum class Mode(val id: Int) { COROUTINES(1), THREADS(2), ASYNC_HTTP_API(3), }
0
Kotlin
0
2
a30d40cc615043beb02fdcba2adfdf3e598a7cf4
90
minter-node-benchmark
Apache License 2.0
waypoint-core/src/main/java/com/squaredcandy/waypoint/core/holder/listener/WaypointHolderListener.kt
squaredcandy
638,860,321
false
{"Kotlin": 174587}
package com.squaredcandy.waypoint.core.holder.listener import com.squaredcandy.waypoint.core.WaypointChangeList @ExperimentalWaypointHolderListenerModifier fun interface WaypointHolderListener { fun onWaypointHolderChanged(changeList: WaypointChangeList) }
0
Kotlin
0
0
a067f6a1a88f53e402d0359688b83ca2b0fbb373
263
waypoint
Apache License 2.0
app/src/main/java/com/elementary/tasks/reminder/preview/AttachmentToUiReminderPreviewAttachment.kt
naz013
165,067,747
false
{"Kotlin": 2972212, "HTML": 20925}
package com.elementary.tasks.reminder.preview import android.net.Uri import com.elementary.tasks.R import com.elementary.tasks.core.data.ui.UiTextElement import com.elementary.tasks.core.os.ColorProvider import com.elementary.tasks.core.os.UnitsConverter import com.elementary.tasks.core.text.UiTextFormat import com.elementary.tasks.core.text.UiTextStyle import com.elementary.tasks.core.utils.TextProvider import com.elementary.tasks.reminder.build.valuedialog.controller.attachments.UriToAttachmentFileAdapter import com.elementary.tasks.reminder.preview.data.UiReminderPreviewAttachment import com.elementary.tasks.reminder.preview.data.UiReminderPreviewData import com.elementary.tasks.reminder.preview.data.UiReminderPreviewHeader class AttachmentToUiReminderPreviewAttachment( private val textProvider: TextProvider, private val colorProvider: ColorProvider, private val unitsConverter: UnitsConverter, private val attachmentFileAdapter: UriToAttachmentFileAdapter ) { operator fun invoke( attachments: List<String> ): List<UiReminderPreviewData> { val data = attachments.map { Uri.parse(it) }.map { val attachment = attachmentFileAdapter(it) UiReminderPreviewAttachment( file = attachment, text = UiTextElement( text = attachment.name, textFormat = UiTextFormat( fontSize = unitsConverter.spToPx(16f), textStyle = UiTextStyle.NORMAL, textColor = colorProvider.getColorOnBackground() ) ) ) } return listOf( UiReminderPreviewHeader( UiTextElement( text = textProvider.getText(R.string.builder_attachments), textFormat = UiTextFormat( fontSize = unitsConverter.spToPx(18f), textStyle = UiTextStyle.BOLD, textColor = colorProvider.getColorOnBackground() ) ) ) ) + data } }
0
Kotlin
3
6
f60a6b1f690b4e1becce00e5475b5bf684f99131
1,917
reminder-kotlin
Apache License 2.0
lcc-content-data/src/main/kotlin/com/joshmanisdabomb/lcc/data/generators/LCCLangData.kt
joshmanisdabomb
537,458,013
false
{"Kotlin": 2724329, "Java": 138822}
package com.joshmanisdabomb.lcc.data.generators import com.joshmanisdabomb.lcc.data.LCCData import com.joshmanisdabomb.lcc.directory.LCCBlocks object LCCLangData { val lang get() = LCCData.lang fun init() { lang["tooltip.lcc.energy"] = "Energy: %1\$s / %2\$s%3\$s" lang["tooltip.lcc.oxygen"] = "Oxygen: %1\$s / %2\$s" lang["tooltip.lcc.contained_armor.consume"] = "Your helmet is preventing you from using this item" lang["tooltip.lcc.imbue.lcc.stinger"] = "Stinger Imbue (%1\$s / %2\$s hits)" lang["itemGroup.lcc.group"] = "Loosely Connected Concepts" lang["itemGroup.lcc.group.set.amount"] = "%s item" lang["itemGroup.lcc.group.set.amount.s"] = "s" lang["itemGroup.lcc.group.set.classic_cloth"] = "Classic Cloths" lang["effect.lcc.stun"] = "Stun" lang["effect.lcc.vulnerable"] = "Vulnerable" lang["effect.lcc.flammable"] = "Flammable" lang["effect.lcc.radiation"] = "Radiation" lang["effect.lcc.fear"] = "Fear" lang["effect.lcc.bleeding"] = "Bleeding" lang["enchantment.lcc.infested"] = "Infested" lang["biome.lcc.wasteland"] = "Wasteland" lang["container.lcc.spawner_table"] = "Arcane Table" lang["container.lcc.refiner"] = "Refiner" lang["container.lcc.composite_processor"] = "Composite Processor" lang["container.lcc.coal_generator"] = "Furnace Generator" lang["container.lcc.oil_generator"] = "Combustion Generator" lang["container.lcc.energy_bank"] = "Energy Bank" lang["container.lcc.atomic_bomb"] = "Atomic Bomb" lang["container.lcc.oxygen_extractor"] = "Oxygen Extractor" lang["container.lcc.kiln"] = "Kiln" lang["container.lcc.nuclear_generator"] = "Nuclear Generator" lang["container.lcc.imbuing"] = "Imbue Weapon" lang["container.lcc.heart_condenser"] = "Heart Condenser" lang["container.lcc.refining.power"] = "Power: %1\$s" lang["container.lcc.refining.power.recipe"] = "Power: %1\$s\nConsumed: %2\$s/t" lang["container.lcc.refining.efficiency"] = "Efficiency: %1\$s%%" lang["container.lcc.refining.efficiency.recipe"] = "Efficiency: %1\$s%%\nMaximum Efficiency: %2\$s%%" lang["container.lcc.refining.time"] = "%1\$s/%2\$s s" lang["container.lcc.refining.recipe.asphalt_mixing"] = "Bituminous Mixing" lang["container.lcc.refining.recipe.pozzolanic_mixing"] = "Pozzolanic Mixing" lang["container.lcc.refining.recipe.uranium"] = "Centrifugal Separation" lang["container.lcc.refining.recipe.treating"] = "Thermal Disinfection" lang["container.lcc.refining.recipe.arc"] = "Electric Arc Smelting" lang["container.lcc.refining.recipe.dry"] = "Heated Drying" lang["container.lcc.refining.recipe.ducrete_mixing"] = "Ducrete Mixing" lang["container.lcc.refining.recipe.pellet_compression"] = "Pellet Compression" lang["container.lcc.refining.recipe.salt"] = "Salt Purification" lang["container.lcc.refining.recipe.paste_mixing"] = "Reagent Binding" lang["container.lcc.refining.recipe.fractional_distillation"] = "Fractional Distillation" lang["container.lcc.refining.recipe.tar_cracking"] = "Tar Cracking" lang["container.lcc.refining.recipe.oil_cracking"] = "Oil Cracking" lang["container.lcc.refining.recipe.polymerization"] = "Polymerization" lang["container.lcc.generator.burn"] = "Remaining Time: %1\$s/%2\$s s" lang["container.lcc.generator.output"] = "Steam Produced: %1\$s/t\nBase Steam from Fuel: %2\$s/t\nSteam Multiplier from Water: %3\$s%%" lang["container.lcc.nuclear_generator.power"] = "Power: %1\$s" lang["container.lcc.nuclear_generator.output"] = "Total Steam Produced: %1\$s/t\nBase Steam Produced: %2\$s/t\nMaximum Safe Output: %3\$s\nMaximum Fuel Approaches: %4\$s/t\nSteam Multiplier from Water: %5\$s%%" lang["container.lcc.nuclear_generator.coolant"] = "Coolant Value: %1\$s units\nDepletion Rate: %2\$s units/t" lang["container.lcc.nuclear_generator.fuel"] = "Fuel Value: %1\$s units\nFuel Value per Item: %2\$s units\nDepletion Rate: %3\$s units/t" lang["container.lcc.nuclear_generator.chance"] = "Meltdown Chance: %1\$s%%/t" lang["container.lcc.nuclear_generator.waste"] = "Progress Towards Next Waste: %1\$s%%\nGeneration Rate: %2\$s%%/t\nMaximum Safe Output: %3\$s\nSafe Output Change: %4\$s/t" lang["container.lcc.nuclear_generator.meltdown"] = "Meltdown in %1\$ss!!!" lang["container.lcc.battery.power"] = "Power: %1\$s" lang["container.lcc.oxygen_extractor.power"] = "Power: %1\$s" lang["container.lcc.oxygen_extractor.oxygen"] = "Oxygen Outflow: %1\$s/t\nHold SHIFT for details" lang["container.lcc.oxygen_extractor.oxygen.advanced"] = "Total Oxygen Outflow: %1\$s/t\n • From Top: %2\$s/t\n • From North: %3\$s/t\n • From East: %4\$s/t\n • From South: %5\$s/t\n • From West: %6\$s/t\n • Dimension Modifier: %7\$s%%" lang["attribute.lcc.name.wasteland.damage"] = "Wasteland Damage" lang["attribute.lcc.name.wasteland.protection"] = "Wasteland Protection" lang["gui.lcc.atomic_bomb.detonate"] = "Detonate" lang["gui.lcc.atomic_bomb.detonate.power"] = "Power: %1\$s" lang["gui.lcc.nuclear_generator.activate"] = "Power On" lang["death.attack.lcc.gauntlet_punch"] = "%1\$s was obliterated by %2\$s using Punch" lang["death.attack.lcc.gauntlet_punch.item"] = "%1\$s was obliterated by %2\$s using Punch of %3\$s" lang["death.attack.lcc.gauntlet_punch_wall"] = "%1\$s was launched into the wall using Punch" lang["death.attack.lcc.gauntlet_punch_wall.player"] = "%1\$s was launched into the wall by %2\$s using Punch" lang["death.attack.lcc.gauntlet_uppercut"] = "%1\$s was struck by %2\$s using Uppercut" lang["death.attack.lcc.gauntlet_uppercut.item"] = "%1\$s was struck by %2\$s using Uppercut of %3\$s" lang["death.attack.lcc.heated"] = "%1\$s was steamed like a vegetable" lang["death.attack.lcc.heated.player"] = "%1\$s stepped on a generator whilst trying to escape %2\$s" lang["death.attack.lcc.boiled"] = "%1\$s was boiled alive" lang["death.attack.lcc.boiled.player"] = "%1\$s ended up boiled alive whilst trying to escape %2\$s" lang["death.attack.lcc.nuke"] = "%1\$s was nuked" lang["death.attack.lcc.nuke.player"] = "%1\$s was nuked by %2\$s" lang["death.attack.lcc.radiation"] = "%1\$s was exposed to ionizing radiation" lang["death.attack.lcc.radiation.player"] = "%1\$s was exposed to ionizing radiation whilst trying to escape %2\$s" lang["en_gb", "death.attack.lcc.radiation"] = "%1\$s was exposed to ionising radiation" lang["en_gb", "death.attack.lcc.radiation.player"] = "%1\$s was exposed to ionising radiation whilst trying to escape %2\$s" lang["death.attack.lcc.hazmat_anoxia"] = "%1\$s couldn't get their helmet off" lang["death.attack.lcc.hazmat_anoxia.player"] = "%1\$s couldn't get their helmet off whilst trying to escape %2\$s" lang["death.attack.lcc.salt"] = "%1\$s was lightly salted by %2\$s" lang["death.attack.lcc.salt.item"] = "%1\$s was lightly salted by %2\$s using %3\$s" lang["death.attack.lcc.spikes"] = "%1\$s was skewered" lang["death.attack.lcc.spikes.player"] = "%1\$s was skewered like a kebab whilst trying to escape %2\$s" lang["subtitles.lcc.block.soaking_soul_sand.jump"] = "Soaking Soul Sand squelches" lang["subtitles.lcc.block.bounce_pad.jump"] = "Bounce Pad protracts" lang["subtitles.lcc.block.bounce_pad.set"] = "Bounce Pad set" lang["subtitles.lcc.entity.pocket_zombie_pigman.ambient"] = "Pocket Zombie Pigman grunts angrily" lang["subtitles.lcc.entity.pocket_zombie_pigman.hurt"] = "Pocket Zombie Pigman hurts" lang["subtitles.lcc.entity.pocket_zombie_pigman.death"] = "Pocket Zombie Pigman dies" lang["subtitles.lcc.block.classic_crying_obsidian.set_spawn"] = "Classic Crying Obsidian sets spawn" lang["subtitles.lcc.entity.atomic_bomb.fuse"] = "Atomic Bomb ticks" lang["subtitles.lcc.entity.atomic_bomb.defuse"] = "Atomic Bomb defused" lang["subtitles.lcc.entity.nuclear_explosion.explode"] = "Nuclear explosion" lang["subtitles.lcc.block.alarm.bell"] = "Alarm rings" lang["subtitles.lcc.block.alarm.nuclear_siren"] = "Alarm siren blares" lang["subtitles.lcc.item.detector.click"] = "Radiation Detector clicks" lang["subtitles.lcc.item.fly_egg.hatch"] = "Fly Eggs hatch" lang["subtitles.lcc.entity.salt.throw"] = "Salt thrown" lang["subtitles.lcc.block.spikes.hurt"] = "Spikes damage" lang["subtitles.lcc.block.improvised_explosive.beep"] = "Improvised Explosive beeps" lang["subtitles.lcc.block.improvised_explosive.constant"] = "Improvised Explosive beeps rapidly" lang["subtitles.lcc.block.improvised_explosive.triggered"] = "Improvised Explosive triggered" lang["subtitles.lcc.block.improvised_explosive.defuse"] = "Improvised Explosive defused" lang["subtitles.lcc.entity.consumer.ambient"] = "Consumer snarls" lang["subtitles.lcc.entity.consumer.hurt"] = "Consumer hurts" lang["subtitles.lcc.entity.consumer.death"] = "Consumer dies" lang["subtitles.lcc.entity.consumer.attack"] = "Consumer chomps" lang["subtitles.lcc.entity.consumer.cqc"] = "Consumer snarls angrily" lang["subtitles.lcc.entity.consumer.tongue.shoot"] = "Consumer extends tongue" lang["subtitles.lcc.entity.consumer.tongue.loop"] = "Consumer licks" lang["subtitles.lcc.entity.consumer.tongue.attach"] = "Consumer tongues something" lang["subtitles.lcc.entity.woodlouse.ambient"] = "Woodlouse hisses" lang["subtitles.lcc.entity.woodlouse.hurt"] = "Woodlouse hurts" lang["subtitles.lcc.entity.woodlouse.death"] = "Woodlouse dies" lang["subtitles.lcc.entity.wasp.loop"] = "Wasp buzzes" lang["subtitles.lcc.entity.wasp.aggressive"] = "Wasp buzzes angrily" lang["subtitles.lcc.entity.wasp.hurt"] = "Wasp hurts" lang["subtitles.lcc.entity.wasp.death"] = "Wasp dies" lang["subtitles.lcc.entity.wasp.sting"] = "Wasp stings" lang["subtitles.lcc.entity.psycho_pig.ambient"] = "Psycho Pig shrieks" lang["subtitles.lcc.entity.psycho_pig.hurt"] = "Psycho Pig hurts" lang["subtitles.lcc.entity.psycho_pig.death"] = "Psycho Pig dies" lang["subtitles.lcc.entity.psycho_pig.reveal"] = "Psycho Pig shrieks" lang["subtitles.lcc.entity.disciple.ambient"] = "Disciple hums" lang["subtitles.lcc.entity.disciple.hurt"] = "Disciple hurts" lang["subtitles.lcc.entity.disciple.death"] = "Disciple dies" lang["subtitles.lcc.entity.disciple.jump"] = "Disciple flaps wings" lang["subtitles.lcc.entity.disciple.fire"] = "Disciple casts" lang["subtitles.lcc.entity.disciple.dust"] = "Disciple Pyre burns" lang["subtitles.lcc.entity.disciple.explosion"] = "Disciple Pyre explodes" lang["subtitles.lcc.entity.rotwitch.ambient"] = "Rotwitch wheezes" lang["subtitles.lcc.entity.rotwitch.hurt"] = "Rotwitch hurts" lang["subtitles.lcc.entity.rotwitch.death"] = "Rotwitch dies" lang["subtitles.lcc.entity.rotwitch.heave"] = "Rotwitch spews" lang["subtitles.lcc.entity.rotwitch.hatch"] = "Flies hatch" lang["subtitles.lcc.entity.fly.ambient"] = "Fly buzzes" lang["subtitles.lcc.entity.fly.death"] = "Fly dies" lang[LCCBlocks.nether_reactor.translationKey.toString() + ".active"] = "Active!" lang[LCCBlocks.nether_reactor.translationKey.toString() + ".incorrect"] = "Not the correct pattern!" lang[LCCBlocks.nether_reactor.translationKey.toString() + ".players"] = "All players need to be close to the reactor." lang[LCCBlocks.nether_reactor.translationKey.toString() + ".y"] = "The reactor must be placed between y=%1\$s and y=%2\$s" lang[LCCBlocks.radar.translationKey.toString() + ".range"] = "Range is %1\$s blocks" lang[LCCBlocks.sapphire_altar.translationKey.toString() + ".minesweeper.malformed"] = "The sapphire altar has been tampered with." lang[LCCBlocks.sapphire_altar.translationKey.toString() + ".minesweeper.unsolvable"] = "Could not generate a solvable minesweeper board. Please try again." lang[LCCBlocks.sapphire_altar.translationKey.toString() + ".arena.malformed"] = "The sapphire altar has been tampered with." lang[LCCBlocks.sapphire_altar.translationKey.toString() + ".arena.player_position"] = "All players that wish to take part must step inside the altar." lang[LCCBlocks.sapphire_altar.translationKey.toString() + ".arena.progress"] = "Sapphire Arena" lang[LCCBlocks.sapphire_altar.translationKey.toString() + ".arena.progress.spawners"] = "Sapphire Arena - Spawners Remaining: %1\$s" lang[LCCBlocks.sapphire_altar.translationKey.toString() + ".arena.progress.hostiles"] = "Sapphire Arena - Hostiles Remaining: %1\$s" lang["commands.lcc.radiation.add.success.single"] = "Added %s to the radiation sickness of %s" lang["commands.lcc.radiation.add.success.multiple"] = "Added %s to the radiation sickness of %s players" lang["commands.lcc.radiation.set.success.single"] = "Set the radiation sickness of %s to %s" lang["commands.lcc.radiation.set.success.multiple"] = "Set the radiation sickness of %s players to %s" lang["commands.lcc.radiation.query"] = "%s has a radiation sickness value of %s" lang["commands.lcc.radiation.failed.living.single"] = "%s must be a living entity to have radiation sickness" lang["commands.lcc.radiation.failed.living.multiple"] = "No entities given were living and cannot receive radiation sickness" lang["commands.lcc.nuclearwinter.add.success"] = "Added %s to the nuclear winter level of %s" lang["commands.lcc.nuclearwinter.set.success"] = "Set the nuclear winter level of %s to %s" lang["commands.lcc.nuclearwinter.query"] = "%s has a nuclear winter level of %s" } }
0
Kotlin
0
0
a836162eaf64a75ca97daffa02c1f9e66bdde1b4
14,303
loosely-connected-concepts
Creative Commons Zero v1.0 Universal
it.unibo.parkmanagerservice/src/it/unibo/parkingmanagerservice/repository/user/IUserRepository.kt
Leaaaf
422,829,094
false
{"Kotlin": 93921, "Handlebars": 30146, "HTML": 25633, "TypeScript": 23203, "Prolog": 11494, "Jupyter Notebook": 10420, "JavaScript": 4625, "Shell": 130}
package it.unibo.parkingmanagerservice.repository.user import it.unibo.parkingmanagerservice.entity.user.User import it.unibo.parkingmanagerservice.entity.user.UserState interface IUserRepository { // CUD fun create(user : User) : User? fun update(user : User) fun delete(id : Long) fun getById(id : Long) : User? fun getByEmail(email : String) : User? fun getByToken(token : String) : User? fun getByState(userState : UserState) : Collection<User> fun getByFirstState(userState : UserState) : User? }
0
Kotlin
0
0
153f620f06775ae57bce4984539d9fb7f1d086ca
514
ParkManagerService
MIT License
wallet/src/main/java/com/android/identity_credential/wallet/ui/prompt/consent/ConsentPromptEntryField.kt
openwallet-foundation-labs
248,844,077
false
{"Kotlin": 4043461, "Java": 591756, "JavaScript": 31381, "Swift": 28030, "HTML": 11768, "Shell": 372, "CSS": 200, "C": 104}
package com.android.identity_credential.wallet.ui.prompt.consent import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.foundation.focusGroup import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FilterChip import androidx.compose.material3.FilterChipDefaults import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.Text import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableIntState import androidx.compose.runtime.MutableState import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.android.identity.trustmanagement.TrustPoint import com.android.identity_credential.wallet.R import com.android.identity_credential.wallet.util.toImageBitmap import kotlinx.coroutines.launch import kotlin.math.floor /** * ConfirmButtonState defines the possible states of the Confirm button in the Consent Prompt. * This state is referenced through [val confirmButtonState] in [ConsentPromptEntryField] * * If the Confirm button state is ENABLED then the Confirm button is enabled for the user to tap. * This invokes the `onConfirm()` callback and closes Consent Prompt composable. * * If Confirm button state is DISABLED then user cannot tap on the Confirm button until the user has * scrolled to the bottom of the list where the state is changed to ENABLED. */ private enum class ConfirmButtonState { // User can confirm sending the requested credentials after scrolling to the bottom ENABLED, // Confirm button cannot be tapped in this state DISABLED, // For initializing the state flow INIT } /** * ConsentPromptEntryField is responsible for showing a bottom sheet modal dialog prompting the user * to consent to sending credential data to requesting party and user can cancel at any time. */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun ConsentPromptEntryField( consentFields: List<ConsentField>, documentName: String, verifier: TrustPoint?, onConfirm: () -> Unit = {}, onCancel: () -> Unit = {} ) { // used for bottom sheet val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) val scope = rememberCoroutineScope() // determine whether user needs to scroll to tap on the Confirm button val confirmButtonState = remember { mutableStateOf(ConfirmButtonState.INIT) } val scrolledToBottom = remember { mutableStateOf(false) } // remember if user scrolled to bottom // the index of the last row that is currently visible val lastVisibleRowIndexState = remember { mutableIntStateOf(0) } // total rows that contain data element texts, with at most 2 per row val totalDataElementRows = remember { floor(consentFields.size / 2.0).toInt().run { if (consentFields.size % 2 != 0) { //odd number of elements this + 1// 1 more row to represent the single element } else { this// even number of elements, row count remains unchanged } } } // the index of the last row that will be/is rendered in the LazyColumn val lastRowIndex = remember { totalDataElementRows - 1 } // if user has not previously scrolled to bottom of list if (!scrolledToBottom.value) { // else if user has already scrolled to bottom, don't change button state // set Confirm button state according to whether there are more rows to be shown to user than // what the user is currently seeing confirmButtonState.value = if (lastRowIndex > lastVisibleRowIndexState.intValue) { ConfirmButtonState.DISABLED // user needs to scroll to reach the bottom of the list } else {// last visible row index has reached the LazyColumnI last row index // remember that user already saw the bottom-most row even if they scroll back up scrolledToBottom.value = true ConfirmButtonState.ENABLED // user has the option to now share their sensitive data } } ModalBottomSheet( modifier = Modifier.fillMaxHeight(0.6F), onDismissRequest = { onCancel() }, sheetState = sheetState, containerColor = MaterialTheme.colorScheme.surface ) { ConsentPromptHeader( documentName = documentName, verifier = verifier ) Box( modifier = Modifier .fillMaxHeight(0.8f) .fillMaxWidth() .padding(top = 16.dp, bottom = 8.dp) ) { DataElementsListView( consentFields = consentFields, lastVisibleRowIndexState = lastVisibleRowIndexState, ) } // show the 2 action button on the bottom of the dialog ConsentPromptActions( confirmButtonState = confirmButtonState, onCancel = { scope.launch { sheetState.hide() onCancel() } }, onConfirm = { onConfirm.invoke() } ) } } /** * Show the title text according to whether there's a TrustPoint's available, and if present, show * the icon too. */ @Composable private fun ConsentPromptHeader( documentName: String, verifier: TrustPoint? ) { // title of dialog, if verifier is null or verifier.displayName is null, use default text val title = if (verifier == null) { LocalContext.current.getString(R.string.consent_prompt_title, documentName) } else { // title is based on TrustPoint's displayName LocalContext.current.getString( R.string.consent_prompt_title_verifier, verifier.displayName, documentName ) } Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp), horizontalArrangement = Arrangement.Center ) { // show icon if icon bytes are present verifier?.displayIcon?.let { iconBytes -> Icon( modifier = Modifier.size(50.dp), // TODO: we're computing a bitmap every recomposition and this could be slow bitmap = iconBytes.toImageBitmap(), contentDescription = stringResource(id = R.string.consent_prompt_icon_description) ) } ?: Spacer(modifier = Modifier.width(24.dp)) Text( text = title, modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onSurface ) } } /** * List View showing 2 columns of data elements requested to be sent to requesting party. * Shows the document name that is used for extracting requested data. * * Report back on param [lastVisibleRowIndexState] the index of the last row that is considered to * be actively visible from Compose (as user scrolls and compose draws). */ @Composable private fun DataElementsListView( consentFields: List<ConsentField>, lastVisibleRowIndexState: MutableIntState, ) { val groupedElements = consentFields.chunked(2).map { pair -> if (pair.size == 1) Pair(pair.first(), null) else Pair(pair.first(), pair.last()) } val lazyListState = rememberLazyListState() val visibleRows = remember { derivedStateOf { lazyListState.layoutInfo.visibleItemsInfo } } if (visibleRows.value.isNotEmpty()) { // notify of the last row's index that's considered visible lastVisibleRowIndexState.intValue = visibleRows.value.last().index } LazyColumn( state = lazyListState, modifier = Modifier .fillMaxWidth() .fillMaxHeight() .focusGroup() .padding(start=10.dp) ) { items(groupedElements.size) { index -> val pair = groupedElements[index] DataElementsRow( left = pair.first, right = pair.second, ) } } } /** * A single row containing 2 columns of data elements to consent to sending to the Verifier. */ @Composable private fun DataElementsRow( left: ConsentField, right: ConsentField?, ) { Row( modifier = Modifier .fillMaxWidth() .padding(bottom = 1.dp), horizontalArrangement = Arrangement.SpaceEvenly ) { val chipModifier = if (right != null) Modifier.weight(1f) else Modifier DataElementView( modifier = chipModifier, consentField = left, ) right?.let { DataElementView( modifier = chipModifier, consentField = right, ) } } } /** * Individual view for a DataElement. */ @Composable private fun DataElementView( modifier: Modifier = Modifier, consentField: ConsentField, ) { FilterChip( modifier = modifier, selected = true, enabled = false, colors = FilterChipDefaults.filterChipColors( disabledContainerColor = Color.Transparent, disabledTrailingIconColor = MaterialTheme.colorScheme.onSurface, disabledLeadingIconColor = MaterialTheme.colorScheme.onSurface, disabledLabelColor = MaterialTheme.colorScheme.onSurface, disabledSelectedContainerColor = Color.Transparent, ), onClick = {}, label = { Text( text = "• ${consentField.displayName}", fontWeight = FontWeight.Normal, style = MaterialTheme.typography.bodyLarge ) }, ) } /** * Bottom actions containing 2 buttons: Cancel and Confirm * Once user taps on Confirm, we disable buttons to prevent unintended taps. */ @Composable private fun ConsentPromptActions( confirmButtonState: MutableState<ConfirmButtonState>, onCancel: () -> Unit, onConfirm: () -> Unit ) { Column(modifier = Modifier.fillMaxHeight()) { Row( horizontalArrangement = Arrangement.SpaceEvenly, modifier = Modifier.padding(horizontal = 10.dp) ) { // Cancel button Button( modifier = Modifier.weight(1f), onClick = { onCancel.invoke() } ) { Text(text = stringResource(id = R.string.consent_prompt_button_cancel)) } Spacer(modifier = Modifier.width(10.dp)) // Confirm button Button( modifier = Modifier.weight(1f), // enabled when user scrolls to the bottom enabled = confirmButtonState.value == ConfirmButtonState.ENABLED, onClick = { onConfirm.invoke() } ) { Text(text = stringResource(id = R.string.consent_prompt_button_confirm)) } } // fade out "scroll to bottom" when user reaches bottom of list (enabled via 'visible' param) AnimatedVisibility( visible = confirmButtonState.value == ConfirmButtonState.DISABLED, enter = fadeIn(), exit = fadeOut() ) { Text( text = stringResource(id = R.string.consent_prompt_text_scroll_to_bottom), fontSize = 12.sp, style = TextStyle.Default.copy( color = Color.Gray ), modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center ) } } }
98
Kotlin
83
161
fdc085a9f2a8b075b4f8ec5f4d4eb9fc752ac049
13,132
identity-credential
Apache License 2.0
app/src/main/java/com/gmail/rallen/gridstrument/event/MidiCCEvent.kt
atommarvel
189,650,334
true
{"Kotlin": 42814, "Java": 14783}
package com.gmail.rallen.gridstrument.event fun getAllNotesOffCCEvent(channel: Int = 0): MidiCCEvent = MidiCCEvent(123, 0, channel) /** * CC is short for Control Change */ data class MidiCCEvent @JvmOverloads constructor(val ctrlNumber: Int, val ctrlValue: Int, val channel: Int = 0) : MidiEvent { override val byteArray = byteArrayOf( (ccByte + channel).toByte(), ctrlNumber.toByte(), ctrlValue.toByte() ) companion object { // Status bits indicating that this is a Control Change message. private const val ccByte = 0xB0 } }
1
Kotlin
1
3
d51bbae837659ad4130685568053f8863afed972
596
GridStrument
MIT License
down-work-app-ktor/src/main/kotlin/v1/OrderController.kt
ponomain
589,205,451
false
null
package v1 import DownWorkContext import DownWorkOrderStubs import fromTransportOrder import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* import ru.otus.otuskotlin.downwork.api.v1.models.OrderCreateRequest import ru.otus.otuskotlin.downwork.api.v1.models.OrderDeleteRequest import ru.otus.otuskotlin.downwork.api.v1.models.OrderGetRequest import ru.otus.otuskotlin.downwork.api.v1.models.OrderSearchRequest import ru.otus.otuskotlin.downwork.api.v1.models.OrderUpdateRequest import toTransportOrder suspend fun ApplicationCall.createOrder() { val request = receive<OrderCreateRequest>() val context = DownWorkContext() context.fromTransportOrder(request) context.orderResponse = DownWorkOrderStubs.get() respond(context.toTransportOrder()) } suspend fun ApplicationCall.getOrder() { val request = receive<OrderGetRequest>() val context = DownWorkContext() context.fromTransportOrder(request) context.orderResponse = DownWorkOrderStubs.get() respond(context.toTransportOrder()) } suspend fun ApplicationCall.updateOrder() { val request = receive<OrderUpdateRequest>() val context = DownWorkContext() context.fromTransportOrder(request) context.orderResponse = DownWorkOrderStubs.get() respond(context.toTransportOrder()) } suspend fun ApplicationCall.deleteOrder() { val request = receive<OrderDeleteRequest>() val context = DownWorkContext() context.fromTransportOrder(request) context.orderResponse = DownWorkOrderStubs.get() respond(context.toTransportOrder()) } suspend fun ApplicationCall.searchOrders() { val request = receive<OrderSearchRequest>() val context = DownWorkContext() context.fromTransportOrder(request) context.ordersResponse.addAll(DownWorkOrderStubs.prepareSearchList("Kotlin")) respond(context.toTransportOrder()) }
0
Kotlin
0
0
1e5cc4a66ca079dd60998901d691c2dc8ec6031a
1,892
DownWork
Apache License 2.0
down-work-app-ktor/src/main/kotlin/v1/OrderController.kt
ponomain
589,205,451
false
null
package v1 import DownWorkContext import DownWorkOrderStubs import fromTransportOrder import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* import ru.otus.otuskotlin.downwork.api.v1.models.OrderCreateRequest import ru.otus.otuskotlin.downwork.api.v1.models.OrderDeleteRequest import ru.otus.otuskotlin.downwork.api.v1.models.OrderGetRequest import ru.otus.otuskotlin.downwork.api.v1.models.OrderSearchRequest import ru.otus.otuskotlin.downwork.api.v1.models.OrderUpdateRequest import toTransportOrder suspend fun ApplicationCall.createOrder() { val request = receive<OrderCreateRequest>() val context = DownWorkContext() context.fromTransportOrder(request) context.orderResponse = DownWorkOrderStubs.get() respond(context.toTransportOrder()) } suspend fun ApplicationCall.getOrder() { val request = receive<OrderGetRequest>() val context = DownWorkContext() context.fromTransportOrder(request) context.orderResponse = DownWorkOrderStubs.get() respond(context.toTransportOrder()) } suspend fun ApplicationCall.updateOrder() { val request = receive<OrderUpdateRequest>() val context = DownWorkContext() context.fromTransportOrder(request) context.orderResponse = DownWorkOrderStubs.get() respond(context.toTransportOrder()) } suspend fun ApplicationCall.deleteOrder() { val request = receive<OrderDeleteRequest>() val context = DownWorkContext() context.fromTransportOrder(request) context.orderResponse = DownWorkOrderStubs.get() respond(context.toTransportOrder()) } suspend fun ApplicationCall.searchOrders() { val request = receive<OrderSearchRequest>() val context = DownWorkContext() context.fromTransportOrder(request) context.ordersResponse.addAll(DownWorkOrderStubs.prepareSearchList("Kotlin")) respond(context.toTransportOrder()) }
0
Kotlin
0
0
1e5cc4a66ca079dd60998901d691c2dc8ec6031a
1,892
DownWork
Apache License 2.0
app/src/main/java/com/linkedintools/di/components/LinkedInUserSettingsComponent.kt
JohannBlake
190,872,147
false
null
package com.linkedintools.di.components import com.linkedintools.da.web.utils.LinkedInConverters import com.linkedintools.di.modules.LinkedInUserSettingsModule import dagger.Component import javax.inject.Singleton /** * Used when accessing a user's LinkedIn settings page. */ @Singleton @Component(modules = [(LinkedInUserSettingsModule::class)]) interface LinkedInUserSettingsComponent { fun inject(htmlConverter: LinkedInConverters.HtmlConverter) }
0
Kotlin
0
0
66d7dc4b9266af3f26b941a045b2cfa0b561ddcf
458
AndroidSampleAppLinkedIn
The Unlicense
src/main/kotlin/com/yapp/web2/domain/account/entity/Account.kt
YAPP-19th
399,059,127
false
null
package com.yapp.web2.domain.account.entity import com.yapp.web2.domain.BaseTimeEntity import com.yapp.web2.domain.folder.entity.AccountFolder import com.yapp.web2.domain.folder.entity.Folder import com.yapp.web2.security.jwt.TokenDto import io.swagger.annotations.ApiModel import io.swagger.annotations.ApiModelProperty import org.springframework.transaction.annotation.Transactional import javax.persistence.CascadeType import javax.persistence.Column import javax.persistence.Entity import javax.persistence.OneToMany import javax.validation.constraints.NotBlank import javax.validation.constraints.NotEmpty @Entity class Account( @Column(unique = true, nullable = true, length = 255) var email: String ) : BaseTimeEntity() { @Column(nullable = true) var password: String? = null @Column(nullable = true) var name: String = "" @Column(nullable = true, length = 20) var socialType: String = "none" @Column(length = 255) var fcmToken: String? = null @Column(length = 10) var remindCycle: Int = 7 @Column(nullable = true, length = 255) var image: String = BASIC_IMAGE_URL @Column(length = 20) var backgroundColor: String = "black" @Column var remindToggle: Boolean = true @Column var deleted: Boolean = false @OneToMany(mappedBy = "account", cascade = [CascadeType.ALL], orphanRemoval = true) var accountFolderList: MutableList<AccountFolder> = mutableListOf() fun inverseRemindToggle(reverse: Boolean) { this.remindToggle = reverse } companion object { fun signUpToAccount(dto: AccountRequestDto.SignUpRequest, encryptPassword: String, name: String): Account { return Account(dto.email, encryptPassword, dto.fcmToken, name) } fun profileToAccount(dto: AccountProfile): Account { return Account(dto.email, dto.image, dto.name, dto.socialType, dto.fcmToken) } fun accountToProfile(account: Account): AccountProfile { return AccountProfile( account.email, account.name, account.image, account.socialType, account.fcmToken ?: "" ) } fun accountToRemindElements(account: Account): RemindElements { return RemindElements(account.remindCycle, account.remindToggle) } const val BASIC_IMAGE_URL: String = "https://yapp-bucket-test.s3.ap-northeast-2.amazonaws.com/basicImage.png" } constructor(email: String, password: String) : this(email) { this.password = <PASSWORD> } constructor(email: String, encryptPassword: String, fcmToken: String, name: String) : this(email) { this.password = <PASSWORD> this.fcmToken = fcmToken this.name = name } constructor(email: String, image: String, nickname: String, socialType: String, fcmToken: String) : this(email) { this.image = image this.name = nickname this.socialType = socialType this.fcmToken = fcmToken } fun addAccountFolder(accountFolder: AccountFolder) { this.accountFolderList.add(accountFolder) } @Transactional fun isInsideAccountFolder(accountFolder: AccountFolder): Boolean { accountFolderList.forEach { if (it.folder.id == accountFolder.folder.id) return true } return false } @ApiModel(description = "소셜로그인 DTO") class AccountProfile( @ApiModelProperty(value = "이메일", required = true, example = "<EMAIL>") @field: NotEmpty(message = "이메일을 입력해주세요") val email: String, @ApiModelProperty(value = "닉네임", required = true, example = "도토리함") @field: NotEmpty(message = "닉네임을 입력해주세요") val name: String, @ApiModelProperty( value = "이미지", example = "https://yapp-bucket-test.s3.ap-northeast-2.amazonaws.com/static/61908b14-a736-46ef-9d89-3ef12ef57e38" ) val image: String, @ApiModelProperty(value = "소셜로그인 종류", required = true, example = "google") @field: NotEmpty(message = "소셜타입을 입력해주세요") val socialType: String, @ApiModelProperty( value = "FCM 토큰", required = true, example = "dOOUnnp-iBs:APA91bF1i7mobIF7kEhi3aVlFuv6A5--P1S..." ) @field: NotEmpty(message = "FCM 토큰을 입력해주세요") val fcmToken: String ) class AccountLoginSuccess( tokenDto: TokenDto, account: Account, isRegistered: Boolean ) { val accessToken = tokenDto.accessToken val refreshToken = tokenDto.refreshToken val email = account.email val name = account.name val image = account.image val socialType = account.socialType val remindCycle = account.remindCycle val remindToggle = account.remindToggle var isRegistered = isRegistered } class RemindElements( val remindCycle: Int?, val remindToggle: Boolean ) class ProfileChanged( val profileImageUrl: String, @field: NotBlank(message = "이름을 입력해주세요") val name: String ) class ImageUrl( val imageUrl: String ) class NextNickName( @field: NotBlank(message = "이름을 입력해주세요") val nickName: String ) fun removeFolderInAccountFolder(folder: Folder) { this.accountFolderList.let { it.removeIf { af -> af.folder == folder } } } fun softDeleteAccount() { this.deleted = true } fun updateFcmToken(fcmToken: String) { this.fcmToken = fcmToken } }
10
Kotlin
1
7
ecc6a3da2a66dceb1a25a4cfe9ed699f0325180a
5,667
Web-Team-2-Backend
Apache License 2.0
src/StringFifoSensor.kt
RomanBelkov
39,004,215
false
{"Text": 1, "Ignore List": 1, "Markdown": 1, "XML": 9, "JAR Manifest": 2, "Kotlin": 23, "Java": 2, "C": 2}
import java.io.BufferedReader import java.io.FileReader import java.io.Closeable import java.util.Optional import java.util.concurrent.Semaphore import kotlin.concurrent.thread import rx.Subscriber import rx.subjects.PublishSubject import java.util.concurrent.CountDownLatch /** * Created by <NAME> on 28.09.15. */ abstract class StringFifoSensor<T>(val path: String): Closeable, AutoCloseable { private var subject = PublishSubject.create<T>() private var isStarted = false private var isClosing = false private var threadHandler : Thread? = null private fun loop() { val streamReader = BufferedReader(FileReader(path)) tailrec fun reading (streamReader: BufferedReader) { if (isClosing == true) {streamReader.close(); return} val line = streamReader.readLine() if (line == null) stop() else { parse(line).ifPresent { subject.onNext(it) } reading(streamReader) } } threadHandler = thread { reading(streamReader) } } abstract fun parse(text: String): Optional<T> open fun start() { if (isStarted == true) throw Exception("Calling start() second time is prohibited") loop() isStarted = true } fun read(): T? { if (isStarted == false) { println("TrikKotlin: Starting the sensor for you!") start() } val countdown = CountDownLatch(1) var result: T? = null thread { subject.asObservable().subscribe(object : Subscriber<T>() { override fun onNext(p0: T) { result = p0 this.unsubscribe() countdown.countDown() } override fun onCompleted() = Unit override fun onError(p0: Throwable) = throw p0 }) } countdown.await() return result } open fun stop() { if (isStarted == false) throw Exception("Calling stop() before start() is prohibited") close() subject = PublishSubject.create<T>() } fun toObservable() = subject.asObservable() override fun close() { if (isStarted == true) { isClosing = true while (threadHandler!!.isAlive) { } subject.onCompleted() isStarted = false isClosing = false } } }
2
Kotlin
0
1
5f9675f4f81ea0483bb9688e5cd401178c3f129e
2,404
TrikKotlin
Apache License 2.0
protocol-union-model/src/main/kotlin/com/rarible/protocol/union/dto/continuation/CollectionContinuation.kt
rarible
424,892,912
false
{"Kotlin": 116809, "HTML": 541}
package com.rarible.protocol.union.dto.continuation import com.rarible.protocol.union.dto.CollectionDto object CollectionContinuation { object ById : ContinuationFactory<CollectionDto, IdContinuation> { override fun getContinuation(entity: CollectionDto): IdContinuation { return IdContinuation(entity.id.value) } } }
0
Kotlin
3
4
0e781e6581d12c08910bfb010d38c4315fc668d9
356
union-openapi
MIT License
spring-social-slideshare/src/main/kotlin/io/t28/springframework/social/slideshare/ext/RestOperationsExtensions.kt
t28hub
280,412,223
false
null
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.t28.springframework.social.slideshare.ext import org.springframework.web.client.RestOperations import org.springframework.web.client.getForObject /** * Extension for [RestOperations.getForObject] converting object to a list. * * @param url The URL string. * @param uriVariables The URI variables to expand the template. * @return The converted list. */ inline fun <reified T> RestOperations.getForListObject(url: String, vararg uriVariables: Any): List<T> { // Convert to a list after deserialize as an array because getForObject erasures generic type. val array = getForObject<Array<T>>(url, *uriVariables) return array.asList() }
1
Kotlin
0
0
a87b4991dbe121f84253825a5c5dc147603be998
1,253
spring-social-slideshare
Apache License 2.0
app/src/main/java/com/example/kotlin/examen/data/network/NetworkModuleDI.kt
DanielQueijeiro
868,704,483
false
{"Kotlin": 22003}
package com.example.kotlin.examen.data.network import LoggingInterceptor import com.example.kotlin.examen.util.Constants import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object NetworkModuleDI { private val gsonFactory: GsonConverterFactory = GsonConverterFactory.create() private val okHttpClient: OkHttpClient = OkHttpClient.Builder() .addInterceptor(LoggingInterceptor()) .build() operator fun invoke(): PersonajeAPIService { return Retrofit.Builder() .baseUrl(Constants.BASE_URL) .client(okHttpClient) .addConverterFactory(gsonFactory) .build() .create(PersonajeAPIService::class.java) } }
0
Kotlin
0
0
81938837a9f1e69e75bdd51a5f160d45df03a0b6
754
ExamenMovil
MIT License
app/src/main/java/com/anangkur/mediku/feature/view/auth/editPassword/EditPasswordActionListener.kt
anangkur
236,449,731
false
null
package com.anangkur.mediku.feature.view.auth.editPassword interface EditPasswordActionListener { fun onClickSave(oldPassword: String?, newPassword: String?, confirmPassword: String?) }
2
Kotlin
1
4
4b4e184a5ea9368c0901262ce9899bad6c56fb87
190
Medi-Ku
MIT License
kontroller/src/main/kotlin/no/ssb/kostra/validation/rule/sosial/kvalifisering/rule/Rule015VedtakDato.kt
statisticsnorway
414,216,275
false
{"Kotlin": 1602090, "TypeScript": 57803, "Batchfile": 6608, "HTML": 694, "SCSS": 110}
package no.ssb.kostra.validation.rule.sosial.kvalifisering.rule import no.ssb.kostra.area.sosial.kvalifisering.KvalifiseringColumnNames.KOMMUNE_NR_COL_NAME import no.ssb.kostra.area.sosial.kvalifisering.KvalifiseringColumnNames.PERSON_JOURNALNR_COL_NAME import no.ssb.kostra.area.sosial.kvalifisering.KvalifiseringColumnNames.SAKSBEHANDLER_COL_NAME import no.ssb.kostra.area.sosial.kvalifisering.KvalifiseringColumnNames.VEDTAK_DATO_COL_NAME import no.ssb.kostra.area.sosial.kvalifisering.KvalifiseringColumnNames.VERSION_COL_NAME import no.ssb.kostra.program.KostraRecord import no.ssb.kostra.program.KotlinArguments import no.ssb.kostra.program.extension.fieldAs import no.ssb.kostra.program.extension.yearWithCentury import no.ssb.kostra.validation.report.Severity import no.ssb.kostra.validation.rule.AbstractRule import no.ssb.kostra.validation.rule.sosial.kvalifisering.KvalifiseringRuleId import java.time.LocalDate class Rule015VedtakDato : AbstractRule<List<KostraRecord>>( KvalifiseringRuleId.VEDTAK_DATO_15.title, Severity.ERROR ) { override fun validate(context: List<KostraRecord>, arguments: KotlinArguments) = context .filterNot { it[KOMMUNE_NR_COL_NAME] == "0301" } .filter { it.fieldAs<LocalDate?>(VEDTAK_DATO_COL_NAME) == null || it.fieldAs<Int>(VERSION_COL_NAME).yearWithCentury() .minus(it.fieldAs<LocalDate>(VEDTAK_DATO_COL_NAME).year) > 4 }.map { createValidationReportEntry( "Feltet for 'Hvilken dato det ble fattet vedtak om program? (søknad innvilget)' med " + "verdien (${it[VEDTAK_DATO_COL_NAME]}) enten mangler utfylling, " + "har ugyldig dato eller dato som er eldre enn 4 år fra rapporteringsåret " + "(${arguments.aargang}). Feltet er obligatorisk å fylle ut.", lineNumbers = listOf(it.lineNumber) ).copy( caseworker = it[SAKSBEHANDLER_COL_NAME], journalId = it[PERSON_JOURNALNR_COL_NAME], ) }.ifEmpty { null } }
2
Kotlin
0
1
682be1572568c1dd5a4dc822012e5d3780ce1d02
2,138
kostra-kontrollprogram
MIT License
app/src/main/java/cn/arsenals/osarsenals/OsApplication.kt
Y-D-Lu
606,605,998
false
null
package cn.arsenals.osarsenals import android.app.Application import android.content.res.Configuration import cn.arsenals.osarsenals.manager.DeviceStatusManager import cn.arsenals.osarsenals.manager.OverviewViewManager import cn.arsenals.osarsenals.utils.Alog class OsApplication: Application() { companion object { private const val TAG = "OsApplication" lateinit var application: Application } init { application = this } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) } override fun onCreate() { super.onCreate() Alog.info(TAG, "Application onCreate") OverviewViewManager.getInstance().init() DeviceStatusManager.getInstance().init() } }
0
Kotlin
0
0
305e4e2d9dcf355bd29e4c4bce4a47ca011b1d78
801
OsArsenals
Apache License 2.0
app/src/main/java/cn/qhplus/emo/ui/page/AboutPage.kt
cgspine
497,802,224
false
null
/* * Copyright 2022 emo Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.qhplus.emo.ui.page import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import cn.qhplus.emo.EmoScheme import cn.qhplus.emo.WebViewActivity import cn.qhplus.emo.config.SchemeConst import cn.qhplus.emo.scheme.ComposeScheme import cn.qhplus.emo.ui.core.TopBar import cn.qhplus.emo.ui.core.TopBarBackIconItem import com.google.accompanist.web.WebView import com.google.accompanist.web.rememberWebViewState @ComposeScheme( action = SchemeConst.SCHEME_ACTION_ABOUT, alternativeHosts = [WebViewActivity::class] ) @Composable fun AboutPage() { Column( modifier = Modifier .fillMaxSize() ) { val topBarIconColor = MaterialTheme.colorScheme.onPrimary TopBar( title = { "About" }, leftItems = remember(topBarIconColor) { listOf( TopBarBackIconItem(tint = topBarIconColor) { EmoScheme.pop() } ) } ) val state = rememberWebViewState("https://github.com/cgspine/emo") WebView( state = state, modifier = Modifier .fillMaxWidth() .weight(1f) ) } }
1
Kotlin
10
103
1bcc50e9343e4b09da81f72a077dafc2c00d6c73
2,093
emo
Apache License 2.0
Laboratorio12/app/src/main/java/com/uvg/gt/laboratorio12/MainActivity.kt
ElrohirGT
666,059,791
false
{"Kotlin": 93244, "Rust": 18596, "Nix": 828}
@file:OptIn(ExperimentalMaterial3WindowSizeClassApi::class, ExperimentalMaterial3Api::class) package com.uvg.gt.laboratorio12 import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.items import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi import androidx.compose.material3.windowsizeclass.WindowSizeClass import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.uvg.gt.laboratorio12.ui.theme.Laboratorio12Theme import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Laboratorio12Theme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { val windowSizeClass = calculateWindowSizeClass(this) MainComponent(windowSizeClass) } } } } } @Composable fun MainComponent(windowSizeClass: WindowSizeClass, modifier: Modifier = Modifier) { val (input, setInput) = remember { mutableStateOf("") } val images = arrayOf( R.drawable.meme00, R.drawable.meme01, R.drawable.meme02, R.drawable.meme03, R.drawable.meme04, R.drawable.meme05, R.drawable.meme06, R.drawable.meme07, R.drawable.meme08, R.drawable.meme09, R.drawable.meme10, R.drawable.meme11, R.drawable.meme12, R.drawable.meme13, R.drawable.meme14, R.drawable.meme15, R.drawable.meme16, R.drawable.meme17, R.drawable.meme18, R.drawable.meme19, R.drawable.meme20, R.drawable.meme21, R.drawable.meme22, R.drawable.meme23, R.drawable.meme24, R.drawable.meme25, R.drawable.meme26, R.drawable.meme27, R.drawable.meme28, R.drawable.meme29, R.drawable.meme30, R.drawable.meme31, R.drawable.meme32, R.drawable.meme33, R.drawable.meme34, R.drawable.meme35, R.drawable.meme36, R.drawable.meme37, R.drawable.meme38, R.drawable.meme39, R.drawable.meme40, R.drawable.meme41, R.drawable.meme42, R.drawable.meme43, R.drawable.meme44, R.drawable.meme45, R.drawable.meme46, R.drawable.meme47, R.drawable.meme48, R.drawable.meme49, R.drawable.meme50, R.drawable.meme51, R.drawable.meme52, R.drawable.meme53, R.drawable.meme54, R.drawable.meme55, R.drawable.meme56, ) if (windowSizeClass.widthSizeClass == WindowWidthSizeClass.Compact) { Column( modifier = modifier .fillMaxWidth() .padding(10.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Text("Bienvenido!", style = MaterialTheme.typography.displayLarge) TextField(value = input, onValueChange = setInput, modifier.fillMaxWidth()) Button(onClick = { /*TODO*/ }, modifier = modifier.fillMaxWidth()) { Text("¡Subir!") } Spacer(modifier = modifier.height(10.dp)) Text("Lista...", style = MaterialTheme.typography.displaySmall) LazyColumn(contentPadding = PaddingValues(10.dp)) { items(images) { Image(painter = painterResource(id = it), contentDescription = "Meme image", modifier = modifier .fillMaxWidth(), contentScale = ContentScale.FillWidth) } } } } else { Column( modifier = modifier .fillMaxWidth() .padding(10.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Text("Bienvenido!", style = MaterialTheme.typography.displayLarge) Row(modifier = modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceAround) { TextField(value = input, onValueChange = setInput) Button(onClick = { /*TODO*/ }) { Text("¡Subir!") } } Spacer(modifier = modifier.height(10.dp)) Text("Lista...", style = MaterialTheme.typography.displaySmall) val columns = if (windowSizeClass.widthSizeClass == WindowWidthSizeClass.Medium) { 5 } else { 10 } LazyVerticalGrid(columns = GridCells.Fixed(columns), contentPadding = PaddingValues(10.dp)) { items(images.size) { Image(painter = painterResource(id = images[it]), contentDescription = "Meme image", modifier = modifier .fillMaxWidth() .padding(10.dp), contentScale = ContentScale.FillWidth) } } } } }
0
Kotlin
0
0
7b1262f48ccc44523ed9554315c6935d3ce87dae
6,762
Desarrollo-de-Aplicaciones-Moviles
MIT License
src/main/kotlin/com/tankobon/domain/models/Manga.kt
fopwoc
445,686,330
false
{"Kotlin": 108306, "Dockerfile": 441}
package com.tankobon.domain.models import com.tankobon.api.models.MangaVolumeModel import java.util.UUID enum class MangaParameterType { ID_TITLE, ID_VOLUME, ID_PAGE, } interface MangaTitleMeta { val title: String val description: String } interface MangaVolumeMeta { val title: String? } // TODO: review inheritance data class MangaUpdate( override val id: UUID, override val title: String? = null, override val content: List<MangaVolumeModel> = emptyList(), ) : IdEntity<UUID>, ContentEntity<MangaVolumeModel>, MangaVolumeMeta
8
Kotlin
0
4
dbb38256649ef763dc9ae5e8c3ec56cc5b776363
570
tankobon-backend-kotlin
MIT License
src/main/kotlin/com/inteligenciadigital/bookmarket/controllers/CustomerController.kt
GabrielIFPB
436,716,510
false
null
package com.inteligenciadigital.bookmarket.controllers import com.inteligenciadigital.bookmarket.exception.CustomerBadRequest import com.inteligenciadigital.bookmarket.exception.CustomerNotFoundException import com.inteligenciadigital.bookmarket.models.Customer import com.inteligenciadigital.bookmarket.models.CustomerBirthdate import com.inteligenciadigital.bookmarket.models.CustomerName import com.inteligenciadigital.bookmarket.service.CustomerServiceImplements import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.* @RestController @RequestMapping("api/customers") class CustomerController(var service: CustomerServiceImplements) { @GetMapping("") fun findAll(): List<Customer> = this.service.all() @GetMapping("/{id}") fun findById(@PathVariable id: Long): Customer = try { this.service.findById(id) } catch (e: CustomerNotFoundException) { throw CustomerNotFoundException("Não encontrado...") } @PostMapping("") @ResponseStatus(HttpStatus.CREATED) fun save(@RequestBody customer: Customer): Customer = this.service.save(customer) @PutMapping("") @ResponseStatus(HttpStatus.OK) fun update(@RequestBody customer: Customer): Customer = try { this.service.update(customer) } catch (e: CustomerNotFoundException) { throw CustomerNotFoundException("não encontrado") } catch (e: CustomerBadRequest) { throw CustomerBadRequest(e.message.toString()) } @PatchMapping("/{id}/birthdate") @ResponseStatus(HttpStatus.OK) fun updateBirthdate( @PathVariable id: Long, @RequestBody customerRequest: CustomerBirthdate): Int = try { this.service.updateBirthdate( id, customerRequest.birthdate ) } catch (e: CustomerNotFoundException) { throw CustomerNotFoundException("Customer ${id}: not found!") } @PatchMapping("/{id}/name") @ResponseStatus(HttpStatus.OK) fun updateName( @PathVariable id: Long, @RequestBody customerRequest: CustomerName): Int = try { this.service.updateName(id, customerRequest.name) } catch (e: CustomerNotFoundException) { throw CustomerNotFoundException("Customer ${id}: not found!") } @DeleteMapping("/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) fun delete(@PathVariable id: Long): Unit = try { this.service.delete(id) } catch (e: CustomerNotFoundException) { throw CustomerNotFoundException("Customer: not found!") } }
0
Kotlin
0
0
56bf7d6058951639f5d6c8d23daf1039e9f0e1a0
2,391
book-market
MIT License
app/src/main/java/io/chaldeaprjkt/yumetsuki/worker/RefreshWorker.kt
nullxception
548,504,514
false
null
package io.chaldeaprjkt.yumetsuki.worker import android.content.Context import androidx.hilt.work.HiltWorker import androidx.work.CoroutineWorker import androidx.work.ExistingPeriodicWorkPolicy import androidx.work.PeriodicWorkRequestBuilder import androidx.work.WorkManager import androidx.work.WorkerParameters import dagger.assisted.Assisted import dagger.assisted.AssistedInject import io.chaldeaprjkt.yumetsuki.R import io.chaldeaprjkt.yumetsuki.data.common.HoYoData import io.chaldeaprjkt.yumetsuki.data.gameaccount.entity.HoYoGame import io.chaldeaprjkt.yumetsuki.data.gameaccount.isEmpty import io.chaldeaprjkt.yumetsuki.data.gameaccount.server import io.chaldeaprjkt.yumetsuki.data.realtimenote.entity.RealtimeNote import io.chaldeaprjkt.yumetsuki.data.settings.entity.NotifierSettings import io.chaldeaprjkt.yumetsuki.domain.repository.GameAccountRepo import io.chaldeaprjkt.yumetsuki.domain.repository.RealtimeNoteRepo import io.chaldeaprjkt.yumetsuki.domain.repository.SessionRepo import io.chaldeaprjkt.yumetsuki.domain.repository.SettingsRepo import io.chaldeaprjkt.yumetsuki.domain.repository.UserRepo import io.chaldeaprjkt.yumetsuki.ui.widget.WidgetEventDispatcher import io.chaldeaprjkt.yumetsuki.util.elog import io.chaldeaprjkt.yumetsuki.util.notifier.Notifier import io.chaldeaprjkt.yumetsuki.util.notifier.NotifierType import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.withContext import java.util.concurrent.TimeUnit @HiltWorker class RefreshWorker @AssistedInject constructor( @Assisted context: Context, @Assisted workerParams: WorkerParameters, private val realtimeNoteRepo: RealtimeNoteRepo, private val gameAccountRepo: GameAccountRepo, private val sessionRepo: SessionRepo, private val widgetEventDispatcher: WidgetEventDispatcher, private val settingsRepo: SettingsRepo, private val userRepo: UserRepo, ) : CoroutineWorker(context, workerParams) { private suspend fun refreshDailyNote() { val active = gameAccountRepo.getActive(HoYoGame.Genshin).firstOrNull() ?: return val cookie = userRepo.ofId(active.hoyolabUid).firstOrNull()?.cookie if (!active.isEmpty() && cookie != null) { realtimeNoteRepo.sync( active.uid, active.server, cookie, ).collect { if (it is HoYoData) { updateData(it.data) } widgetEventDispatcher.refreshAll() } } } private suspend fun updateData(realtimeNote: RealtimeNote) { val expeditionTime = sessionRepo.data.firstOrNull()?.expeditionTime ?: 0 val notifierSettings = settingsRepo.data.firstOrNull()?.notifier ?: NotifierSettings.Empty val note = realtimeNoteRepo.data.firstOrNull() ?: RealtimeNote.Empty val savedResin = note.currentResin val currentResin = realtimeNote.currentResin val num = notifierSettings.onResin.value if (num >= 40) { for (i in 40..160 step 40) { if (i % num == 0 && i in savedResin + 1..currentResin) { notify(NotifierType.Resin(i)) } } } val nowExpeditionTime = realtimeNote.expeditionSettledTime if (notifierSettings.onExpeditionCompleted && 1 in (nowExpeditionTime)..expeditionTime && realtimeNote.expeditions.isNotEmpty() && nowExpeditionTime == 0 ) { notify(NotifierType.ExpeditionCompleted) } val nowHomeCoinRecoveryTime = realtimeNote.realmCurrencyRecoveryTime if (notifierSettings.onRealmCurrencyFull && 1 in nowHomeCoinRecoveryTime..note.realmCurrencyRecoveryTime && realtimeNote.totalRealmCurrency != 0 && nowHomeCoinRecoveryTime == 0 ) { notify(NotifierType.RealmCurrencyFull) } sessionRepo.update { session -> session.copy( lastGameDataSync = System.currentTimeMillis(), expeditionTime = realtimeNote.expeditionSettledTime ) } widgetEventDispatcher.refreshAll() } private fun notify(type: NotifierType) { if (type is NotifierType.CheckIn) return val title = when (type) { is NotifierType.Resin -> applicationContext.getString(R.string.push_resin_title) is NotifierType.ExpeditionCompleted -> applicationContext.getString(R.string.push_expedition_title) is NotifierType.RealmCurrencyFull -> applicationContext.getString(R.string.push_realm_currency_title) else -> return } val msg = when (type) { is NotifierType.Resin, -> applicationContext.resources.run { if (type.value == 160) { getString(R.string.push_msg_resin_full) } else { getString(R.string.push_msg_resin_num, type.value) } } NotifierType.ExpeditionCompleted -> applicationContext.getString(R.string.push_msg_expedition_done) NotifierType.RealmCurrencyFull -> applicationContext.getString(R.string.push_msg_realm_currency_full) else -> return } Notifier.send(type, applicationContext, title, msg) } override suspend fun doWork() = withContext(Dispatchers.IO) { try { refreshDailyNote() Result.success() } catch (e: Exception) { elog(e) widgetEventDispatcher.refreshAll() Result.failure() } } companion object { private const val TAG = "AutoRefreshWork" fun start(workManager: WorkManager?, period: Long) { if (period == -1L || workManager == null) return workManager.cancelAllWorkByTag(TAG) val request = PeriodicWorkRequestBuilder<RefreshWorker>(period, TimeUnit.MINUTES).addTag(TAG) .build() workManager.enqueueUniquePeriodicWork(TAG, ExistingPeriodicWorkPolicy.UPDATE, request) } fun stop(workManager: WorkManager?) { workManager?.cancelAllWorkByTag(TAG) } } }
0
Kotlin
0
2
0bb9fb3d8fd8370df44355aed4645b420130c456
6,280
yumetsuki
MIT License
detail/src/main/java/com/onirutla/githubuser/detail/DetailViewModel.kt
onirutlA
416,776,047
false
null
package com.onirutla.githubuser.detail import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.asLiveData import androidx.lifecycle.switchMap import androidx.lifecycle.viewModelScope import com.onirutla.githubuser.core.data.UIState import com.onirutla.githubuser.core.domain.data.User import com.onirutla.githubuser.core.domain.repository.UserRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class DetailViewModel @Inject constructor( private val userRepository: UserRepository, ) : ViewModel() { private val _username = MutableLiveData<String>() val user: LiveData<UIState<User>> = _username.switchMap { userRepository.getDetailBy(it).asLiveData(viewModelScope.coroutineContext) } fun setFavorite(user: User) { viewModelScope.launch { userRepository.setFavorite(user) } } fun getUser(username: String) { _username.value = username } }
0
Kotlin
0
2
959940cf7aa9d54b48440b8ddd164eb06d4ce7dd
1,089
github-user
Apache License 2.0
registry/src/main/kotlin/com/example/demo/DemoApplication.kt
K0zka
317,312,723
false
null
package com.example.demo import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer @SpringBootApplication @EnableEurekaServer class DemoApplication fun main(args: Array<String>) { runApplication<DemoApplication>(*args) }
0
Kotlin
0
0
5f890b4256aa3f7734b1527cac6aea4dda8b0959
356
spring-boot-playground
The Unlicense
spring-kt/src/main/java/com/yazan98/kego/example/kt/demo/kego/response/KegoResponseContent.kt
Yazan98
260,540,090
false
null
package com.yazan98.kego.example.kt.demo.kego.response /** * Name : Yazan98 * Date : 5/2/2020 * Time : 2:46 AM * Project Name : IntelliJ IDEA */ interface KegoResponseContent
0
Kotlin
0
0
5792243cf6a87134e0952bfd4f402e38dae9613d
180
Feature-Flag-Example
Apache License 2.0
shared/src/main/java/dev/zwander/shared/components/LongClickableIconButton.kt
zacharee
664,480,223
false
{"Kotlin": 140112, "AIDL": 334}
@file:Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE", "EXPOSED_PARAMETER_TYPE") package dev.zwander.shared.components import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size import androidx.compose.material3.IconButtonColors import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.LocalContentColor import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.material3.ripple import androidx.compose.material3.tokens.IconButtonTokens import androidx.compose.material3.value import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.semantics.Role @OptIn(ExperimentalFoundationApi::class) @Composable fun LongClickableIconButton( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, colors: IconButtonColors = IconButtonDefaults.iconButtonColors(), interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, onLongClick: (() -> Unit)? = null, content: @Composable () -> Unit, ) { Box( modifier = modifier .minimumInteractiveComponentSize() .size(IconButtonTokens.StateLayerSize) .clip(IconButtonTokens.StateLayerShape.value) .background(color = colors.containerColor(enabled)) .combinedClickable( onClick = onClick, enabled = enabled, role = Role.Button, interactionSource = interactionSource, indication = ripple( bounded = false, radius = IconButtonTokens.StateLayerSize / 2 ), onLongClick = onLongClick, ), contentAlignment = Alignment.Center ) { val contentColor = colors.contentColor(enabled) CompositionLocalProvider(LocalContentColor provides contentColor, content = content) } }
6
Kotlin
3
97
2619100762e7cc25f3f4d27bab3b458ccc23763d
2,390
MastodonRedirect
MIT License
src/main/kotlin/com/luciofm/Democracy.kt
luciofm
260,319,147
false
null
package com.luciofm import java.security.InvalidParameterException class Democracy { var debugEnabled = false fun countVotes(lines: List<String>): Pair<Int, Map<String, Int>> { val votes = parseVotes(lines) return processVotes(votes) } fun parseVotes(lines: List<String>): Map<String, Vote> { val votes = hashMapOf<String, Vote>() lines.forEach { line -> val (voter, what, who) = line.split(" ") if (voter.isEmpty() or what.isEmpty() or who.isEmpty()) { throw IllegalStateException("Invalid line format: $line") } val action = parseAction(what) val vote = Vote(voter.toLowerCase(), action, who.toLowerCase()) votes.put(vote.voter, vote)?.let { throw IllegalStateException("duplicate voter: ${vote.voter}") } } return votes } private fun processVotes(map: Map<String, Vote>): Pair<Int, Map<String, Int>> { var invalid = 0 val castedVotes = hashMapOf<String, Int>() map.forEach { (_, vote) -> try { val castedVote = if (vote.action == Action.PICK) { // look for vote.voter vote, since it is a pick action... findVote(vote.voter, "", vote.voter, map) } else { // look for the delegate vote recursively findVote(vote.voter, vote.voter, vote.who, map) } addVote(castedVote, castedVotes) debug { "${vote.voter} voted for $castedVote" } } catch (ex: Throwable) { invalid++ debug { "Invalid vote: ${ex.message}" } } } return Pair(invalid, castedVotes) } // voter: keeps track who is the original voter // currentVoter is the current voter, for example "Paul delegate John", "John pick Ringo", on the second iteration // original will be Paul, and current will be john // selection: the vote to look for... "Paul delegate John" -> selection would be John private fun findVote(voter: String, currentVoter: String, selection: String, map: Map<String, Vote>): String { map[selection].let { vote -> if (voter == vote?.who) throw InvalidParameterException("voter and vote.who must be different: $voter, ${vote.who}") if (currentVoter == vote?.who) throw InvalidParameterException("currentVoter and vote.who must be different: $currentVoter, ${vote.who}") return when (vote?.action) { Action.PICK -> { if (currentVoter == selection) { throw InvalidParameterException("Invalid self vote") } vote.who } Action.DELEGATE -> findVote(voter, vote.voter, vote.who, map) null -> throw InvalidParameterException("Vote not found for: ${vote?.action}") } } } private fun addVote(what: String, castedVotes: HashMap<String, Int>) { val votes = (castedVotes[what] ?: 0) + 1 castedVotes[what] = votes } fun parseAction(what: String): Action { return when(what.toLowerCase()) { "pick" -> Action.PICK "delegate" -> Action.DELEGATE else -> throw InvalidParameterException("expected values \"pick\" and \"delegate\": actual value: \"$what\"") } } private fun debug(message: () -> String) { if (debugEnabled) println(message()) } } enum class Action { PICK, DELEGATE } data class Vote( val voter: String, val action: Action, val who: String )
0
Kotlin
0
0
4f38aea9638e0e52f1115ef63d3f641ed1e05d9f
3,734
LiquidDemocracy
MIT License
feature/watchlist/src/test/kotlin/com/azizutku/movie/feature/watchlist/data/repository/WatchlistRepositoryImplTest.kt
azizutku
579,143,942
false
null
package com.azizutku.movie.feature.watchlist.data.repository import android.util.Log import androidx.paging.testing.asSnapshot import app.cash.turbine.test import com.azizutku.movie.core.common.extensions.orFalse import com.azizutku.movie.core.common.extensions.orTrue import com.azizutku.movie.core.common.vo.DataState import com.azizutku.movie.core.database.model.WatchlistEntity import com.azizutku.movie.core.testing.fakes.watchlist.FakeWatchlistLocalDataSourceImpl import com.azizutku.movie.core.testing.models.movieEntity import com.azizutku.movie.core.testing.models.movieEntity2 import com.azizutku.movie.core.testing.util.CoroutineRule import com.azizutku.movie.feature.watchlist.domain.model.WatchlistMovieLocalMapper import io.mockk.every import io.mockk.mockkStatic import kotlinx.coroutines.launch import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Rule import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertFalse class WatchlistRepositoryImplTest { @get:Rule val coroutineRule = CoroutineRule() private lateinit var watchlistRepository: WatchlistRepositoryImpl private lateinit var fakeWatchlistLocalDataSourceImpl: FakeWatchlistLocalDataSourceImpl @Before fun setUp() { fakeWatchlistLocalDataSourceImpl = FakeWatchlistLocalDataSourceImpl() watchlistRepository = WatchlistRepositoryImpl( localDataSource = fakeWatchlistLocalDataSourceImpl, localMapper = WatchlistMovieLocalMapper(), ) mockkStatic(Log::isLoggable) every { Log.isLoggable(any(), any()) } returns false } @Test fun `calling addMovie emits expected states and adds movie to local cache`() = runTest { // Arrange val movieId = 1 // Act val addMovieFlow = watchlistRepository.addMovie(movieId) // Assert launch { addMovieFlow.test { assert(awaitItem() is DataState.Loading) val dataState = awaitItem() assert(dataState is DataState.Success) assert((dataState as? DataState.Success)?.data?.isInWatchlist.orFalse()) cancelAndIgnoreRemainingEvents() } assert(fakeWatchlistLocalDataSourceImpl.isMovieInWatchlist(movieId = movieId)) } runCurrent() } @Test fun `calling removeMovie emits expected states and removes movie from local cache`() = runTest { // Arrange val movieId = 1 watchlistRepository.addMovie(movieId) // Act val removeMovieFlow = watchlistRepository.removeMovie(movieId) // Assert launch { removeMovieFlow.test { assert(awaitItem() is DataState.Loading) val dataState = awaitItem() assert(dataState is DataState.Success) assertFalse((dataState as? DataState.Success)?.data?.isInWatchlist.orTrue()) cancelAndIgnoreRemainingEvents() } assertFalse(fakeWatchlistLocalDataSourceImpl.isMovieInWatchlist(movieId = movieId)) } runCurrent() } @Test fun `calling getAllMovies emits expected states and retrieves all movies from local cache`() = runTest { // Arrange val movieEntities = listOf( movieEntity, movieEntity2, ) fakeWatchlistLocalDataSourceImpl.movieEntitiesForPagingSource = movieEntities // Act val getAllMovieFlow = watchlistRepository.getAllMovies() // Assert launch { val watchlistMovies = getAllMovieFlow.asSnapshot() assertEquals( expected = movieEntities.map { WatchlistMovieLocalMapper().map(it) }, actual = watchlistMovies, ) } runCurrent() } @Test fun `calling isMovieInWatchlist emits expected states for movie present in watchlist`() = runTest { // Arrange val movieId = 1 fakeWatchlistLocalDataSourceImpl.addToWatchlist( WatchlistEntity( movieId = movieId, addedAt = System.currentTimeMillis(), ), ) // Act val isMovieInWatchlistFlow = watchlistRepository.isMovieInWatchlist(movieId) // Assert launch { isMovieInWatchlistFlow.test { assert(awaitItem() is DataState.Loading) val dataState = awaitItem() assert(dataState is DataState.Success) assert((dataState as? DataState.Success)?.data?.isInWatchlist.orFalse()) cancelAndIgnoreRemainingEvents() } } runCurrent() } @Test fun `calling isMovieInWatchlist emits expected states for movie absent from watchlist`() = runTest { // Arrange val movieId = 1 // Act val isMovieInWatchlistFlow = watchlistRepository.isMovieInWatchlist(movieId) // Assert launch { isMovieInWatchlistFlow.test { assert(awaitItem() is DataState.Loading) val dataState = awaitItem() assert(dataState is DataState.Success) assertFalse((dataState as? DataState.Success)?.data?.isInWatchlist.orTrue()) cancelAndIgnoreRemainingEvents() } } runCurrent() } }
0
null
4
36
d6e8a01a41d1f61fc1b233cb32e17505c0707a20
5,861
Modular-Clean-Arch-Movie-App
MIT License
KmpCrypto/src/commonMain/kotlin/com/oldguy/crypto/BlockCipherECB.kt
skolson
467,705,703
false
{"Kotlin": 355093, "Ruby": 2202, "Prolog": 34}
package com.oldguy.crypto class ECBBlockCipher(val cipher: BlockCipher) : BlockCipher { override val algorithmName = cipher.algorithmName override val blockSize = cipher.blockSize override val ivSize = blockSize override fun init(forEncryption: Boolean, params: CipherParameters) { if (params is ParametersWithIV) { cipher.init(forEncryption, params.parameters) } else if (params is KeyParameter) { cipher.init(forEncryption, params) } else { throw IllegalArgumentException("invalid parameters passed to ECB") } } override fun processBlock( inBlock: UByteArray, inOff: Int, outBlock: UByteArray, outOff: Int ): Int { return cipher.processBlock(inBlock, inOff, outBlock, outOff) } override fun reset() { cipher.reset() } }
0
Kotlin
0
1
265fb4f8b7c1d9bb4fe82f44f328fe8d7b3898f2
882
KmpCrypto
Apache License 2.0
app/src/main/java/com/dicoding/asclepius/view/main/MainActivity.kt
Pavelmez
802,382,087
false
{"Kotlin": 29615}
package com.dicoding.asclepius.view.main import android.content.Intent import android.net.Uri import android.os.Bundle import android.os.Environment import android.provider.MediaStore import android.util.Log import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.core.content.FileProvider import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import com.dicoding.asclepius.adapter.NewsAdapter import com.dicoding.asclepius.databinding.ActivityMainBinding import com.dicoding.asclepius.helper.ImageClassifierHelper import com.dicoding.asclepius.view.result.ResultActivity import com.dicoding.asclepius.view.history.HistoryActivity import com.dicoding.asclepius.view.news.NewsActivity import com.yalantis.ucrop.UCrop import com.yalantis.ucrop.model.AspectRatio import org.tensorflow.lite.task.vision.classifier.Classifications import java.io.File import java.text.SimpleDateFormat import java.util.Date import java.util.Locale class MainActivity : AppCompatActivity(), ImageClassifierHelper.ClassifierListener { private lateinit var binding: ActivityMainBinding private lateinit var imageClassifierHelper: ImageClassifierHelper private var currentImageUri: Uri? = null private lateinit var currentImageFile: File private lateinit var mainViewModel: MainViewModel private lateinit var newsAdapter: NewsAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.galleryButton.setOnClickListener { startGallery() } binding.analyzeButton.setOnClickListener { analyzeImage() } binding.historyButton.setOnClickListener { moveToHistory() } imageClassifierHelper = ImageClassifierHelper( context = this, classifierListener = this ) // Initialize MainViewModel mainViewModel = ViewModelProvider(this)[MainViewModel::class.java] // Initialize RecyclerView and its adapter newsAdapter = NewsAdapter { clickedItem -> // Handle item click here val intent = Intent(this@MainActivity, NewsActivity::class.java) intent.putExtra("title", clickedItem.title) intent.putExtra("description", clickedItem.description) intent.putExtra("imageUrl", clickedItem.urlToImage) startActivity(intent) } binding.recyclerView.apply { layoutManager = LinearLayoutManager(this@MainActivity, LinearLayoutManager.HORIZONTAL, false) adapter = newsAdapter } // Observe the articlesList LiveData and update the adapter mainViewModel.articlesList.observe(this, Observer { articles -> articles?.let { newsAdapter.submitList(it) } }) } private fun startGallery() { // TODO: Mendapatkan gambar dari Gallery. val pickImageIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) launcherGallery.launch(pickImageIntent) } private val launcherGallery = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode == RESULT_OK) { val selectedImageUri: Uri? = result.data?.data selectedImageUri?.let { uri -> currentImageFile = createImageFile() val destinationUri = Uri.fromFile(currentImageFile) val maxWidth = 800 // Example max width val maxHeight = 600 // Example max height // Define custom aspect ratio options val aspectRatioOptions = listOf( AspectRatio("16:9", 16f, 9f), AspectRatio("4:3", 4f, 3f), AspectRatio("1:1", 1f, 1f) ) val options = UCrop.Options().apply { setAspectRatioOptions(0, *aspectRatioOptions.toTypedArray()) } UCrop.of(uri, destinationUri) .withOptions(options) .withMaxResultSize(maxWidth, maxHeight) .start(this@MainActivity) } } else { showToast("No image selected") } } private fun createImageFile(): File { // Create an image file name with a unique timestamp val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date()) val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES) return File.createTempFile( "cropped_image_$timeStamp", /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) { val resultUri = UCrop.getOutput(data!!) resultUri?.let { currentImageUri = it // Update currentImageUri with the URI of the cropped image showImage() } } else if (resultCode == UCrop.RESULT_ERROR) { val cropError = UCrop.getError(data!!) cropError?.message?.let { showToast(it) } } } private fun showImage() { // TODO: Display the image corresponding to the currentImageUri. currentImageUri?.let { Log.d("Image URI", "showImage: $it") binding.previewImageView.setImageURI(it) } } private fun analyzeImage() { // TODO: Analyze the selected image if (::currentImageFile.isInitialized) { currentImageFile.let { file -> val uri = FileProvider.getUriForFile(this, applicationContext.packageName + ".provider", file) imageClassifierHelper.classifyStaticImage(uri) } } else { showToast("Please select an image first") } } private fun resultsToString(results: List<Classifications>): String { val resultStringBuilder = StringBuilder() for (classification in results) { val sortedCategories = classification.categories.sortedByDescending { it.score } val highestLabel = sortedCategories.firstOrNull()?.label ?: "Unknown" val highestScore = sortedCategories.firstOrNull()?.score ?: 0f val highestScorePercentage = highestScore * 100 resultStringBuilder.append("$highestLabel = ${highestScorePercentage.formatPercentage(2)}%\n") } return resultStringBuilder.toString() } private fun Float.formatPercentage(digits: Int): String { return String.format("%.${digits}f", this) } override fun onResults(results: List<Classifications>?, inferenceTime: Long) { if (results != null && results.isNotEmpty()) { val resultString = resultsToString(results) moveToResult(Uri.fromFile(currentImageFile), resultString) // Use URI from currentImageFile } else { showToast("No classification results available") } } private fun moveToResult(uri: Uri, results: String) { val intent = Intent(this, ResultActivity::class.java).apply { putExtra(ResultActivity.EXTRA_IMAGE_URI, uri.toString()) putExtra(ResultActivity.EXTRA_RESULTS, results) } startActivity(intent) } private fun moveToHistory() { val intent = Intent(this, HistoryActivity::class.java) startActivity(intent) } private fun showToast(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } override fun onError(error: String) { showToast(error) } }
0
Kotlin
0
0
7cf6a739ae0e8e494d93408c8819a41a4ced463a
8,116
Basic-Cancer-Checker
MIT License
platform/projectModel-api/src/com/intellij/openapi/components/StoredProperty.kt
jonnybot0
114,696,203
true
{"Text": 3007, "XML": 4479, "Ant Build System": 18, "Shell": 37, "Markdown": 17, "Ignore List": 27, "Git Attributes": 6, "Batchfile": 31, "Kotlin": 1613, "Java": 57302, "Java Properties": 87, "HTML": 2615, "Groovy": 2563, "INI": 206, "JFlex": 23, "XSLT": 109, "JavaScript": 180, "CSS": 63, "desktop": 1, "Python": 10084, "SVG": 189, "C#": 32, "Diff": 125, "Roff": 73, "Roff Manpage": 4, "Smalltalk": 14, "Rich Text Format": 2, "JSON": 267, "CoffeeScript": 3, "JSON with Comments": 1, "OpenStep Property List": 2, "YAML": 96, "Perl": 4, "J": 18, "Protocol Buffer": 2, "JAR Manifest": 9, "fish": 1, "Gradle": 42, "EditorConfig": 2, "E-mail": 18, "Maven POM": 1, "Checksums": 58, "Java Server Pages": 25, "C": 36, "AspectJ": 2, "HLSL": 2, "Erlang": 1, "Ruby": 2, "AMPL": 4, "Linux Kernel Module": 1, "Makefile": 2, "Microsoft Visual Studio Solution": 6, "C++": 14, "Objective-C": 9, "CMake": 3, "VBScript": 1, "NSIS": 8, "PHP": 46, "Thrift": 2, "Cython": 9, "TeX": 7, "reStructuredText": 50, "Gettext Catalog": 125, "Jupyter Notebook": 5, "Regular Expression": 3}
/* * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.intellij.openapi.components import com.intellij.openapi.util.ModificationTracker import kotlin.reflect.KProperty internal class ObjectStoredProperty<T>(private val defaultValue: T) : StoredPropertyBase<T>() { private var value = defaultValue override operator fun getValue(thisRef: BaseState, property: KProperty<*>): T = value override fun setValue(thisRef: BaseState, property: KProperty<*>, value: T) { if (this.value != value) { thisRef.ownModificationCount++ this.value = value } } override fun isEqualToDefault() = defaultValue == value override fun equals(other: Any?) = this === other || (other is ObjectStoredProperty<*> && value == other.value) override fun hashCode() = value?.hashCode() ?: 0 override fun toString() = if (isEqualToDefault()) "" else value?.toString() ?: super.toString() override fun setValue(other: StoredProperty): Boolean { @Suppress("UNCHECKED_CAST") val newValue = (other as ObjectStoredProperty<T>).value if (newValue == value) { return false } value = newValue return true } override fun getModificationCount(): Long { val value = value return if (value is ModificationTracker) value.modificationCount else 0 } } internal class NormalizedStringStoredProperty(override val defaultValue: String?) : PrimitiveStoredPropertyBase<String?>() { override var value = defaultValue override operator fun getValue(thisRef: BaseState, property: KProperty<*>) = value override fun setValue(thisRef: BaseState, property: KProperty<*>, value: String?) { val newValue = if (value.isNullOrEmpty()) null else value if (this.value != newValue) { thisRef.ownModificationCount++ this.value = newValue } } override fun equals(other: Any?) = this === other || (other is NormalizedStringStoredProperty && value == other.value) override fun hashCode() = value?.hashCode() ?: 0 override fun toString() = if (isEqualToDefault()) "" else value ?: super.toString() override fun setValue(other: StoredProperty): Boolean { val newValue = (other as NormalizedStringStoredProperty).value if (newValue == value) { return false } value = newValue return true } }
0
Java
0
0
46dec51f368273b47060464492801d5a359e2311
2,392
intellij-community
Apache License 2.0
commons/src/main/java/com/jay/commons/widget/AppTextInputLayout.kt
jayashankar987
176,063,592
false
{"Gradle": 4, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "JSON": 1, "Proguard": 2, "Kotlin": 24, "XML": 27, "Gradle Kotlin DSL": 1, "Java": 3}
package com.jay.commons.widget import android.content.Context import android.graphics.Typeface import android.support.design.widget.TextInputLayout import android.util.AttributeSet import com.jay.commons.R class AppTextInputLayout : TextInputLayout { constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { init(attrs) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init(attrs) } constructor(context: Context) : super(context) { init(null) } private fun init(attrs: AttributeSet?) { if (!isInEditMode && attrs != null) { val typpedArray = context.obtainStyledAttributes(attrs, R.styleable.PoppinsFont) val fontStyle = typpedArray.getInt(R.styleable.PoppinsFont_textFontStyle, FontStyle.FONT_POPPINS_REGULAR) val tf = Typeface.createFromAsset(context.assets, FontStyle.getFont(fontStyle)) typeface = tf } } }
0
Kotlin
0
0
dea3e98e39fc43d2b7d47d5c5f7d8e43b49ebb6e
1,014
LocalityApp
Apache License 2.0
data/RF03814/rnartist.kts
fjossinet
449,239,232
false
{"Kotlin": 8214424}
import io.github.fjossinet.rnartist.core.* rnartist { ss { rfam { id = "RF03814" name = "consensus" use alignment numbering } } theme { details { value = 3 } color { location { 1 to 23 56 to 78 } value = "#0aa37b" } color { location { 25 to 26 54 to 55 } value = "#7f29db" } color { location { 28 to 32 48 to 52 } value = "#dd93ac" } color { location { 34 to 35 46 to 47 } value = "#718263" } color { location { 24 to 24 56 to 55 } value = "#44d39b" } color { location { 27 to 27 53 to 53 } value = "#2039a0" } color { location { 33 to 33 48 to 47 } value = "#f7afda" } color { location { 36 to 45 } value = "#3fc459" } color { location { 79 to 79 } value = "#999571" } } }
0
Kotlin
0
0
3016050675602d506a0e308f07d071abf1524b67
1,533
Rfam-for-RNArtist
MIT License
blekotlin/src/main/java/com/steleot/blekotlin/internal/helper/BleDefaultLogger.kt
Vivecstel
321,435,519
false
null
package com.steleot.blekotlin.internal.helper import android.util.Log import com.steleot.blekotlin.BuildConfig import com.steleot.blekotlin.helper.BleLogger /** * The Default implementation for the [BleLogger]. */ internal class BleDefaultLogger : BleLogger { override fun isEnabled(): Boolean = !BuildConfig.DEBUG override fun log( tag: String, message: String ) { if (isEnabled()) Log.d(tag, message) } }
0
Kotlin
0
2
d379c43d99c524161d57c59eddd430b8e8323e1b
453
ble-kotlin
Apache License 2.0
router/src/main/java/com/speakerboxlite/router/RouterTabs.kt
AlexExiv
688,805,446
false
{"Kotlin": 438264}
package com.speakerboxlite.router import com.speakerboxlite.router.command.CommandExecutor typealias OnTabChangeCallback = (Int) -> Unit /** * Use this router in the tab's Adapter class */ interface RouterTabs { /** * Set this property to allow the Router to manage tab changes dynamically. * Use cases: * - When a tab has no pushed screens, it automatically changes the selected tab to the first one upon a physical back button click. * - When you use a singleton screen and it's placed in a tab, the Router will automatically switch to the corresponding tab. * * IMPORTANT: Do not set it in the Fragment's `init` method or as a `lazy var`. You should set it in the `onViewCreate` * or `onViewCreated` methods. */ var tabChangeCallback: OnTabChangeCallback? /** * Current selected tab's index */ val tabIndex: Int /** * Navigate to the tab with the specified `index`. Use this method to change a tab and make it possible to intercept routing by middlewares. * Avoid changing tabs by other means. * * @param index The index of the tab to which you want to switch. * * @return `true` if the tab has been changed; `false` otherwise. */ fun route(index: Int): Boolean /** * Creates a host view, binds a router to it, and sets the view specified by `path` as its root screen. * It's important to create all screens at adapter creation time to ensure proper functionality, especially for singleton screens. * * @param index The index of the screen in the adapter. * @param path The path to the screen connected by the `RouteController`. */ fun route(index: Int, path: RoutePath, recreate: Boolean): String /** * Binds a command executor. This method should be called in the `onResume()` methods of the activity and fragment. * Any saved operations will be immediately dispatched. * * @param executor The binding executor. */ fun bindExecutor(executor: CommandExecutor) /** * Resets a command executor. This method should be called in the `onPause()` methods of the activity and fragment. * Any pending operations will be pushed onto the stack before calling `bindExecutor`. */ fun unbindExecutor() /** * Get router with index */ operator fun get(index: Int): RouterTab }
8
Kotlin
2
3
5ecc382454908f6f0ad2a72c81edff79ff71763e
2,400
Router-Android
MIT License
domain/src/main/java/com/seo4d696b75/android/ekisagasu/domain/dataset/LatestDataVersion.kt
Seo-4d696b75
247,417,963
false
{"Kotlin": 421916}
package com.seo4d696b75.android.ekisagasu.domain.dataset import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import java.text.StringCharacterIterator @Serializable data class LatestDataVersion( val version: Long, @SerialName("size") val length: Long, ) { fun fileSize(): String { var bytes = length if (bytes < 0) return "0 B" if (bytes < 1000) return "$bytes B" val ci = StringCharacterIterator("KMGTPE") while (bytes >= 999_950) { bytes /= 1000 ci.next() } return String.format("%.1f %cB", bytes.toFloat() / 1000.0f, ci.current()) } }
4
Kotlin
0
0
ca323eb5aa46187d16d335a10fd64d51bfd6c651
669
checkhelper
MIT License
src/main/kotlin/hu/advent/of/code/year2023/day4/Puzzle4B.kt
sztojkatamas
568,512,275
false
{"Kotlin": 157914}
package hu.advent.of.code.year2023.day4 import hu.advent.of.code.AdventOfCodePuzzle import hu.advent.of.code.BaseChallenge @AdventOfCodePuzzle class Puzzle4B: BaseChallenge(2023) { override fun run() { printPuzzleName() loadDataFromFile("data4.txt") val scoreMap = mutableMapOf<Int, Int>() val cards = mutableListOf<Int>() // Init repeat(data.size) { cards.add(1) } data.forEach { line -> val splittedLine = line.split(":","|") val card = splittedLine[1].split(" ").filter { it != "" }.toSet() val hand = splittedLine[2].split(" ").filter { it != "" }.toSet() scoreMap[splittedLine[0].split(" ").filter { it != "" }[1].toInt()] = (card intersect hand).size } cards.forEachIndexed { idx, num -> repeat(num) { repeat(scoreMap[idx+1]!!.toInt()) { cards[idx + 1 + it] = cards[idx + 1 + it] + 1 } } } println("Total number of scratchcards: " + cards.sum()) } }
0
Kotlin
0
0
6aa9e53d06f8cd01d9bb2fcfb2dc14b7418368c9
1,085
advent-of-code-universe
MIT License
app/src/main/java/volovyk/guerrillamail/data/emails/EmailRepository.kt
oleksandrvolovyk
611,731,548
false
{"Kotlin": 122688, "Java": 767}
package volovyk.guerrillamail.data.emails import kotlinx.coroutines.flow.Flow import volovyk.guerrillamail.data.emails.model.Email import volovyk.guerrillamail.util.State interface EmailRepository { suspend fun getEmailById(emailId: String): Email? suspend fun setEmailAddress(newAddress: String) suspend fun deleteEmail(email: Email?) suspend fun deleteAllEmails() suspend fun retryConnectingToMainDatabase() fun observeAssignedEmail(): Flow<String?> fun observeEmails(): Flow<List<Email>> fun observeState(): Flow<State> fun observeMainRemoteEmailDatabaseAvailability(): Flow<Boolean> }
0
Kotlin
0
0
fb360bbc957a560a8fde574f069ce31cb1a38ace
628
guerrilla-mail-android-client
MIT License
src/main/kotlin/example02/Example02Mapper.kt
jeffgbutler
123,967,004
false
{"Kotlin": 81133}
package example02 import org.apache.ibatis.annotations.Select interface Example02Mapper { @Select( "select id, first_name, last_name, birth_date, employed, occupation", "from Person where id = #{value}" ) fun selectPersonById(id: Int): Person }
1
Kotlin
10
45
2903b784fb2dd97a0a93ac99b2e1c9c05ec74d85
276
mybatis-kotlin-examples
MIT License
app/src/androidTest/java/com/test/TestApp.kt
ETSEmpiricalStudyKotlinAndroidApps
496,716,943
true
{"Kotlin": 111686, "Java": 1387}
@file:Suppress("unused") package com.test import android.app.Application import android.content.Context import androidx.test.runner.AndroidJUnitRunner import dagger.hilt.android.testing.HiltTestApplication class TestApp : AndroidJUnitRunner() { override fun newApplication( cl: ClassLoader?, appName: String?, context: Context? ): Application { return super.newApplication( cl, HiltTestApplication::class.java.name, context ) } }
0
null
0
0
4a06616b14298e4003fb0ed15b012f2f1b4cd19b
480
RoomPaging3TestProject
Apache License 2.0
app/src/main/java/com/deonolarewaju/product_catalogue/MainActivity.kt
deonwaju
729,797,385
false
{"Kotlin": 48833}
package com.deonolarewaju.product_catalogue import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.core.view.WindowCompat import com.google.accompanist.systemuicontroller.rememberSystemUiController import com.deonolarewaju.product_catalogue.navGraph.AppNavigation import com.deonolarewaju.product_catalogue.ui.theme.ProductcatalogueTheme import com.deonolarewaju.product_catalogue.util.Dimens import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) WindowCompat.setDecorFitsSystemWindows(window, false) setContent { ProductcatalogueTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { AppContent() } } } } } @Composable fun AppContent() { Box( modifier = Modifier .fillMaxSize() ) { AppNavigation() } }
0
Kotlin
0
1
fead009cfd7e36c09d4c8965c768c6b6f12d75d8
1,700
Product-catalogue
MIT License
common/features/base/src/commonMain/kotlin/ru/tetraquark/ton/explorer/features/base/theme/ThemeMode.kt
Tetraquark
608,328,051
false
null
package ru.tetraquark.ton.explorer.features.base.theme enum class ThemeMode { SYSTEM, LIGHT, DARK }
0
Kotlin
0
3
7cb84104b8631f0d29cbec82754351bd43a40ed1
113
TONSkanner
MIT License
src/main/kotlin/com/angusmorton/kedux/recorder/RecordingStore.kt
AngusMorton
52,205,790
false
null
package com.angusmorton.kedux.recorder import com.angusmorton.kedux.Action import com.angusmorton.kedux.Store import com.angusmorton.kedux.State import com.angusmorton.kedux.Subscription /** * The com.angusmorton.kedux.recorder.RecordingStore is a store that keeps the history of your application. * * You will interact with this by dispatching [com.angusmorton.kedux.recorder.RecordingActions] directly to the store. e.g. * */ class RecordingStore<S : State> : Store<S> { /* * The RecordingStore works by lifting the original store the delegating directly to the lifted store. */ private val liftedStore: Store<RecordingState<S>> override fun currentState(): S { return liftedStore.currentState().computedStates[liftedStore.currentState().currentStateIndex] } override fun dispatch(action: Action): Action { // If the Action is not a com.angusmorton.kedux.recorder.RecordingAction then we wrap it and assume it's being performed. // Otherwise we pass it on as normal. var actionToDispatch = action if (action !is RecordingAction) actionToDispatch = RecordingAction.perform(action) return liftedStore.dispatch(actionToDispatch) } override fun subscribe(subscriber: (S) -> Unit): Subscription { return liftedStore.subscribe { subscriber(currentState()) } } internal constructor(initAction: Action, initialState: S, reducer: (S, Action) -> S) { val liftedReducer: (RecordingState<S>, Action) -> RecordingState<S> = createRecordingReducer(initialState, initAction, reducer) val liftedState = RecordingState(committedState = initialState, stagedActions = listOf(initAction), computedStates = listOf(initialState)) this.liftedStore = Store.create(liftedState, liftedReducer) } companion object { /** * Creates and returns a Store implementation that will record all actions that pass through it and provide options to replay/load/save/time travel. */ fun <S : State> create(initAction: Action, initialState: S, reducer: (S, Action) -> S): Store<S> { return RecordingStore(initAction, initialState, reducer) } } }
0
Kotlin
0
0
1efcff24701cb7d71084a483eb35cf4cecbb5ae9
2,212
kedux-recorder
Apache License 2.0
app/src/main/java/dev/iwilltry42/timestrap/ui/clients/ClientsViewModel.kt
iwilltry42
276,853,576
false
null
package dev.iwilltry42.timestrap.ui.clients import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import dev.iwilltry42.timestrap.R import dev.iwilltry42.timestrap.content.clients.ClientContent.Client /** * [RecyclerView.Adapter] that can display a [Client]. */ class ClientRecyclerViewAdapter( private val values: List<Client>, private val itemClickListener: OnItemClickListener ) : RecyclerView.Adapter<ClientRecyclerViewAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.fragment_item_list_item, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = values[position] holder.bind(item, itemClickListener) } override fun getItemCount(): Int = values.size inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { private val itemName: TextView = view.findViewById(R.id.item_name) override fun toString(): String { return super.toString() + " '" + itemName.text + "'" } // bind item to the view holder fun bind(client: Client, clickListener: OnItemClickListener) { itemName.text = client.name itemView.setOnClickListener { clickListener.onItemClicked(client) } } } } // interface for custom on-click listeners for the cardview items interface OnItemClickListener { fun onItemClicked(client: Client) }
0
Kotlin
0
0
3b6b353c59cbb288949e2d8cd6dbfd979dcbc9db
1,718
timestrap-android
MIT License