path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/main/kotlin/eu/scisneromam/mc/scismmoutils/commands/HammerCommand.kt
awsdcrafting
202,380,518
false
null
package eu.scisneromam.mc.scismmoutils.commands import co.aikar.commands.BaseCommand import co.aikar.commands.CommandHelp import co.aikar.commands.annotation.* import eu.scisneromam.mc.scismmoutils.functions.Hammer import eu.scisneromam.mc.scismmoutils.main.Main.Companion.MAIN import eu.scisneromam.mc.scismmoutils.utils.sendPrefixedMessage import org.bukkit.command.CommandSender import org.bukkit.entity.Player import java.lang.Integer.min /** * Project: ScisUtils * Initially created by scisneromam on 12.08.2019. * @author scisneromam * --------------------------------------------------------------------- * Copyright © 2019 | scisneromam | All rights reserved. */ @CommandAlias("hammer") @CommandPermission("scisUtils.hammer.use") @Description("Hammer") class HammerCommand : BaseCommand() { @Default @Subcommand("toggle") fun onToggle(player: Player) { val on = MAIN.blockBreakListener.toggleFunction(player, MAIN.blockBreakListener.hammer) val msg = if (on) { "on" } else { "off" } player.sendPrefixedMessage("Hammer is now toggled $msg") } @Subcommand("help") @HelpCommand fun onHelp(sender: CommandSender, help: CommandHelp) { help.showHelp() } @Subcommand("mode") @Syntax("individually | square | cube") @Description("Sets the mode of the hammer") @CommandCompletion("individually|square|cube") fun onMode(player: Player, @Optional arg: String?) { val mode = MAIN.blockBreakListener.hammer.modePerPlayer.getOrPut(player, { Hammer.Mode() }) if (arg == null) { player.sendPrefixedMessage("Your current mode is ${mode.mode}") } else { when (arg.toLowerCase()) { "individually" -> { mode.mode = Hammer.HammerMode.INDIVIDUALLY } "square" -> { mode.mode = Hammer.HammerMode.SQUARE } "cube" -> { mode.mode = Hammer.HammerMode.CUBE } else -> { player.sendPrefixedMessage("You provided an invalid mode") return } } player.sendPrefixedMessage("Set mode to $arg") } } @Subcommand("radius") @Syntax("[lrRad] [udRad] [depth]") @Description("Sets the radius of the hammer") fun onRadius(player: Player, @Optional lrRad: Int?, @Optional udRad: Int?, @Optional depth: Int?) { val mode = MAIN.blockBreakListener.hammer.modePerPlayer.getOrPut(player, { Hammer.Mode() }) val level = MAIN.dbConnection.breakXpFunction.getXPLevel(player.uniqueId).level if (lrRad == null && udRad == null && depth == null) { } else { if (lrRad != null && lrRad >= 0) { mode.leftRightSize = min(lrRad, level * 2) } if (udRad != null && udRad >= 0) { mode.upDownSize = min(udRad, level * 2) } if (depth != null && depth >= 0) { mode.depth = min(depth, level * 4) } } player.sendPrefixedMessage("Your current radii are ${mode.leftRightSize} ${mode.upDownSize} ${mode.depth}") } @Subcommand("items") @Syntax("info | give | show | list") @Description("Fills your inventory with your mined items") @CommandCompletion("info|give|show|list") fun onItems(player: Player, @Optional arg: String?) { val blockBreakListener = MAIN.blockBreakListener if (arg == null) { player.sendPrefixedMessage("//todo") //player.sendPrefixedMessage("You have ${itemSave.itemAmount} items over ${itemSave.itemStackAmount} ItemStacks") } else { when (arg.toLowerCase()) { "give" -> blockBreakListener.fillInventory(player) "show" -> blockBreakListener.openInventory(player) "list" -> { player.sendPrefixedMessage("//todo") } else -> player.sendPrefixedMessage("//todo") //else -> player.sendPrefixedMessage("You have ${itemSave.itemAmount} items over ${itemSave.itemStackAmount} ItemStacks") } } } }
4
Kotlin
0
0
0d171e6ee52973a585a2633bf62ede0209c7296e
4,529
ScisMMOUtils
MIT License
kmp-nativecoroutines-compiler/src/main/kotlin/com/rickclephas/kmp/nativecoroutines/compiler/utils/NativeCoroutinesClassIds.kt
rickclephas
374,341,212
false
{"Kotlin": 231144, "Swift": 40082, "Java": 7157, "Ruby": 2852}
package com.rickclephas.kmp.nativecoroutines.compiler.utils import com.rickclephas.kmp.nativecoroutines.compiler.utils.NativeCoroutinesFqNames as FqNames import org.jetbrains.kotlin.name.ClassId public object NativeCoroutinesClassIds { public val nativeCoroutines: ClassId = ClassId.topLevel(FqNames.nativeCoroutines) public val nativeCoroutineScope: ClassId = ClassId.topLevel(FqNames.nativeCoroutineScope) public val nativeCoroutinesIgnore: ClassId = ClassId.topLevel(FqNames.nativeCoroutinesIgnore) public val nativeCoroutinesRefined: ClassId = ClassId.topLevel(FqNames.nativeCoroutinesRefined) public val nativeCoroutinesRefinedState: ClassId = ClassId.topLevel(FqNames.nativeCoroutinesRefinedState) public val nativeCoroutinesState: ClassId = ClassId.topLevel(FqNames.nativeCoroutinesState) }
17
Kotlin
31
924
d86ab678169f8db7674074d97845ced1a7ecdb23
824
KMP-NativeCoroutines
MIT License
src/iosMain/kotlin/utils/TimeZoneUtils.kt
MrAsterisco
327,316,170
false
null
package io.github.mrasterisco.Date.utils import platform.Foundation.NSTimeZone import platform.Foundation.localTimeZone import platform.Foundation.timeZoneWithName @Suppress("unused") actual class TimeZoneUtils { actual companion object { actual fun getDefault(): Any { return NSTimeZone.localTimeZone } actual fun getTimeZone(identifier: String): Any? { return NSTimeZone.timeZoneWithName(identifier) } actual fun getIdentifier(timeZone: Any): String { return (timeZone as NSTimeZone).name } } }
0
Kotlin
0
0
1bd5e920642cd1b8793bc9b8f81e4d17d866a5d9
596
Date
MIT License
app/src/main/java/com/davoh/laravelmyappointments/ui/menu/myAppointments/AppointmentDetailsFragment.kt
DDavoH
339,810,573
false
null
package com.davoh.laravelmyappointments.ui.menu.myAppointments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.navigation.fragment.navArgs import com.davoh.laravelmyappointments.R import com.davoh.laravelmyappointments.data.model.Appointment import com.davoh.laravelmyappointments.databinding.FragmentAppointmentDetailsBinding import com.davoh.laravelmyappointments.utils.toast import dagger.hilt.android.AndroidEntryPoint import java.text.SimpleDateFormat import java.util.* @AndroidEntryPoint class AppointmentDetailsFragment : Fragment() { private var _binding: FragmentAppointmentDetailsBinding? = null private val binding get() = _binding!! private val args: AppointmentDetailsFragmentArgs by navArgs() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { _binding = FragmentAppointmentDetailsBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val appointment = args.appointment binding.tvDoctorName.text = appointment.doctor.name binding.tvSpecialty.text = appointment.specialty.name binding.tvScheduledDateAndHour.text = "${appointment.scheduledDate} A las: ${appointment.scheduledTime}" binding.tvDescription.text = appointment.description binding.tvType.text = appointment.type binding.tvAppointmentId.text = getString(R.string.appointment_id, appointment.id) val formatter = SimpleDateFormat("dd/MMMM/yyyy", Locale.getDefault()) val calendar: Calendar = Calendar.getInstance() calendar.timeInMillis = appointment.createdAt binding.tvCreatedAt.text = "Cita registrada el dia ${formatter.format(calendar.time)}" binding.tvStatus.text = appointment.status when(appointment.status){ "Reservada"->{ binding.statusMiniCard.setBackgroundResource(R.color.orange_200) } "Confirmada"->{ binding.statusMiniCard.setBackgroundResource(R.color.blue_200) } "Cancelada"->{ binding.statusMiniCard.setBackgroundResource(R.color.red_200) } "Atendida"->{ binding.statusMiniCard.setBackgroundResource(R.color.green_200) } } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
1
09607062b55484087bebd3e4af9a735965f176ea
2,659
Kotlin-MVVM-AppointmentsApp
Apache License 2.0
src/test/kotlin/com/mituuz/fuzzier/FuzzyMoverTest.kt
MituuZ
735,641,775
false
{"Kotlin": 118570}
package com.mituuz.fuzzier import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.modules import com.intellij.openapi.project.rootManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiManager import com.intellij.testFramework.LightVirtualFile import com.intellij.testFramework.TestApplicationManager import com.intellij.testFramework.fixtures.CodeInsightTestFixture import com.mituuz.fuzzier.components.SimpleFinderComponent import com.mituuz.fuzzier.entities.FuzzyMatchContainer import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import javax.swing.DefaultListModel import javax.swing.ListModel class FuzzyMoverTest { @Suppress("unused") private var testApplicationManager: TestApplicationManager = TestApplicationManager.getInstance() private var fuzzyMover: FuzzyMover = FuzzyMover() private val testUtil: TestUtil = TestUtil() @Test fun `Check that files are moved correctly`() { val filePaths = listOf("src/asd/main.log", "src/nope") val myFixture: CodeInsightTestFixture = testUtil.setUpProject(filePaths) val basePath = myFixture.findFileInTempDir("src").canonicalPath val project = myFixture.project val virtualFile = VirtualFileManager.getInstance().findFileByUrl("file://$basePath/nope") val virtualDir = VirtualFileManager.getInstance().findFileByUrl("file://$basePath/asd/") fuzzyMover.component = SimpleFinderComponent() fuzzyMover.component.fileList.model = getListModel(virtualDir) fuzzyMover.component.fileList.selectedIndex = 0 fuzzyMover.component.isDirSelector = true ApplicationManager.getApplication().runReadAction { fuzzyMover.movableFile = virtualFile?.let { PsiManager.getInstance(project).findFile(it) }!! } if (basePath != null) { fuzzyMover.handleInput(project).thenRun{ var targetFile = VirtualFileManager.getInstance().findFileByUrl("file://$basePath/asd/nope") assertNotNull(targetFile) targetFile = VirtualFileManager.getInstance().findFileByUrl("file://$basePath/nope") assertNull(targetFile) }.join() } myFixture.tearDown() } @Test fun `Use the correct steps to move files`() { val filePaths = listOf("src/asd/main.log", "src/nope") val myFixture: CodeInsightTestFixture = testUtil.setUpProject(filePaths) val basePath = myFixture.findFileInTempDir("src").canonicalPath val project = myFixture.project fuzzyMover.component = SimpleFinderComponent() val virtualFile = VirtualFileManager.getInstance().findFileByUrl("file://$basePath/nope") val virtualDir = VirtualFileManager.getInstance().findFileByUrl("file://$basePath/asd/") fuzzyMover.component.fileList.model = getListModel(virtualFile) fuzzyMover.component.fileList.selectedIndex = 0 if (basePath != null) { fuzzyMover.handleInput(project).join() fuzzyMover.component.fileList.model = getListModel(virtualDir) fuzzyMover.component.fileList.selectedIndex = 0 fuzzyMover.handleInput(project).thenRun{ var targetFile = VirtualFileManager.getInstance().findFileByUrl("file://$basePath/asd/nope") assertNotNull(targetFile) targetFile = VirtualFileManager.getInstance().findFileByUrl("file://$basePath/nope") assertNull(targetFile) }.join() } myFixture.tearDown() } @Test fun `Multi module test move to same module`() { val module1Files = listOf("src1/main.kt", "src1/test/app.log") val module2Files = listOf("src2/tool.kt") val myFixture: CodeInsightTestFixture = testUtil.setUpMultiModuleProject(module1Files, module2Files) val project = myFixture.project assertEquals(2, project.modules.size) val basePath = project.modules[0].rootManager.contentRoots[0] fuzzyMover.component = SimpleFinderComponent() fuzzyMover.currentFile = LightVirtualFile("") val virtualFile = VirtualFileManager.getInstance().findFileByUrl("$basePath/main.kt") val virtualDir = VirtualFileManager.getInstance().findFileByUrl("$basePath/test/") fuzzyMover.component.fileList.model = getListModel(virtualFile) fuzzyMover.component.fileList.selectedIndex = 0 if (basePath != null) { fuzzyMover.handleInput(project).join() fuzzyMover.component.fileList.model = getListModel(virtualDir) fuzzyMover.component.fileList.selectedIndex = 0 fuzzyMover.handleInput(project).thenRun{ var targetFile = VirtualFileManager.getInstance().findFileByUrl("$basePath/test/main.kt") assertNotNull(targetFile) targetFile = VirtualFileManager.getInstance().findFileByUrl("$basePath/main.kt") assertNull(targetFile) }.join() } myFixture.tearDown() } @Test fun `Multi module test move to different module`() { val module1Files = listOf("src1/MoveMe.kt", "src1/test/app.log") val module2Files = listOf("src2/tool.kt", "src2/target/test.kt") val myFixture: CodeInsightTestFixture = testUtil.setUpMultiModuleProject(module1Files, module2Files) val project = myFixture.project assertEquals(2, project.modules.size) val module1BasePath = project.modules[0].rootManager.contentRoots[0] val module2BasePath = project.modules[1].rootManager.contentRoots[0] fuzzyMover.component = SimpleFinderComponent() fuzzyMover.currentFile = LightVirtualFile("") val virtualFile = VirtualFileManager.getInstance().findFileByUrl("$module1BasePath/MoveMe.kt") val virtualDir = VirtualFileManager.getInstance().findFileByUrl("$module2BasePath/target/") fuzzyMover.component.fileList.model = getListModel(virtualFile) fuzzyMover.component.fileList.selectedIndex = 0 if (module1BasePath != null) { fuzzyMover.handleInput(project).join() fuzzyMover.component.fileList.model = getListModel(virtualDir) fuzzyMover.component.fileList.selectedIndex = 0 fuzzyMover.handleInput(project).thenRun{ var targetFile = VirtualFileManager.getInstance().findFileByUrl("$module2BasePath/target/MoveMe.kt") assertNotNull(targetFile) targetFile = VirtualFileManager.getInstance().findFileByUrl("$module1BasePath/MoveMe.kt") assertNull(targetFile) }.join() } myFixture.tearDown() } private fun getListModel(virtualFile: VirtualFile?): ListModel<FuzzyMatchContainer?> { val listModel = DefaultListModel<FuzzyMatchContainer?>() if (virtualFile != null) { val container = FuzzyMatchContainer(FuzzyMatchContainer.FuzzyScore(), virtualFile.path, virtualFile.name) listModel.addElement(container) } return listModel } }
5
Kotlin
3
9
6acd1aced3cdc91fb94d0ad404390ebb240d9801
7,268
fuzzier
MIT License
service-query/src/main/kotlin/org/veupathdb/service/mblast/query/model/QueryUserMeta.kt
VEuPathDB
303,794,401
false
{"Kotlin": 1600360, "Java": 404589, "RAML": 120840, "Dockerfile": 3585, "Shell": 2218, "SQL": 2160}
package org.veupathdb.service.mblast.query.model /** * # Query Job User Metadata * * User metadata attached to a BLAST query job. * * @author <NAME> - https://github.com/foxcapades * @since 2.0.0 */ interface QueryUserMeta { /** * ID of the user attached to the query job. */ val userID: Long /** * Optional short summary provided by the user for the query job. */ val summary: String? /** * Optional long description provided by the user for the query job. */ val description: String? } data class QueryUserMetaImpl( override val userID: Long, override val summary: String?, override val description: String? ) : QueryUserMeta
17
Kotlin
0
0
80ba2d33499425427842d134bb04b8bc20568af1
694
service-multi-blast
Apache License 2.0
src/main/kotlin/org/opensearch/replication/task/shard/ShardReplicationChangesTracker.kt
opensearch-project
323,830,219
false
{"Kotlin": 1005221, "Python": 17931, "Shell": 8517}
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. * * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ package org.opensearch.replication.task.shard import org.opensearch.replication.ReplicationSettings import kotlinx.coroutines.delay import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import org.opensearch.common.logging.Loggers import org.opensearch.index.shard.IndexShard import java.util.Collections import java.util.concurrent.atomic.AtomicLong import kotlin.collections.ArrayList /** * Since we have added support for fetching batch of operations in parallel, we need to keep track of * how many operations have been fetched and what batch needs to be fetched next. This creates the * problem of concurrency with shared mutable state (https://kotlinlang.org/docs/shared-mutable-state-and-concurrency.html). * ShardReplicationChangesTracker abstracts away all that complexity from ShardReplicationTask. * Every reader coroutine in a shard has to interact with the tracker for: * 1. Requesting the range of operations to be fetched in the batch. * 2. Updating the final status of the batch fetch. */ class ShardReplicationChangesTracker(indexShard: IndexShard, private val replicationSettings: ReplicationSettings) { private val log = Loggers.getLogger(javaClass, indexShard.shardId())!! private val mutex = Mutex() private val missingBatches = Collections.synchronizedList(ArrayList<Pair<Long, Long>>()) private val observedSeqNoAtLeader = AtomicLong(indexShard.localCheckpoint) private val seqNoAlreadyRequested = AtomicLong(indexShard.localCheckpoint) private val batchSize = replicationSettings.batchSize /** * Provides a range of operations to be fetched next. * * Here are the guarantees that this method provides: * 1. All reader coroutines get unique range of operations to fetch. * 2. It'll ensure that the complete range of operations would be fetched. * 3. Mutex in this method ensures that only one coroutine is requesting the batch at a time. * If there are multiple coroutines, they'll be waiting in order to get the range of operations to fetch. * 4. If we've already fetched all the operations from leader, there would be one and only one * reader polling on leader per shard. */ suspend fun requestBatchToFetch():Pair<Long, Long> { mutex.withLock { logDebug("Waiting to get batch. requested: ${seqNoAlreadyRequested.get()}, leader: ${observedSeqNoAtLeader.get()}") // Wait till we have batch to fetch. Note that if seqNoAlreadyRequested is equal to observedSeqNoAtLeader, // we still should be sending one more request to fetch which will just do a poll and eventually timeout // if no new operations are there on the leader (configured via TransportGetChangesAction.WAIT_FOR_NEW_OPS_TIMEOUT) while (seqNoAlreadyRequested.get() > observedSeqNoAtLeader.get() && missingBatches.isEmpty()) { delay(replicationSettings.pollDuration.millis) } // missing batch takes higher priority. return if (missingBatches.isNotEmpty()) { logDebug("Fetching missing batch ${missingBatches[0].first}-${missingBatches[0].second}") missingBatches.removeAt(0) } else { // return the next batch to fetch and update seqNoAlreadyRequested. val fromSeq = seqNoAlreadyRequested.getAndAdd(batchSize.toLong()) + 1 val toSeq = fromSeq + batchSize - 1 logDebug("Fetching the batch $fromSeq-$toSeq") Pair(fromSeq, toSeq) } } } /** * Ensures that we've successfully fetched a particular range of operations. * In case of any failure(or we didn't get complete batch), we make sure that we're fetching the * missing operations in the next batch. */ fun updateBatchFetched(success: Boolean, fromSeqNoRequested: Long, toSeqNoRequested: Long, toSeqNoReceived: Long, seqNoAtLeader: Long) { if (success) { // we shouldn't ever be getting more operations than requested. assert(toSeqNoRequested >= toSeqNoReceived) { "${Thread.currentThread().getName()} Got more operations in the batch than requested" } logDebug("Updating the batch fetched. ${fromSeqNoRequested}-${toSeqNoReceived}/${toSeqNoRequested}, seqNoAtLeader:$seqNoAtLeader") // If we didn't get the complete batch that we had requested. if (toSeqNoRequested > toSeqNoReceived) { // If this is the last batch being fetched, update the seqNoAlreadyRequested. if (seqNoAlreadyRequested.get() == toSeqNoRequested) { seqNoAlreadyRequested.updateAndGet { toSeqNoReceived } } else { // Else, add to the missing operations to missing batch logDebug("Didn't get the complete batch. Adding the missing operations ${toSeqNoReceived + 1}-${toSeqNoRequested}") missingBatches.add(Pair(toSeqNoReceived + 1, toSeqNoRequested)) } } // Update the sequence number observed at leader. observedSeqNoAtLeader.getAndUpdate { value -> if (seqNoAtLeader > value) seqNoAtLeader else value } logDebug("observedSeqNoAtLeader: ${observedSeqNoAtLeader.get()}") } else { // If this is the last batch being fetched, update the seqNoAlreadyRequested. if (seqNoAlreadyRequested.get() == toSeqNoRequested) { seqNoAlreadyRequested.updateAndGet { fromSeqNoRequested - 1 } } else { // If this was not the last batch, we might have already fetched other batch of // operations after this. Adding this to missing. logDebug("Adding batch to missing $fromSeqNoRequested-$toSeqNoRequested") missingBatches.add(Pair(fromSeqNoRequested, toSeqNoRequested)) } } } private fun logDebug(msg: String) { log.debug("${Thread.currentThread().name}: $msg") } }
77
Kotlin
58
48
0cc41c620b96a4798adbe2237e48b67269e3e509
6,392
cross-cluster-replication
Apache License 2.0
dashboard/src/main/java/studio/crud/feature/dashboard/widget/type/totalpercentline/TotalPercentLineWidgetDataHandlerImpl.kt
crud-studio
390,327,908
false
null
package studio.crud.feature.dashboard.widget.type.totalpercentline import org.springframework.stereotype.Component import studio.crud.feature.dashboard.enums.DashboardWidgetType import studio.crud.feature.dashboard.model.DashboardWidget import studio.crud.feature.dashboard.widget.WidgetHelper import studio.crud.feature.dashboard.widget.type.core.AbstractDashboardWidgetTypeDataHandler @Component class TotalPercentLineWidgetDataHandlerImpl( private val widgetHelper: WidgetHelper ) : AbstractDashboardWidgetTypeDataHandler<TotalPercentLineWidgetResultDTO, TotalPercentLineWidgetSettingsPojo>() { override val getType: DashboardWidgetType = DashboardWidgetType.TotalPercentLine override fun getData(widget: DashboardWidget, settings: TotalPercentLineWidgetSettingsPojo): TotalPercentLineWidgetResultDTO { val total = widgetHelper.runNativeQuery(settings.totalQuery).first() as Number val entries = widgetHelper.runNativeQuery(settings.lineQuery) as List<Number> val lastEntry = entries.last() val beforeLastEntry = entries[entries.lastIndex-1] val change = (lastEntry.toDouble() - beforeLastEntry.toDouble()) / beforeLastEntry.toDouble() * 100.0 return TotalPercentLineWidgetResultDTO(total.toLong(), change, entries) } }
6
Kotlin
0
0
6cb1d5f7b3fc7117c9fbaaf6708ac93ae631e674
1,290
feature-depot
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/Seller.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Bold.Seller: ImageVector get() { if (_seller != null) { return _seller!! } _seller = Builder(name = "Seller", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(9.0f, 12.0f) curveToRelative(3.309f, 0.0f, 6.0f, -2.691f, 6.0f, -6.0f) reflectiveCurveTo(12.309f, 0.0f, 9.0f, 0.0f) reflectiveCurveTo(3.0f, 2.691f, 3.0f, 6.0f) reflectiveCurveToRelative(2.691f, 6.0f, 6.0f, 6.0f) close() moveTo(9.0f, 3.0f) curveToRelative(1.654f, 0.0f, 3.0f, 1.346f, 3.0f, 3.0f) reflectiveCurveToRelative(-1.346f, 3.0f, -3.0f, 3.0f) reflectiveCurveToRelative(-3.0f, -1.346f, -3.0f, -3.0f) reflectiveCurveToRelative(1.346f, -3.0f, 3.0f, -3.0f) close() moveTo(24.0f, 16.0f) curveToRelative(0.0f, 1.105f, -0.831f, 2.0f, -1.857f, 2.0f) horizontalLineToRelative(-0.619f) curveToRelative(-1.026f, 0.0f, -1.857f, -0.895f, -1.857f, -2.0f) curveToRelative(0.0f, 1.105f, -0.831f, 2.0f, -1.857f, 2.0f) horizontalLineToRelative(-0.619f) curveToRelative(-1.026f, 0.0f, -1.857f, -0.895f, -1.857f, -2.0f) curveToRelative(0.0f, 1.105f, -0.831f, 2.0f, -1.857f, 2.0f) horizontalLineToRelative(-0.619f) curveToRelative(-1.026f, 0.0f, -1.857f, -0.895f, -1.857f, -2.0f) lineToRelative(1.238f, -4.0f) horizontalLineToRelative(10.524f) lineToRelative(1.238f, 4.0f) close() moveTo(20.0f, 19.0f) horizontalLineToRelative(3.0f) verticalLineToRelative(5.0f) horizontalLineToRelative(-11.0f) verticalLineToRelative(-5.0f) horizontalLineToRelative(3.0f) verticalLineToRelative(2.0f) horizontalLineToRelative(5.0f) verticalLineToRelative(-2.0f) close() moveTo(9.52f, 14.0f) lineToRelative(-0.932f, 3.0f) horizontalLineToRelative(-3.588f) curveToRelative(-1.103f, 0.0f, -2.0f, 0.897f, -2.0f, 2.0f) verticalLineToRelative(5.0f) lineTo(0.0f, 24.0f) verticalLineToRelative(-5.0f) curveToRelative(0.0f, -2.757f, 2.243f, -5.0f, 5.0f, -5.0f) horizontalLineToRelative(4.52f) close() } } .build() return _seller!! } private var _seller: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,602
icons
MIT License
src/main/kotlin/com/github/h3rmt/intellijyuck/psi/YuckElementType.kt
H3rmt
675,780,800
false
{"Kotlin": 36626, "Java": 35139, "Lex": 2900, "V": 57}
package com.github.h3rmt.intellijyuck.psi import com.github.h3rmt.intellijyuck.YuckLanguage import com.intellij.psi.tree.IElementType class YuckElementType(debugName: String) : IElementType(debugName, YuckLanguage)
1
Kotlin
0
1
e1cdcc74f1340bbd182e03cad7be537c7e1f8652
217
intellij-yuck
MIT License
src/main/kotlin/com/example/coreweb/domains/labels/services/LabelService.kt
teambankrupt
292,072,114
false
{"Kotlin": 171003, "Java": 55138, "HTML": 22230}
package com.example.coreweb.domains.labels.services import com.example.coreweb.domains.base.services.CrudServiceV4 import com.example.coreweb.domains.labels.models.entities.Label interface LabelService : CrudServiceV4<Label>
3
Kotlin
0
2
c13155ebb7733fdf06a74beb090266196c9f5272
226
coreweb
Apache License 2.0
app/src/main/java/io/aiico/memora/MemoraApp.kt
isalig
249,266,229
false
null
package io.aiico.memora import android.app.Application import io.aiico.memora.data.NotesRepository import io.aiico.memora.data.db.MemoraDb @Suppress("unused") class MemoraApp : Application() { override fun onCreate() { super.onCreate() with(MemoraDb.createInstance(this)) { NotesRepository.init(this) } } }
0
Kotlin
0
1
ad790560bf4c80522fff87618dcad3cef48d544f
353
memora-android
Apache License 2.0
app/src/main/java/dev/pinaki/cannaguide/data/store/JournalEntry.kt
Pinaki93
758,573,200
false
{"Kotlin": 66538}
package dev.pinaki.cannaguide.data.store import java.util.Date sealed interface JournalEntry { val id: Int? val entryDate: Date }
0
Kotlin
0
0
376645d97607bc6c88e99afb622c9e1fa5e7213f
139
Cannaguide
MIT License
plugin/src/main/kotlin/de/timfreiheit/plugin/resourceplaceholders/ResourcePlaceholdersPlugin.kt
timfreiheit
108,669,705
false
null
package de.timfreiheit.plugin.resourceplaceholders import com.android.build.gradle.AppExtension import com.android.build.gradle.AppPlugin import com.android.build.gradle.LibraryExtension import com.android.build.gradle.LibraryPlugin import com.android.build.gradle.api.AndroidSourceSet import com.android.build.gradle.api.BaseVariant import com.android.builder.model.SourceProvider import org.gradle.api.DomainObjectSet import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.file.FileCollection import java.io.File class ResourcePlaceholdersPlugin : Plugin<Project> { private lateinit var config: ResourcePlaceholdersExtension private var pluginConfigured = false override fun apply(project: Project) { config = project.extensions.create("resourcePlaceholders", ResourcePlaceholdersExtension::class.java) // wait for other plugins added to support applying this before the android plugin project.plugins.whenPluginAdded { project.afterEvaluate { _ -> configure(project) } } } private fun configure(project: Project) { if (pluginConfigured) { // this plugin might be configured multiple times depending on the apply order from other plugins return } project.plugins.all { val variants: DomainObjectSet<out BaseVariant>? = when (it) { is AppPlugin -> project.extensions.getByType(AppExtension::class.java).applicationVariants is LibraryPlugin -> project.extensions.getByType(LibraryExtension::class.java).libraryVariants else -> null } if (variants?.isNotEmpty() == true) { pluginConfigured = true configureAndroid(project, variants) } } } private fun <T : BaseVariant> configureAndroid(project: Project, variants: DomainObjectSet<T>) { variants.forEach { variant -> var files: FileCollection = project.files() variant.sourceSets.forEach { sourceSet -> val collectedFiles = searchFilesInSourceSet(sourceSet) val fileCollection = project.files(collectedFiles) files = files.plus(fileCollection) ?: fileCollection } val outputDirectory = getOutputDirForVariant(project, variant) // add new resource folder to sourceSet with the highest priority // this makes sure the new icons will override the original one val sourceProvider = variant.sourceSets[variant.sourceSets.size - 1] if (sourceProvider is AndroidSourceSet) { sourceProvider.res.srcDir(outputDirectory) } else { throw IllegalStateException("sourceProvider is not an AndroidSourceSet") } val taskName = "resourcePlaceholdersFor${variant.name.capitalize()}" val task = project.tasks.create(taskName, ResourcePlaceholdersTask::class.java).apply { sources = files outputDir = outputDirectory placeholders = variant.buildType.manifestPlaceholders + variant.mergedFlavor.manifestPlaceholders.toMutableMap().apply { put("applicationId", variant.applicationId) }.toMap() } // register task to make it run before resource merging // add dummy folder because the folder is already added to an sourceSet // when using the folder defined in the argument the generated resources are at the lowest priority // and will cause an conflict with the existing once variant.registerGeneratedResFolders(project.files(File(outputDirectory, "_dummy")).builtBy(task)) } } private fun searchFilesInSourceSet(sourceSet: SourceProvider): List<File> { val files = mutableListOf<File>() for (resDirectory in sourceSet.resDirectories) { config.files.forEach { fileName -> val file = File(resDirectory, fileName) if (file.exists() && !file.isDirectory) { files.add(file) } } } return files } private fun getOutputDirForVariant(project: Project, variant: BaseVariant): File { return project.file("${project.buildDir}/generated/res/resourcesPlaceholders/${variant.flavorName}/${variant.buildType.name}/") } }
5
null
10
87
3af9c0265f93b59c1a62eee2eb60307736b912bf
4,507
ResourcePlaceholdersPlugin
MIT License
app/src/main/java/com/nmrc/note/data/model/util/SettingsListener.kt
16george
348,022,465
false
null
package com.nmrc.note.data.model.util interface SettingsListener { fun darkMode(state: Boolean): Boolean fun bugReports() }
0
Kotlin
0
1
d7daa12f5383191993f6fb2fb7e2a5c1681af476
134
Note
Apache License 2.0
app/src/main/kotlin/no/nav/paw/arbeidssokerregisteret/profilering/application/ApplicationTopology.kt
navikt
740,873,630
false
{"Kotlin": 46528, "Dockerfile": 604}
package no.nav.paw.arbeidssokerregisteret.profilering.application import no.nav.paw.arbeidssokerregisteret.api.v1.Periode import no.nav.paw.arbeidssokerregisteret.api.v3.OpplysningerOmArbeidssoeker import no.nav.paw.arbeidssokerregisteret.profilering.application.profilering.profiler import no.nav.paw.arbeidssokerregisteret.profilering.personinfo.PersonInfoTjeneste import org.apache.kafka.streams.StreamsBuilder import org.apache.kafka.streams.Topology import org.slf4j.LoggerFactory fun applicationTopology( suppressionConfig: SuppressionConfig<Long, Periode>, streamBuilder: StreamsBuilder, personInfoTjeneste: PersonInfoTjeneste, applicationConfiguration: ApplicationConfiguration ): Topology { val logger = LoggerFactory.getLogger("applicationTopology") val periodeTabell = streamBuilder .stream<Long, Periode>(applicationConfiguration.periodeTopic) .conditionallySuppress(suppressionConfig) .mapValues { _, periode -> if (periode.avsluttet == null) periode else null } .toTable() streamBuilder .stream<Long, OpplysningerOmArbeidssoeker>(applicationConfiguration.opplysningerTopic) .peek { _, opplysninger -> logger.trace("Opplysninger id (prejoin): {}", opplysninger.id) } .join(periodeTabell) { opplysninger, periode -> periode?.identitetsnummer?.let { identitetsnummer -> identitetsnummer to opplysninger } } .peek { _, v -> logger.trace("Opplysninger id (postjoin): {}", v.second.id) } .mapValues { _, (identitetsnummer, opplysninger) -> val personInfo = personInfoTjeneste.hentPersonInfo(identitetsnummer, opplysninger.id) personInfo to opplysninger }.mapValues { _, (personInfo, opplysninger) -> profiler(personInfo, opplysninger) }.to(applicationConfiguration.profileringTopic) return streamBuilder.build() }
0
Kotlin
0
0
8be978ae78fa1e2faaf84efb05af35399a553dd1
1,930
paw-arbeidssokerregisteret-profilering
MIT License
superwall/src/main/java/com/superwall/sdk/paywall/presentation/get_presentation_result/GetPresentationResultLogic.kt
superwall
642,585,064
false
{"Kotlin": 1190760}
package com.superwall.sdk.paywall.presentation.get_presentation_result import com.superwall.sdk.models.triggers.InternalTriggerResult import com.superwall.sdk.paywall.presentation.result.PresentationResult object GetPresentationResultLogic { fun convertTriggerResult(triggerResult: InternalTriggerResult): PresentationResult = when (triggerResult) { is InternalTriggerResult.EventNotFound -> PresentationResult.EventNotFound() is InternalTriggerResult.Holdout -> PresentationResult.Holdout(triggerResult.experiment) is InternalTriggerResult.Error -> PresentationResult.PaywallNotAvailable() is InternalTriggerResult.NoRuleMatch -> PresentationResult.NoRuleMatch() is InternalTriggerResult.Paywall -> PresentationResult.Paywall(triggerResult.experiment) } }
6
Kotlin
3
9
2582de8d48af7c0ad080e30949d920e8a34d9219
839
Superwall-Android
MIT License
src/main.kt
sbauer322
231,718,772
false
null
import ccspkt.chapter3.CSP import ccspkt.chapter3.QueensConstraint import ccspkt.chapter4.Graph fun main() { // chapter3Main() chapter4Main() } fun chapter3Main() { val columns: MutableList<Int> = mutableListOf(1,2,3,4,5,6,7,8) val rows: MutableMap<Int, List<Int>> = mutableMapOf() columns.forEach { column -> rows[column] = listOf(1,2,3,4,5,6,7,8) } val csp = CSP(columns, rows) csp.addConstraint(QueensConstraint(columns)) val solution = csp.backtrackingSearch() // val csp = CSPE(columns, rows) // csp.addConstraint(QueensConstraintE(columns)) // val solution = csp.backtrackingSearch() if (solution != null) { print(solution) } else { print("No solution found") } } fun chapter4Main() { val cityGraph = Graph<String>( mutableListOf("Seattle", "San Francisco", "Los Angeles", "Riverside", "Phoenix", "Chicago", "Boston", "New York", "Atlanta", "Miami", "Dallas", "Houston", "Detroit", "Philadelphia", "Washington")) cityGraph.addEdgeByVertices("Seattle", "Chicago") cityGraph.addEdgeByVertices("Seattle", "San Francisco") cityGraph.addEdgeByVertices("San Francisco", "Riverside") cityGraph.addEdgeByVertices("San Francisco", "Los Angeles") cityGraph.addEdgeByVertices("Los Angeles", "Riverside") cityGraph.addEdgeByVertices("Los Angeles", "Phoenix") cityGraph.addEdgeByVertices("Riverside", "Phoenix") cityGraph.addEdgeByVertices("Riverside", "Chicago") cityGraph.addEdgeByVertices("Phoenix", "Dallas") cityGraph.addEdgeByVertices("Phoenix", "Houston") cityGraph.addEdgeByVertices("Dallas", "Chicago") cityGraph.addEdgeByVertices("Dallas", "Atlanta") cityGraph.addEdgeByVertices("Dallas", "Houston") cityGraph.addEdgeByVertices("Houston", "Atlanta") cityGraph.addEdgeByVertices("Houston", "Miami") cityGraph.addEdgeByVertices("Atlanta", "Chicago") cityGraph.addEdgeByVertices("Atlanta", "Washington") cityGraph.addEdgeByVertices("Atlanta", "Miami") cityGraph.addEdgeByVertices("Miami", "Washington") cityGraph.addEdgeByVertices("Chicago", "Detroit") cityGraph.addEdgeByVertices("Detroit", "Boston") cityGraph.addEdgeByVertices("Detroit", "Washington") cityGraph.addEdgeByVertices("Detroit", "New York") cityGraph.addEdgeByVertices("Boston", "New York") cityGraph.addEdgeByVertices("New York", "Philadelphia") cityGraph.addEdgeByVertices("Philadelphia", "Washington") print(cityGraph) }
0
Kotlin
0
0
95f2b5948551010868952f4f93616b05ed99e917
2,519
ccsp_kt
Apache License 2.0
app/src/main/java/com/github/acarlsen/android/coverage/data/repositories/CocktailDBRepoImpl.kt
acarlsen
585,978,582
false
null
package com.github.acarlsen.android.coverage.data.repositories import com.github.acarlsen.android.coverage.data.mappers.CocktailMapper import com.github.acarlsen.android.coverage.data.service.CocktailDBService import com.github.acarlsen.android.coverage.domain.models.CocktailModel import com.github.acarlsen.android.coverage.domain.repositories.CocktailDBRepo import javax.inject.Inject class CocktailDBRepoImpl @Inject constructor( private val apiService: CocktailDBService, private val cocktailMapper: CocktailMapper, ) : CocktailDBRepo { override suspend fun lookupRandomCocktail(): CocktailModel { return cocktailMapper.toCocktailModel(apiService.lookupRandomCocktail().drinks.first()) } }
0
Kotlin
0
0
2810f140e44b98b8cbb6c0ec15c15b7456e19a28
721
androidJacocoCoverage
Apache License 2.0
vico/views/src/main/java/com/patrykandpatrick/vico/views/common/shader/DynamicShaders.kt
patrykandpatrick
338,848,755
false
{"Kotlin": 781620, "CSS": 166}
/* * Copyright 2024 by <NAME> and <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. */ @file:Suppress("UnusedReceiverParameter") package com.patrykandpatrick.vico.views.common.shader import com.patrykandpatrick.vico.core.common.shader.DynamicShader import com.patrykandpatrick.vico.core.common.shader.DynamicShaders import com.patrykandpatrick.vico.core.common.shader.LinearGradientShader /** * Creates a [DynamicShader] in the form of a horizontal gradient. * * @param colors the sRGB colors to be distributed along the gradient line. */ public fun DynamicShaders.horizontalGradient(vararg colors: Int): DynamicShader = horizontalGradient(colors) /** * Creates a [DynamicShader] in the form of a horizontal gradient. * * @param colors the sRGB colors to be distributed along the gradient line. * @param positions controls the position of each color on the gradient line. Each element of the array should belong to * the interval [[0, 1]], where 0 corresponds to the start of the gradient line, and 1 corresponds to the end of the * gradient line. If `null` (the default value) is passed, the colors will be distributed evenly along the gradient * line. */ public fun DynamicShaders.horizontalGradient( colors: IntArray, positions: FloatArray? = null, ): DynamicShader = LinearGradientShader(colors, positions, true) /** * Creates a [DynamicShader] in the form of a vertical gradient. * * @param colors the sRGB colors to be distributed along the gradient line. */ public fun DynamicShaders.verticalGradient(vararg colors: Int): DynamicShader = verticalGradient(colors) /** * Creates a [DynamicShader] in the form of a vertical gradient. * * @param colors the sRGB colors to be distributed along the gradient line. * @param positions controls the position of each color on the gradient line. Each element of the array should belong to * the interval [[0, 1]], where 0 corresponds to the start of the gradient line, and 1 corresponds to the end of the * gradient line. If `null` (the default value) is passed, the colors will be distributed evenly along the gradient * line. */ public fun DynamicShaders.verticalGradient( colors: IntArray, positions: FloatArray? = null, ): DynamicShader = LinearGradientShader(colors, positions, false)
3
Kotlin
102
1,681
e46778f999edcc1ef676aa21c9a4eecd5c6cc60a
2,801
vico
Apache License 2.0
app/src/main/java/com/steleot/jetpackcompose/playground/compose/foundationlayout/FoundationLayoutScreen.kt
Sagar19RaoRane
410,922,276
true
{"Kotlin": 887894}
package com.steleot.jetpackcompose.playground.compose.foundationlayout import androidx.compose.runtime.Composable import androidx.navigation.NavHostController import com.steleot.jetpackcompose.playground.compose.rest.MainScreen import com.steleot.jetpackcompose.playground.navigation.FoundationLayoutNavRoutes import com.steleot.jetpackcompose.playground.navigation.MainNavRoutes val routes = listOf( FoundationLayoutNavRoutes.AbsolutePadding, FoundationLayoutNavRoutes.AspectRatio, FoundationLayoutNavRoutes.Box, FoundationLayoutNavRoutes.BoxWithConstraints, FoundationLayoutNavRoutes.Column, FoundationLayoutNavRoutes.DefaultMinSize, FoundationLayoutNavRoutes.Intrinsic, FoundationLayoutNavRoutes.MatchParentSize, FoundationLayoutNavRoutes.Offset, FoundationLayoutNavRoutes.PaddingFromBaseline, FoundationLayoutNavRoutes.PaddingFrom, FoundationLayoutNavRoutes.Padding, FoundationLayoutNavRoutes.Row, FoundationLayoutNavRoutes.Size, FoundationLayoutNavRoutes.Spacer, FoundationLayoutNavRoutes.Weight, ) @Composable fun FoundationLayoutScreen(navController: NavHostController) { MainScreen( navController = navController, title = MainNavRoutes.FoundationLayout, list = routes, ) }
0
null
0
1
91d0a3571031a97a437e13ab103a6cd7092f1598
1,280
Jetpack-Compose-Playground
Apache License 2.0
MapboxSearch/sdk/src/test/java/com/mapbox/search/record/FavoriteRecordTest.kt
mapbox
438,355,708
false
{"Kotlin": 2244740, "Java": 41736, "Python": 18980, "Shell": 17499}
package com.mapbox.search.record import com.mapbox.search.tests_support.createSearchAddress import com.mapbox.search.tests_support.createTestFavoriteRecord import com.mapbox.test.dsl.TestCase import org.junit.jupiter.api.TestFactory internal class FavoriteRecordTest { @TestFactory fun `Check index tokens`() = TestCase { Given("FavoriteRecord") { When("FavoriteRecord doesn't have address") { val recordWithoutAddress = createTestFavoriteRecord(address = null) Then("Index tokens should be empty", emptyList<String>(), recordWithoutAddress.indexTokens) } When("FavoriteRecord have address with filled fields") { val address = createSearchAddress( place = "test place", street = "test street", houseNumber = "test houseNumber" ) Then( "Index tokens should contain place, street, houseNumber", listOf("test place", "test street", "test houseNumber"), createTestFavoriteRecord(address = address).indexTokens ) } } } }
18
Kotlin
7
33
20495edc31fd684e956de3c3713cc25113e0d425
1,172
mapbox-search-android
Apache License 2.0
features/login/src/main/java/com/chesire/nekome/app/login/credentials/ui/UIState.kt
Chesire
223,272,337
false
{"Kotlin": 740322, "Ruby": 1682}
package com.chesire.nekome.app.login.credentials.ui import androidx.annotation.StringRes data class UIState( val username: String, val hasUsernameError: Boolean, val password: String, val hasPasswordError: Boolean, val isPerformingLogin: Boolean, val loginButtonEnabled: Boolean, @StringRes val errorSnackbarMessage: Int?, val navigateScreenEvent: Boolean? ) { companion object { val empty: UIState get() = UIState( username = "", hasUsernameError = false, password = "", hasPasswordError = false, isPerformingLogin = false, loginButtonEnabled = false, errorSnackbarMessage = null, navigateScreenEvent = null ) } }
24
Kotlin
42
471
191def4011f659972951d3766bfb4e5af4076ab1
817
Nekome
Apache License 2.0
core/client/src/main/kotlin/org/http4k/connect/Action.kt
http4k
295,641,058
false
{"Kotlin": 1624429, "Handlebars": 10370, "CSS": 5434, "Shell": 3178, "JavaScript": 2076, "Python": 1834, "HTML": 675}
package org.http4k.connect import org.http4k.core.Request import org.http4k.core.Response interface Action<R> { fun toRequest(): Request fun toResult(response: Response): R }
7
Kotlin
17
37
94e71e6bba87d9c79ac29f7ba23bdacd0fdf354c
185
http4k-connect
Apache License 2.0
app/src/main/java/com/djinc/edumotive/screens/ar/PlaneDetectionError.kt
edumotive
469,670,311
false
{"Kotlin": 189611}
package com.djinc.edumotive.screens.ar import androidx.compose.foundation.layout.* import androidx.compose.material.Icon import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Warning import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.djinc.edumotive.R import com.djinc.edumotive.constants.WindowSize import com.djinc.edumotive.ui.theme.PinkPrimary import com.djinc.edumotive.ui.theme.fonts @Composable fun PlaneDetectionError() { val configuration = LocalConfiguration.current val screenWidth = configuration.screenWidthDp + 1 val windowSize = if (screenWidth < 600) WindowSize.Compact else if (screenWidth < 840) WindowSize.Medium else WindowSize.Expanded Box( contentAlignment = if (windowSize == WindowSize.Expanded) Alignment.BottomStart else Alignment.TopEnd, modifier = Modifier.fillMaxSize() ) { Row( horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(horizontal = 16.dp, vertical = 6.dp) ) { Icon( Icons.Rounded.Warning, contentDescription = "Warning icon", tint = PinkPrimary, ) Text( text = stringResource(id = R.string.cannot_find_plane), color = PinkPrimary, fontWeight = FontWeight.Medium, fontSize = 16.sp, fontFamily = fonts, modifier = Modifier.padding(top = 5.dp) ) } } }
0
Kotlin
1
4
8f1b914d0b0374cc7251994419968ae63c575844
1,940
edumotive
MIT License
app/src/main/java/com/codelab/basiclayouts/ui/home/HomeScreen.kt
1guccii
875,159,473
false
{"Kotlin": 18701}
package com.codelab.basiclayouts.ui.home
0
Kotlin
0
0
5bbc1844b12d628963949c3a9c3f570aafe464bf
42
google-intermediate_android_developer
Apache License 2.0
app/src/main/java/moe/feng/danmaqua/ui/common/list/SimpleDiffItemCallback.kt
danmaqua
237,640,502
false
null
package moe.feng.danmaqua.ui.common.list import androidx.recyclerview.widget.DiffUtil open class SimpleDiffItemCallback<T : Any>( val oldItems: List<T>, val newItems: List<T> ) : DiffUtil.Callback() { override fun getOldListSize(): Int { return oldItems.size } override fun getNewListSize(): Int { return newItems.size } override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return areItemsTheSame(oldItems[oldItemPosition], newItems[newItemPosition]) } open fun areItemsTheSame(oldItem: T, newItem: T): Boolean { return oldItem == newItem } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return areContentsTheSame(oldItems[oldItemPosition], newItems[newItemPosition]) } open fun areContentsTheSame(oldItem: T, newItem: T): Boolean { return areItemsTheSame(oldItem, newItem) } }
1
Kotlin
9
137
68694b9f1e575af8541680afe96e2a3108338828
961
danmaqua-android
Apache License 2.0
app/src/main/java/com/logic/uasg/StudentListActivity.kt
GovindaPaliwal
206,713,929
false
null
package com.logic.uasg import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import com.logic.uasg.model.User import com.logic.uasg.util.DatabaseUtils import com.logic.uasg.util.DatabaseUtils.Companion.INPUT_COLUMN_Email import com.logic.uasg.util.DatabaseUtils.Companion.INPUT_COLUMN_ID import com.logic.uasg.util.DatabaseUtils.Companion.INPUT_COLUMN_Name import kotlinx.android.synthetic.main.activity_list.* import java.util.ArrayList class StudentListActivity : AppCompatActivity() { private var databaseUtils: DatabaseUtils? = null private val dataList = ArrayList<User>() protected override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_list) databaseUtils = DatabaseUtils(getBaseContext()) val cursor = databaseUtils!!.getAllUser if (cursor.moveToFirst()) { while (!cursor.isAfterLast()) { val listDetails = User( cursor.getInt(cursor.getColumnIndex(INPUT_COLUMN_ID)), cursor.getString(cursor.getColumnIndex(INPUT_COLUMN_Name)), cursor.getString(cursor.getColumnIndex(INPUT_COLUMN_Email)) ) dataList.add(listDetails) cursor.moveToNext() } } for (i in 0 until dataList.size) { txt_list!!.append(dataList[i].email + "\n\n") Log.e("user email", "" + dataList[i].email) } } }
0
Kotlin
0
1
8a34fdd78d82dcabf5c9b4835284dfc085ff8687
1,547
Universal-Acceptance-UASG-In-Kotlin
Apache License 2.0
local/src/main/java/com/vadmax/timetosleep/local/data/ServerConfigLocalModel.kt
VadimZhuk0v
403,318,456
false
{"Kotlin": 214064, "Ruby": 928}
package com.vadmax.timetosleep.local.data data class ServerConfigLocalModel(val ipAddress: String, val port: Int)
0
Kotlin
1
1
927e28d6b0dc422cb0d4a70be067566be13f40bb
115
TimeToSleep
MIT License
app/src/main/java/com/dosti/scamfolio/db/repositories/Repository.kt
zeroParanoie
803,017,723
false
{"Kotlin": 145065}
package com.dosti.scamfolio.db.repositories import android.util.Log import com.dosti.scamfolio.api.model.CoinBalance import com.dosti.scamfolio.api.model.Wallet import com.dosti.scamfolio.db.entities.CoinModelAPIDB import com.dosti.scamfolio.db.entities.Coin import com.dosti.scamfolio.db.entities.Purchasing import com.dosti.scamfolio.db.entities.User import com.dosti.scamfolio.db.dao.ScamfolioDao import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class Repository(private val dao: ScamfolioDao) { fun login(username : String, password : String) : User? { return dao.loadByLogin(username, password) } fun signIn(username: String, password: String) { dao.insert(user = User(username, password)) } fun getPurchasingList(username: String) : List<Purchasing>{ return dao.getPurchasingList(username) } fun insertPurchasing(purchasing: Purchasing){ CoroutineScope(Dispatchers.IO).launch{ dao.insertPurchasing(purchasing) } } fun checkUserExistence(username: String): Boolean{ return dao.checkUserExistence(username) } fun insertCoinAPI(coin: MutableList<CoinModelAPIDB>){ dao.insertCoinAPI(coin) } fun loadAllCoin() : MutableList<CoinModelAPIDB> { return dao.loadAllCoin() } fun isEmpty() : Boolean { return dao.isEmpty() } fun chechFetchedDate(): Long{ return dao.chechFetchedDate() } fun resetCoinList(){ CoroutineScope(Dispatchers.IO).launch{ dao.resetCoinList() } } fun insertCoinForBalance(name:String, price: Double){ CoroutineScope(Dispatchers.IO).launch{ dao.insertCoinForBalance(coin= Coin(name,price)) } } fun getCurrentPrice(name: String) :String?{ return dao.getCurrentPrice(name) } fun getAllPurchasingForBalance(name: String) :List<CoinBalance> { return dao.getAllPurchasingForBalance(name) } suspend fun getQuantityCoinByiD(coinId: String, username: String) : Double{ return withContext(Dispatchers.IO) { val negativeCoin = dao.getNegativeQuantityCoinByiD(coinId, username) val positiveCoin = dao.getPositiveQuantityCoinByiD(coinId, username) val total = positiveCoin - negativeCoin Log.d("Wallet Coin", total.toString()) total } } fun getAllCoinSummary(name: String) : List<Wallet>{ return dao.getUserCoinSummary(name) } fun updateCoinForBalance(name:String, price: Double) { return dao.updateCoinForBalance(Coin(name, price)) } fun getCoinImage(coinId: String) : String{ return dao.getCoinImage(coinId) } suspend fun getAllCoins(username: String): List<String> { return withContext(Dispatchers.IO) { dao.getAllCoins(username) } } }
0
Kotlin
2
0
7c289f15d0bde345ffad4322f31e95d0cda6e9a3
3,000
ScamFolio
Do What The F*ck You Want To Public License
src/test/kotlin/it/valeriovaudi/vauthenticator/openid/connect/idtoken/IdTokenTest.kt
bassista
262,500,046
true
{"Kotlin": 89774, "JavaScript": 9725, "HTML": 1854, "Dockerfile": 178}
package it.valeriovaudi.vauthenticator.openid.connect.idtoken import it.valeriovaudi.vauthenticator.time.Clock import org.hamcrest.core.Is import org.junit.Assert.assertThat import org.junit.Test import org.junit.runner.RunWith import org.mockito.BDDMockito.given import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner @RunWith(MockitoJUnitRunner::class) class IdTokenTest { @Mock lateinit var clock: Clock @Test fun `create a new id token`() { val clockTime: Long = 10000 given(clock.nowInSeconds()) .willReturn(clockTime) val actual = IdToken.createIdToken(iss = "AN_ISS", sub = "A_SUB", authentication = TestableOAuth2Authentication(), clock = clock) val expected = IdToken("USER_NAME", "AN_ISS", "A_SUB", "A_CLIENT_APPLICATION_ID", "A_NONCE", clockTime * 20, clockTime, clockTime) assertThat(actual, Is.`is`(expected)) } }
0
null
0
0
ed4ec3f1bc0773a99f165f2c6d6489067684e662
1,034
vauthenticator
Apache License 2.0
kotlin-web/src/jsMain/kotlin/web/events/CustomEvent.kt
JetBrains
93,250,841
false
{"Kotlin": 11691809, "JavaScript": 168519}
@file:Suppress( "EXTERNAL_CLASS_CONSTRUCTOR_PROPERTY_PARAMETER", ) package web.events external interface CustomEventInit<T> : EventInit { var detail: T } external class CustomEvent<T>( override val type: EventType<CustomEvent<T>>, init: CustomEventInit<T> = definedExternally, ) : Event { val detail: T }
32
Kotlin
174
1,252
8f788651776064a30ce1688160b7ef9c314a6fe9
328
kotlin-wrappers
Apache License 2.0
core/src/main/java/co/yugang/album/core/loader/AlbumLoader.kt
YuGangLee
288,134,834
false
null
package co.yugang.album.core.loader import android.content.Context import android.net.Uri import android.provider.MediaStore import androidx.loader.content.CursorLoader import co.yugang.album.core.DifferentialColumnName class AlbumLoader private constructor(context: Context, uri: Uri) : CursorLoader( context, uri, PROJECTION, null, null, DEFAULT_ORDER_BY ) { companion object { private val DEFAULT_ORDER_BY = "${DifferentialColumnName.BUCKET_NAME} COLLATE NOCASE ASC" private val PROJECTION = arrayOf( MediaStore.MediaColumns._ID, DifferentialColumnName.BUCKET_ID, DifferentialColumnName.BUCKET_NAME ) @JvmStatic fun newPhotoAlbumLoader(context: Context) = AlbumLoader(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) @JvmStatic fun newVideoAlbumLoader(context: Context) = AlbumLoader(context, MediaStore.Video.Media.EXTERNAL_CONTENT_URI) } }
0
Kotlin
0
1
e6aae46b55c06b1e4d301c1a50a3518a729dd64e
1,044
MediaSelector
Apache License 2.0
app/src/main/java/com/example/businesscard/MainActivity.kt
saurabhburnwal
753,565,570
false
{"Kotlin": 9042}
package com.example.businesscard import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image 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.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AccountCircle import androidx.compose.material.icons.filled.Call import androidx.compose.material.icons.filled.Email import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.businesscard.ui.theme.BusinessCardTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { BusinessCardTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { BusinessCardApp() } } } } } @Composable fun BusinessCardApp() { Column( verticalArrangement = Arrangement.Center, modifier = Modifier .fillMaxSize() .padding(16.dp) .background(Color(0x489C73A3)) ) { MainContent( stringResource(id = R.string.full_name), stringResource(id = R.string.title), ) } Column( verticalArrangement = Arrangement.Bottom, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxSize() .padding(16.dp) ) { Footer( stringResource(id = R.string.phone_number), stringResource(id = R.string.social_media_handle), stringResource(id = R.string.email_id) ) } } @Composable private fun MainContent( fullName: String, title: String ) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxWidth() ) { Image( painterResource(id = R.drawable.ic_banner_foreground), contentDescription = null, modifier = Modifier .width(125.dp) .height(100.dp) ) Text( text = fullName, fontSize = 24.sp, ) Text( text = title, fontSize = 16.sp, ) } } @Composable private fun Footer( mobile: String, handle: String, email: String ) { Column { Row { Icon( Icons.Filled.Call, contentDescription = "Call Icon.", modifier = Modifier.padding(4.dp) ) Text( text = mobile, modifier = Modifier.padding(4.dp) ) } Row { Icon( Icons.Filled.AccountCircle, contentDescription = "Account Icon", modifier = Modifier.padding(4.dp) ) Text( text = handle, modifier = Modifier.padding(8.dp) ) } Row { Icon( Icons.Filled.Email, contentDescription = "Mail Icon", modifier = Modifier.padding(4.dp) ) Text( text = email, modifier = Modifier.padding(4.dp) ) } } } @Preview(showBackground = true) @Composable fun GreetingPreview() { BusinessCardTheme { BusinessCardApp() } }
0
Kotlin
0
0
ee4b8ca899351425ef7305eb26613752769c7231
4,540
businesscard
MIT License
src/main/java/com/github/grishberg/profiler/analyzer/converter/DeObfuscatorConverter.kt
geaden
307,074,946
true
{"Kotlin": 289336, "Java": 128917, "HTML": 9265, "Shell": 1435}
package com.github.grishberg.profiler.analyzer.converter import proguard.retrace.DeObfuscator private const val SIGNATURE_REGEX = "\\((.*)\\)(.*)" class DeObfuscatorConverter( private val deObfuscator: DeObfuscator ) : NameConverter { private val reg = Regex(SIGNATURE_REGEX) private val argumentsReader = ArgumentsReader() override fun convertClassName(sourceClassName: String): String { return deObfuscator.originalClassName(sourceClassName) } override fun convertMethodName(className: String, sourceMethodName: String, signature: String?): String { var typeFromSignature: String? = null var argumentsFromSignature: String? = null if (signature != null) { val match = reg.find(signature) if (match != null) { val argumentSignature = match.groupValues[1] val typeSignature = match.groupValues[2] typeFromSignature = argumentsReader.read(typeSignature).firstOrNull()?.name if (typeFromSignature != null) { typeFromSignature = deObfuscator.originalClassName(typeFromSignature) } argumentsFromSignature = decodeArguments(argumentSignature) } } return deObfuscator.originalMethodName(className, sourceMethodName, typeFromSignature, argumentsFromSignature) } private fun decodeArguments(argumentSignature: String): String? { val argumentsList = argumentsReader.read(argumentSignature).map { if (it.type == Type.OBFUSCATED) deObfuscator.originalClassName(it.name) else it.name } if (argumentsList.isEmpty()) { return null } return argumentsList.joinToString(",") } }
0
Kotlin
0
0
e5c6b0f5098f3db767ce1fc507941b44b9d43782
1,799
android-methods-profiler
Apache License 2.0
relive-simulator-core/src/commonMain/kotlin/xyz/qwewqa/relive/simulator/core/gen/GenFieldEffect.kt
qwewqa
390,928,568
false
null
@file:Suppress("PropertyName") package xyz.qwewqa.relive.simulator.core.gen import kotlinx.serialization.Serializable @Serializable data class GenFieldEffect( val buff_type1: Int, val buff_type1_target_id: Int, val buff_type1_value_list: Array<Int>, val buff_type2: Int, val buff_type2_target_id: Int, val buff_type2_value_list: Array<Int>, val buff_type3: Int, val buff_type3_target_id: Int, val buff_type3_value_list: Array<Int>, val buff_type4: Int, val buff_type4_target_id: Int, val buff_type4_value_list: Array<Int>, val buff_type5: Int, val buff_type5_target_id: Int, val buff_type5_value_list: Array<Int>, val description: Map<String, String> = emptyMap(), val effect_name: String = "", val icon_id: Int, val name: Map<String, String>, val _id_: Int ) expect val valuesGenFieldEffect: Map<Int, GenFieldEffect>
0
Kotlin
11
7
e32dab696f56ead176e35fca40add33ad1e7f742
862
relight
MIT License
tutorial/src/androidTest/kotlin/com/kaspersky/kaspresso/tutorial/tutorial/LoginActivityTest.kt
sophie5363
867,609,889
false
{"Kotlin": 758946, "Shell": 1880, "Makefile": 387}
package com.kaspersky.kaspresso.tutorial import androidx.test.ext.junit.rules.activityScenarioRule import com.kaspersky.kaspresso.testcases.api.testcase.TestCase import com.kaspersky.kaspresso.tutorial.tutorial.LoginActivity import org.junit.Rule import org.junit.Test class LoginActivityTest : TestCase() { @get:Rule val activityRule = activityScenarioRule<MainActivity>() @Test fun loginSuccessfulIfUsernameAndPasswordCorrect() { run { step("Try to login with correct username and password") { scenario( LoginScenario( username = "123456", password = "123456", ) ) } step("Check current screen") { device.activities.isCurrent(LoginActivity::class.java) } } } @Test fun loginUnsuccessfulIfUsernameIncorrect() { run { step("Try to login with incorrect username") { scenario( LoginScenario( username = "12", password = "123456", ) ) } step("Check current screen") { device.activities.isCurrent(LoginActivity::class.java) } } } @Test fun loginUnsuccessfulIfPasswordIncorrect() { run { step("Try to login with incorrect password") { scenario( LoginScenario( username = "123456", password = "12345", ) ) } step("Check current screen") { device.activities.isCurrent(LoginActivity::class.java) } } } }
0
Kotlin
0
0
bd8d7fcc2daa31a6721349aa72df1bd783962edf
1,846
tutoKaspresso
Apache License 2.0
endlessRunnersGame/src/main/kotlin/cz/woitee/endlessRunners/game/tracking/TrackingUtils.kt
woitee
219,872,458
false
null
package cz.woitee.endlessRunners.game.tracking import cz.woitee.endlessRunners.game.actions.ApplyGameEffectAction import cz.woitee.endlessRunners.game.actions.NoAction import cz.woitee.endlessRunners.game.actions.abstract.GameAction import cz.woitee.endlessRunners.game.actions.abstract.HoldButtonAction import cz.woitee.endlessRunners.game.actions.composite.ConditionalAction import cz.woitee.endlessRunners.game.actions.composite.ConditionalHoldAction import cz.woitee.endlessRunners.game.collisions.collisionEffects.IUndoableCollisionEffect import cz.woitee.endlessRunners.game.collisions.collisionEffects.NoCollisionEffect import cz.woitee.endlessRunners.game.collisions.collisionEffects.composite.ConditionalCollisionEffect import cz.woitee.endlessRunners.game.conditions.GameCondition import cz.woitee.endlessRunners.game.descriptions.GameDescription import cz.woitee.endlessRunners.game.effects.NoEffect import cz.woitee.endlessRunners.game.effects.NoTimedEffect import cz.woitee.endlessRunners.game.effects.UndoableGameEffect import cz.woitee.endlessRunners.game.effects.composite.ConditionalEffect /** * Utils capable of inserting tracking components into any game. */ object TrackingUtils { /** * Changes every action, effect and condition in the game to a Tracking version of the object. * Returns a convenient GameDescriptionTracking object with references to a list of all such actions, objects and * effects. */ fun addTracking(gameDescription: GameDescription): GameDescriptionTracking { val tracking = GameDescriptionTracking() for ((i, action) in gameDescription.allActions.withIndex()) { gameDescription.allActions[i] = addActionToTracking(action, tracking) } for ((i, effect) in gameDescription.permanentEffects.withIndex()) { gameDescription.permanentEffects[i] = addEffectToTracking(effect as UndoableGameEffect, tracking) } for ((i, collisionEffect) in gameDescription.collisionEffects.entries) { gameDescription.collisionEffects[i] = addCollisionEffectToTracking(collisionEffect as IUndoableCollisionEffect, tracking) } return tracking } private fun addActionToTracking(action: GameAction, tracking: GameDescriptionTracking, isInnerAction: Boolean = false): GameAction { if (action is ConditionalAction) { action.condition = addConditionToTracking(action.condition, tracking) // we could add the separate actions to tracking, but we get that information from toplevel action and conditions // inner levels only add other conditions to tracking, but not themselves addActionToTracking(action.trueAction, tracking, true) addActionToTracking(action.falseAction, tracking, true) } if (action is ConditionalHoldAction) { action.applicableCondition = addConditionToTracking(action.applicableCondition, tracking) action.keptApplyingCondition = addConditionToTracking(action.keptApplyingCondition, tracking) action.stopApplyingCondition = addConditionToTracking(action.stopApplyingCondition, tracking) addActionToTracking(action.holdButtonAction, tracking, true) } if (action is ApplyGameEffectAction) { action.gameEffect = addEffectToTracking(action.gameEffect, tracking) } return if (action is HoldButtonAction) { val trackingAction = TrackingHoldAction(action) if (action != NoAction && !isInnerAction) { tracking.holdActions.add(trackingAction) } trackingAction } else { val trackingAction = TrackingAction(action) if (action != NoAction && !isInnerAction) { tracking.actions.add(trackingAction) } trackingAction } } private fun addEffectToTracking(effect: UndoableGameEffect, tracking: GameDescriptionTracking, isInnerEffect: Boolean = false): TrackingEffect { if (effect is ConditionalEffect) { effect.condition = addConditionToTracking(effect.condition, tracking) addEffectToTracking(effect.trueEffect as UndoableGameEffect, tracking, true) addEffectToTracking(effect.falseEffect as UndoableGameEffect, tracking, true) } val trackingEffect = TrackingEffect(effect) if (effect != NoEffect && effect != NoTimedEffect && !isInnerEffect) tracking.effects.add(trackingEffect) return trackingEffect } private fun addCollisionEffectToTracking(effect: IUndoableCollisionEffect, tracking: GameDescriptionTracking, isInnerEffect: Boolean = false): TrackingCollisionEffect { if (effect is ConditionalCollisionEffect) { effect.condition = addConditionToTracking(effect.condition, tracking) addCollisionEffectToTracking(effect.trueEffect as IUndoableCollisionEffect, tracking, true) addCollisionEffectToTracking(effect.falseEffect as IUndoableCollisionEffect, tracking, true) } val trackingEffect = TrackingCollisionEffect(effect) if (effect != NoCollisionEffect && !isInnerEffect) tracking.collisionEffects.add(trackingEffect) return trackingEffect } private fun addConditionToTracking(condition: GameCondition, tracking: GameDescriptionTracking): TrackingCondition { val trackingCondition = TrackingCondition(condition) tracking.conditions.add(trackingCondition) return trackingCondition } }
0
Kotlin
0
1
5c980f44397f0b4f122e7b2cb51b82cf1c0419df
5,515
endlessRunners
Apache License 2.0
app/src/main/java/com/example/androiddevchallenge/network/models/ProgressType.kt
TheAmazingBnD
346,931,444
false
null
package com.example.androiddevchallenge.network.models sealed class ProgressType(open val data: Any? = null) { object NotAsked: ProgressType() object Loading: ProgressType() data class Result(override val data: Any): ProgressType(data) data class Failure(override val data: Any): ProgressType(data) }
0
Kotlin
0
0
af6c7ab663c3bca02114188c82aeb955948565f7
322
ComposeChallengeThree
Apache License 2.0
packages/react-native-notificare-push-ui/android/src/main/java/re/notifica/push/ui/react_native/NotificarePushUIModule.kt
Notificare
313,432,978
false
null
package re.notifica.push.ui.react_native import android.net.Uri import com.facebook.react.bridge.* import re.notifica.Notificare import re.notifica.internal.NotificareLogger import re.notifica.models.NotificareNotification import re.notifica.push.ui.NotificarePushUI import re.notifica.push.ui.ktx.pushUI public class NotificarePushUIModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext), NotificarePushUI.NotificationLifecycleListener { override fun getName(): String = "NotificarePushUIModule" override fun initialize() { super.initialize() EventBroker.setup(reactApplicationContext) Notificare.pushUI().addLifecycleListener(this) } override fun invalidate() { super.invalidate() Notificare.pushUI().removeLifecycleListener(this) } @ReactMethod public fun addListener(@Suppress("UNUSED_PARAMETER") eventName: String) { // Keep: Required for RN built in Event Emitter Calls. } @ReactMethod public fun removeListeners(@Suppress("UNUSED_PARAMETER") count: Int) { // Keep: Required for RN built in Event Emitter Calls. } // region Notificare Push UI @ReactMethod public fun presentNotification(data: ReadableMap, promise: Promise) { val notification: NotificareNotification try { notification = NotificareNotification.fromJson(data.toJson()) } catch (e: Exception) { promise.reject(DEFAULT_ERROR_CODE, e) return } val activity = currentActivity ?: run { promise.reject(DEFAULT_ERROR_CODE, "Cannot present a notification without an activity.") return } Notificare.pushUI().presentNotification(activity, notification) promise.resolve(null) } @ReactMethod public fun presentAction(notificationData: ReadableMap, actionData: ReadableMap, promise: Promise) { val notification: NotificareNotification val action: NotificareNotification.Action try { notification = NotificareNotification.fromJson(notificationData.toJson()) action = NotificareNotification.Action.fromJson(actionData.toJson()) } catch (e: Exception) { promise.reject(DEFAULT_ERROR_CODE, e) return } val activity = currentActivity ?: run { promise.reject(DEFAULT_ERROR_CODE, "Cannot present a notification action without an activity.") return } Notificare.pushUI().presentAction(activity, notification, action) promise.resolve(null) } // endregion // region NotificarePushUI.NotificationLifecycleListener override fun onNotificationWillPresent(notification: NotificareNotification) { try { EventBroker.dispatchEvent("notification_will_present", notification.toJson().toReactMap()) } catch (e: Exception) { NotificareLogger.error("Failed to emit the notification_will_present event.", e) } } override fun onNotificationPresented(notification: NotificareNotification) { try { EventBroker.dispatchEvent("notification_presented", notification.toJson().toReactMap()) } catch (e: Exception) { NotificareLogger.error("Failed to emit the notification_presented event.", e) } } override fun onNotificationFinishedPresenting(notification: NotificareNotification) { try { EventBroker.dispatchEvent("notification_finished_presenting", notification.toJson().toReactMap()) } catch (e: Exception) { NotificareLogger.error("Failed to emit the notification_finished_presenting event.", e) } } override fun onNotificationFailedToPresent(notification: NotificareNotification) { try { EventBroker.dispatchEvent("notification_failed_to_present", notification.toJson().toReactMap()) } catch (e: Exception) { NotificareLogger.error("Failed to emit the notification_failed_to_present event.", e) } } override fun onNotificationUrlClicked(notification: NotificareNotification, uri: Uri) { try { val arguments = Arguments.createMap() arguments.putMap("notification", notification.toJson().toReactMap()) arguments.putString("url", uri.toString()) EventBroker.dispatchEvent("notification_url_clicked", arguments) } catch (e: Exception) { NotificareLogger.error("Failed to emit the notification_url_clicked event.", e) } } override fun onActionWillExecute(notification: NotificareNotification, action: NotificareNotification.Action) { try { val arguments = Arguments.createMap() arguments.putMap("notification", notification.toJson().toReactMap()) arguments.putMap("action", action.toJson().toReactMap()) EventBroker.dispatchEvent("action_will_execute", arguments) } catch (e: Exception) { NotificareLogger.error("Failed to emit the action_will_execute event.", e) } } override fun onActionExecuted(notification: NotificareNotification, action: NotificareNotification.Action) { try { val arguments = Arguments.createMap() arguments.putMap("notification", notification.toJson().toReactMap()) arguments.putMap("action", action.toJson().toReactMap()) EventBroker.dispatchEvent("action_executed", arguments) } catch (e: Exception) { NotificareLogger.error("Failed to emit the action_executed event.", e) } } override fun onActionFailedToExecute( notification: NotificareNotification, action: NotificareNotification.Action, error: Exception? ) { try { val arguments = Arguments.createMap() arguments.putMap("notification", notification.toJson().toReactMap()) arguments.putMap("action", action.toJson().toReactMap()) if (error != null) arguments.putString("error", error.localizedMessage) EventBroker.dispatchEvent("action_failed_to_execute", arguments) } catch (e: Exception) { NotificareLogger.error("Failed to emit the action_failed_to_execute event.", e) } } override fun onCustomActionReceived( notification: NotificareNotification, action: NotificareNotification.Action, uri: Uri ) { try { val arguments = Arguments.createMap() arguments.putMap("notification", notification.toJson().toReactMap()) arguments.putMap("action", action.toJson().toReactMap()) arguments.putString("url", uri.toString()) EventBroker.dispatchEvent("custom_action_received", arguments) } catch (e: Exception) { NotificareLogger.error("Failed to emit the custom_action_received event.", e) } } // endregion public companion object { internal const val DEFAULT_ERROR_CODE = "notificare_error" } }
0
Kotlin
0
1
33193a750b18051c15a40a4c55be7c940b2552ad
7,159
notificare-sdk-react-native
MIT License
src/main/kotlin/kvmInternals/instructions/ioAbstractions/printr.kt
ChippyPlus
850,474,357
false
{"Kotlin": 74636}
package org.example.kvmInternals.instructions.ioAbstractions import org.example.data.registers.enumIdenifiers.SuperRegisterType import org.example.helpers.fullRegisterRead fun IoAbstractions.printr(register: SuperRegisterType) { println(fullRegisterRead(register)) }
0
Kotlin
0
1
86733d9aa14f896af295c1cc9b941d85a04d71a5
272
MVM
MIT License
host/src/commonMain/kotlin/wasi/preview1/function/FdSyncSyscallFdatasyncFunctionHandle.kt
illarionov
848,247,126
false
{"Kotlin": 991649}
/* * Copyright 2024, the wasi-emscripten-host project authors and contributors. Please see the AUTHORS file * for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. * SPDX-License-Identifier: Apache-2.0 */ package at.released.weh.host.wasi.preview1.function import at.released.weh.filesystem.model.Errno import at.released.weh.filesystem.model.Fd import at.released.weh.filesystem.op.sync.SyncFd import at.released.weh.host.EmbedderHost import at.released.weh.host.base.function.HostFunction import at.released.weh.host.base.function.HostFunctionHandle import at.released.weh.host.emscripten.EmscriptenHostFunction import at.released.weh.host.wasi.preview1.WasiHostFunction public class FdSyncSyscallFdatasyncFunctionHandle private constructor( host: EmbedderHost, function: HostFunction, private val syncMetadata: Boolean, ) : HostFunctionHandle(function, host) { public fun execute( fd: Fd, ): Errno = host.fileSystem.execute(SyncFd, SyncFd(fd, syncMetadata)) .fold( ifLeft = { it.errno }, ifRight = { Errno.SUCCESS }, ) public companion object { public fun fdSync( host: EmbedderHost, ): FdSyncSyscallFdatasyncFunctionHandle = FdSyncSyscallFdatasyncFunctionHandle( host = host, function = WasiHostFunction.FD_SYNC, syncMetadata = true, ) public fun syscallFdatasync( host: EmbedderHost, ): FdSyncSyscallFdatasyncFunctionHandle = FdSyncSyscallFdatasyncFunctionHandle( host = host, function = EmscriptenHostFunction.SYSCALL_FDATASYNC, syncMetadata = false, ) } }
0
Kotlin
0
2
eac1f7473d21ca17c16e4b1b01185c9e4c7c81a5
1,752
wasi-emscripten-host
Apache License 2.0
FormularioEjemplo/app/src/main/java/com/example/formularioejemplo/Ventana2/ui/Ventana2.kt
aranzabe
705,187,569
false
{"Kotlin": 266897, "Java": 8590}
package com.example.formularioejemplo.Ventana2.ui import Modelo.Almacen import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.navigation.NavHostController import com.example.formularioejemplo.Rutas @Composable fun Pant2(navController: NavHostController) { Column(modifier = Modifier .fillMaxSize() ){ Text(text = "Hola esto es la pantalla 2") Text(text = "Valor del arrayList: ${Almacen.usuarios.toString()}") Button(onClick = { navController.navigate(Rutas.Login) }) { Text(text = "Volver") } } }
0
Kotlin
0
0
64110550565c356a708f4f3347d5177d0b228ccc
899
Android_Compose_DAM2_2023_2024
MIT License
app/src/main/java/lol/calico/uctutors/generated/api/v1/GetMessagesResponseKt.kt
calico32
715,594,197
false
{"Kotlin": 456590, "TypeScript": 218807, "Java": 99962}
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: api/v1/messages.proto // Generated files should ignore deprecation warnings @file:Suppress("DEPRECATION") package lol.calico.uctutors.generated.api.v1; @kotlin.jvm.JvmName("-initializegetMessagesResponse") public inline fun getMessagesResponse(block: lol.calico.uctutors.generated.api.v1.GetMessagesResponseKt.Dsl.() -> kotlin.Unit): lol.calico.uctutors.generated.api.v1.GetMessagesResponse = lol.calico.uctutors.generated.api.v1.GetMessagesResponseKt.Dsl._create(lol.calico.uctutors.generated.api.v1.GetMessagesResponse.newBuilder()).apply { block() }._build() /** * Protobuf type `api.v1.GetMessagesResponse` */ public object GetMessagesResponseKt { @kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class) @com.google.protobuf.kotlin.ProtoDslMarker public class Dsl private constructor( private val _builder: lol.calico.uctutors.generated.api.v1.GetMessagesResponse.Builder ) { public companion object { @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _create(builder: lol.calico.uctutors.generated.api.v1.GetMessagesResponse.Builder): Dsl = Dsl(builder) } @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _build(): lol.calico.uctutors.generated.api.v1.GetMessagesResponse = _builder.build() /** * `.api.v1.MessageList message_list = 1 [json_name = "messageList"];` */ public var messageList: lol.calico.uctutors.generated.api.v1.MessageList @JvmName("getMessageList") get() = _builder.getMessageList() @JvmName("setMessageList") set(value) { _builder.setMessageList(value) } /** * `.api.v1.MessageList message_list = 1 [json_name = "messageList"];` */ public fun clearMessageList() { _builder.clearMessageList() } /** * `.api.v1.MessageList message_list = 1 [json_name = "messageList"];` * @return Whether the messageList field is set. */ public fun hasMessageList(): kotlin.Boolean { return _builder.hasMessageList() } } } @kotlin.jvm.JvmSynthetic public inline fun lol.calico.uctutors.generated.api.v1.GetMessagesResponse.copy(block: `lol.calico.uctutors.generated.api.v1`.GetMessagesResponseKt.Dsl.() -> kotlin.Unit): lol.calico.uctutors.generated.api.v1.GetMessagesResponse = `lol.calico.uctutors.generated.api.v1`.GetMessagesResponseKt.Dsl._create(this.toBuilder()).apply { block() }._build() public val lol.calico.uctutors.generated.api.v1.GetMessagesResponseOrBuilder.messageListOrNull: lol.calico.uctutors.generated.api.v1.MessageList? get() = if (hasMessageList()) getMessageList() else null
0
Kotlin
0
0
a92325ff8dd6ce831fd230b92d3d1be288451143
2,702
uctutors
MIT License
src/main/kotlin/org/crystal/intellij/lang/stubs/indexes/CrystalVariableShortNameIndex.kt
asedunov
353,165,557
false
{"Kotlin": 1661507, "Java": 554445, "Crystal": 245131, "Lex": 192822, "HTML": 445}
package org.crystal.intellij.lang.stubs.indexes import org.crystal.intellij.lang.psi.CrDefinitionWithFqName class CrystalVariableShortNameIndex : CrystalStringStubIndexExtensionBase<CrDefinitionWithFqName>() { companion object Helper: HelperBase<CrDefinitionWithFqName>( CrystalVariableShortNameIndex::class.java, CrDefinitionWithFqName::class.java ) override val helper get() = Helper }
11
Kotlin
4
33
2e255da6c56a33109b8c58a0aa1a692abf977da2
426
intellij-crystal-lang
Apache License 2.0
src/main/kotlin/net/leanix/vsm/gitlab/broker/connector/adapter/graphql/parser/LanguageParser.kt
leanix
671,435,549
false
{"Kotlin": 107795, "Dockerfile": 244}
package net.leanix.vsm.gitlab.broker.connector.adapter.graphql.parser import net.leanix.gitlabbroker.connector.adapter.graphql.data.allgroupsquery.RepositoryLanguage import net.leanix.vsm.gitlab.broker.connector.domain.Language object LanguageParser { fun parse(languages: List<RepositoryLanguage>?): List<Language> { return if (!languages.isNullOrEmpty()) { languages.map { Language( it.name, it.name, it.share!!, ) } } else { emptyList() } } }
1
Kotlin
0
2
760c2e60cb09341752ce950956dbaf8e9a64e00a
609
vsm-gitlab-broker
Apache License 2.0
app/src/main/java/com/example/cifrades/utils/FormatoEntrada.kt
luizgadel
515,012,335
false
{"Kotlin": 21084}
package com.example.cifrades.utils enum class FormatoEntrada { TEXTO_SIMPLES, HEXADECIMAL, }
0
Kotlin
0
0
9d99fb42aa2e8b86c302019406b51a4c5bd25d36
101
cifra-des-app
MIT License
app/src/main/java/com/example/recyclerview/MainActivity.kt
Wira07
737,255,233
false
{"Kotlin": 13411}
package com.example.recyclerview import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.animation.AnimationUtils import android.widget.Toast import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.recyclerview.data.Food import com.example.recyclerview.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private lateinit var recyclerView: RecyclerView private lateinit var seaFood: RecyclerView private val list = ArrayList<Food>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) // Inisialisasi RecyclerView recyclerView = findViewById(R.id.seafood) // Set animasi pada RecyclerView val itemAnimator = DefaultItemAnimator() itemAnimator.addDuration = 6000 // Durasi animasi tambahan recyclerView.itemAnimator = itemAnimator runItemAnimation() seaFood = findViewById(R.id.seafood) seaFood.setHasFixedSize(true) list.addAll(getListHeroes()) showRecyclerList() } private fun runItemAnimation() { val animation = AnimationUtils.loadAnimation(this, R.anim.item_animation) // Memulai animasi pada setiap item di RecyclerView for (i in 0 until recyclerView.childCount) { val child = recyclerView.getChildAt(i) child.startAnimation(animation) } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_main, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.about_page -> { val moveIntent = Intent(this@MainActivity, AboutActivity::class.java) startActivity(moveIntent) return true } R.id.action_list -> { seaFood.layoutManager = LinearLayoutManager(this) } R.id.action_grid -> { seaFood.layoutManager = GridLayoutManager(this, 2) } } return super.onOptionsItemSelected(item) } private fun getListHeroes(): ArrayList<Food> { val dataName = resources.getStringArray(R.array.data_name) val dataDescription = resources.getStringArray(R.array.data_description) val dataPhoto = resources.getStringArray(R.array.data_photo) val dataGender = resources.getStringArray(R.array.gender) val listFood = ArrayList<Food>() for (i in dataName.indices) { val food = Food(dataName[i], dataDescription[i], dataPhoto[i], dataGender[i]) listFood.add(food) } return listFood } private fun showSelectedFood(hero: Food) { Toast.makeText(this, "Kamu memilih " + hero.name, Toast.LENGTH_SHORT).show() } private fun showRecyclerList() { seaFood.layoutManager = LinearLayoutManager(this) val listFoodAdapter = ListFoodAdapter(list) seaFood.adapter = listFoodAdapter listFoodAdapter.setOnItemClickCallback(object : ListFoodAdapter.OnItemClickCallback { override fun onItemClicked(data: Food) { val intent = Intent( this@MainActivity, Description::class.java ) intent.putExtra(Description.DATA_FOOD, data) startActivity(intent) showSelectedFood(data) } }) } }
0
Kotlin
0
0
6970a3a53244276328a2f649d8e8d7929e71d719
3,972
RecyclerView
Intel Open Source License
sms-service/src/test/kotlin/com/porterhead/sms/provider/clicksend/ClickSendProviderTest.kt
kayazas123
285,784,960
true
{"HTML": 968750, "Kotlin": 75358, "Shell": 1346, "Dockerfile": 579, "JavaScript": 547}
package com.porterhead.sms.provider.clicksend import com.github.tomakehurst.wiremock.WireMockServer import com.github.tomakehurst.wiremock.client.WireMock import com.github.tomakehurst.wiremock.core.WireMockConfiguration import com.porterhead.sms.domain.SmsMessage import com.porterhead.sms.provider.ProviderResponse import com.porterhead.sms.provider.twilio.TwilioData import com.porterhead.sms.resource.GetSmsMessageResourceTest import org.apache.commons.lang3.RandomStringUtils import org.junit.jupiter.api.* import org.junit.jupiter.api.Assertions.assertTrue @TestInstance(TestInstance.Lifecycle.PER_CLASS) class ClickSendProviderTest { val wireMockServer = WireMockServer(WireMockConfiguration().dynamicPort()) var provider = ClickSendProvider() @BeforeAll fun setup() { wireMockServer.start() provider.apiKey = RandomStringUtils.randomAlphanumeric(24) provider.username = RandomStringUtils.randomAlphanumeric(10) provider.endpoint = "http://localhost:${wireMockServer.port()}/clicksend-mock" } @AfterAll fun tearDown() { wireMockServer.stop() } @BeforeEach fun reset() { wireMockServer.resetAll() } @Test fun `Send an Sms Message and expect 200 and status s SUCCESS`() { wireMockServer.stubFor(WireMock.post(WireMock.urlPathMatching("/clicksend-mock")) .willReturn(WireMock.aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(ClickSendData().validResponse))) val status = provider.sendSms(messageDouble()) assertTrue(status == ProviderResponse.SUCCESS(provider.getName())) wireMockServer.verify(1, WireMock.postRequestedFor(WireMock.urlEqualTo("/clicksend-mock"))) } @Test fun `Send an Sms Message and expect 200 but status is INVALID_RECIPIENT`() { wireMockServer.stubFor(WireMock.post(WireMock.urlPathMatching("/clicksend-mock")) .willReturn(WireMock.aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(ClickSendData().invalidRecipient))) val status = provider.sendSms(messageDouble()) assertTrue(status is ProviderResponse.FAILED && status.failureMessage == "INVALID_RECIPIENT") } @Test fun `Send an Sms Message and expect 401`() { wireMockServer.stubFor(WireMock.post(WireMock.urlPathMatching("/clicksend-mock")) .willReturn(WireMock.aResponse() .withStatus(401) .withHeader("Content-Type", "application/json") .withBody(TwilioData().unauthorizedResponse))) val status = provider.sendSms(messageDouble()) assertTrue(status is ProviderResponse.FAILED && status.failureMessage == "Unauthorized") } @Test fun `Send an Sms Message and get socket timeout`() { wireMockServer.stubFor(WireMock.post(WireMock.urlPathMatching("/clicksend-mock")) .willReturn(WireMock.aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(ClickSendData().validResponse) .withFixedDelay(6000))) //1 sec longer than the configured read timeout val status = provider.sendSms(messageDouble()) assertTrue(status is ProviderResponse.FAILED) } private fun messageDouble(): SmsMessage { return SmsMessage(id = GetSmsMessageResourceTest.id, fromNumber = "+1234567890", toNumber = "+1234567899", text = "Hello World") } }
0
null
0
0
b5d5865863d9201a1380071bda7fcd1cc5a8a5fc
3,795
sms-service
Apache License 2.0
subprojects/material/src/main/kotlin/fr/javatic/reactkt/material/components/Button.kt
ylemoigne
46,154,904
false
{"JavaScript": 172345, "Kotlin": 91968, "CSS": 10270, "HTML": 2395}
/* * Copyright 2015 Yann Le Moigne * * 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 fr.javatic.reactkt.material.components import fr.javatic.reactkt.core.ReactElement import fr.javatic.reactkt.core.ktx import fr.javatic.reactkt.core.utils.Classes import fr.javatic.reactkt.material.MaterialComponent class Button : MaterialComponent<ButtonProps>() { override fun render(): ReactElement { val classes = Classes("mdl-button", "mdl-js-button raised", props.className) classes.add(props.floating, "mdl-button--fab") classes.add(props.colored, "mdl-button--colored") classes.add(props.ripple, "mdl-js-ripple-effect") classes.add(props.raised, "mdl-button--raised") classes.add(props.primary, "mdl-button--primary") classes.add(props.accent, "mdl-button--accent") classes.add(props.icon, "mdl-button--icon") classes.add(props.floating ?: false && props.mini ?: false, "mdl-button--mini-fab") return ktx { button("disabled" to props.disabled, "className" to classes.build()) { +props.children } } } }
0
JavaScript
1
7
fc005c935216b217400f1dfeecc0a3aac934b2cf
1,627
ReactKT
Apache License 2.0
app/src/main/java/com/rubyfood/features/NewQuotation/interfaces/SalesmanOnClick.kt
DebashisINT
443,953,616
false
{"Kotlin": 13546090, "Java": 993113}
package com.rubyfood.features.NewQuotation.interfaces import com.rubyfood.features.member.model.TeamListDataModel interface SalesmanOnClick { fun OnClick(obj: TeamListDataModel) }
0
Kotlin
0
0
dcf8cc0098d652c8fc063a4049a0fa7f9b73af95
185
RubyFood
Apache License 2.0
grave/src/main/kotlin/com/tombspawn/models/slack/Attachment.kt
aman400
166,827,316
false
null
package com.tombspawn.models.slack import com.google.gson.annotations.SerializedName class Attachment( @SerializedName("callback_id") var callbackId: String? = null, @SerializedName("fallback") var fallback: String? = null, @SerializedName("text") var text: String? = null, @SerializedName("id") var id: Int? = 0, @SerializedName("color") var color: String? = null, @SerializedName("actions") var actions: MutableList<Action>? = null, @SerializedName("attachment_type") var attachmentType: AttachmentType? = null ) { operator fun Action.unaryPlus() { if(actions == null) { actions = mutableListOf() } actions?.add(this) } operator fun MutableList<Action>.unaryPlus() { if(actions == null) { actions = this } else { actions?.addAll(this) } } operator fun MutableList<Action>?.invoke(function: MutableList<Action>?.() -> Unit) { function() } enum class AttachmentType(val value: String) { @SerializedName("default") DEFAULT("default") } } fun attachment(block: Attachment.() -> Unit) = Attachment().apply(block)
1
Kotlin
0
1
0a21c7d176f022585bda404e735a718f5d7ffdac
1,183
tombspawn
Apache License 2.0
navigation-research/core/src/main/kotlin/ru/hh/navigation/common/MultiStackScreen.kt
hhru
558,759,425
false
null
package ru.hh.navigation.common import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Home import androidx.compose.material.icons.outlined.List import androidx.compose.material.icons.outlined.Star import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment.Companion.CenterHorizontally import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.rememberVectorPainter import androidx.compose.ui.tooling.preview.Preview val TABS = listOf( Icons.Outlined.Home to "first", Icons.Outlined.List to "second", Icons.Outlined.Star to "third" ) @Composable fun MultiStackScreenContent( selectedPos: Int, onTabClick: (Int) -> Unit, modifier: Modifier = Modifier, tabs: List<Pair<ImageVector, String>> = TABS, innerContent: @Composable (PaddingValues) -> Unit, ) { Scaffold( bottomBar = { BottomNavigation { tabs.forEachIndexed { index, item -> BottomNavigationItem( selected = selectedPos == index, onClick = { onTabClick(index) }, icon = { Column(horizontalAlignment = CenterHorizontally) { Icon( painter = rememberVectorPainter(item.first), contentDescription = item.second ) Text(text = item.second) } }, ) } } }, modifier = modifier ) { innerContent(it) } } @Preview @Composable private fun PreviewMultiStack() { MaterialTheme { MultiStackScreenContent( tabs = TABS, selectedPos = 1, onTabClick = {} ) { Text(text = "Hello!") } } }
0
Kotlin
0
7
40f0a2af17438971a92bd6c7178959a18af284e1
2,163
jetpack-compose-navigation-research
MIT License
src/test/kotlin/devapp/CloudStyleGlobal.kt
Anivie
500,668,170
false
null
package devapp import javafx.scene.Cursor.HAND import javafx.scene.paint.Color.* import javafx.scene.paint.Paint import javafx.scene.text.FontWeight import tornadofx.* class CloudStyleGlobal:Stylesheet() { companion object{ val selectionBar by cssproperty<MultiValue<Paint>>("-fx-selection-bar") val selectionBarNonFocused by cssproperty<MultiValue<Paint>>("-fx-selection-bar-non-focused") } init { val blueBorderColor = box(c(193, 197, 205)) val blueBorderColorFocus = box(c(50, 150, 255)) button { backgroundColor += c(236,245,255) backgroundRadius += box(5.px) borderColor += box(c(179,216,255)) borderRadius += box(5.px) textFill = c(64,158,255) and(hover) { backgroundColor += c(64,158,255) borderColor += box(c(64,158,255)) textFill = WHITE } and(pressed) { backgroundColor += c(58,142,230) borderColor += box(c(58,142,230)) textFill = WHITE } fontSize = 15.px padding = box(5.px,10.px) cursor = HAND } textField { borderRadius += box(5.px) borderColor += blueBorderColor borderWidth += box(1.3.px) accentColor = c(46,188,232) backgroundColor += WHITE padding = box(5.px,3.px) fontSize = 14.px and(focused) { borderColor += blueBorderColorFocus } } listView { listCell { and(odd) { backgroundColor += WHITE } and(hover) { backgroundColor += c(245,247,250) } backgroundColor += WHITE fontSize = 15.px textFill = c(117,117,117) padding = box(10.px,0.px,10.px,5.px) borderColor += box(TRANSPARENT,TRANSPARENT,c(235,238,245),TRANSPARENT) } and(focused) { listCell { and(selected) { backgroundColor += c(236,245,255) textFill = c(117,117,117) } } } scrollBar { decrementArrow { minWidth = 0.px minHeight = 0.px prefWidth = 0.px prefHeight = 0.px visibility= FXVisibility.HIDDEN } incrementArrow{ minWidth = 0.px minHeight = 0.px prefWidth = 0.px prefHeight = 0.px visibility= FXVisibility.HIDDEN } decrementButton{ minWidth = 0.px minHeight = 0.px prefWidth = 0.px prefHeight = 0.px visibility= FXVisibility.HIDDEN } incrementButton{ minWidth = 0.px minHeight = 0.px prefWidth = 0.px prefHeight = 0.px visibility= FXVisibility.HIDDEN } and(vertical) { padding = box(0.px) prefWidth = 9.px backgroundColor += WHITE thumb{ backgroundColor += c(221,222,224) backgroundInsets += box(0.px) backgroundRadius += box(5.px) and(pressed) { backgroundColor += c(199,201,204) } } } } and(focused) { borderColor += blueBorderColorFocus } borderColor += blueBorderColor borderWidth += box(1.px) backgroundInsets += box(0.px) } textArea { content { backgroundColor += WHITE } borderRadius += box(5.px) borderColor += blueBorderColor borderWidth += box(1.3.px) accentColor = c("2EBCE8") backgroundColor += WHITE padding = box(5.px,3.px) fontSize = 17.px and(focused) { borderColor += blueBorderColorFocus } scrollBar { decrementArrow { minWidth = 0.px minHeight = 0.px prefWidth = 0.px prefHeight = 0.px visibility= FXVisibility.HIDDEN } incrementArrow{ minWidth = 0.px minHeight = 0.px prefWidth = 0.px prefHeight = 0.px visibility= FXVisibility.HIDDEN } decrementButton{ minWidth = 0.px minHeight = 0.px prefWidth = 0.px prefHeight = 0.px visibility= FXVisibility.HIDDEN } incrementButton{ minWidth = 0.px minHeight = 0.px prefWidth = 0.px prefHeight = 0.px visibility= FXVisibility.HIDDEN } and(vertical, horizontal) { padding = box(0.px) prefWidth = 9.px backgroundColor += WHITE thumb{ backgroundColor += c(236,245,255) backgroundInsets += box(0.px) backgroundRadius += box(0.px) and(pressed) { backgroundColor += c(124,188,255) } } } } } label { fontSize = 13.px textFill = c(117,117,117) } comboBox { backgroundColor += WHITE borderColor += blueBorderColor borderRadius += box(5.px) cursor = HAND child(listCell) { fontSize = 17.px } child(arrowButton) { child(arrow) { shape = "M460.8 755.2a26.112 26.112 0 0 1-18.944-8.704L97.792 363.008a25.6 25.6 0 1 1 37.888-34.304L460.8 691.2l326.656-363.008a25.6 25.6 0 0 1 37.888 34.304L481.28 747.008a26.112 26.112 0 0 1-20.48 8.192z" backgroundColor += c(220,223,230) prefHeight = 5.px prefWidth = 10.px } and(pressed) { arrow { backgroundColor += c(103, 106, 113) } } } child(comboBoxPopup) { listView { listCell { and(hover) { backgroundColor += c(245,247,250) } and(selected) { textFill = c(64,158,254) backgroundColor += c(245,247,250) } backgroundColor += WHITE textFill = c(0,0,0,0.5) fontSize = 17.px cursor = HAND } borderColor += box(c(228,231,237)) } scrollBar { decrementArrow { minWidth = 0.px minHeight = 0.px prefWidth = 0.px prefHeight = 0.px visibility= FXVisibility.HIDDEN } incrementArrow{ minWidth = 0.px minHeight = 0.px prefWidth = 0.px prefHeight = 0.px visibility= FXVisibility.HIDDEN } decrementButton{ minWidth = 0.px minHeight = 0.px prefWidth = 0.px prefHeight = 0.px visibility= FXVisibility.HIDDEN } incrementButton{ minWidth = 0.px minHeight = 0.px prefWidth = 0.px prefHeight = 0.px visibility= FXVisibility.HIDDEN } and(vertical) { padding = box(0.px) prefWidth = 9.px backgroundColor += WHITE thumb{ backgroundColor += c(236,245,255) backgroundInsets += box(0.px) backgroundRadius += box(0.px) and(pressed) { backgroundColor += c(124,188,255) } } } } } and(focused) { borderColor += blueBorderColorFocus } and(editable) { child(textField) { borderWidth += box(0.px) } child(arrowButton) { backgroundColor += WHITE } } } checkBox { box { backgroundColor += WHITE backgroundRadius += box(3.px) borderColor += blueBorderColor borderRadius += box(3.px) } and(selected) { box { backgroundColor += c(64,158,255) borderColor += blueBorderColorFocus } mark { backgroundColor += WHITE shape = "M299,396l2-2,3,3,6-6,2,2-8,8Z" } } fontSize = 14.px cursor = HAND textFill = c(117,117,117) } scrollPane { viewport { backgroundColor += TRANSPARENT } backgroundColor += TRANSPARENT } scrollBar { decrementArrow { minWidth = 0.px minHeight = 0.px prefWidth = 0.px prefHeight = 0.px visibility= FXVisibility.HIDDEN } incrementArrow{ minWidth = 0.px minHeight = 0.px prefWidth = 0.px prefHeight = 0.px visibility= FXVisibility.HIDDEN } decrementButton{ minWidth = 0.px minHeight = 0.px prefWidth = 0.px prefHeight = 0.px visibility= FXVisibility.HIDDEN } incrementButton{ minWidth = 0.px minHeight = 0.px prefWidth = 0.px prefHeight = 0.px visibility= FXVisibility.HIDDEN } and(vertical) { padding = box(0.px) prefWidth = 9.px backgroundColor += WHITE thumb{ backgroundColor += c(236,245,255) backgroundInsets += box(0.px) backgroundRadius += box(0.px) and(pressed) { backgroundColor += c(124,188,255) } } } and(horizontal) { padding = box(0.px) prefHeight = 9.px backgroundColor += WHITE thumb{ backgroundColor += c(236,245,255) backgroundInsets += box(0.px) backgroundRadius += box(0.px) and(pressed) { backgroundColor += c(124,188,255) } } } } datePicker { arrowButton { backgroundColor += WHITE cursor = HAND and(hover, focused) { backgroundColor += c(247, 247, 247) } child(arrow) { shape = "M896 448H128v447.957333l477.738667 0.021334L896 895.957333V448z m0-42.666667V192.042667C896 192 768 192 768 192V149.333333h128.042667A42.666667 42.666667 0 0 1 938.666667 192.042667v703.914666A42.624 42.624 0 0 1 896.064 938.666667H127.936A42.666667 42.666667 0 0 1 85.333333 895.957333V192.042667C85.333333 168.469333 104.256 149.333333 127.957333 149.333333H256v42.666667l-128 0.042667V405.333333h768zM298.666667 85.333333h42.666666v170.666667h-42.666666V85.333333z m384 0h42.666666v170.666667h-42.666666V85.333333zM384 149.333333h256v42.666667H384V149.333333z" } } datePickerPopup { child(monthYearPane) { spinner { child(button) { cursor = HAND backgroundColor += WHITE borderColor += box(TRANSPARENT) } child(label) { fontWeight = FontWeight.BOLD } } backgroundColor += WHITE borderWidth += box(0.px,0.px,1.px,0.px) borderColor += box(c(217,217,217)) } child(calendarGrid) { backgroundColor += WHITE } dateCell { and(hover) { backgroundColor += c(245,245,245) textFill = BLACK } and(focused) { backgroundColor += c(24,144,255) textFill = WHITE } backgroundRadius += box(3.px) borderColor += box(TRANSPARENT) cursor = HAND } nextMonth { and(hover) { backgroundColor += c(245,245,245) textFill = c(217,217,217) } backgroundColor += TRANSPARENT textFill = c(217,217,217) } } textField { borderColor += box(TRANSPARENT) } and(focused) { borderColor += box(c(64,169,255)) } borderColor += box(c(217,217,217)) borderRadius += box(3.px) backgroundColor += WHITE } tableView { columnHeader { backgroundColor += WHITE padding = box(10.px, 5.px, 5.px, 5.px) borderColor += box(c(235,238,245)) borderWidth += box(0.px, 0.5.px) } filler { backgroundColor += WHITE } tableRowCell { and(odd) { backgroundColor += c(250,250,250) } and(hover) { backgroundColor += c(245,247,250) } and(selected) { backgroundColor += c(236,245,255) text { fill = BLACK } } borderColor += box(c(235,238,245)) borderWidth += box(0.5.px, 0.px) } tableCell { and(selected) { textFill = BLACK } padding = box(10.px) fontSize = 13.px } selectionBar.value += WHITE selectionBarNonFocused.value += WHITE and(focused) { borderColor += blueBorderColorFocus } borderColor += blueBorderColor borderWidth += box(1.px) backgroundInsets += box(0.px) } spinner { incrementArrowButton { and(hover) { incrementArrow { backgroundColor += c(64,158,255) } } incrementArrow { shape = "M887.328477 617.152318 533.951458 267.007553c-0.512619-0.512619-1.216181-0.672598-1.759763-1.152533-0.127295-0.127295-0.159978-0.319957-0.287273-0.447252-12.576374-12.416396-32.831716-12.352748-45.280796 0.192662L136.511544 618.944765c-12.447359 12.576374-12.352748 32.800753 0.192662 45.248112 6.239161 6.175514 14.399785 9.280473 22.527725 9.280473 8.224271 0 16.479505-3.168606 22.720387-9.471415L509.792985 333.185325l332.480043 329.407768c6.239161 6.175514 14.368821 9.280473 22.527725 9.280473 8.255235 0 16.479505-3.168606 22.720387-9.471415C899.968499 649.85674 899.872168 629.599677 887.328477 617.152318z" } cursor = HAND backgroundColor += c(245,247,250) borderColor += box(TRANSPARENT, TRANSPARENT, c(220,223,230), c(220,223,230)) } decrementArrowButton { and(hover) { decrementArrow { backgroundColor += c(64,158,255) } } decrementArrow { shape = "M890.335385 330.911222c-12.576374-12.416396-32.800753-12.352748-45.248112 0.192662L517.248327 661.951458 184.831931 332.512727c-12.576374-12.447359-32.800753-12.352748-45.280796 0.192662-12.447359 12.576374-12.352748 32.831716 0.192662 45.280796l353.311652 350.112082c0.543583 0.543583 1.247144 0.672598 1.792447 1.183497 0.127295 0.127295 0.159978 0.287273 0.287273 0.416288 6.239161 6.175514 14.399785 9.280473 22.527725 9.280473 8.224271 0 16.479505-3.168606 22.720387-9.471415l350.112082-353.311652C902.975407 363.615643 902.880796 343.360301 890.335385 330.911222z" } cursor = HAND backgroundColor += c(245,247,250) borderColor += box(TRANSPARENT, TRANSPARENT, TRANSPARENT,c(220,223,230)) } textField { borderColor += box(WHITE) } borderColor += box(c(220,223,230)) borderRadius += box(5.px) backgroundInsets += box(0.px) backgroundRadius += box(5.px) and(hover) { borderColor += box(c(192,196,204)) } } tabPane { tabHeaderBackground { backgroundColor += TRANSPARENT borderColor += box(c(228,231,237)) borderWidth += box(0.px, 0.px, 3.px, 0.px) } and(top) { tabHeaderArea { backgroundInsets += box(0.px, 0.px, 1.px, 0.px) padding = box(5.px,2.px,0.px,0.px) } } tab { and(selected) { borderColor += box(c(64,158,255)) tabLabel { textFill = c(64,158,255) } } and(hover) { tabLabel { textFill = c(64,158,255) } } tabLabel { fontSize = 15.px } focusIndicator { borderWidth += box(0.px) } padding = box(5.0.px, 16.0.px) cursor = HAND backgroundColor += TRANSPARENT borderWidth += box(0.px, 0.px, 3.px, 0.px) borderColor += box(c(228,231,237)) } borderColor += blueBorderColor borderRadius += box(5.px) } pagination { leftArrowButton { and(hover) { leftArrow { backgroundColor += c(64, 158, 255) } } leftArrow { shape = "M401.066667 512l302.933333 302.933333-59.733333 59.733334L341.333333 571.733333 281.6 512 341.333333 452.266667l302.933334-302.933334 59.733333 59.733334L401.066667 512z" } backgroundColor += c(240, 242, 245) backgroundInsets += box(0.px) borderColor += box(TRANSPARENT) } rightArrowButton { and(hover) { rightArrow { backgroundColor += c(64, 158, 255) } padding = box(0.px) } rightArrow { shape = "M584.533333 512l-302.933333 302.933333L341.333333 874.666667l302.933334-302.933334 59.733333-59.733333-59.733333-59.733333L341.333333 145.066667 281.6 209.066667l302.933333 302.933333z" } backgroundColor += c(240, 242, 245) backgroundInsets += box(0.px) borderColor += box(TRANSPARENT) } numberButton { and(hover) { textFill = c(64,158,255) } and(selected) { backgroundColor += c(64,158,255) textFill = WHITE } backgroundColor += c(240, 242, 245) backgroundInsets += box(0.px) backgroundRadius += box(3.px) borderColor += box(TRANSPARENT) cursor = HAND } } contextMenu { backgroundInsets += box(0.px) menuItem { and(hover, focused) { backgroundColor += c(238,238,238) } label { textFill = BLACK padding = box(5.px,100.px,5.px,5.px) } } } slider { track { backgroundColor += c(228,231,237) } thumb { backgroundColor += WHITE borderColor += box(c(64,158,255)) borderRadius += box(1.em) cursor = HAND and(pressed) { backgroundColor += c(228,231,237) } } } progressBar { backgroundColor += WHITE backgroundInsets += box(0.px) padding = box(0.px) track { backgroundColor += c(235,238,245) } bar { backgroundColor += c(64,158,255) } } treeView { treeCell { and(hover) { backgroundColor += c(245,247,250) } and (selected) { backgroundColor += c(245,247,250) } and(empty) { backgroundColor += TRANSPARENT } treeDisclosureNode { arrow { backgroundColor += c(168,171,178) } } backgroundColor += WHITE textFill = BLACK cursor = HAND } backgroundColor += WHITE } } }
0
CSS
4
21
ab1768d96b4787d4c07f5655e88b864c61ab5690
24,109
ElementFX
Apache License 2.0
year2019/day23/part1/src/main/kotlin/com/curtislb/adventofcode/year2019/day23/part1/Year2019Day23Part1.kt
curtislb
226,797,689
false
{"Kotlin": 2246966}
/* --- Day 23: Category Six --- The droids have finished repairing as much of the ship as they can. Their report indicates that this was a Category 6 disaster - not because it was that bad, but because it destroyed the stockpile of Category 6 network cables as well as most of the ship's network infrastructure. You'll need to rebuild the network from scratch. The computers on the network are standard Intcode computers that communicate by sending packets to each other. There are 50 of them in total, each running a copy of the same Network Interface Controller (NIC) software (your puzzle input). The computers have network addresses 0 through 49; when each computer boots up, it will request its network address via a single input instruction. Be sure to give each computer a unique network address. Once a computer has received its network address, it will begin doing work and communicating over the network by sending and receiving packets. All packets contain two values named X and Y. Packets sent to a computer are queued by the recipient and read in the order they are received. To send a packet to another computer, the NIC will use three output instructions that provide the destination address of the packet followed by its X and Y values. For example, three output instructions that provide the values 10, 20, 30 would send a packet with X=20 and Y=30 to the computer with address 10. To receive a packet from another computer, the NIC will use an input instruction. If the incoming packet queue is empty, provide -1. Otherwise, provide the X value of the next packet; the computer will then use a second input instruction to receive the Y value for the same packet. Once both values of the packet are read in this way, the packet is removed from the queue. Note that these input and output instructions never block. Specifically, output instructions do not wait for the sent packet to be received - the computer might send multiple packets before receiving any. Similarly, input instructions do not wait for a packet to arrive - if no packet is waiting, input instructions should receive -1. Boot up all 50 computers and attach them to your network. What is the Y value of the first packet sent to address 255? */ package com.curtislb.adventofcode.year2019.day23.part1 import com.curtislb.adventofcode.year2019.day23.network.Network import com.curtislb.adventofcode.year2019.day23.network.packet.BasePacketListener import com.curtislb.adventofcode.year2019.day23.network.packet.Packet import java.math.BigInteger import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2019, day 23, part 1. * * @param inputPath The path to the input file for this puzzle. * @param computerCount The number of computers in the network. */ fun solve( inputPath: Path = Paths.get("..", "input", "input.txt"), computerCount: Int = 50 ): BigInteger? { // Listen for the first Y value received by the NAT. var firstNatPacketY: BigInteger? = null val natPacketListener = object : BasePacketListener() { override fun onPacketReceived(packet: Packet): Boolean { firstNatPacketY = packet.y return true // Stop the network. } } val network = Network(inputPath.toFile(), computerCount, natPacketListener) network.run() return firstNatPacketY } fun main() = when (val solution = solve()) { null -> println("No packet received by the NAT.") else -> println(solution) }
0
Kotlin
1
1
21296f86840c409ac84053ed854ca508f9dbe66d
3,499
AdventOfCode
MIT License
src/main/kotlin/solve/importer/view/LoadingScreen.kt
prime-slam
542,695,410
false
{"Kotlin": 442756}
package solve.importer.view import io.github.palexdev.materialfx.controls.MFXProgressSpinner import javafx.geometry.Insets import javafx.scene.layout.BorderPane import javafx.scene.layout.Priority import javafx.scene.layout.VBox import javafx.scene.paint.Color import kotlinx.coroutines.cancel import solve.styles.Style import solve.utils.mfxButton import tornadofx.* class LoadingScreen : View("Loading") { private val primaryColor: Color = Color.valueOf(Style.primaryColor) private val controlPanel: ControlPanel by inject() private val progressSpinner = MFXProgressSpinner().apply { color1 = primaryColor color2 = primaryColor color3 = primaryColor color4 = primaryColor } override val root = borderpane { prefHeight = 570.0 prefWidth = 453.0 style = "-fx-background-color: #ffffff" top { label("Import a directory") { hgrow = Priority.ALWAYS prefHeight = 0.0 prefWidth = 200.0 style = "-fx-font-family: ${Style.fontCondensed}; -fx-font-size: ${Style.headerFontSize}" BorderPane.setMargin(this, Insets(0.0, 0.0, 0.0, 24.0)) } } center { vbox(15) { BorderPane.setMargin(this, Insets(200.0, 0.0, 0.0, 170.0)) add( progressSpinner.apply { VBox.setMargin(this, Insets(0.0, 0.0, 0.0, 30.0)) } ) label("Please, wait...") { style = "-fx-font-size: ${Style.headerFontSize}; -fx-font-family: ${Style.fontCondensed}" } } } bottom { borderpane { right { mfxButton("CANCEL") { BorderPane.setMargin(this, Insets(0.0, 24.0, 24.0, 0.0)) maxWidth = 75.0 prefHeight = 23.0 style = Style.buttonStyle action { controlPanel.coroutineScope.cancel() close() } } } } } } }
52
Kotlin
0
8
67352bd0ed1f437fad6b151400898f57ae926c67
2,451
SOLVE
MIT License
save-sandbox/src/main/kotlin/com/saveourtool/save/sandbox/SaveSandbox.kt
saveourtool
300,279,336
false
null
package com.saveourtool.save.sandbox import com.saveourtool.save.sandbox.config.ConfigProperties import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.autoconfigure.domain.EntityScan import org.springframework.boot.context.properties.EnableConfigurationProperties /** * An entrypoint for spring boot for save-sandbox */ @SpringBootApplication @EnableConfigurationProperties(ConfigProperties::class) @EntityScan( "com.saveourtool.save.entities", "com.saveourtool.save.sandbox.entity", ) open class SaveSandbox fun main(args: Array<String>) { SpringApplication.run(SaveSandbox::class.java, *args) }
160
Kotlin
1
31
d83a26b101c0f809d39a6deab4e183de04cc7832
710
save-cloud
MIT License
application/src/main/kotlin/org/gxf/standalonenotifyinggateway/coaphttpproxy/logging/RemoteLoggingWebClient.kt
OSGP
697,215,585
false
{"Kotlin": 38111}
package org.gxf.standalonenotifyinggateway.coaphttpproxy.logging import org.gxf.standalonenotifyinggateway.coaphttpproxy.http.HttpClient import org.springframework.stereotype.Component import org.springframework.web.client.RestClient @Component class RemoteLoggingWebClient(private val webClient: RestClient) { fun remoteLogMessage(message: String) { executeErrorRequest(message) } private fun executeErrorRequest(body: String) { webClient .post() .uri(HttpClient.ERROR_PATH) .body(body) .retrieve() } }
1
Kotlin
1
0
f30e0f26c78dc4aa1ba90ec1df871e85eacbbb59
600
sng-coap-http-proxy
Apache License 2.0
domain/src/test/java/com/grishko188/domain/features/poi/interactor/DeletePoiUseCaseTest.kt
grishko188
574,075,114
false
{"Kotlin": 623659}
package com.grishko188.domain.features.poi.interactor import com.grishko188.domain.MockitoHelper.anyNonNull import com.grishko188.domain.MockitoHelper.argumentCaptor import com.grishko188.domain.MockitoHelper.capture import com.grishko188.domain.MockitoHelper.mock import com.grishko188.domain.MockitoHelper.whenever import com.grishko188.domain.features.poi.models.PoiModel import com.grishko188.domain.features.poi.repo.PoiRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito.times import org.mockito.Mockito.verify import org.mockito.junit.MockitoJUnitRunner import kotlin.test.assertEquals @ExperimentalCoroutinesApi @RunWith(MockitoJUnitRunner::class) class DeletePoiUseCaseTest { @Mock private lateinit var repository: PoiRepository private lateinit var SUT: DeletePoiUseCase @Before fun setup() { Dispatchers.setMain(UnconfinedTestDispatcher()) SUT = DeletePoiUseCase(repository, UnconfinedTestDispatcher()) } @After fun teardown() { Dispatchers.resetMain() } @Test fun `test DeletePoiUseCase invokes deletePoi repo function`() = runTest { val model = mock<PoiModel>() SUT.invoke(DeletePoiUseCase.Params(model)) val captor = argumentCaptor<PoiModel>() verify(repository, times(1)).deletePoi(capture(captor)) assertEquals(captor.value, model) } @Test(expected = Throwable::class) fun `test DeletePoiUseCase throws exception when deletePoi throws exception`() = runTest { val model = mock<PoiModel>() whenever(repository.deletePoi(anyNonNull())).thenThrow(IllegalStateException()) SUT.invoke(DeletePoiUseCase.Params(model)) } }
0
Kotlin
3
55
599037f8a2aee0696cd20609eaf734d75e9af1ba
2,063
Points-of-interest
Apache License 2.0
domain/src/test/java/com/grishko188/domain/features/poi/interactor/DeletePoiUseCaseTest.kt
grishko188
574,075,114
false
{"Kotlin": 623659}
package com.grishko188.domain.features.poi.interactor import com.grishko188.domain.MockitoHelper.anyNonNull import com.grishko188.domain.MockitoHelper.argumentCaptor import com.grishko188.domain.MockitoHelper.capture import com.grishko188.domain.MockitoHelper.mock import com.grishko188.domain.MockitoHelper.whenever import com.grishko188.domain.features.poi.models.PoiModel import com.grishko188.domain.features.poi.repo.PoiRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito.times import org.mockito.Mockito.verify import org.mockito.junit.MockitoJUnitRunner import kotlin.test.assertEquals @ExperimentalCoroutinesApi @RunWith(MockitoJUnitRunner::class) class DeletePoiUseCaseTest { @Mock private lateinit var repository: PoiRepository private lateinit var SUT: DeletePoiUseCase @Before fun setup() { Dispatchers.setMain(UnconfinedTestDispatcher()) SUT = DeletePoiUseCase(repository, UnconfinedTestDispatcher()) } @After fun teardown() { Dispatchers.resetMain() } @Test fun `test DeletePoiUseCase invokes deletePoi repo function`() = runTest { val model = mock<PoiModel>() SUT.invoke(DeletePoiUseCase.Params(model)) val captor = argumentCaptor<PoiModel>() verify(repository, times(1)).deletePoi(capture(captor)) assertEquals(captor.value, model) } @Test(expected = Throwable::class) fun `test DeletePoiUseCase throws exception when deletePoi throws exception`() = runTest { val model = mock<PoiModel>() whenever(repository.deletePoi(anyNonNull())).thenThrow(IllegalStateException()) SUT.invoke(DeletePoiUseCase.Params(model)) } }
0
Kotlin
3
55
599037f8a2aee0696cd20609eaf734d75e9af1ba
2,063
Points-of-interest
Apache License 2.0
domain/auth/src/main/kotlin/io/github/siyual_park/auth/configuration/AuthenticationConfiguration.kt
siyul-park
403,557,925
false
null
package io.github.siyual_park.auth.configuration import io.github.siyual_park.auth.domain.authentication.AuthenticateFilter import io.github.siyual_park.auth.domain.authentication.AuthenticateMapping import io.github.siyual_park.auth.domain.authentication.AuthenticateStrategy import io.github.siyual_park.auth.domain.authentication.Authenticator import io.github.siyual_park.auth.domain.authentication.TypeMatchAuthenticateFilter import org.springframework.beans.BeansException import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.ApplicationContext import org.springframework.context.annotation.Configuration import org.springframework.core.annotation.AnnotationAwareOrderComparator @Configuration class AuthenticationConfiguration( private val applicationContext: ApplicationContext ) { @Autowired(required = true) fun configAuthenticator(authenticator: Authenticator) { applicationContext.getBeansOfType(AuthenticateStrategy::class.java).values .sortedWith(AnnotationAwareOrderComparator.INSTANCE) .forEach { it.javaClass.annotations.filterIsInstance<AuthenticateMapping>() .forEach { annotation -> val filter = getFilter(annotation) authenticator.register(filter, it) } } } private fun getFilter(mapping: AuthenticateMapping): AuthenticateFilter { val filterBeen = try { applicationContext.getBean(mapping.filterBy.java) } catch (e: BeansException) { null } return if (filterBeen is AuthenticateFilter) { filterBeen } else { TypeMatchAuthenticateFilter(mapping.filterBy) } } }
8
Kotlin
0
18
332711a52465e0a10c0125aecf52dd00e247cf58
1,797
spring-webflux-multi-module-boilerplate
MIT License
stream-chat-android-client/src/main/java/io/getstream/chat/android/client/plugin/listeners/ChannelMarkReadListener.kt
GetStream
177,873,527
false
{"Kotlin": 8578375, "MDX": 2150736, "Java": 271477, "JavaScript": 6737, "Shell": 5229}
/* * Copyright (c) 2014-2022 Stream.io Inc. All rights reserved. * * Licensed under the Stream License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://github.com/GetStream/stream-chat-android/blob/main/LICENSE * * 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.getstream.chat.android.client.plugin.listeners import io.getstream.chat.android.client.ChatClient import io.getstream.result.Result /** * Listener for [ChatClient.markRead] requests. */ public interface ChannelMarkReadListener { /** * Run precondition for the request. If it returns [Result.Success] then the request is run otherwise it returns * [Result.Failure] and no request is made. * * @param channelType Type of the channel to mark as read. * @param channelId Id of the channel to mark as read. * * @return [Result.Success] if precondition passes, otherwise [Result.Failure]. */ public suspend fun onChannelMarkReadPrecondition( channelType: String, channelId: String, ): Result<Unit> }
24
Kotlin
273
1,451
8e46f46a68810d8086c48a88f0fff29faa2629eb
1,401
stream-chat-android
FSF All Permissive License
field/src/main/kotlin/org/ua/und97n/synthlife/field/Direction.kt
Und97n
755,901,669
false
{"Kotlin": 73633}
package org.ua.und97n.synthlife.field import org.ua.und97n.synthlife.field.Utils.getByIndexSafe enum class Direction(private val xDiff: Int, private val yDiff: Int) { // UP_LEFT(-1,1 -1), UP(0, -1), // UP_RIGHT(+1, -1), RIGHT(+1, 0), // DOWN_RIGHT(+1, +1), DOWN(0, +1), // DOWN_LEFT(-1, +1), LEFT(-1, 0), ; operator fun plus(v: Int): Direction = Direction.entries.getByIndexSafe(this.ordinal+v) operator fun minus(v: Int): Direction = Direction.entries.getByIndexSafe(this.ordinal-v) fun mirror(): Direction = when (this) { UP -> DOWN DOWN -> UP RIGHT -> LEFT LEFT -> RIGHT } fun moveX(x: Int): Int = x + xDiff fun moveY(y: Int): Int = y + yDiff }
0
Kotlin
0
0
95cb8b42a8a2df7f9f40dee0936baa009bebc8e7
786
SynthLife
MIT License
bubbleshowcase/src/main/java/com/elconfidencial/bubbleshowcase/BubbleShowCase.kt
horizon-ariadust
153,224,124
true
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 12, "XML": 23, "Java": 3}
package com.elconfidencial.bubbleshowcase import android.app.Activity import android.content.Context import android.content.Context.MODE_PRIVATE import android.content.SharedPreferences import android.graphics.Bitmap import android.graphics.RectF import android.graphics.drawable.Drawable import android.os.Build import android.os.Handler import android.support.v4.content.ContextCompat import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.RelativeLayout import java.lang.ref.WeakReference /** * Created by jcampos on 04/09/2018. */ class BubbleShowCase(builder: BubbleShowCaseBuilder){ private val SHARED_PREFS_NAME = "BubbleShowCasePrefs" private val FOREGROUND_LAYOUT_ID = 731 private val DURATION_SHOW_CASE_ANIMATION = 200 //ms private val DURATION_BACKGROUND_ANIMATION = 700 //ms private val DURATION_BEATING_ANIMATION = 700 //ms private val MAX_WIDTH_MESSAGE_VIEW_TABLET = 420 //dp /** * Enum class which corresponds to each valid position for the BubbleMessageView arrow */ enum class ArrowPosition { TOP, BOTTOM, LEFT, RIGHT } /** * Highlight mode. It represents the way that the target view will be highlighted * - VIEW_LAYOUT: Default value. All the view box is highlighted (the rectangle where the view is contained). Example: For a TextView, all the element is highlighted (characters and background) * - VIEW_SURFACE: Only the view surface is highlighted, but not the background. Example: For a TextView, only the characters will be highlighted */ enum class HighlightMode { VIEW_LAYOUT, VIEW_SURFACE } private val mActivity: WeakReference<Activity> = builder.mActivity!! //BubbleMessageView params private val mImage: Drawable? = builder.mImage private val mTitle: String? = builder.mTitle private val mSubtitle: String? = builder.mSubtitle private val mCloseAction: Drawable? = builder.mCloseAction private val mBackgroundColor: Int? = builder.mBackgroundColor private val mTextColor: Int? = builder.mTextColor private val mTitleTextSize: Int? = builder.mTitleTextSize private val mSubtitleTextSize: Int? = builder.mSubtitleTextSize private val mShowOnce: String? = builder.mShowOnce private val mDisableTargetClick: Boolean = builder.mDisableTargetClick private val mDisableCloseAction: Boolean = builder.mDisableCloseAction private val mHighlightMode: BubbleShowCase.HighlightMode? = builder.mHighlightMode private val mHideArrow: Boolean = builder.mHideArrow private val mArrowPositionList: MutableList<ArrowPosition> = builder.mArrowPositionList private val mNextText: String = builder.mNextText private val mShowNext: Boolean = builder.mShowNext private val mNextTextColor: Int? = builder.mNextTextColor private val mNextTextSize: Int? = builder.mNextTextSize private val mTargetView: WeakReference<View>? = builder.mTargetView private val mBubbleShowCaseListener: BubbleShowCaseListener? = builder.mBubbleShowCaseListener private val mCurrentProgress: Int? = builder.mCurrentProgress private val mTotalProgress: Int? = builder.mTotalProgress private val mEnableAnimation: Boolean = builder.mEnableAnimation //Sequence params private val mSequenceListener: SequenceShowCaseListener? = builder.mSequenceShowCaseListener private val isFirstOfSequence: Boolean = builder.mIsFirstOfSequence!! private val isLastOfSequence: Boolean = builder.mIsLastOfSequence!! //References private var foregroundLayoutWithBlur: RelativeLayout? = null private var bubbleMessageViewBuilder: BubbleMessageView.Builder? = null fun show(){ if(mShowOnce != null){ if(isBubbleShowCaseHasBeenShowedPreviously(mShowOnce)){ notifyDismissToSequenceListener() return } else{ registerBubbleShowCaseInPreferences(mShowOnce) } } val rootView = getViewRoot(mActivity.get()!!) foregroundLayoutWithBlur = getForegroundLayoutWithBlur() bubbleMessageViewBuilder = getBubbleMessageViewBuilder() if (mTargetView != null && mArrowPositionList.size <= 1) { //Wait until the end of the layout animation, to avoid problems with pending scrolls or view movements val handler = Handler() handler.postDelayed({ val target = mTargetView.get()!! //If the arrow list is empty, the arrow position is set by default depending on the targetView position on the screen if(mArrowPositionList.isEmpty()){ if(ScreenUtils.isViewLocatedAtHalfTopOfTheScreen(mActivity.get()!!, target)) mArrowPositionList.add(ArrowPosition.TOP) else mArrowPositionList.add(ArrowPosition.BOTTOM) bubbleMessageViewBuilder = getBubbleMessageViewBuilder() } if (ScreenUtils.isVisibleOnScreen(target)) { addTargetViewAtForegroundLayout(target, foregroundLayoutWithBlur) addBubbleMessageViewDependingOnTargetView(target, bubbleMessageViewBuilder!!, foregroundLayoutWithBlur) } else { dismiss() } }, DURATION_BACKGROUND_ANIMATION.toLong()) } else { addBubbleMessageViewOnScreenCenter(bubbleMessageViewBuilder!!, foregroundLayoutWithBlur) } if(isFirstOfSequence){ //Add the foreground layout above the root view val animation = AnimationUtils.getFadeInAnimation(0, DURATION_BACKGROUND_ANIMATION) foregroundLayoutWithBlur?.let { rootView.addView(AnimationUtils.setAnimationToView(foregroundLayoutWithBlur!!, animation)) } } } fun dismiss() { notifyDismissToSequenceListener() if (foregroundLayoutWithBlur != null && isLastOfSequence) { //Remove foreground layout if the BubbleShowCase is the last of the sequence val rootView = getViewRoot(mActivity.get()!!) rootView.removeView(foregroundLayoutWithBlur) foregroundLayoutWithBlur = null } else { //Remove all the views created over the foreground layout waiting for the next BubbleShowCsse in the sequence foregroundLayoutWithBlur?.removeAllViews() } } private fun notifyDismissToSequenceListener(){ mSequenceListener?.let { mSequenceListener.onDismiss() } } private fun getViewRoot(activity: Activity): ViewGroup { val androidContent = activity.findViewById<ViewGroup>(android.R.id.content) return androidContent.parent.parent as ViewGroup } private fun getForegroundLayoutWithBlur(): RelativeLayout { if(mActivity.get()!!.findViewById<RelativeLayout>(FOREGROUND_LAYOUT_ID) != null) return mActivity.get()!!.findViewById(FOREGROUND_LAYOUT_ID) val backgroundLayout = RelativeLayout(mActivity.get()!!) backgroundLayout.id = FOREGROUND_LAYOUT_ID backgroundLayout.layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) backgroundLayout.setBackgroundColor(ContextCompat.getColor(mActivity.get()!!, R.color.transparent_grey)) backgroundLayout.isClickable = true return backgroundLayout } private fun getBubbleMessageViewBuilder(): BubbleMessageView.Builder{ return BubbleMessageView.Builder() .from(mActivity.get()!!) .showNext(mShowNext) .nextText(mNextText) .nextTextColor(mNextTextColor) .nextTextSize(mNextTextSize) .hideArrow(mHideArrow) .arrowPosition(mArrowPositionList) .backgroundColor(mBackgroundColor) .textColor(mTextColor) .titleTextSize(mTitleTextSize) .subtitleTextSize(mSubtitleTextSize) .title(mTitle) .subtitle(mSubtitle) .image(mImage) .closeActionImage(mCloseAction) .disableCloseAction(mDisableCloseAction) .progress(mCurrentProgress, mTotalProgress) .enableAnimation(mEnableAnimation) .listener(object : OnDismissBubbleMessageViewListener{ override fun onDismiss() { dismiss() mBubbleShowCaseListener?.onClose(this@BubbleShowCase) } override fun onNext() { dismiss() mBubbleShowCaseListener?.onNextClick(this@BubbleShowCase) } }) } private fun isBubbleShowCaseHasBeenShowedPreviously(id: String): Boolean{ val mPrefs = mActivity.get()!!.getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE) return getString(mPrefs, id)!=null } private fun registerBubbleShowCaseInPreferences(id: String){ val mPrefs = mActivity.get()!!.getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE) setString(mPrefs, id, id) } fun getString(mPrefs: SharedPreferences, key: String): String? { return mPrefs.getString(key, null) } fun setString(mPrefs: SharedPreferences, key: String, value: String) { val editor = mPrefs.edit() editor.putString(key, value) editor.apply() } /** * This function takes a screenshot of the targetView, creating an ImageView from it. This new ImageView is also set on the layout passed by param */ private fun addTargetViewAtForegroundLayout(targetView: View?, foregroundLayout: RelativeLayout?) { if(targetView==null) return val targetScreenshot = takeScreenshot(targetView, mHighlightMode) val targetScreenshotView = RoundedImageView(mActivity.get()!!) targetScreenshotView.setImageBitmap(targetScreenshot) targetScreenshotView.setOnClickListener { if(!mDisableTargetClick) dismiss() mBubbleShowCaseListener?.onTargetClick(this) } val targetViewParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT) targetViewParams.setMargins(getXposition(targetView), getYposition(targetView), getScreenWidth(mActivity.get()!!) - (getXposition(targetView) + targetView.width), 0) if (mEnableAnimation) { foregroundLayout?.addView(AnimationUtils.setBouncingAnimation(targetScreenshotView, 0, DURATION_BEATING_ANIMATION), targetViewParams) } else { foregroundLayout?.addView(targetScreenshotView, targetViewParams) } } /** * This function creates the BubbleMessageView depending the position of the target and the desired arrow position. This new view is also set on the layout passed by param */ private fun addBubbleMessageViewDependingOnTargetView(targetView: View?, bubbleMessageViewBuilder: BubbleMessageView.Builder, foregroundLayout: RelativeLayout?) { if(targetView==null) return val showCaseParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT) when (bubbleMessageViewBuilder.mArrowPosition[0]) { ArrowPosition.LEFT -> { showCaseParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT) if(ScreenUtils.isViewLocatedAtHalfTopOfTheScreen(mActivity.get()!!, targetView)){ showCaseParams.setMargins( getXposition(targetView) + targetView.width, getYposition(targetView), if(isTablet()) getScreenWidth(mActivity.get()!!) - (getXposition(targetView) + targetView.width) - getMessageViewWidthOnTablet(getScreenWidth(mActivity.get()!!) - (getXposition(targetView) + targetView.width)) else 0, 0) showCaseParams.addRule(RelativeLayout.ALIGN_PARENT_TOP) } else{ showCaseParams.setMargins( getXposition(targetView) + targetView.width, 0, if(isTablet()) getScreenWidth(mActivity.get()!!) - (getXposition(targetView) + targetView.width) - getMessageViewWidthOnTablet(getScreenWidth(mActivity.get()!!) - (getXposition(targetView) + targetView.width)) else 0, getScreenHeight(mActivity.get()!!) - getYposition(targetView) - targetView.height) showCaseParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM) } } ArrowPosition.RIGHT -> { showCaseParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT) if(ScreenUtils.isViewLocatedAtHalfTopOfTheScreen(mActivity.get()!!, targetView)){ showCaseParams.setMargins( if(isTablet()) getXposition(targetView) - getMessageViewWidthOnTablet(getXposition(targetView)) else 0, getYposition(targetView), getScreenWidth(mActivity.get()!!) - getXposition(targetView), 0) showCaseParams.addRule(RelativeLayout.ALIGN_PARENT_TOP) } else{ showCaseParams.setMargins( if(isTablet()) getXposition(targetView) - getMessageViewWidthOnTablet(getXposition(targetView)) else 0, 0, getScreenWidth(mActivity.get()!!) - getXposition(targetView), getScreenHeight(mActivity.get()!!) - getYposition(targetView) - targetView.height) showCaseParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM) } } ArrowPosition.TOP -> { showCaseParams.addRule(RelativeLayout.ALIGN_PARENT_TOP) if(ScreenUtils.isViewLocatedAtHalfLeftOfTheScreen(mActivity.get()!!, targetView)){ showCaseParams.setMargins( if (isTablet()) getXposition(targetView) else 0, getYposition(targetView) + targetView.height, if (isTablet()) getScreenWidth(mActivity.get()!!) - getXposition(targetView) - getMessageViewWidthOnTablet(getScreenWidth(mActivity.get()!!) - getXposition(targetView)) else 0, 0) } else{ showCaseParams.setMargins( if (isTablet()) getXposition(targetView) + targetView.width - getMessageViewWidthOnTablet(getXposition(targetView)) else 0, getYposition(targetView) + targetView.height, if (isTablet()) getScreenWidth(mActivity.get()!!) - getXposition(targetView) - targetView.width else 0, 0) } } ArrowPosition.BOTTOM -> { showCaseParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM) if(ScreenUtils.isViewLocatedAtHalfLeftOfTheScreen(mActivity.get()!!, targetView)){ showCaseParams.setMargins( if (isTablet()) getXposition(targetView) else 0, 0, if (isTablet()) getScreenWidth(mActivity.get()!!) - getXposition(targetView) - getMessageViewWidthOnTablet(getScreenWidth(mActivity.get()!!) - getXposition(targetView)) else 0, getScreenHeight(mActivity.get()!!) - getYposition(targetView)) } else { showCaseParams.setMargins( if (isTablet()) getXposition(targetView) + targetView.width - getMessageViewWidthOnTablet(getXposition(targetView)) else 0, 0, if (isTablet()) getScreenWidth(mActivity.get()!!) - getXposition(targetView) - targetView.width else 0, getScreenHeight(mActivity.get()!!) - getYposition(targetView)) } } } val bubbleMessageView = bubbleMessageViewBuilder.targetViewScreenLocation(RectF( getXposition(targetView).toFloat(), getYposition(targetView).toFloat(), getXposition(targetView).toFloat() + targetView.width, getYposition(targetView).toFloat() + targetView.height)) .build() bubbleMessageView.id = createViewId() val animation = AnimationUtils.getScaleAnimation(0, DURATION_SHOW_CASE_ANIMATION) foregroundLayout?.addView(AnimationUtils.setAnimationToView(bubbleMessageView, animation), showCaseParams) } /** * This function creates a BubbleMessageView and it is set on the center of the layout passed by param */ private fun addBubbleMessageViewOnScreenCenter(bubbleMessageViewBuilder: BubbleMessageView.Builder, foregroundLayout: RelativeLayout?) { val showCaseParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT) showCaseParams.addRule(RelativeLayout. CENTER_VERTICAL) val bubbleMessageView: BubbleMessageView = bubbleMessageViewBuilder.build() bubbleMessageView.id = createViewId() if(isTablet()) showCaseParams.setMargins( if (isTablet()) getScreenWidth(mActivity.get()!!)/2 - ScreenUtils.dpToPx(MAX_WIDTH_MESSAGE_VIEW_TABLET)/2 else 0, 0, if (isTablet()) getScreenWidth(mActivity.get()!!)/2 - ScreenUtils.dpToPx(MAX_WIDTH_MESSAGE_VIEW_TABLET)/2 else 0, 0) val animation = AnimationUtils.getScaleAnimation(0, DURATION_SHOW_CASE_ANIMATION) foregroundLayout?.addView(AnimationUtils.setAnimationToView(bubbleMessageView, animation), showCaseParams) } private fun createViewId(): Int { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { View.generateViewId() } else { System.currentTimeMillis().toInt() / 1000 } } private fun takeScreenshot(targetView: View, highlightMode: HighlightMode?): Bitmap? { if (highlightMode==null || highlightMode == HighlightMode.VIEW_LAYOUT) return takeScreenshotOfLayoutView(targetView) return takeScreenshotOfSurfaceView(targetView) } private fun takeScreenshotOfLayoutView(targetView: View): Bitmap? { if (targetView.width == 0 || targetView.height == 0) { return null } val rootView = getViewRoot(mActivity.get()!!) val currentScreenView = rootView.getChildAt(0) currentScreenView.buildDrawingCache() val bitmap: Bitmap bitmap = Bitmap.createBitmap(currentScreenView.drawingCache, getXposition(targetView), getYposition(targetView), targetView.width, targetView.height) currentScreenView.isDrawingCacheEnabled = false currentScreenView.destroyDrawingCache() return bitmap } private fun takeScreenshotOfSurfaceView(targetView: View): Bitmap? { if (targetView.width == 0 || targetView.height == 0) { return null } targetView.isDrawingCacheEnabled = true val bitmap: Bitmap = Bitmap.createBitmap(targetView.drawingCache) targetView.isDrawingCacheEnabled = false return bitmap } private fun getXposition(targetView: View): Int{ return ScreenUtils.getAxisXpositionOfViewOnScreen(targetView) - getScreenHorizontalOffset() } private fun getYposition(targetView: View): Int{ return ScreenUtils.getAxisYpositionOfViewOnScreen(targetView) - getScreenVerticalOffset() } private fun getScreenHeight(context: Context): Int{ return ScreenUtils.getScreenHeight(context) - getScreenVerticalOffset() } private fun getScreenWidth(context: Context): Int{ return ScreenUtils.getScreenWidth(context) - getScreenHorizontalOffset() } private fun getScreenVerticalOffset(): Int{ return if(foregroundLayoutWithBlur!=null) ScreenUtils.getAxisYpositionOfViewOnScreen(foregroundLayoutWithBlur!!) else 0 } private fun getScreenHorizontalOffset(): Int{ return if(foregroundLayoutWithBlur!=null) ScreenUtils.getAxisXpositionOfViewOnScreen(foregroundLayoutWithBlur!!) else 0 } private fun getMessageViewWidthOnTablet(availableSpace: Int): Int{ return if(availableSpace > ScreenUtils.dpToPx(MAX_WIDTH_MESSAGE_VIEW_TABLET)) ScreenUtils.dpToPx(MAX_WIDTH_MESSAGE_VIEW_TABLET) else availableSpace } private fun isTablet(): Boolean = mActivity.get()!!.resources.getBoolean(R.bool.isTablet) }
0
Kotlin
0
0
e3474849527c407b92cf3a2ef33f4aa3f3e382e5
20,946
BubbleShowCase-Android
MIT License
app/src/main/java/no/hyper/memoryormdemo/Profile.kt
naseemakhtar994
64,830,265
false
{"Java": 67775, "Kotlin": 2067}
package no.hyper.memoryormdemo /** * Created by Jean on 5/12/2016. */ data class Profile ( var name : String, var age : Int, var human : Boolean, var gear : List<Gear>? = null, var house : House? = null, var id : String? = null)
1
null
1
1
9dad72d97661f3bd68b878a5c058fdf90e4f71e4
279
memory-orm
MIT License
ui/runtime/sources/com/meowbase/ui/core/text/FontStyle.kt
siylt007
336,180,880
true
{"Kotlin": 1405824, "Java": 474434, "Dart": 14190, "HTML": 70}
package com.meowbase.ui.core.text import android.graphics.Typeface /* * author: 凛 * date: 2020/8/10 11:22 PM * github: https://github.com/RinOrz * description: 定义字体的粗体斜体风格,这可能在自定义字体后被覆盖? */ enum class FontStyle(val real: Int) { Normal(Typeface.NORMAL), /** 粗体 */ Bold(Typeface.BOLD), /** 斜体 */ Italic(Typeface.ITALIC), /** 粗斜体 */ BoldItalic(Typeface.BOLD_ITALIC), }
0
null
0
0
df82f0588beb13fbd22308b3d015852c25781612
389
toolkit
Apache License 2.0
usvm-sample-language/src/main/kotlin/org/usvm/language/Domain.kt
UnitTestBot
586,907,774
false
null
package org.usvm.language class Program( val name: String, val structs: List<Struct>, val methods: List<Method<SampleType?>> ) class Method<out R : SampleType?>( val name: String, val argumentsTypes: List<SampleType>, val returnType: R, val body: Body?, ) class Body( var registersCount: Int, val stmts: List<Stmt> ) class Struct( val name: String, val fields: Set<Field<SampleType>> ) { override fun toString() = name } class Field<out T : SampleType>( val name: String, val type: T, ) { override fun toString() = name }
4
Kotlin
0
2
a504c78f51690c551c6080d2c964c6a352b761f2
588
usvm
Apache License 2.0
app/src/main/java/com/kmmania/runninguserpreferences/info/InfoFragment.kt
dlgiao
399,046,961
false
null
package com.kmmania.runninguserpreferences.info import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.kmmania.runninguserpreferences.databinding.FragmentInfoBinding class InfoFragment : Fragment() { private var _infoBinding: FragmentInfoBinding? = null private val infoBinding get() = _infoBinding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _infoBinding = FragmentInfoBinding.inflate(inflater, container, false) val rootView = infoBinding.root return rootView } override fun onDestroy() { super.onDestroy() _infoBinding = null } }
0
Kotlin
0
0
346e0990218a72a61ab0c1030a213a2056343532
812
running_user_prefs_android
MIT License
src/main/kotlin/com/sarahisweird/maidbot/maidapi/MaidRequest.kt
SarahIsWeird
571,018,251
false
{"Kotlin": 7867}
package com.sarahisweird.maidbot.maidapi import kotlinx.serialization.Serializable @Serializable data class MaidRequest( val category: MaidType, val amount: Int, )
0
Kotlin
0
3
c2a09b2f476a2e1c3f361b2f2c7266aeb8c515be
174
maid-bot
Do What The F*ck You Want To Public License
src/attachment/Koin.kt
DiSSCo
517,633,705
false
null
package org.synthesis.attachment import org.koin.dsl.module val attachmentsModule = module { single<AttachmentReferenceStore> { PgAttachmentReferenceStore( sqlClient = get() ) } single { AttachmentProvider( store = get(), filesystem = get() ) } }
0
Kotlin
0
0
a2277d627647d1669c3714da455f37fe6c2e93ae
335
elvis-backend
Apache License 2.0
image-loader/src/commonMain/kotlin/com/seiko/imageloader/component/keyer/Keyer.kt
qdsfdhvh
502,954,331
false
{"Kotlin": 824269, "Swift": 717, "HTML": 496}
package com.seiko.imageloader.component.keyer import com.seiko.imageloader.option.Options fun interface Keyer { fun key(data: Any, options: Options, type: Type): String? enum class Type { Memory, Disk, } }
32
Kotlin
15
432
bdf4a1e89113552abe98d250f192ea55bd8a2c24
238
compose-imageloader
MIT License
image-loader/src/commonMain/kotlin/com/seiko/imageloader/component/keyer/Keyer.kt
qdsfdhvh
502,954,331
false
{"Kotlin": 824269, "Swift": 717, "HTML": 496}
package com.seiko.imageloader.component.keyer import com.seiko.imageloader.option.Options fun interface Keyer { fun key(data: Any, options: Options, type: Type): String? enum class Type { Memory, Disk, } }
32
Kotlin
15
432
bdf4a1e89113552abe98d250f192ea55bd8a2c24
238
compose-imageloader
MIT License
src/main/kotlin/com/github/mikesafonov/jira/telegram/service/ChatService.kt
gagapopa
226,065,130
true
{"Kotlin": 271856, "TSQL": 6615, "Dockerfile": 281}
package com.github.mikesafonov.jira.telegram.service import com.github.mikesafonov.jira.telegram.dao.Chat import com.github.mikesafonov.jira.telegram.dao.ChatRepository import com.github.mikesafonov.jira.telegram.dao.State import org.springframework.stereotype.Service /** * @author <NAME> */ @Service class ChatService(private val chatRepository: ChatRepository){ fun addNewChat(jiraLogin: String, telegramId: Long) { val validatedJiraLogin = validateJiraLogin(jiraLogin) val validatedTelegramId = validateTelegramId(telegramId) val chat = Chat(null, validatedJiraLogin, validatedTelegramId, State.INIT) chatRepository.save(chat) } /** * Searching in database chat with [telegramId] telegram chat id. * @param telegramId telegram chat id * @return true if [telegramId] exist in database */ private fun isTelegramUserExist(telegramId: Long): Boolean { return chatRepository.findByTelegramId(telegramId) != null } /** * Validates [jiraLogin] : check if login not blank and not exist in database * @param jiraLogin jira login * @return [jiraLogin] back if check success * @throws AddChatException */ private fun validateJiraLogin(jiraLogin: String): String { if (jiraLogin.isBlank()) { throw AddChatException("Wrong command args: jiraLogin must not be blank") } if (isJiraUserExist(jiraLogin)) { throw AddChatException("Jira login $jiraLogin already exist") } return jiraLogin } /** * Validates [telegramId] : check if chat id non negative and not exist in database * @param telegramId telegram chat id * @return [telegramId] back if check success * @throws AddChatException */ private fun validateTelegramId(telegramId: Long): Long { if (telegramId <= 0) { throw AddChatException("Wrong command args: telegramId must be a positive number") } if (isTelegramUserExist(telegramId)) { throw AddChatException("Telegram id $telegramId already exist") } return telegramId } /** * Searching in database chat with [jiraId] jira login. * @param jiraId jira login * @return true if [jiraId] exist in database */ private fun isJiraUserExist(jiraId: String): Boolean { return chatRepository.findByJiraId(jiraId) != null } }
0
Kotlin
0
0
4b5b335b98217476b3239100d15533f038536524
2,447
jira-telegram-bot
MIT License
app/src/dummy/java/com/radixdlt/android/apps/wallet/ui/di/module/DatabaseModule.kt
radixdlt
158,528,536
false
null
package com.radixdlt.android.apps.wallet.ui.di.module import android.content.Context import androidx.room.Room import com.radixdlt.android.apps.wallet.RadixWalletDatabase import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class DatabaseModule { @Provides @Singleton fun providesRadixWalletDatabaseDatabase(context: Context): RadixWalletDatabase = Room.inMemoryDatabaseBuilder(context, RadixWalletDatabase::class.java).build() @Provides @Singleton fun providesAssetDao(database: RadixWalletDatabase) = database.assetDao() @Provides @Singleton fun providesTransactionsDao(database: RadixWalletDatabase) = database.transactionsDao() }
1
Kotlin
4
17
2fa15c9b2d65040072cbb413a3549f8f489ed6ca
716
radixdlt-wallet-android
MIT License
scan-engine/src/main/java/de/tillhub/scanengine/theme/Color.kt
tillhub
459,124,731
false
{"Kotlin": 89838}
package de.tillhub.scanengine.theme import androidx.compose.ui.graphics.Color val OrbitalBlue = Color(0xFF279FF6)
0
Kotlin
0
2
ac232d7b2261c6c90384536caf8bfa0672d0ff49
116
scan-engine
MIT License
fields-material/src/main/kotlin/dev/icerock/moko/fields/material/binding/TextInputLayoutBinding.kt
icerockdev
210,294,803
false
null
/* * Copyright 2022 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. */ package dev.icerock.moko.fields.material.binding import android.text.Editable import android.text.TextWatcher import androidx.lifecycle.LifecycleOwner import com.google.android.material.textfield.TextInputLayout import dev.icerock.moko.fields.core.FormField import dev.icerock.moko.resources.desc.StringDesc import kotlinx.coroutines.DisposableHandle fun TextInputLayout.bindFormField( lifecycleOwner: LifecycleOwner, formField: FormField<String, StringDesc>, ): DisposableHandle { val dataObserver: DisposableHandle = formField.observeData(lifecycleOwner) { value: String -> if (editText?.text.toString() == value) return@observeData editText?.setText(value) } val watcher = object : TextWatcher { override fun afterTextChanged(s: Editable?) = Unit override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { val str = s.toString() if (str == formField.value()) return formField.setValue(str) } } editText?.addTextChangedListener(watcher) editText?.setOnFocusChangeListener { _, hasFocus -> if (hasFocus) return@setOnFocusChangeListener formField.validate() } val errorObserver: DisposableHandle = formField.observeError(lifecycleOwner) { errorMessage: StringDesc? -> error = errorMessage?.toString(context) isErrorEnabled = errorMessage != null } return DisposableHandle { editText?.removeTextChangedListener(watcher) editText?.onFocusChangeListener = null dataObserver.dispose() errorObserver.dispose() } }
2
Kotlin
6
17
b85ba7e780c09311fcf9274964ec91025319aec4
1,861
moko-fields
Apache License 2.0
src/main/kotlin/com/dev/userservice/UserServiceApplication.kt
i4ba1
774,224,013
false
{"Kotlin": 5143}
package com.dev.userservice import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.cache.annotation.EnableCaching @EnableCaching @SpringBootApplication class UserServiceApplication fun main(args: Array<String>) { runApplication<UserServiceApplication>(*args) }
0
Kotlin
0
0
de268ec6184dcc4bc5ba238773eaec5617442899
355
kotlin-spring-be
MIT License
app/src/main/java/com/example/myapplication/photoViewModel/PhotoFactory.kt
Timur-wq
452,668,715
false
null
package com.example.myapplication.photoViewModel import android.app.Application import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider class PhotoFactory(val application: Application, val byteArray: ByteArray) : ViewModelProvider.AndroidViewModelFactory(application) { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return PhotoModel(application, byteArray) as T } }
1
Kotlin
0
0
4d585754192719a360771a4bc87c35293f8f3f89
426
Photo-eng
MIT License
graphql-kotlin-schema-generator/src/test/kotlin/com/expedia/graphql/generator/types/InputPropertyBuilderTest.kt
gscheibel
206,803,902
true
{"Kotlin": 377798, "Shell": 2887}
package com.expedia.graphql.generator.types import com.expedia.graphql.annotations.GraphQLDescription import com.expedia.graphql.annotations.GraphQLName import com.expedia.graphql.test.utils.SimpleDirective import org.junit.jupiter.api.Test import kotlin.test.assertEquals internal class InputPropertyBuilderTest : TypeTestHelper() { private lateinit var builder: InputPropertyBuilder override fun beforeTest() { builder = InputPropertyBuilder(generator) } private data class InputPropertyTestClass( @GraphQLDescription("Custom description") val description: String, @GraphQLName("newName") val changeMe: String, @SimpleDirective val directiveWithNoPrefix: String, @property:SimpleDirective val directiveWithPrefix: String ) @Test fun `Input property can have a description`() { val result = builder.inputProperty(InputPropertyTestClass::description, InputPropertyTestClass::class) assertEquals("Custom description", result.description) } @Test fun `Input property names can change`() { val result = builder.inputProperty(InputPropertyTestClass::changeMe, InputPropertyTestClass::class) assertEquals("newName", result.name) } @Test fun `Input property can have directives`() { val resultWithNoPrefix = builder.inputProperty(InputPropertyTestClass::directiveWithNoPrefix, InputPropertyTestClass::class) assertEquals(1, resultWithNoPrefix.directives.size) assertEquals("simpleDirective", resultWithNoPrefix.directives.first().name) val resultWithPrefix = builder.inputProperty(InputPropertyTestClass::directiveWithPrefix, InputPropertyTestClass::class) assertEquals(1, resultWithPrefix.directives.size) assertEquals("simpleDirective", resultWithPrefix.directives.first().name) } }
0
null
0
0
771b92a646c31a490b4ef521db50d505e4c585a3
1,899
graphql-kotlin
Apache License 2.0
app/src/main/java/com/mustafagur/marketim/DetailActivity.kt
mustafawp
640,644,105
false
{"Kotlin": 122806}
package com.mustafagur.marketim import DatabaseHelper import android.content.Intent import android.graphics.BitmapFactory import android.graphics.Color import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.widget.Button import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AlertDialog import java.text.SimpleDateFormat import java.util.* class DetailActivity : AppCompatActivity() { var urunid = 0 var urunadi = "" var urunfiyati = 0.0 var urunadedi = "" var urunskt = "" var urunimg: ByteArray? = null var notificationdanmi: Boolean = false private lateinit var detayUadi: TextView private lateinit var detayUfiyat: TextView private lateinit var detayUadet: TextView private lateinit var detayUskt: TextView private lateinit var detayUkz: TextView private lateinit var detayUimg: ImageView private fun init() { detayUadi = findViewById(R.id.detailUrunAdi) detayUfiyat = findViewById(R.id.detailUrunFiyati) detayUadet = findViewById(R.id.detailUrunAdedi) detayUskt = findViewById(R.id.detailUrunSKT) detayUkz = findViewById(R.id.detailUrunKalanZ) detayUimg = findViewById(R.id.detailLogo) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_detail) init() urunid = intent.getIntExtra("urunid", 0) urunadi = intent.getStringExtra("urunadi").toString() urunfiyati = intent.getDoubleExtra("urunfiyati", 0.0) urunadedi = intent.getStringExtra("urunadedi").toString() urunskt = intent.getStringExtra("urunskt").toString() notificationdanmi = intent.getBooleanExtra("notifications",false) val currentDate = Calendar.getInstance().time val dateFormat = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()) val expiryDate = dateFormat.parse(urunskt) var daysRemaining = ((expiryDate.time - currentDate.time) / (24L * 60L * 60L * 1000L)).toString() urunimg = intent.getByteArrayExtra("urunfotografi") detayUadi.setText("Ürün Adı: $urunadi") detayUfiyat.setText("Ürün Fiyatı: ${urunfiyati.toString()}") detayUadet.setText("Ürün Adedi: "+ urunadedi.toString()) if (daysRemaining.toInt() <= 0) { detayUkz.setText("Ürün Kullanıma Uygun değil") detayUkz.setTextColor(Color.RED) } else { detayUkz.setText("Kullanılabilirlik Süresi: $daysRemaining Gün") detayUkz.setTextColor(Color.rgb(255,64,129)) } detayUskt.setText("Ürün SKT: $urunskt") val bitmap = urunimg?.let { BitmapFactory.decodeByteArray(urunimg, 0, it.size) } if (bitmap != null) { Log.e("w","geliyo 3") detayUimg.setImageBitmap(bitmap) } else { detayUimg.setImageResource(R.drawable.logo) Log.e("sa","geliyo 4") } } fun urunuSil(view: View) { val dialogView = LayoutInflater.from(this).inflate(R.layout.sure_dialog, null) val builder = AlertDialog.Builder(this).setView(dialogView).setCancelable(true) val dialog = builder.create() val baslik: TextView = dialogView.findViewById(R.id.text_title) val icerik: TextView = dialogView.findViewById(R.id.text_content) baslik.setText("Marketim | Silme İşlemi") icerik.setText("Bu ürünü silmek istediğine emin misin? Bu işlemin geri dönüşü olmayacak.") val buttonOk: Button = dialogView.findViewById(R.id.button_sil) val buttonNo: Button = dialogView.findViewById(R.id.button_silme) buttonOk.setText("Evet, eminim") buttonNo.setText("Hayır, bekle") buttonOk.setOnClickListener { val db = DatabaseHelper(this) db.deleteData(urunid) db.close() Toast.makeText(this,"Başarıyla Ürün Silindi!",Toast.LENGTH_LONG).show() finish() val main = MainActivity() main.finish() val go = Intent(this@DetailActivity, MainActivity::class.java) startActivity(go) dialog.dismiss() } buttonNo.setOnClickListener { dialog.dismiss() } dialog.setCanceledOnTouchOutside(true) dialog.show() } fun urunuGuncelle(view: View) { finish() val intent = Intent(this, UpdateItemActivity::class.java) intent.putExtra("urunid", urunid) intent.putExtra("urunadi", urunadi) intent.putExtra("urunfiyati", urunfiyati) intent.putExtra("urunadedi", urunadedi) intent.putExtra("urunskt", urunskt) intent.putExtra("urunfotografi", urunimg) startActivity(intent) } fun backToMain(view: View) { if (notificationdanmi) { val intent = Intent(this,MainActivity::class.java) startActivity(intent) } finish() } }
0
Kotlin
0
3
224943f1c2fe70bde936b01833ef50cf2fd5302c
5,135
MarketApp
MIT License
src/com/hxz/mpxjs/web/symbols/VueInputPropSymbol.kt
wuxianqiang
508,329,768
false
{"Kotlin": 1447881, "Vue": 237479, "TypeScript": 106023, "JavaScript": 93869, "HTML": 17163, "Assembly": 12226, "Lex": 11227, "Java": 2846, "Shell": 1917, "Pug": 338}
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.hxz.mpxjs.web.symbols import com.intellij.lang.javascript.psi.JSType import com.intellij.model.Pointer import com.intellij.webSymbols.SymbolKind import com.intellij.webSymbols.WebSymbolOrigin import com.intellij.webSymbols.html.WebSymbolHtmlAttributeValue import com.hxz.mpxjs.model.VueComponent import com.hxz.mpxjs.model.VueInputProperty import com.hxz.mpxjs.model.VueModelVisitor import com.hxz.mpxjs.web.VueWebSymbolsQueryConfigurator class VueInputPropSymbol(property: VueInputProperty, owner: VueComponent, origin: WebSymbolOrigin) : VueNamedWebSymbol<VueInputProperty>(property, owner, origin) { override val kind: SymbolKind get() = VueWebSymbolsQueryConfigurator.KIND_VUE_COMPONENT_PROPS override val type: JSType? get() = item.jsType override val required: Boolean get() = item.required override val attributeValue: WebSymbolHtmlAttributeValue = object : WebSymbolHtmlAttributeValue { override val default: String? get() = item.defaultValue } override fun createPointer(): Pointer<VueInputPropSymbol> = object : NamedSymbolPointer<VueInputProperty, VueInputPropSymbol>(this) { override fun locateSymbol(owner: VueComponent): VueInputProperty? { var result: VueInputProperty? = null // TODO ambiguous resolution in case of duplicated names owner.acceptPropertiesAndMethods(object : VueModelVisitor() { override fun visitInputProperty(prop: VueInputProperty, proximity: Proximity): Boolean { if (prop.name == name) { result = prop } return result == null } }) return result } override fun createWrapper(owner: VueComponent, symbol: VueInputProperty): VueInputPropSymbol = VueInputPropSymbol(symbol, owner, origin) } }
2
Kotlin
0
4
e069e8b340ab04780ac13eab375d900f21bc7613
2,008
intellij-plugin-mpx
Apache License 2.0
src/main/kotlin/io/github/pshegger/aoc/common/Iterable+.kt
PsHegger
325,498,299
false
null
package io.github.pshegger.aoc.common fun <T> Iterable<T>.updated(index: Int, newValue: T) = mapIndexed { i, t -> if (i == index) newValue else t } fun Iterable<String>.splitByBlank(): List<List<String>> = fold(listOf(emptyList())) { acc, str -> if (str.isBlank()) { acc + listOf(emptyList()) } else { acc.dropLast(1) + listOf(acc.last() + str) } } fun <T> Iterable<Iterable<T>>.findCommons() = map { it.toSet() } .reduce { a, b -> a.intersect(b) } fun <T> Iterable<T>.permutations(): List<List<T>> { fun go(ls: List<T>): List<List<T>> { return when (ls.size) { 0, 1 -> listOf(ls) else -> ls.flatMap { item -> go(ls - item).map { listOf(item) + it } } } } return go(this.toList()) } fun <R> Iterable<String>.extractAll(extractor: RegExtractor, block: (List<String>) -> R): List<R> = mapNotNull { extractor.extract(it, block) }
0
Kotlin
0
0
346a8994246775023686c10f3bde90642d681474
953
advent-of-code
MIT License
app/src/main/java/com/rmakiyama/skeleton/ui/MainActivity.kt
rmakiyama
252,239,199
false
null
package com.rmakiyama.skeleton.ui import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.navigation.NavController import androidx.navigation.NavDestination import androidx.navigation.Navigation import androidx.navigation.ui.setupActionBarWithNavController import com.rmakiyama.skeleton.R import com.rmakiyama.skeleton.databinding.ActivityMainBinding import com.rmakiyama.skeleton.ui.home.HomeFragmentDirections import dagger.android.support.DaggerAppCompatActivity import java.util.* class MainActivity : DaggerAppCompatActivity() { private lateinit var binding: ActivityMainBinding private val navController: NavController by lazy { Navigation.findNavController(this, R.id.nav_host_fragment) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolbar) setupActionBarWithNavController(navController) navController.addOnDestinationChangedListener { _, destination, _ -> onDestinationChange(destination) } binding.fab.setOnClickListener { navController.navigate( HomeFragmentDirections.actionHomeToDetail( UUID.randomUUID().toString() ) ) } } override fun onSupportNavigateUp() = navController.navigateUp() override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_settings -> true else -> super.onOptionsItemSelected(item) } } private fun onDestinationChange(destination: NavDestination) { when (destination.id) { R.id.home -> binding.fab.show() else -> binding.fab.hide() } } }
0
Kotlin
0
3
3ae4aa3fe433d0c988f82627a89a14eee7e26f35
2,049
android-skeleton
Apache License 2.0
compose_material3/src/main/java/dev/vengateshm/compose_material3/testing/couroutines/ColdDataSource.kt
vengateshm
670,054,614
false
{"Kotlin": 1781634, "Java": 43780}
package dev.vengateshm.compose_material3.testing.couroutines import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf class ColdDataSource : DataSource { override suspend fun emit(value: Int) { } override fun counts(): Flow<Int> { return flowOf(1, 2, 3, 4, 5) } }
0
Kotlin
0
1
6fa0f1c3170c56264ba85db4ac081831d6623575
308
Android-Kotlin-Jetpack-Compose-Practice
Apache License 2.0
app/src/main/java/com/seif/booksislandapp/presentation/intro/authentication/forget_password/viewmodel/ForgetPasswordViewModel.kt
SeifEldinMohamed
570,587,114
false
null
package com.seif.booksislandapp.presentation.intro.authentication.forget_password.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.google.firebase.auth.FirebaseAuth import com.seif.booksislandapp.R import com.seif.booksislandapp.utils.ResourceProvider import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class ForgetPasswordViewModel@Inject constructor( private val resourceProvider: ResourceProvider ) : ViewModel() { private lateinit var auth: FirebaseAuth private var _forgetPasswordState = MutableStateFlow<ForgetPasswordState>(ForgetPasswordState.Init) val forgetPasswordState = _forgetPasswordState.asStateFlow() fun resetPassword(email: String) { auth = FirebaseAuth.getInstance() setLoading(true) viewModelScope.launch(Dispatchers.IO) { auth.sendPasswordResetEmail(email).addOnSuccessListener { setLoading(false) _forgetPasswordState.value = ForgetPasswordState.ResetSuccessfully("Please Check Your Email") } .addOnFailureListener { setLoading(false) showError(it.message.toString()) } } } private fun setLoading(status: Boolean) { when (status) { true -> { _forgetPasswordState.value = ForgetPasswordState.IsLoading(true) } false -> { _forgetPasswordState.value = ForgetPasswordState.IsLoading(false) } } } private fun showError(message: String) { when (message) { resourceProvider.string(R.string.no_internet) -> { _forgetPasswordState.value = ForgetPasswordState.NoInternetConnection(message) } else -> { _forgetPasswordState.value = ForgetPasswordState.ShowError(message) } } } }
0
Kotlin
0
0
8a65e6406811c2d6c59064c5e1af8f9493aa7cc2
2,102
Books-Island-App
Apache License 2.0
shared/src/iosMain/kotlin/com/github/tyngstast/borsdatavaluationalarmer/model/AddAlarmCallbackViewModel.kt
Tyngstast
446,124,190
false
null
package com.github.tyngstast.borsdatavaluationalarmer.model import com.github.tyngstast.borsdatavaluationalarmer.FlowAdapter @Suppress("unused") class AddAlarmCallbackViewModel(addAlarmModel: AddAlarmModel) : CallbackViewModel() { override val viewModel = BaseAddAlarmViewModel(addAlarmModel) val kpis: FlowAdapter<List<Item>> = viewModel.kpiStateFlow.asCallbacks() val instruments: FlowAdapter<List<Item>> = viewModel.instrumentStateFlow.asCallbacks() fun getInstruments(value: String) { viewModel.getInstruments(value) } fun getKpis(value: String) { viewModel.getKpis(value) } fun addAlarm(kpiValue: Double, isAbove: Boolean) { viewModel.addAlarm(kpiValue, isAbove) } }
0
Kotlin
0
0
1a90b2efeb82399d5e58243bd8df81e2bb41268d
738
borsdata-valuation-alarmer
MIT License
src/main/kotlin/unibz/cs/semint/kprime/domain/db/DatabaseTrademark.kt
kprime-dev
722,929,885
false
{"Kotlin": 383495, "XSLT": 1078, "HTML": 372, "Makefile": 218}
package unibz.cs.semint.kprime.domain.db enum class DatabaseTrademark { H2,PSQL,unknown }
0
Kotlin
0
0
63429395f454148e1652bc0b597c32dd08c15383
94
kprime-arm
MIT License
SceytChatUiKit/src/main/java/com/sceyt/chatuikit/styles/messages_list/item/AudioWaveformStyle.kt
sceyt
549,073,085
false
{"Kotlin": 2675924, "Java": 107920}
package com.sceyt.chatuikit.styles.messages_list.item import android.content.Context import android.content.res.TypedArray import androidx.annotation.ColorInt import androidx.annotation.StyleableRes import com.sceyt.chatuikit.styles.StyleConstants.UNSET_COLOR import com.sceyt.chatuikit.styles.StyleCustomizer data class AudioWaveformStyle( @ColorInt val trackColor: Int, @ColorInt val progressColor: Int, ) { companion object { var styleCustomizer = StyleCustomizer<AudioWaveformStyle> { _, style -> style } } internal class Builder( private val context: Context, private val typedArray: TypedArray ) { @ColorInt private var trackColor: Int = UNSET_COLOR @ColorInt private var progressColor: Int = UNSET_COLOR fun trackColor(@StyleableRes index: Int, @ColorInt defValue: Int = trackColor) = apply { this.trackColor = typedArray.getColor(index, defValue) } fun progressColor(@StyleableRes index: Int, @ColorInt defValue: Int = progressColor) = apply { this.progressColor = typedArray.getColor(index, defValue) } fun build() = AudioWaveformStyle( trackColor = trackColor, progressColor = progressColor ).let { styleCustomizer.apply(context, it) } } }
0
Kotlin
1
2
ce9c1b95555fadaafcd11f0d073fcdb07ca49600
1,352
sceyt-chat-android-uikit
MIT License
sample/src/main/java/uk/gov/hmrc/components/sample/organisms/EditableListViewModel.kt
hmrc
299,591,950
false
null
/* * Copyright 2023 HM Revenue & Customs * * 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 uk.gov.hmrc.components.sample.organisms import uk.gov.hmrc.components.organism.editable.EditableListView data class EditableListViewModel( override var name: String, override var value: String, override var buttonText: String, override var valueContentDescription: String? = null, override val onClickListener: (Int) -> Unit ) : EditableListView.EditableItem
2
Kotlin
2
6
7742cd115ce6a6804b2d6aa856cc1be7034a746c
993
android-components
Apache License 2.0
ExpandableRecyclerView/src/main/java/com/as1k/expandablerecyclerview/listener/ParentListItemExpandCollapseListener.kt
as1k
361,688,512
false
null
package com.as1k.expandablerecyclerview.listener interface ParentListItemExpandCollapseListener{ fun onParentListItemExpanded(position:Int) fun onParentListItemCollapsed(position:Int) }
0
Kotlin
0
0
ed4df62ab147c0955197af1f606c55d65e6de441
195
ExpandableRecyclerView
MIT License
taxiql-query-engine/src/main/java/com/orbitalhq/query/ValueWithTypeName.kt
orbitalapi
541,496,668
false
{"TypeScript": 9344934, "Kotlin": 5669840, "HTML": 201985, "SCSS": 170620, "HCL": 55741, "Java": 29373, "JavaScript": 24697, "Shell": 8800, "Dockerfile": 7001, "Smarty": 4741, "CSS": 2966, "Mustache": 1392, "Batchfile": 983, "MDX": 884, "PLpgSQL": 337}
package com.orbitalhq.query import com.fasterxml.jackson.annotation.JsonRawValue import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.core.TreeNode import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.JsonDeserializer import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.orbitalhq.schemas.QualifiedName /** * This differs from the TypeNamedInstance in that it's more lightweight. * We only include the type data occasionally (ie., the first time we send a result) * and after that, it's raw data. * This is experimental, as this approach may cause issues with polymorphic types. However, * let's cross that bridge later. */ data class ValueWithTypeName( val typeName: String?, /** * Contains the anonymous types used in this type definition. * Ideally, this would be typed as Set<Type>, however our Type objects are designed * to write TO json, not read FROM json. * * This causes problems when we're trying to rebuild ValueWithTypeName from a db * record. * * As the intended use of the ValueWithTypeName is on the client (web), just store * the types as raw JSON. */ @JsonRawValue @JsonDeserialize(using = JsonAsStringDeserializer::class) val anonymousTypes: String, /** * This is the serialized instance, as converted by a RawObjectMapper. */ val value: Any?, /** * An id for the value - normally the hash of the originating typedInstance. * We need to use this so that we can look up the rich typed instance * later to power lineage features etc. * Note that even TypedNull has a hashcode, so should be ok. * It's possible we'll get hash collisions, so will need to tackle that * bridge later - though if two TypedInstances in a query result generate * the same hashCode, it's probably ok to use their lineage interchangably. */ val valueId: Int, /** * When this instance has been generated as a direct result of a query, * this queryId is populated. */ val queryId: String? = null ) { constructor(typeName: QualifiedName?, anonymousTypes: String = NO_ANONYMOUS_TYPES, value: Any?, valueId: Int, queryId: String?) : this( typeName?.parameterizedName, anonymousTypes, value, valueId, queryId ) constructor(anonymousTypes: String, value: Any?, valueId: Int, queryId: String?) : this( null as String?, anonymousTypes, value, valueId, queryId ) companion object { const val NO_ANONYMOUS_TYPES = "[]" // empty array } } class JsonAsStringDeserializer: JsonDeserializer<String>() { override fun deserialize(jsonParser: JsonParser, DeserializationContext: DeserializationContext?): String { return jsonParser.codec.readTree<TreeNode>(jsonParser).toString() } }
9
TypeScript
10
292
2be59abde0bd93578f12fc1e2ecf1f458a0212ec
2,860
orbital
Apache License 2.0
features/login/src/main/java/taiwan/no/one/feat/login/presentation/auths/GoogleConfig.kt
pokk
263,073,196
false
null
/* * MIT License * * Copyright (c) 2020 Jieyi * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package taiwan.no.one.feat.login.presentation.auths import android.content.Context import android.content.Intent import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInOptions import taiwan.no.one.dropbeat.R internal object GoogleConfig { fun getIntent(context: Context): Intent { val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(context.getString(R.string.default_web_client_id)) .requestEmail() .build() return GoogleSignIn.getClient(context, gso).signInIntent } }
2
Kotlin
3
16
6d173194dcd3c44db46dfe6b0ef691b9322da975
1,762
DropBeat
MIT License
apps/etterlatte-migrering/src/main/kotlin/migrering/LagreKoblingRiver.kt
navikt
417,041,535
false
{"Kotlin": 5883491, "TypeScript": 1429790, "Handlebars": 21334, "Shell": 10666, "HTML": 1734, "Dockerfile": 745, "CSS": 598, "PLpgSQL": 556}
package no.nav.etterlatte.migrering import no.nav.etterlatte.libs.common.rapidsandrivers.setEventNameForHendelseType import no.nav.etterlatte.rapidsandrivers.BEHANDLING_ID_KEY import no.nav.etterlatte.rapidsandrivers.ListenerMedLoggingOgFeilhaandtering import no.nav.etterlatte.rapidsandrivers.SAK_ID_KEY import no.nav.etterlatte.rapidsandrivers.behandlingId import no.nav.etterlatte.rapidsandrivers.migrering.Migreringshendelser import no.nav.etterlatte.rapidsandrivers.migrering.PESYS_ID_KEY import no.nav.etterlatte.rapidsandrivers.migrering.pesysId import no.nav.etterlatte.rapidsandrivers.sakId import no.nav.helse.rapids_rivers.JsonMessage import no.nav.helse.rapids_rivers.MessageContext import no.nav.helse.rapids_rivers.RapidsConnection import org.slf4j.LoggerFactory internal class LagreKoblingRiver(rapidsConnection: RapidsConnection, private val pesysRepository: PesysRepository) : ListenerMedLoggingOgFeilhaandtering() { private val logger = LoggerFactory.getLogger(this::class.java) init { initialiserRiver(rapidsConnection, Migreringshendelser.LAGRE_KOPLING) { validate { it.requireKey(PESYS_ID_KEY) } validate { it.requireKey(BEHANDLING_ID_KEY) } validate { it.requireKey(SAK_ID_KEY) } } } override fun haandterPakke( packet: JsonMessage, context: MessageContext, ) { logger.info("Lagrer kopling fra pesyssak ${packet.pesysId} til behandling ${packet.behandlingId}") pesysRepository.lagreKoplingTilBehandling(packet.behandlingId, packet.pesysId, packet.sakId) packet.setEventNameForHendelseType(Migreringshendelser.LAGRE_GRUNNLAG) context.publish(packet.toJson()) logger.info( "Publiserte oppdatert migreringshendelse for ${packet.behandlingId} " + "med lagra kopling til pesyssak ${packet.pesysId}", ) } }
13
Kotlin
0
6
9c58a2993c789b4bb05d0c9f491f8db8f44248de
1,899
pensjon-etterlatte-saksbehandling
MIT License
CryptoAC/src/jsMain/kotlin/eu/fbk/st/cryptoac/view/components/custom/CryptoACSelect.kt
stfbk
292,768,224
false
{"JavaScript": 22741621, "Kotlin": 2367601, "Shell": 14642, "Batchfile": 9481, "SCSS": 6830, "CSS": 5868, "Open Policy Agent": 2902, "HTML": 984, "Assembly": 419}
package eu.fbk.st.cryptoac.view.components.custom import eu.fbk.st.cryptoac.view.components.materialui.inputLabel import eu.fbk.st.cryptoac.view.components.materialui.menuItem import eu.fbk.st.cryptoac.view.components.materialui.select import kotlinx.js.Object import react.* external interface CryptoACSelectProps : Props { /** The label for the select object */ var label: String /** Whether the item should be disabled */ var disabled: Boolean /** The default value of the select object */ var defaultValue: String /** The list of possible values */ var options: List<String> /** Invoked when the field changes value */ var onChange: (String) -> Unit /** Whether to add a first option "Select" */ var selectOption: Boolean /** The ID of the label */ var labelId: String /** The ID of the select object */ var id: String /** The name of the select object */ var name: String /** The auto width property of the React component */ var autoWidth: Boolean /** Further CSS properties to pass to the select object auto */ var selectStyle: Object } external interface CryptoACSelectState : State { /** Current value of select object */ var value: String /** Whether to render the value on change by user */ var changedByUser: Boolean /** Whether the component was just mounted */ var justMounted: Boolean } /** A custom component for a paper */ class CryptoACSelect : RComponent<CryptoACSelectProps, CryptoACSelectState>() { override fun RBuilder.render() { if (props.labelId != undefined && props.label != undefined) { inputLabel { attrs { id = props.labelId } +props.label } } select { attrs { disabled = props.disabled style = props.selectStyle autoWidth = props.autoWidth name = props.name id = props.id inputProps = JSON.parse("""{ "name":"${props.name}" }""".trimMargin()) labelId = props.labelId label = props.label value = state.value onChange = { e -> val newChoice = e.asDynamic().target.value as String setState { value = newChoice changedByUser = true } props.onChange(newChoice) } } if (props.selectOption) { menuItem { attrs { value = "Select" } +"Select" } } props.options.forEach { menuItem { attrs { value = it } +it } } } } override fun CryptoACSelectState.init() { justMounted = true changedByUser = false /** Execute before the render in both the Mounting and Updating lifecycle phases */ CryptoACSelect::class.js.asDynamic().getDerivedStateFromProps = { props: CryptoACSelectProps, state: CryptoACSelectState -> if (state.justMounted || !state.changedByUser) { state.value = if (props.defaultValue == undefined) props.options.first() else props.defaultValue } state.changedByUser = false state.justMounted = false } } } /** Extend RBuilder for easier use of this React component */ fun cryptoACSelect(handler: CryptoACSelectProps.() -> Unit): ReactElement<Props> { return createElement { child(CryptoACSelect::class) { attrs(handler) } }!! }
0
JavaScript
0
2
13958f84e7e8c5e40a78afc5c737e6443bc1ac37
3,890
CryptoAC
Apache License 2.0
tiles/src/main/kotlin/com/aeccue/tiles/grid/GridNine.kt
aeccue
695,985,710
false
{"Kotlin": 130164}
/* * Designed and developed by aeccue. * * 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.aeccue.tiles.grid import androidx.compose.foundation.gestures.Orientation import com.aeccue.tiles.grid.tree.tileGridLayoutTree internal fun gridEightLayoutTree( layout: TileGrid.Layout.GridEight, positions: List<Float>? = null ) = when (layout) { TileGrid.Layout.GridEight.One -> layoutOneTree(positions) TileGrid.Layout.GridEight.Two -> layoutTwoTree(positions) TileGrid.Layout.GridEight.Three -> layoutThreeTree(positions) TileGrid.Layout.GridEight.Four -> layoutFourTree(positions) TileGrid.Layout.GridEight.Five -> layoutFiveTree(positions) TileGrid.Layout.GridEight.Six -> layoutSixTree(positions) } private fun layoutOneTree(positions: List<Float>?) = tileGridLayoutTree( layout = TileGrid.Layout.GridEight.One, orientation = Orientation.Vertical ) { addChain(relativePosition = positions?.get(0) ?: 0f) { addLeaf(relativePosition = positions?.get(1) ?: 0f) addLeaf(relativePosition = positions?.get(2) ?: 0.5f) } addChain(relativePosition = positions?.get(3) ?: 0.25f) { addLeaf(relativePosition = positions?.get(4) ?: 0f) addLeaf(relativePosition = positions?.get(5) ?: 0.5f) } addChain(relativePosition = positions?.get(6) ?: 0.5f) { addLeaf(relativePosition = positions?.get(7) ?: 0f) addLeaf(relativePosition = positions?.get(8) ?: 0.5f) } addChain(relativePosition = positions?.get(9) ?: 0.75f) { addLeaf(relativePosition = positions?.get(10) ?: 0f) addLeaf(relativePosition = positions?.get(11) ?: 0.5f) } } private fun layoutTwoTree(positions: List<Float>?) = tileGridLayoutTree( layout = TileGrid.Layout.GridEight.Two, orientation = Orientation.Vertical, canFlipVertical = true ) { addChain(relativePosition = positions?.get(0) ?: 0f) { addLeaf(relativePosition = positions?.get(1) ?: 0f) addLeaf(relativePosition = positions?.get(2) ?: 0.25f) addLeaf(relativePosition = positions?.get(3) ?: 0.5f) addLeaf(relativePosition = positions?.get(4) ?: 0.75f) } addLeaf(relativePosition = positions?.get(5) ?: 0.25f) addChain(relativePosition = positions?.get(6) ?: 0.75f) { addLeaf(relativePosition = positions?.get(7) ?: 0f) addLeaf(relativePosition = positions?.get(8) ?: (1f / 3f)) addLeaf(relativePosition = positions?.get(9) ?: (2f / 3f)) } } private fun layoutThreeTree(positions: List<Float>?) = tileGridLayoutTree( layout = TileGrid.Layout.GridEight.Three, orientation = Orientation.Vertical, canFlipVertical = true ) { addChain(relativePosition = positions?.get(0) ?: 0f) { addLeaf(relativePosition = positions?.get(1) ?: 0f) addLeaf(relativePosition = positions?.get(2) ?: 0.25f) addLeaf(relativePosition = positions?.get(3) ?: 0.5f) addLeaf(relativePosition = positions?.get(4) ?: 0.75f) } addChain(relativePosition = positions?.get(5) ?: 0.2f) { addLeaf(relativePosition = positions?.get(6) ?: 0f) addLeaf(relativePosition = positions?.get(7) ?: 0.5f) } addChain(relativePosition = positions?.get(8) ?: 0.6f) { addLeaf(relativePosition = positions?.get(9) ?: 0f) addLeaf(relativePosition = positions?.get(10) ?: 0.5f) } } private fun layoutFourTree(positions: List<Float>?) = tileGridLayoutTree( layout = TileGrid.Layout.GridEight.Four, orientation = Orientation.Vertical ) { addChain(relativePosition = positions?.get(0) ?: 0f) { addLeaf(relativePosition = positions?.get(1) ?: 0f) addLeaf(relativePosition = positions?.get(2) ?: (1f / 3f)) addLeaf(relativePosition = positions?.get(3) ?: (2f / 3f)) } addChain(relativePosition = positions?.get(4) ?: 0.25f) { addLeaf(relativePosition = positions?.get(5) ?: 0f) addLeaf(relativePosition = positions?.get(6) ?: 0.5f) } addChain(relativePosition = positions?.get(7) ?: 0.75f) { addLeaf(relativePosition = positions?.get(8) ?: 0f) addLeaf(relativePosition = positions?.get(9) ?: (1f / 3f)) addLeaf(relativePosition = positions?.get(10) ?: (2f / 3f)) } } private fun layoutFiveTree(positions: List<Float>?) = tileGridLayoutTree( layout = TileGrid.Layout.GridEight.Five, orientation = Orientation.Vertical, canFlipVertical = true ) { addChain(relativePosition = positions?.get(0) ?: 0f) { addLeaf(relativePosition = positions?.get(1) ?: 0f) addLeaf(relativePosition = positions?.get(2) ?: 0.25f) addLeaf(relativePosition = positions?.get(3) ?: 0.5f) addLeaf(relativePosition = positions?.get(4) ?: 0.75f) } addChain(relativePosition = positions?.get(5) ?: 0.2f) { addLeaf(relativePosition = positions?.get(6) ?: 0f) addLeaf(relativePosition = positions?.get(7) ?: 0.5f) } addChain(relativePosition = positions?.get(8) ?: 0.6f) { addLeaf(relativePosition = positions?.get(9) ?: 0f) addLeaf(relativePosition = positions?.get(10) ?: 0.5f) } } private fun layoutSixTree(positions: List<Float>?) = tileGridLayoutTree( layout = TileGrid.Layout.GridEight.Six, orientation = Orientation.Horizontal ) { addChain(relativePosition = positions?.get(0) ?: 0f) { addLeaf(relativePosition = positions?.get(1) ?: 0f) addLeaf(relativePosition = positions?.get(2) ?: 0.5f) } addChain(relativePosition = positions?.get(3) ?: 0.25f) { addLeaf(relativePosition = positions?.get(4) ?: 0f) addLeaf(relativePosition = positions?.get(5) ?: 0.5f) } addChain(relativePosition = positions?.get(6) ?: 0.5f) { addLeaf(relativePosition = positions?.get(7) ?: 0f) addLeaf(relativePosition = positions?.get(8) ?: 0.5f) } addChain(relativePosition = positions?.get(9) ?: 0.75f) { addLeaf(relativePosition = positions?.get(10) ?: 0f) addLeaf(relativePosition = positions?.get(11) ?: 0.5f) } }
0
Kotlin
0
0
3a3318a715daf15429cd5fcbec11dd3e4b1f799a
7,045
tiles
Apache License 2.0
app/src/main/java/com/moonwinston/motivationaltodolist/ui/monthly/MonthlyFragment.kt
winstonmoon
321,340,734
false
{"Kotlin": 103614}
package com.moonwinston.motivationaltodolist.ui.monthly import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.findNavController import androidx.viewpager2.widget.ViewPager2 import com.moonwinston.motivationaltodolist.R import com.moonwinston.motivationaltodolist.databinding.FragmentMonthlyBinding import com.moonwinston.motivationaltodolist.ui.main.MainViewModel import com.moonwinston.motivationaltodolist.utils.Language import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import java.time.Month import java.time.format.TextStyle import java.util.Locale @AndroidEntryPoint class MonthlyFragment: Fragment() { private lateinit var binding: FragmentMonthlyBinding private val viewModel: MonthlyViewModel by activityViewModels() private val mainViewModel: MainViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentMonthlyBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initDisplayCoachMark() binding.calendarViewPager.adapter = MonthlyScreenSlidePagerAdapter(this@MonthlyFragment) binding.calendarViewPager.setCurrentItem(START_POSITION, false) binding.calendarViewPager.setPageTransformer(ZoomOutPageTransformer()) binding.settingsButton.setOnClickListener { it.findNavController().navigate(R.id.action_monthly_to_settings) } viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.yearAndMonth.onEach { yearAndMonth -> binding.monthlyTitleTextView.text = viewModel.createMonthlyTitle(yearAndMonth.first, yearAndMonth.second, mainViewModel.languageIndex.value) }.launchIn(viewLifecycleOwner.lifecycleScope) } } } private fun initDisplayCoachMark() { if (viewModel.isCoachMonthlyDismissed.value.not()) { binding.coachMonthly.containerCoach.visibility = View.VISIBLE binding.coachMonthly.containerCoach.setOnClickListener { binding.coachMonthly.containerCoach.visibility = View.GONE viewModel.setCoachMonthlyAsDismissed(true) } } } //TODO fix inner class ZoomOutPageTransformer : ViewPager2.PageTransformer { private val MIN_SCALE = 0.85f private val MIN_ALPHA = 0.5f override fun transformPage(view: View, position: Float) { view.apply { val pageWidth = width val pageHeight = height when { position < -1 -> { // [-Infinity,-1) // This page is way off-screen to the left. alpha = 0f } position <= 1 -> { // [-1,1] // Modify the default slide transition to shrink the page as well val scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position)) val vertMargin = pageHeight * (1 - scaleFactor) / 2 val horzMargin = pageWidth * (1 - scaleFactor) / 2 translationX = if (position < 0) { horzMargin - vertMargin / 2 } else { horzMargin + vertMargin / 2 } // Scale the page down (between MIN_SCALE and 1) scaleX = scaleFactor scaleY = scaleFactor // Fade the page relative to its size. alpha = (MIN_ALPHA + (((scaleFactor - MIN_SCALE) / (1 - MIN_SCALE)) * (1 - MIN_ALPHA))) } else -> { // (1,+Infinity] // This page is way off-screen to the right. alpha = 0f } } } } } }
5
Kotlin
1
4
370530712a33283ebe136bcf961c813111f74669
4,626
motivational-todo-list-android
Apache License 2.0
tests/e2e-test-util/src/main/kotlin/aws/sdk/kotlin/testing/Utils.kt
awslabs
121,333,316
false
{"Kotlin": 1076968, "Smithy": 8546, "TypeScript": 1488, "JavaScript": 1134, "Dockerfile": 391}
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package aws.sdk.kotlin.testing import aws.smithy.kotlin.runtime.http.engine.DefaultHttpEngine import aws.smithy.kotlin.runtime.http.engine.HttpClientEngine import aws.smithy.kotlin.runtime.http.engine.crt.CrtHttpEngine /** * Printable ASCII characters */ val PRINTABLE_CHARS = (32 until 127).map(Int::toChar).joinToString("") /** * Run the [block] with each supported engine */ suspend fun withAllEngines(block: suspend (HttpClientEngine) -> Unit) { val engines = listOf( DefaultHttpEngine(), CrtHttpEngine(), ) engines.forEach { engine -> engine.use { block(engine) } } }
79
Kotlin
49
407
287408211f193624d37678d66b0f31f457017d08
758
aws-sdk-kotlin
Apache License 2.0
src/app/src/main/java/com/dev_vlad/car_v/views/sellers/add/AddCarImagesFragment.kt
vlad-ed-git
340,000,420
false
null
package com.dev_vlad.car_v.views.sellers.add import android.app.Activity.RESULT_OK import android.content.DialogInterface import android.content.Intent import android.os.Bundle import android.provider.MediaStore import android.view.* import androidx.appcompat.app.AlertDialog import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import androidx.navigation.ui.onNavDestinationSelected import androidx.recyclerview.widget.LinearLayoutManager import com.dev_vlad.car_v.CarVApp import com.dev_vlad.car_v.R import com.dev_vlad.car_v.databinding.FragmentAddCarImagesBinding import com.dev_vlad.car_v.util.MyLogger import com.dev_vlad.car_v.util.VerticalSpacingItemDecorator import com.dev_vlad.car_v.util.showSnackBarToUser import com.dev_vlad.car_v.view_models.sellers.add.AddCarImagesViewModel import com.dev_vlad.car_v.view_models.sellers.add.AddCarImagesViewModelFactory import com.dev_vlad.car_v.views.adapters.sellers.MyCarImagesAdapter import com.dev_vlad.car_v.util.REQUEST_IMAGE_IN_GALLERY class AddCarImagesFragment : Fragment(), MyCarImagesAdapter.ImageActionsListeners { companion object { private val TAG = AddCarImagesFragment::class.java.simpleName } private var _binding: FragmentAddCarImagesBinding? = null private val binding get() = _binding!! private val addCarImgsVm: AddCarImagesViewModel by viewModels { val carApp = (activity?.application as CarVApp) AddCarImagesViewModelFactory(carApp.carRepo) } private val photosAdapter = MyCarImagesAdapter(this) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment _binding = FragmentAddCarImagesBinding.inflate(inflater, container, false) setHasOptionsMenu(true) initViews() return binding.root } private val args: AddCarImagesFragmentArgs by navArgs() override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) addCarImgsVm.loadCarDataById(args.CarId) addCarImgsVm.observeCarImages().observe(viewLifecycleOwner, androidx.lifecycle.Observer { MyLogger.logThis( TAG, ".getCarImages().observe()", "has ${it?.size} images" ) if (it != null) photosAdapter.setNewImages(it) }) addCarImgsVm.getSavingState().observe(viewLifecycleOwner, Observer { when (it) { AddCarImagesViewModel.SavingState.SAVING -> { binding.subtitle.setText(R.string.saving_please_wait) binding.loadingBar.isVisible = true } AddCarImagesViewModel.SavingState.SAVED -> { binding.loadingBar.isVisible = false goToSellersHome() } AddCarImagesViewModel.SavingState.ERROR -> { binding.apply { container.showSnackBarToUser( msgResId = addCarImgsVm.errMsgRes ?: R.string.saving_unknown_err, isErrorMsg = true, actionMessage = R.string.ok_txt ) subtitle.setText(R.string.please_add_photos) loadingBar.isVisible = false } } else -> { } } }) } private fun initViews() { binding.apply { photosRv.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false) photosRv.adapter = photosAdapter photosRv.addItemDecoration(VerticalSpacingItemDecorator(30)) laterBtn.setOnClickListener { confirmAddPhotosLater() } addPicBtn.setOnClickListener { addPhoto() } } } private fun addPhoto() { //todo take photo feature addPhotoFromGallery() } private fun addPhotoFromGallery() { val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) intent.type = "image/*" val mimeTypes = arrayOf("image/jpeg", "image/png", "image/jpg") intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes) intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION startActivityForResult(intent,REQUEST_IMAGE_IN_GALLERY) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == REQUEST_IMAGE_IN_GALLERY && resultCode == RESULT_OK) { MyLogger.logThis( TAG, " addPhotoFromGallery() -> onActivityResult()", "returned data ${data?.data}" ) data?.data?.let { imgUri -> addCarImgsVm.addImage(imgUri.toString()) } } } private var alertDialog: AlertDialog? = null private fun confirmAddPhotosLater() { if (alertDialog != null) { if (alertDialog!!.isShowing) return else alertDialog = null } alertDialog = activity?.let { val builder = AlertDialog.Builder(it) builder.apply { setTitle(R.string.add_photos_later_confirm_title) setPositiveButton(R.string.ok_txt, DialogInterface.OnClickListener { dialog, _ -> dialog.dismiss() goToSellersHome() }) setNegativeButton(R.string.cancel_adding_photos_later, DialogInterface.OnClickListener { dialog, _ -> dialog.dismiss() }) } builder.create() } alertDialog?.show() } private fun goToSellersHome() { val action = AddCarImagesFragmentDirections.actionAddCarImagesFragmentToSellersHomeFragment() findNavController().navigate(action) } private fun saveCarImages() { addCarImgsVm.save() } private fun deleteSelectedImages() { val imgsSelected = addCarImgsVm.getSelectedImagesNum() val title: Int val positiveMessage: Int if (imgsSelected == 0) { title = R.string.select_imgs_to_delete positiveMessage = R.string.got_it_txt } else { title = R.string.delete_selected_images positiveMessage = R.string.yes_txt } if (alertDialog != null) { if (alertDialog!!.isShowing) return else alertDialog = null } alertDialog = activity?.let { val builder = AlertDialog.Builder(it) builder.apply { setTitle(title) setPositiveButton(positiveMessage, DialogInterface.OnClickListener { dialog, _ -> dialog.dismiss() addCarImgsVm.deleteSelectedImages() }) setNegativeButton(R.string.cancel_action_txt, DialogInterface.OnClickListener { dialog, _ -> dialog.dismiss() }) } builder.create() } alertDialog?.show() } /******************** MENU ****************/ override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.sellers_add_car, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_save -> { saveCarImages() true } R.id.action_delete -> { deleteSelectedImages() true } else -> item.onNavDestinationSelected(findNavController()) || super.onOptionsItemSelected( item ) } } /************ DELETE OR UN-DELETE IMAGES *****************/ override fun onSelectImage(imgUrl: String) { addCarImgsVm.selectCarImg(imgUrl) } override fun onUnSelectImage(imgUrl: String) { addCarImgsVm.unSelectCarImg(imgUrl) } override fun onDestroyView() { super.onDestroyView() if (alertDialog?.isShowing == true) alertDialog?.dismiss() alertDialog = null _binding = null } }
0
Kotlin
0
0
ad2f9dc29cd1d98d62f3753801c169e08ab29a70
8,831
car_valuation_prototype_app
MIT License
src/main/kotlin/one/devos/osuv2kt/models/beatmap/BeatmapsetDiscussion.kt
devOS-Sanity-Edition
856,181,413
false
{"Kotlin": 49164}
package one.devos.osuv2kt.models.beatmap import com.google.gson.JsonElement import one.devos.osuv2kt.models.CurrentUserAttributes import java.time.OffsetDateTime public data class BeatmapsetDiscussion( public val beatmap: Beatmap?, public val beatmapId: Int?, public val beatmapset: Beatmapset?, public val beatmapsetId: Int, public val canBeResolved: Boolean, public val canGrantKudosu: Boolean, public val createdAt: OffsetDateTime, public val currentUserAttributes: CurrentUserAttributes, public val deletedAt: OffsetDateTime?, public val deletedById: Int?, public val id: Int, public val kudosuDenied: Boolean, public val lastPostAt: OffsetDateTime, public val messageType: JsonElement, // TODO: This is supposed to be type MessageType but it is undocumented public val parentId: Int?, public val posts: Array<BeatmapsetDiscussionPost>, public val resolved: Boolean, public val startingPost: BeatmapsetDiscussionPost?, public val timestamp: Int, public val updatedAt: OffsetDateTime, public val userId: Int )
0
Kotlin
0
0
ebefb4d6ad7003c46c4e482d8229af8df6552b81
1,099
osuv2kt
MIT License
src/test/kotlin/canon/parser/xml/strategy/MultipleChoiceStrategyTest.kt
leftshiftone
205,671,409
false
null
package canon.parser.xml.strategy import canon.extension.toNode import canon.parser.xml.CanonXmlParser import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class MultipleChoiceStrategyTest { @Test fun `ordinary parsing`() { val xml = "<multipleChoice id='testId' class='testClass' name='testName' sieve='true'>" + "<choice id='testId2' class='testClass' text='testText' selected='true'></choice>" + "<choice id='testId3' class='testClass' text='testText' selected='false'></choice>" + "</multipleChoice>" val parsed = MultipleChoiceStrategy().parse(xml.toNode(), CanonXmlParser()::toRenderables) assertThat(parsed).isNotNull assertThat(parsed.id).isEqualTo("testId") assertThat(parsed.`class`).isEqualTo("testClass") assertThat(parsed.name).isEqualTo("testName") assertThat(parsed.sieve).isEqualTo(true) assertThat(parsed.renderables).hasSize(2) } @Test fun `ordinary parsing with default value for sieve is true`() { val xml = "<multipleChoice id='testId' class='testClass' name='testName'>" + "<choice id='testId2' class='testClass' text='testText' selected='true'></choice>" + "<choice id='testId3' class='testClass' text='testText' selected='false'></choice>" + "</multipleChoice>" val parsed = MultipleChoiceStrategy().parse(xml.toNode(), CanonXmlParser()::toRenderables) assertThat(parsed).isNotNull assertThat(parsed.id).isEqualTo("testId") assertThat(parsed.`class`).isEqualTo("testClass") assertThat(parsed.name).isEqualTo("testName") assertThat(parsed.sieve).isEqualTo(true) assertThat(parsed.renderables).hasSize(2) } }
0
Kotlin
1
0
5babc577eeca5655cf92e64dd2693c591c72eb50
1,816
canon
MIT License